title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Javascript Number() Function | 06 Jul, 2020
Below is the example of the Number() function.
Example:<script> // JavaScript to illustrate // Number() function function func() { // Original string var a = true; var value = Number(a); document.write(value); }// Driver codefunc();</script>
<script> // JavaScript to illustrate // Number() function function func() { // Original string var a = true; var value = Number(a); document.write(value); }// Driver codefunc();</script>
Output:1
1
The Number() function is used to convert data type to number.
Syntax:
Number(object)
Parameters: This function accept a single parameter as mentioned above and described below:
object: This parameter holds the objects that will be converted any type of javascript variable to number type.
Return Values: Number() function returns the number format for any type of javascript variable.
Below examples illustrate the Number() function in JavaScript:
Example 1:Input : Number(true);
Number(false);
Output : 1
0
Input : Number(true);
Number(false);
Output : 1
0
Example 2: Not a number is returned by the compiler.Input : Number("10 20");
Output: NaN
Input : Number("10 20");
Output: NaN
Example 3: The Number() method above returns the number of milliseconds since 1.1.1970.Input : Number(new Date("2017-09-30"));
Output : 1506729600000
Input : Number(new Date("2017-09-30"));
Output : 1506729600000
Example 4:Input : Number("John");
Output : NaN
Input : Number("John");
Output : NaN
More example codes for the above function are as follows:
Program 1:
<script> // JavaScript to illustrate Number() function function func() { // Original string var a = "10 20"; var value = Number(a); document.write(value); }// Driver codefunc();</script>
Output:
NaN
Program 2:
<script> // JavaScript to illustrate Number() function function func() { var value = Number(new Date("2017-09-30")); document.write(value); }// Driver codefunc();</script>
Output:
1506729600000
Program 4:
<script> // JavaScript to illustrate Number() function function func() { var value = Number("John"); document.write(value); }// Driver codefunc();</script>
Output:
NaN
Supported Browsers:
Google Chrome
Firefox
Internet Explorer
Safari
Opera
javascript-functions
JavaScript-Numbers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n06 Jul, 2020"
},
{
"code": null,
"e": 75,
"s": 28,
"text": "Below is the example of the Number() function."
},
{
"code": null,
"e": 315,
"s": 75,
"text": "Example:<script> // JavaScript to illustrate // Number() function function func() { // Original string var a = true; var value = Number(a); document.write(value); }// Driver codefunc();</script> "
},
{
"code": "<script> // JavaScript to illustrate // Number() function function func() { // Original string var a = true; var value = Number(a); document.write(value); }// Driver codefunc();</script> ",
"e": 547,
"s": 315,
"text": null
},
{
"code": null,
"e": 556,
"s": 547,
"text": "Output:1"
},
{
"code": null,
"e": 558,
"s": 556,
"text": "1"
},
{
"code": null,
"e": 620,
"s": 558,
"text": "The Number() function is used to convert data type to number."
},
{
"code": null,
"e": 628,
"s": 620,
"text": "Syntax:"
},
{
"code": null,
"e": 643,
"s": 628,
"text": "Number(object)"
},
{
"code": null,
"e": 735,
"s": 643,
"text": "Parameters: This function accept a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 847,
"s": 735,
"text": "object: This parameter holds the objects that will be converted any type of javascript variable to number type."
},
{
"code": null,
"e": 943,
"s": 847,
"text": "Return Values: Number() function returns the number format for any type of javascript variable."
},
{
"code": null,
"e": 1006,
"s": 943,
"text": "Below examples illustrate the Number() function in JavaScript:"
},
{
"code": null,
"e": 1088,
"s": 1006,
"text": "Example 1:Input : Number(true);\n Number(false);\nOutput : 1\n 0"
},
{
"code": null,
"e": 1160,
"s": 1088,
"text": "Input : Number(true);\n Number(false);\nOutput : 1\n 0"
},
{
"code": null,
"e": 1249,
"s": 1160,
"text": "Example 2: Not a number is returned by the compiler.Input : Number(\"10 20\");\nOutput: NaN"
},
{
"code": null,
"e": 1286,
"s": 1249,
"text": "Input : Number(\"10 20\");\nOutput: NaN"
},
{
"code": null,
"e": 1436,
"s": 1286,
"text": "Example 3: The Number() method above returns the number of milliseconds since 1.1.1970.Input : Number(new Date(\"2017-09-30\"));\nOutput : 1506729600000"
},
{
"code": null,
"e": 1499,
"s": 1436,
"text": "Input : Number(new Date(\"2017-09-30\"));\nOutput : 1506729600000"
},
{
"code": null,
"e": 1547,
"s": 1499,
"text": "Example 4:Input : Number(\"John\");\nOutput : NaN\n"
},
{
"code": null,
"e": 1585,
"s": 1547,
"text": "Input : Number(\"John\");\nOutput : NaN\n"
},
{
"code": null,
"e": 1643,
"s": 1585,
"text": "More example codes for the above function are as follows:"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": "Program 1:"
},
{
"code": "<script> // JavaScript to illustrate Number() function function func() { // Original string var a = \"10 20\"; var value = Number(a); document.write(value); }// Driver codefunc();</script>",
"e": 1882,
"s": 1654,
"text": null
},
{
"code": null,
"e": 1890,
"s": 1882,
"text": "Output:"
},
{
"code": null,
"e": 1894,
"s": 1890,
"text": "NaN"
},
{
"code": null,
"e": 1905,
"s": 1894,
"text": "Program 2:"
},
{
"code": "<script> // JavaScript to illustrate Number() function function func() { var value = Number(new Date(\"2017-09-30\")); document.write(value); }// Driver codefunc();</script>",
"e": 2100,
"s": 1905,
"text": null
},
{
"code": null,
"e": 2108,
"s": 2100,
"text": "Output:"
},
{
"code": null,
"e": 2122,
"s": 2108,
"text": "1506729600000"
},
{
"code": null,
"e": 2133,
"s": 2122,
"text": "Program 4:"
},
{
"code": "<script> // JavaScript to illustrate Number() function function func() { var value = Number(\"John\"); document.write(value); }// Driver codefunc();</script>",
"e": 2312,
"s": 2133,
"text": null
},
{
"code": null,
"e": 2320,
"s": 2312,
"text": "Output:"
},
{
"code": null,
"e": 2324,
"s": 2320,
"text": "NaN"
},
{
"code": null,
"e": 2344,
"s": 2324,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 2358,
"s": 2344,
"text": "Google Chrome"
},
{
"code": null,
"e": 2366,
"s": 2358,
"text": "Firefox"
},
{
"code": null,
"e": 2384,
"s": 2366,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2391,
"s": 2384,
"text": "Safari"
},
{
"code": null,
"e": 2397,
"s": 2391,
"text": "Opera"
},
{
"code": null,
"e": 2418,
"s": 2397,
"text": "javascript-functions"
},
{
"code": null,
"e": 2437,
"s": 2418,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 2448,
"s": 2437,
"text": "JavaScript"
},
{
"code": null,
"e": 2465,
"s": 2448,
"text": "Web Technologies"
},
{
"code": null,
"e": 2563,
"s": 2465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2624,
"s": 2563,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2696,
"s": 2624,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2736,
"s": 2696,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2788,
"s": 2736,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2829,
"s": 2788,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2891,
"s": 2829,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2924,
"s": 2891,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2985,
"s": 2924,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3035,
"s": 2985,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python – time.ctime() Method | 16 Jul, 2021
Python time.ctime() method converts a time in seconds since the epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). Current time is returned by localtime() is used when the time tuple is not present.
Syntax: time.ctime([ sec ])
Parameter:
sec: number of seconds to be converted into string representation.
Example 1:
Let’s move to the code with an explanation :
Python3
# import moduleimport time # here no parameter is passedprint(time.ctime())
Output:
Thu Mar 18 11:00:19 2021
It prints the standard time equivalent to asctime() method.
Example 2:
Let’s Have a look at asctime() method:
Python3
# import timeimport time # gives local timea = time.localtime() c = time.asctime(a)print(c)
Output:
Thu Mar 18 11:01:02 2021
Example 3:
Let’s move to another example where we will pass seconds as a parameter to ctime() method.
Python3
# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1615799665.584516))
Output:
Mon Mar 15 14:44:25 2021
Example 4:
Here is another example where we pass a parameter to ctime() method.
Python3
# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1000))
Output:
Thu Jan 1 05:46:40 1970
surindertarika1234
Picked
Python time-module
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 286,
"s": 54,
"text": "Python time.ctime() method converts a time in seconds since the epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). Current time is returned by localtime() is used when the time tuple is not present."
},
{
"code": null,
"e": 314,
"s": 286,
"text": "Syntax: time.ctime([ sec ])"
},
{
"code": null,
"e": 325,
"s": 314,
"text": "Parameter:"
},
{
"code": null,
"e": 392,
"s": 325,
"text": "sec: number of seconds to be converted into string representation."
},
{
"code": null,
"e": 403,
"s": 392,
"text": "Example 1:"
},
{
"code": null,
"e": 448,
"s": 403,
"text": "Let’s move to the code with an explanation :"
},
{
"code": null,
"e": 456,
"s": 448,
"text": "Python3"
},
{
"code": "# import moduleimport time # here no parameter is passedprint(time.ctime())",
"e": 532,
"s": 456,
"text": null
},
{
"code": null,
"e": 540,
"s": 532,
"text": "Output:"
},
{
"code": null,
"e": 565,
"s": 540,
"text": "Thu Mar 18 11:00:19 2021"
},
{
"code": null,
"e": 626,
"s": 565,
"text": "It prints the standard time equivalent to asctime() method. "
},
{
"code": null,
"e": 637,
"s": 626,
"text": "Example 2:"
},
{
"code": null,
"e": 676,
"s": 637,
"text": "Let’s Have a look at asctime() method:"
},
{
"code": null,
"e": 684,
"s": 676,
"text": "Python3"
},
{
"code": "# import timeimport time # gives local timea = time.localtime() c = time.asctime(a)print(c)",
"e": 776,
"s": 684,
"text": null
},
{
"code": null,
"e": 784,
"s": 776,
"text": "Output:"
},
{
"code": null,
"e": 809,
"s": 784,
"text": "Thu Mar 18 11:01:02 2021"
},
{
"code": null,
"e": 820,
"s": 809,
"text": "Example 3:"
},
{
"code": null,
"e": 911,
"s": 820,
"text": "Let’s move to another example where we will pass seconds as a parameter to ctime() method."
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Python3"
},
{
"code": "# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1615799665.584516))",
"e": 1047,
"s": 919,
"text": null
},
{
"code": null,
"e": 1055,
"s": 1047,
"text": "Output:"
},
{
"code": null,
"e": 1080,
"s": 1055,
"text": "Mon Mar 15 14:44:25 2021"
},
{
"code": null,
"e": 1091,
"s": 1080,
"text": "Example 4:"
},
{
"code": null,
"e": 1160,
"s": 1091,
"text": "Here is another example where we pass a parameter to ctime() method."
},
{
"code": null,
"e": 1168,
"s": 1160,
"text": "Python3"
},
{
"code": "# import time moduleimport time # passing number of seconds as# parameter to ctime() methodprint(time.ctime(1000))",
"e": 1283,
"s": 1168,
"text": null
},
{
"code": null,
"e": 1291,
"s": 1283,
"text": "Output:"
},
{
"code": null,
"e": 1316,
"s": 1291,
"text": "Thu Jan 1 05:46:40 1970"
},
{
"code": null,
"e": 1335,
"s": 1316,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1342,
"s": 1335,
"text": "Picked"
},
{
"code": null,
"e": 1361,
"s": 1342,
"text": "Python time-module"
},
{
"code": null,
"e": 1368,
"s": 1361,
"text": "Python"
},
{
"code": null,
"e": 1466,
"s": 1368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1498,
"s": 1466,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1525,
"s": 1498,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1546,
"s": 1525,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1569,
"s": 1546,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1625,
"s": 1569,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1656,
"s": 1625,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1698,
"s": 1656,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1740,
"s": 1698,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1779,
"s": 1740,
"text": "Python | datetime.timedelta() function"
}
] |
Dmitry – Passive Information Gathering Tool in Kali Linux | 15 Apr, 2021
Dmitry is a free and open-source tool available on GitHub. The tool is used for information gathering. You can download the tool and install in your Kali Linux. Dmitry stands for DeepMagic Information Gathering Tool. It’s a command-line tool Using Dmitry tool You can collect information about the target, this information can be used for social engineering attacks. It can be used to gather a number of valuable pieces of information
Dmitry Tool can be used to search subdomains of the target.
Dmitry Tool can be used to find open ports of the target system.
Dmitry Tool can be used to perform TCP scan.
Dmitry Tool can be used with netcraft service to get the target information such as operating system, web server details, web host details, hosting service details, etc.
Dmitry Tool can be used with whois service to get the target information such as registered domain, name, address, the contact information of the person who registered it.
Dmitry Tool can be used to get email addresses that are associated with the domain of the target.
Dmitry Tool is a command-line tool. There are various commands of the Dmitry tool that can be used with different commands. Different flags used with commands. Flags are given below.
Step 1. Turn on your Kali Linux. Move to Desktop Directory.
command : cd Desktop
Step 2. Now create a new directory called Dmitry.
command : mkdir Dmitry
Step 3. As you have created the Dmitry Directory. Now move into this directory because in this directory you have to install Dmitry tool.
command : cd Dmitry
Step 4. As you can see now you are in Dmitry directory. Now you have to clone and download the Dmitry tool from GitHub. Clone the tool using the following command.
command : git clone https://github.com/jaygreig86/dmitry.git
Step 5. Congratulations the Dmitry tool has been downloaded into your Kali Linux. Now you can use the tool. Now to check the listing of the directory using the following command.
command : ls
Step 6. You can see a new directory here called dmitry. Move to this directory using the following command and list the content using the following commands.
command : cd dmitry , ls
Step 7. The file has been downloaded in the directory now you have to install the directory using following command. This will download all the dependencies.
Command : sudo apt-get install automake autoconf
Step 8. All the dependencies have been downloaded, Now you have to give permissions to the tool using following command.
Command : chmod +x configure
Step 9. Permission has been given to the tool for execution. It’s time to initialize the configuration file using the following command.
Command : ./configure
Step 10. Now, this is the time to make a configuration available for the tool, to do that type following command.
command : make
Step 11. Now install the tool using the following command.
Command : make install./
Step 12. Finally, all the dependencies and tool configuration have been completed now you can run the tool using the following command.
Command : ./dmitry
You can see the tool is in the running mode now we can see different flags here. These flags can be used with commands to set a target and to get information about the target. Now we will see some examples to use the tool. Some examples are given below.
Run the tool and type the following command for any basic information gathering.
command : ./dmitry scanme.org
Instead of scanme.org you can take any domain name here which is your target.
Run the tool and type the following command with the flag for specific information gathering. We have used -o flag here to get details about ports.
command : ./dmitry -o scanme.org
Kali-Linux
How To
Linux-Unix
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, 2021"
},
{
"code": null,
"e": 463,
"s": 28,
"text": "Dmitry is a free and open-source tool available on GitHub. The tool is used for information gathering. You can download the tool and install in your Kali Linux. Dmitry stands for DeepMagic Information Gathering Tool. It’s a command-line tool Using Dmitry tool You can collect information about the target, this information can be used for social engineering attacks. It can be used to gather a number of valuable pieces of information"
},
{
"code": null,
"e": 523,
"s": 463,
"text": "Dmitry Tool can be used to search subdomains of the target."
},
{
"code": null,
"e": 588,
"s": 523,
"text": "Dmitry Tool can be used to find open ports of the target system."
},
{
"code": null,
"e": 633,
"s": 588,
"text": "Dmitry Tool can be used to perform TCP scan."
},
{
"code": null,
"e": 803,
"s": 633,
"text": "Dmitry Tool can be used with netcraft service to get the target information such as operating system, web server details, web host details, hosting service details, etc."
},
{
"code": null,
"e": 975,
"s": 803,
"text": "Dmitry Tool can be used with whois service to get the target information such as registered domain, name, address, the contact information of the person who registered it."
},
{
"code": null,
"e": 1073,
"s": 975,
"text": "Dmitry Tool can be used to get email addresses that are associated with the domain of the target."
},
{
"code": null,
"e": 1257,
"s": 1073,
"text": "Dmitry Tool is a command-line tool. There are various commands of the Dmitry tool that can be used with different commands. Different flags used with commands. Flags are given below. "
},
{
"code": null,
"e": 1317,
"s": 1257,
"text": "Step 1. Turn on your Kali Linux. Move to Desktop Directory."
},
{
"code": null,
"e": 1338,
"s": 1317,
"text": "command : cd Desktop"
},
{
"code": null,
"e": 1388,
"s": 1338,
"text": "Step 2. Now create a new directory called Dmitry."
},
{
"code": null,
"e": 1411,
"s": 1388,
"text": "command : mkdir Dmitry"
},
{
"code": null,
"e": 1549,
"s": 1411,
"text": "Step 3. As you have created the Dmitry Directory. Now move into this directory because in this directory you have to install Dmitry tool."
},
{
"code": null,
"e": 1569,
"s": 1549,
"text": "command : cd Dmitry"
},
{
"code": null,
"e": 1735,
"s": 1569,
"text": "Step 4. As you can see now you are in Dmitry directory. Now you have to clone and download the Dmitry tool from GitHub. Clone the tool using the following command. "
},
{
"code": null,
"e": 1796,
"s": 1735,
"text": "command : git clone https://github.com/jaygreig86/dmitry.git"
},
{
"code": null,
"e": 1975,
"s": 1796,
"text": "Step 5. Congratulations the Dmitry tool has been downloaded into your Kali Linux. Now you can use the tool. Now to check the listing of the directory using the following command."
},
{
"code": null,
"e": 1988,
"s": 1975,
"text": "command : ls"
},
{
"code": null,
"e": 2146,
"s": 1988,
"text": "Step 6. You can see a new directory here called dmitry. Move to this directory using the following command and list the content using the following commands."
},
{
"code": null,
"e": 2171,
"s": 2146,
"text": "command : cd dmitry , ls"
},
{
"code": null,
"e": 2329,
"s": 2171,
"text": "Step 7. The file has been downloaded in the directory now you have to install the directory using following command. This will download all the dependencies."
},
{
"code": null,
"e": 2378,
"s": 2329,
"text": "Command : sudo apt-get install automake autoconf"
},
{
"code": null,
"e": 2499,
"s": 2378,
"text": "Step 8. All the dependencies have been downloaded, Now you have to give permissions to the tool using following command."
},
{
"code": null,
"e": 2528,
"s": 2499,
"text": "Command : chmod +x configure"
},
{
"code": null,
"e": 2665,
"s": 2528,
"text": "Step 9. Permission has been given to the tool for execution. It’s time to initialize the configuration file using the following command."
},
{
"code": null,
"e": 2687,
"s": 2665,
"text": "Command : ./configure"
},
{
"code": null,
"e": 2801,
"s": 2687,
"text": "Step 10. Now, this is the time to make a configuration available for the tool, to do that type following command."
},
{
"code": null,
"e": 2816,
"s": 2801,
"text": "command : make"
},
{
"code": null,
"e": 2875,
"s": 2816,
"text": "Step 11. Now install the tool using the following command."
},
{
"code": null,
"e": 2900,
"s": 2875,
"text": "Command : make install./"
},
{
"code": null,
"e": 3036,
"s": 2900,
"text": "Step 12. Finally, all the dependencies and tool configuration have been completed now you can run the tool using the following command."
},
{
"code": null,
"e": 3055,
"s": 3036,
"text": "Command : ./dmitry"
},
{
"code": null,
"e": 3309,
"s": 3055,
"text": "You can see the tool is in the running mode now we can see different flags here. These flags can be used with commands to set a target and to get information about the target. Now we will see some examples to use the tool. Some examples are given below."
},
{
"code": null,
"e": 3390,
"s": 3309,
"text": "Run the tool and type the following command for any basic information gathering."
},
{
"code": null,
"e": 3420,
"s": 3390,
"text": "command : ./dmitry scanme.org"
},
{
"code": null,
"e": 3498,
"s": 3420,
"text": "Instead of scanme.org you can take any domain name here which is your target."
},
{
"code": null,
"e": 3646,
"s": 3498,
"text": "Run the tool and type the following command with the flag for specific information gathering. We have used -o flag here to get details about ports."
},
{
"code": null,
"e": 3679,
"s": 3646,
"text": "command : ./dmitry -o scanme.org"
},
{
"code": null,
"e": 3690,
"s": 3679,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3697,
"s": 3690,
"text": "How To"
},
{
"code": null,
"e": 3708,
"s": 3697,
"text": "Linux-Unix"
}
] |
Find median of BST in O(n) time and O(1) space | 26 May, 2022
Given a Binary Search Tree, find median of it. If no. of nodes are even: then median = ((n/2th node + ((n)/2th+1) node) /2 If no. of nodes are odd : then median = (n+1)/2th node.For example, median of below BST is 12.
More Examples:
Given BST(with odd no. of nodes) is :
6
/ \
3 8
/ \ / \
1 4 7 9
Inorder of Given BST will be : 1, 3, 4, 6, 7, 8, 9
So, here median will 6.
Given BST(with even no. of nodes) is :
6
/ \
3 8
/ \ /
1 4 7
Inorder of Given BST will be : 1, 3, 4, 6, 7, 8
So, here median will (4+6)/2 = 5.
Asked in: Google
To find the median, we need to find the Inorder of the BST because its Inorder will be in sorted order and then find the median i.e. The idea is based on K’th smallest element in BST using O(1) Extra SpaceThe task is very simple if we are allowed to use extra space but Inorder traversal using recursion and stack both use Space which is not allowed here. So, the solution is to do Morris Inorder traversal as it doesn’t require any extra space.
Implementation:
1- Count the no. of nodes in the given BST
using Morris Inorder Traversal.
2- Then Perform Morris Inorder traversal one
more time by counting nodes and by checking if
count is equal to the median point.
To consider even no. of nodes an extra pointer
pointing to the previous node is used.
C++
Java
Python3
C#
Javascript
/* C++ program to find the median of BST in O(n) time and O(1) space*/#include<bits/stdc++.h>using namespace std; /* A binary search tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, *right;}; // A utility function to create a new BST nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search tree using Morris Inorder traversal*/int counNodes(struct Node *root){ struct Node *current, *pre; // Initialise count of nodes as 0 int count = 0; if (root == NULL) return count; current = root; while (current != NULL) { if (current->left == NULL) { // Count node if its left is NULL count++; // Move to its right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; // Increment count if the current // node is to be visited count++; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) space using Morris Inorder traversal*/int findMedian(struct Node *root){ if (root == NULL) return 0; int count = counNodes(root); int currCount = 0; struct Node *current = root, *pre, *prev; while (current != NULL) { if (current->left == NULL) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev->data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev->data + current->data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current->data; else if (count%2==0 && currCount == (count/2)+1) return (prev->data+current->data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} /* Driver program to test above functions*/int main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << "\nMedian of BST is " << findMedian(root); return 0;}
/* Java program to find the median of BST in O(n)time and O(1) space*/class GfG { /* A binary search tree Node has data, pointerto left child and a pointer to right child */static class Node{ int data; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/static int counNodes(Node root){ Node current, pre; // Initialise count of nodes as 0 int count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/static int findMedian(Node root){if (root == null) return 0; int count = counNodes(root); int currCount = 0; Node current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count%2==0 && currCount == (count/2)+1) return (prev.data+current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/public static void main(String[] args){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); System.out.println("Median of BST is " + findMedian(root));}} // This code is contributed by prerna saini.
# Python program to find closest# value in Binary search Tree _MIN=-2147483648_MAX=2147483648 # Helper function that allocates # a new node with the given data # and None left and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None """ A utility function to insert a new node withgiven key in BST """def insert(node,key): """ If the tree is empty, return a new node """ if (node == None): return newNode(key) """ Otherwise, recur down the tree """ if (key < node.data): node.left = insert(node.left, key) elif (key > node.data): node.right = insert(node.right, key) """ return the (unchanged) node pointer """ return node """ Function to count nodes in a binary search tree using Morris Inorder traversal"""def counNodes(root): # Initialise count of nodes as 0 count = 0 if (root == None): return count current = root while (current != None): if (current.left == None): # Count node if its left is None count+=1 # Move to its right current = current.right else: """ Find the inorder predecessor of current """ pre = current.left while (pre.right != None and pre.right != current): pre = pre.right """ Make current as right child of its inorder predecessor """ if(pre.right == None): pre.right = current current = current.left else: pre.right = None # Increment count if the current # node is to be visited count += 1 current = current.right return count """ Function to find median in O(n) time and O(1) space using Morris Inorder traversal"""def findMedian(root): if (root == None): return 0 count = counNodes(root) currCount = 0 current = root while (current != None): if (current.left == None): # count current node currCount += 1 # check if current node is the median # Odd case if (count % 2 != 0 and currCount == (count + 1)//2): return prev.data # Even case elif (count % 2 == 0 and currCount == (count//2)+1): return (prev.data + current.data)//2 # Update prev for even no. of nodes prev = current #Move to the right current = current.right else: """ Find the inorder predecessor of current """ pre = current.left while (pre.right != None and pre.right != current): pre = pre.right """ Make current as right child of its inorder predecessor """ if (pre.right == None): pre.right = current current = current.left else: pre.right = None prev = pre # Count current node currCount+= 1 # Check if the current node is the median if (count % 2 != 0 and currCount == (count + 1) // 2 ): return current.data elif (count%2 == 0 and currCount == (count // 2) + 1): return (prev.data+current.data)//2 # update prev node for the case of even # no. of nodes prev = current current = current.right # Driver Codeif __name__ == '__main__': """ Constructed binary tree is 50 / \ 30 70 / \ / \ 20 40 60 80 """ root = newNode(50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("Median of BST is ",findMedian(root)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)
/* C# program to find the median of BST in O(n)time and O(1) space*/using System;class GfG{ /* A binary search tree Node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/static int counNodes(Node root){ Node current, pre; // Initialise count of nodes as 0 int count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/static int findMedian(Node root){if (root == null) return 0; int count = counNodes(root); int currCount = 0; Node current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/public static void Main(String []args){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Console.WriteLine("Median of BST is " + findMedian(root));}} // This code is contributed by Arnab Kundu
<script> /* JavaScript program to findthe median of BST in O(n)time and O(1) space*/ /* A binary search tree Node has data, pointerto left child and a pointer to right child */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // A utility function to create a new BST nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */function insert(node , key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/function counNodes(root){ var current, pre; // Initialise count of nodes as 0 var count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/function findMedian(root){if (root == null) return 0; var count = counNodes(root); var currCount = 0; var current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count%2==0 && currCount == (count/2)+1) return (prev.data+current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ var root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); document.write("Median of BST is " + findMedian(root)); // This code is contributed by todaysgaurav </script>
Output:
Median of BST is 50
Reference: https://www.careercup.com/question?id=4882624968392704This 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prerna saini
SHUBHAMSINGH10
andrew1234
todaysgaurav
arorakashish0911
simmytarika5
neemajjoshi2003
Amazon
Google
median-finding
Order-Statistics
statistical-algorithms
Traversal
Binary Search Tree
Amazon
Google
Traversal
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find postorder traversal of BST from preorder traversal
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Optimal Binary Search Tree | DP-24
Sorted Array to Balanced BST
Inorder Successor in Binary Search Tree
Merge Two Balanced Binary Search Trees
Convert a normal BST to Balanced BST
set vs unordered_set in C++ STL
Inorder predecessor and successor for a given key in BST
Find the node with minimum value in a Binary Search Tree | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 272,
"s": 52,
"text": "Given a Binary Search Tree, find median of it. If no. of nodes are even: then median = ((n/2th node + ((n)/2th+1) node) /2 If no. of nodes are odd : then median = (n+1)/2th node.For example, median of below BST is 12. "
},
{
"code": null,
"e": 289,
"s": 272,
"text": "More Examples: "
},
{
"code": null,
"e": 787,
"s": 289,
"text": " Given BST(with odd no. of nodes) is : \n 6\n / \\\n 3 8\n / \\ / \\\n 1 4 7 9\n\nInorder of Given BST will be : 1, 3, 4, 6, 7, 8, 9\nSo, here median will 6.\n\nGiven BST(with even no. of nodes) is : \n 6\n / \\\n 3 8\n / \\ / \n 1 4 7 \n\nInorder of Given BST will be : 1, 3, 4, 6, 7, 8\nSo, here median will (4+6)/2 = 5."
},
{
"code": null,
"e": 805,
"s": 787,
"text": "Asked in: Google "
},
{
"code": null,
"e": 1252,
"s": 805,
"text": "To find the median, we need to find the Inorder of the BST because its Inorder will be in sorted order and then find the median i.e. The idea is based on K’th smallest element in BST using O(1) Extra SpaceThe task is very simple if we are allowed to use extra space but Inorder traversal using recursion and stack both use Space which is not allowed here. So, the solution is to do Morris Inorder traversal as it doesn’t require any extra space. "
},
{
"code": null,
"e": 1574,
"s": 1252,
"text": "Implementation:\n1- Count the no. of nodes in the given BST\n using Morris Inorder Traversal.\n2- Then Perform Morris Inorder traversal one \n more time by counting nodes and by checking if \n count is equal to the median point.\n To consider even no. of nodes an extra pointer\n pointing to the previous node is used."
},
{
"code": null,
"e": 1580,
"s": 1576,
"text": "C++"
},
{
"code": null,
"e": 1585,
"s": 1580,
"text": "Java"
},
{
"code": null,
"e": 1593,
"s": 1585,
"text": "Python3"
},
{
"code": null,
"e": 1596,
"s": 1593,
"text": "C#"
},
{
"code": null,
"e": 1607,
"s": 1596,
"text": "Javascript"
},
{
"code": "/* C++ program to find the median of BST in O(n) time and O(1) space*/#include<bits/stdc++.h>using namespace std; /* A binary search tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, *right;}; // A utility function to create a new BST nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */struct Node* insert(struct Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search tree using Morris Inorder traversal*/int counNodes(struct Node *root){ struct Node *current, *pre; // Initialise count of nodes as 0 int count = 0; if (root == NULL) return count; current = root; while (current != NULL) { if (current->left == NULL) { // Count node if its left is NULL count++; // Move to its right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; // Increment count if the current // node is to be visited count++; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) space using Morris Inorder traversal*/int findMedian(struct Node *root){ if (root == NULL) return 0; int count = counNodes(root); int currCount = 0; struct Node *current = root, *pre, *prev; while (current != NULL) { if (current->left == NULL) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev->data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev->data + current->data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current->data; else if (count%2==0 && currCount == (count/2)+1) return (prev->data+current->data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} /* Driver program to test above functions*/int main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << \"\\nMedian of BST is \" << findMedian(root); return 0;}",
"e": 6612,
"s": 1607,
"text": null
},
{
"code": "/* Java program to find the median of BST in O(n)time and O(1) space*/class GfG { /* A binary search tree Node has data, pointerto left child and a pointer to right child */static class Node{ int data; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/static int counNodes(Node root){ Node current, pre; // Initialise count of nodes as 0 int count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/static int findMedian(Node root){if (root == null) return 0; int count = counNodes(root); int currCount = 0; Node current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count%2==0 && currCount == (count/2)+1) return (prev.data+current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/public static void main(String[] args){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); System.out.println(\"Median of BST is \" + findMedian(root));}} // This code is contributed by prerna saini.",
"e": 11507,
"s": 6612,
"text": null
},
{
"code": "# Python program to find closest# value in Binary search Tree _MIN=-2147483648_MAX=2147483648 # Helper function that allocates # a new node with the given data # and None left and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None \"\"\" A utility function to insert a new node withgiven key in BST \"\"\"def insert(node,key): \"\"\" If the tree is empty, return a new node \"\"\" if (node == None): return newNode(key) \"\"\" Otherwise, recur down the tree \"\"\" if (key < node.data): node.left = insert(node.left, key) elif (key > node.data): node.right = insert(node.right, key) \"\"\" return the (unchanged) node pointer \"\"\" return node \"\"\" Function to count nodes in a binary search tree using Morris Inorder traversal\"\"\"def counNodes(root): # Initialise count of nodes as 0 count = 0 if (root == None): return count current = root while (current != None): if (current.left == None): # Count node if its left is None count+=1 # Move to its right current = current.right else: \"\"\" Find the inorder predecessor of current \"\"\" pre = current.left while (pre.right != None and pre.right != current): pre = pre.right \"\"\" Make current as right child of its inorder predecessor \"\"\" if(pre.right == None): pre.right = current current = current.left else: pre.right = None # Increment count if the current # node is to be visited count += 1 current = current.right return count \"\"\" Function to find median in O(n) time and O(1) space using Morris Inorder traversal\"\"\"def findMedian(root): if (root == None): return 0 count = counNodes(root) currCount = 0 current = root while (current != None): if (current.left == None): # count current node currCount += 1 # check if current node is the median # Odd case if (count % 2 != 0 and currCount == (count + 1)//2): return prev.data # Even case elif (count % 2 == 0 and currCount == (count//2)+1): return (prev.data + current.data)//2 # Update prev for even no. of nodes prev = current #Move to the right current = current.right else: \"\"\" Find the inorder predecessor of current \"\"\" pre = current.left while (pre.right != None and pre.right != current): pre = pre.right \"\"\" Make current as right child of its inorder predecessor \"\"\" if (pre.right == None): pre.right = current current = current.left else: pre.right = None prev = pre # Count current node currCount+= 1 # Check if the current node is the median if (count % 2 != 0 and currCount == (count + 1) // 2 ): return current.data elif (count%2 == 0 and currCount == (count // 2) + 1): return (prev.data+current.data)//2 # update prev node for the case of even # no. of nodes prev = current current = current.right # Driver Codeif __name__ == '__main__': \"\"\" Constructed binary tree is 50 / \\ 30 70 / \\ / \\ 20 40 60 80 \"\"\" root = newNode(50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print(\"Median of BST is \",findMedian(root)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)",
"e": 15748,
"s": 11507,
"text": null
},
{
"code": "/* C# program to find the median of BST in O(n)time and O(1) space*/using System;class GfG{ /* A binary search tree Node has data, pointerto left child and a pointer to right child */public class Node{ public int data; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/static int counNodes(Node root){ Node current, pre; // Initialise count of nodes as 0 int count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/static int findMedian(Node root){if (root == null) return 0; int count = counNodes(root); int currCount = 0; Node current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/public static void Main(String []args){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Console.WriteLine(\"Median of BST is \" + findMedian(root));}} // This code is contributed by Arnab Kundu",
"e": 20670,
"s": 15748,
"text": null
},
{
"code": "<script> /* JavaScript program to findthe median of BST in O(n)time and O(1) space*/ /* A binary search tree Node has data, pointerto left child and a pointer to right child */ class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } // A utility function to create a new BST nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = null; temp.right = null; return temp;} /* A utility function to insert a new node withgiven key in BST */function insert(node , key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.data) node.left = insert(node.left, key); else if (key > node.data) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} /* Function to count nodes in a binary search treeusing Morris Inorder traversal*/function counNodes(root){ var current, pre; // Initialise count of nodes as 0 var count = 0; if (root == null) return count; current = root; while (current != null) { if (current.left == null) { // Count node if its left is NULL count++; // Move to its right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if(pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; // Increment count if the current // node is to be visited count++; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count;} /* Function to find median in O(n) time and O(1) spaceusing Morris Inorder traversal*/function findMedian(root){if (root == null) return 0; var count = counNodes(root); var currCount = 0; var current = root, pre = null, prev = null; while (current != null) { if (current.left == null) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return prev.data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev.data + current.data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current.right; } else { /* Find the inorder predecessor of current */ pre = current.left; while (pre.right != null && pre.right != current) pre = pre.right; /* Make current as right child of its inorder predecessor */ if (pre.right == null) { pre.right = current; current = current.left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre.right = null; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current.data; else if (count%2==0 && currCount == (count/2)+1) return (prev.data+current.data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current.right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return -1;} /* Driver code*/ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ var root = null; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); document.write(\"Median of BST is \" + findMedian(root)); // This code is contributed by todaysgaurav </script>",
"e": 25691,
"s": 20670,
"text": null
},
{
"code": null,
"e": 25701,
"s": 25691,
"text": "Output: "
},
{
"code": null,
"e": 25721,
"s": 25701,
"text": "Median of BST is 50"
},
{
"code": null,
"e": 26208,
"s": 25721,
"text": "Reference: https://www.careercup.com/question?id=4882624968392704This 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 26221,
"s": 26208,
"text": "prerna saini"
},
{
"code": null,
"e": 26236,
"s": 26221,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 26247,
"s": 26236,
"text": "andrew1234"
},
{
"code": null,
"e": 26260,
"s": 26247,
"text": "todaysgaurav"
},
{
"code": null,
"e": 26277,
"s": 26260,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26290,
"s": 26277,
"text": "simmytarika5"
},
{
"code": null,
"e": 26306,
"s": 26290,
"text": "neemajjoshi2003"
},
{
"code": null,
"e": 26313,
"s": 26306,
"text": "Amazon"
},
{
"code": null,
"e": 26320,
"s": 26313,
"text": "Google"
},
{
"code": null,
"e": 26335,
"s": 26320,
"text": "median-finding"
},
{
"code": null,
"e": 26352,
"s": 26335,
"text": "Order-Statistics"
},
{
"code": null,
"e": 26375,
"s": 26352,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 26385,
"s": 26375,
"text": "Traversal"
},
{
"code": null,
"e": 26404,
"s": 26385,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26411,
"s": 26404,
"text": "Amazon"
},
{
"code": null,
"e": 26418,
"s": 26411,
"text": "Google"
},
{
"code": null,
"e": 26428,
"s": 26418,
"text": "Traversal"
},
{
"code": null,
"e": 26447,
"s": 26428,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26545,
"s": 26447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26601,
"s": 26545,
"text": "Find postorder traversal of BST from preorder traversal"
},
{
"code": null,
"e": 26671,
"s": 26601,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 26706,
"s": 26671,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 26735,
"s": 26706,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 26775,
"s": 26735,
"text": "Inorder Successor in Binary Search Tree"
},
{
"code": null,
"e": 26814,
"s": 26775,
"text": "Merge Two Balanced Binary Search Trees"
},
{
"code": null,
"e": 26851,
"s": 26814,
"text": "Convert a normal BST to Balanced BST"
},
{
"code": null,
"e": 26883,
"s": 26851,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 26940,
"s": 26883,
"text": "Inorder predecessor and successor for a given key in BST"
}
] |
How to Enable Shell Script Debugging Mode in Linux? | 18 May, 2021
Linux is a very popular operating system especially among developers and in the computer science world, as it comes along with its powerful ability to play with the kernel. Major Linux distributions (often referred to as Linux distros) are Open Source (Source Code available and can be modified on request) in nature like Ubuntu, CentOS, etc.
Bash is a very popular shell scripting language that is executed in the back-end when you open the terminal in Linux. DevOps (Operations Team responsible for deployment more often) use Bash/Shell scripting (series of commands written in a file to execute together in an ordered fashion) to automate usual/minimalist/trivial tasks for example running checking of time stamps on which file is generated/updated, checking for a number of files, etc.
Debugging is terminology that means the process of identifying errors and possibly resolving them in computer hardware or software. Just like all the other programming/coding languages debugging is crucial in bash/shell scripting in order to understand the flow of the program and resolve any errors if they occur.
In this article let us discuss two ways of debugging a shell script, to help strengthen the understanding I will try to take 1 simple shell script (Hello World and List) and will build on it with an example of a conditional shell script (odd/even).
1. Using bash options (-x, -n, -v): The following are various options explained in detail:
-x: It helps in tracing command output before executing them, when we run the script using this option we get each line of code traced before it is executed and its respective output printed in the terminal. The following is a simple HelloWorld.sh script and its execution screenshots depict the same.
#! /bin/bash
# print Hello World
echo 'Hello World'
# Listing all components on root
ls /
Output:
Figure 1: Tracing HelloWorld.sh Output using -x option of bash.
In the above figure we see code traced (printed) before it is executed, then its relevant output, and further the code for listing (ls) is traced followed by its execution. Let’s build further with the following example (OddEven.sh) which prompts the user for input and tells whether the entered number is Odd/Even Number.
#! /bin/bash
# Take input from the user
echo -n "Enter a number"
read n
# Calculate remainder using mod (%) operator
remainder=$(( $n % 2 ))
# Odd or Even Check
if [ $remainder -eq 0 ]
then
echo "You have entered $n -- which is an Even number"
else
echo "You have entered $n -- which is an Odd number"
fi
Output:
Figure 2: Tracing OddEven.sh Output using -x option of bash.
Similar to the prior example each line of code is traced before it is executed.
-n: It helps in checking the syntax errors if there are any in the shell script prior to executing it. With a boom in the technology of cloud computing, it is essential to know various command-line options to check syntax errors. It is difficult to have GUI (Graphical User Interfaces) or designated IDEs (Integrated Development Environments) on Virtual Machines executing in the cloud. So this option helps with getting syntax checks performed on a script using CLI (Command Line Interface). Let’s understand its application using the example below which has OddEven.sh Script which by purpose has a small syntax error.
#! /bin/bash
# Take input from the user
echo -n "Enter a number"
read n
# Calculate remainder using mod (%) operator
remainder=$(( $n % 2 ))
# Odd or Even Check
if [ $remainder -eq 0 ]
then
echo "You have entered $n -- which is an Even number'
else
echo "You have entered $n -- which is an Odd number"
fi
Output:
Figure 3: Checking Syntax-Errors in OddEven.sh using -n option of bash.
When the script is executed with -n option output shows the exact line number location of the line of code where it got a syntax error. Then when the error is fixed and run it again with the same option the following output is shown-
Figure 4: After correcting Syntax-Errors in OddEven.sh using -n option of bash.
This shows that the script is syntax-errors-free.
-v: If there is a need to read the comments and entire script while the script is executing, then -v option helps us achieve this goal. The following example screenshot shows how -v and -x differ from each other and how we can use -v option. The same OddEven.sh script file as shown in the above examples is used in the below example.
Figure 5: View Comments and Code while they are executing in OddEven.sh
In the above code all comments and code are visible (like the entire “if block” and not only the lines which are executed).
One slight drawback with this is there is a need to perform debug checks on the entire script, if the script is huge it is quite tough/tedious to find useful insights from the output of -x option. So let us have a look at debugging only some specific part of a script in the Next way of Debugging.
2. Using set -x inside script for the specific script.
Let’s assume we want to debug/trace only a certain logical part of OddEven.sh Script and not the whole script. We can set -x flag before the code we want to debug and then set it again back to +x where tracing of code needs to be disabled. The following example code and screenshot help us depict this scenario.
#! /bin/bash
# Take input from the user
echo -n "Enter a number"
read n
# Enabling trace
set -x
# Calculate remainder using mod (%) operator
remainder=$(( $n % 2 ))
# Disabling trace
set +x
# Odd or Even Check
if [ $remainder -eq 0 ]
then
echo "You have entered $n -- which is an Even number"
else
echo "You have entered $n -- which is an Odd number"
fi
Output:
Figure 6: Debugging/Tracing on certain lines of code in a Shell Script.
Here in this example only the logical bit of OddEven.sh Script is being debugged. Only those outputs are traced in terminal output where the set -x option is specified.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 398,
"s": 54,
"text": "Linux is a very popular operating system especially among developers and in the computer science world, as it comes along with its powerful ability to play with the kernel. Major Linux distributions (often referred to as Linux distros) are Open Source (Source Code available and can be modified on request) in nature like Ubuntu, CentOS, etc. "
},
{
"code": null,
"e": 845,
"s": 398,
"text": "Bash is a very popular shell scripting language that is executed in the back-end when you open the terminal in Linux. DevOps (Operations Team responsible for deployment more often) use Bash/Shell scripting (series of commands written in a file to execute together in an ordered fashion) to automate usual/minimalist/trivial tasks for example running checking of time stamps on which file is generated/updated, checking for a number of files, etc."
},
{
"code": null,
"e": 1161,
"s": 845,
"text": "Debugging is terminology that means the process of identifying errors and possibly resolving them in computer hardware or software. Just like all the other programming/coding languages debugging is crucial in bash/shell scripting in order to understand the flow of the program and resolve any errors if they occur. "
},
{
"code": null,
"e": 1410,
"s": 1161,
"text": "In this article let us discuss two ways of debugging a shell script, to help strengthen the understanding I will try to take 1 simple shell script (Hello World and List) and will build on it with an example of a conditional shell script (odd/even)."
},
{
"code": null,
"e": 1501,
"s": 1410,
"text": "1. Using bash options (-x, -n, -v): The following are various options explained in detail:"
},
{
"code": null,
"e": 1803,
"s": 1501,
"text": "-x: It helps in tracing command output before executing them, when we run the script using this option we get each line of code traced before it is executed and its respective output printed in the terminal. The following is a simple HelloWorld.sh script and its execution screenshots depict the same."
},
{
"code": null,
"e": 1895,
"s": 1803,
"text": "#! /bin/bash\n\n# print Hello World\necho 'Hello World'\n\n# Listing all components on root\nls /"
},
{
"code": null,
"e": 1903,
"s": 1895,
"text": "Output:"
},
{
"code": null,
"e": 1967,
"s": 1903,
"text": "Figure 1: Tracing HelloWorld.sh Output using -x option of bash."
},
{
"code": null,
"e": 2290,
"s": 1967,
"text": "In the above figure we see code traced (printed) before it is executed, then its relevant output, and further the code for listing (ls) is traced followed by its execution. Let’s build further with the following example (OddEven.sh) which prompts the user for input and tells whether the entered number is Odd/Even Number."
},
{
"code": null,
"e": 2600,
"s": 2290,
"text": "#! /bin/bash\n\n# Take input from the user\necho -n \"Enter a number\"\nread n\n\n# Calculate remainder using mod (%) operator\nremainder=$(( $n % 2 ))\n\n# Odd or Even Check\nif [ $remainder -eq 0 ]\nthen\n echo \"You have entered $n -- which is an Even number\"\nelse\n echo \"You have entered $n -- which is an Odd number\"\nfi"
},
{
"code": null,
"e": 2608,
"s": 2600,
"text": "Output:"
},
{
"code": null,
"e": 2669,
"s": 2608,
"text": "Figure 2: Tracing OddEven.sh Output using -x option of bash."
},
{
"code": null,
"e": 2749,
"s": 2669,
"text": "Similar to the prior example each line of code is traced before it is executed."
},
{
"code": null,
"e": 3370,
"s": 2749,
"text": "-n: It helps in checking the syntax errors if there are any in the shell script prior to executing it. With a boom in the technology of cloud computing, it is essential to know various command-line options to check syntax errors. It is difficult to have GUI (Graphical User Interfaces) or designated IDEs (Integrated Development Environments) on Virtual Machines executing in the cloud. So this option helps with getting syntax checks performed on a script using CLI (Command Line Interface). Let’s understand its application using the example below which has OddEven.sh Script which by purpose has a small syntax error."
},
{
"code": null,
"e": 3680,
"s": 3370,
"text": "#! /bin/bash\n\n# Take input from the user\necho -n \"Enter a number\"\nread n\n\n# Calculate remainder using mod (%) operator\nremainder=$(( $n % 2 ))\n\n# Odd or Even Check\nif [ $remainder -eq 0 ]\nthen\n echo \"You have entered $n -- which is an Even number'\nelse\n echo \"You have entered $n -- which is an Odd number\"\nfi"
},
{
"code": null,
"e": 3688,
"s": 3680,
"text": "Output:"
},
{
"code": null,
"e": 3760,
"s": 3688,
"text": "Figure 3: Checking Syntax-Errors in OddEven.sh using -n option of bash."
},
{
"code": null,
"e": 3994,
"s": 3760,
"text": "When the script is executed with -n option output shows the exact line number location of the line of code where it got a syntax error. Then when the error is fixed and run it again with the same option the following output is shown-"
},
{
"code": null,
"e": 4074,
"s": 3994,
"text": "Figure 4: After correcting Syntax-Errors in OddEven.sh using -n option of bash."
},
{
"code": null,
"e": 4124,
"s": 4074,
"text": "This shows that the script is syntax-errors-free."
},
{
"code": null,
"e": 4459,
"s": 4124,
"text": "-v: If there is a need to read the comments and entire script while the script is executing, then -v option helps us achieve this goal. The following example screenshot shows how -v and -x differ from each other and how we can use -v option. The same OddEven.sh script file as shown in the above examples is used in the below example."
},
{
"code": null,
"e": 4531,
"s": 4459,
"text": "Figure 5: View Comments and Code while they are executing in OddEven.sh"
},
{
"code": null,
"e": 4655,
"s": 4531,
"text": "In the above code all comments and code are visible (like the entire “if block” and not only the lines which are executed)."
},
{
"code": null,
"e": 4953,
"s": 4655,
"text": "One slight drawback with this is there is a need to perform debug checks on the entire script, if the script is huge it is quite tough/tedious to find useful insights from the output of -x option. So let us have a look at debugging only some specific part of a script in the Next way of Debugging."
},
{
"code": null,
"e": 5008,
"s": 4953,
"text": "2. Using set -x inside script for the specific script."
},
{
"code": null,
"e": 5320,
"s": 5008,
"text": "Let’s assume we want to debug/trace only a certain logical part of OddEven.sh Script and not the whole script. We can set -x flag before the code we want to debug and then set it again back to +x where tracing of code needs to be disabled. The following example code and screenshot help us depict this scenario."
},
{
"code": null,
"e": 5681,
"s": 5320,
"text": "#! /bin/bash\n\n# Take input from the user\necho -n \"Enter a number\"\nread n\n\n# Enabling trace\nset -x\n\n# Calculate remainder using mod (%) operator\nremainder=$(( $n % 2 ))\n\n# Disabling trace\nset +x\n\n# Odd or Even Check\nif [ $remainder -eq 0 ]\nthen\n echo \"You have entered $n -- which is an Even number\"\nelse\n echo \"You have entered $n -- which is an Odd number\"\nfi"
},
{
"code": null,
"e": 5689,
"s": 5681,
"text": "Output:"
},
{
"code": null,
"e": 5761,
"s": 5689,
"text": "Figure 6: Debugging/Tracing on certain lines of code in a Shell Script."
},
{
"code": null,
"e": 5930,
"s": 5761,
"text": "Here in this example only the logical bit of OddEven.sh Script is being debugged. Only those outputs are traced in terminal output where the set -x option is specified."
},
{
"code": null,
"e": 5937,
"s": 5930,
"text": "Picked"
},
{
"code": null,
"e": 5950,
"s": 5937,
"text": "Shell Script"
},
{
"code": null,
"e": 5961,
"s": 5950,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6059,
"s": 5961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6085,
"s": 6059,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 6120,
"s": 6085,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 6157,
"s": 6120,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 6186,
"s": 6157,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 6220,
"s": 6186,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 6257,
"s": 6220,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 6294,
"s": 6257,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 6333,
"s": 6294,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 6373,
"s": 6333,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
Java Program for Tower of Hanoi | 16 Jun, 2022
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk.
Java
// Java recursive program to solve tower of hanoi puzzle class GFG{ // Java recursive function to solve tower of hanoi puzzle static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 1) { System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod); } // Driver method public static void main(String args[]) { int n = 4; // Number of disks towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods }}
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Time Complexity: O(2n)
Auxiliary Space: O(n)
Please refer complete article on Program for Tower of Hanoi for more details!
chandramauliguptach
Java Programs
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, 2022"
},
{
"code": null,
"e": 510,
"s": 52,
"text": "Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. "
},
{
"code": null,
"e": 515,
"s": 510,
"text": "Java"
},
{
"code": "// Java recursive program to solve tower of hanoi puzzle class GFG{ // Java recursive function to solve tower of hanoi puzzle static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 1) { System.out.println(\"Move disk 1 from rod \" + from_rod + \" to rod \" + to_rod); return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); System.out.println(\"Move disk \" + n + \" from rod \" + from_rod + \" to rod \" + to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod); } // Driver method public static void main(String args[]) { int n = 4; // Number of disks towerOfHanoi(n, \\'A\\', \\'C\\', \\'B\\'); // A, B and C are names of rods }}",
"e": 1271,
"s": 515,
"text": null
},
{
"code": null,
"e": 1279,
"s": 1271,
"text": "Output:"
},
{
"code": null,
"e": 1774,
"s": 1279,
"text": " Move disk 1 from rod A to rod B\n Move disk 2 from rod A to rod C\n Move disk 1 from rod B to rod C\n Move disk 3 from rod A to rod B\n Move disk 1 from rod C to rod A\n Move disk 2 from rod C to rod B\n Move disk 1 from rod A to rod B\n Move disk 4 from rod A to rod C\n Move disk 1 from rod B to rod C\n Move disk 2 from rod B to rod A\n Move disk 1 from rod C to rod A\n Move disk 3 from rod B to rod C\n Move disk 1 from rod A to rod B\n Move disk 2 from rod A to rod C\n Move disk 1 from rod B to rod C"
},
{
"code": null,
"e": 1797,
"s": 1774,
"text": "Time Complexity: O(2n)"
},
{
"code": null,
"e": 1819,
"s": 1797,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1897,
"s": 1819,
"text": "Please refer complete article on Program for Tower of Hanoi for more details!"
},
{
"code": null,
"e": 1917,
"s": 1897,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 1931,
"s": 1917,
"text": "Java Programs"
}
] |
GATE | GATE-CS-2014-(Set-1) | Question 65 | 10 Apr, 2018
The minimum number of comparisons required to find the minimum and the maximum of 100 numbers is ______________.(A) 148(B) 147(C) 146(D) 140Answer: (A)Explanation: Steps to find minimum and maximum element out of n numbers:
1. Pick 2 elements(a, b), compare them. (say a > b)
2. Update min by comparing (min, b)
3. Update max by comparing (max, a)
Therefore, we need 3 comparisons for each 2 elements, so total number of required comparisons will be (3n)/2 – 2, because we do not need to update min or max in the very first step.
Recurrence relation will be:
T(n) = T(⌈n/2⌉)+T(⌊n/2⌋)+2 = 2T(n/2)+2 = ⌈3n/2⌉-2
By putting the value n=100, (3*100/2)-2 = 148 which is answer.
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Apr, 2018"
},
{
"code": null,
"e": 277,
"s": 53,
"text": "The minimum number of comparisons required to find the minimum and the maximum of 100 numbers is ______________.(A) 148(B) 147(C) 146(D) 140Answer: (A)Explanation: Steps to find minimum and maximum element out of n numbers:"
},
{
"code": null,
"e": 401,
"s": 277,
"text": "1. Pick 2 elements(a, b), compare them. (say a > b)\n2. Update min by comparing (min, b)\n3. Update max by comparing (max, a)"
},
{
"code": null,
"e": 583,
"s": 401,
"text": "Therefore, we need 3 comparisons for each 2 elements, so total number of required comparisons will be (3n)/2 – 2, because we do not need to update min or max in the very first step."
},
{
"code": null,
"e": 612,
"s": 583,
"text": "Recurrence relation will be:"
},
{
"code": null,
"e": 662,
"s": 612,
"text": "T(n) = T(⌈n/2⌉)+T(⌊n/2⌋)+2 = 2T(n/2)+2 = ⌈3n/2⌉-2"
},
{
"code": null,
"e": 725,
"s": 662,
"text": "By putting the value n=100, (3*100/2)-2 = 148 which is answer."
},
{
"code": null,
"e": 748,
"s": 725,
"text": " Quiz of this Question"
},
{
"code": null,
"e": 769,
"s": 748,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 795,
"s": 769,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 800,
"s": 795,
"text": "GATE"
}
] |
Modifying existing data in SQL | 10 Sep, 2021
In this article, we are going to cover how we can modify the existing data in SQL. There are lots of situations where we need to alter and need to update existing data. Let’s discuss one by one.
1. ALTER Command : ALTER is an SQL command used in Relational DBMS and is a Data Definition Language (DDL) statement. ALTER can be used to update the table’s structure in the database (like add, delete, drop indexes, columns, and constraints, modify the attributes of the tables in the database).
ALTER command is most commonly used to improve SQL SELECT queries by adding and removing indexes.
SYNTAX : Adding a column to the existing table –
ALTER TABLE tableName
ADD columnName columnDefinition;
Example –
ALTER TABLE Student
ADD marks_obtained Number (3);
Before : Student Table
After : Student Table
marks_obtained
SYNTAX : Removing column from existing table –
ALTER TABLE tableName
DROP COLUMN columnName;
Example –
ALTER TABLE Student
DROP COLUMN city;
Before : Student table
After: Student table
SYNTAX :
Changing column name in the existing table –
ALTER TABLE tableName
RENAME COLUMN olderName TO newName;
Example –
ALTER TABLE student
RENAME COLUMN contactTO contact_no;
Before : Student table
After : Student table
2. UPDATE Command :
UPDATE is an SQL command used in Relational DBMS and is a Data Manipulation Language (DML) statement. It is used to manipulate the data of any existing column. But can’t change the table’s definition.
SYNTAX : Updating data in existing table –
UPDATE table_name
SET column1 = value1,
column2 = value2, ... WHERE condition;
Example –
UPDATE student
SET contact = 91111. WHERE name =ashu;
Before : Student table
Without the WHERE clause, all records in the table will be updated.
Difference Between ALTER and UPDATE Command in SQL :
arorakashish0911
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "In this article, we are going to cover how we can modify the existing data in SQL. There are lots of situations where we need to alter and need to update existing data. Let’s discuss one by one. "
},
{
"code": null,
"e": 522,
"s": 224,
"text": "1. ALTER Command : ALTER is an SQL command used in Relational DBMS and is a Data Definition Language (DDL) statement. ALTER can be used to update the table’s structure in the database (like add, delete, drop indexes, columns, and constraints, modify the attributes of the tables in the database). "
},
{
"code": null,
"e": 621,
"s": 522,
"text": "ALTER command is most commonly used to improve SQL SELECT queries by adding and removing indexes. "
},
{
"code": null,
"e": 671,
"s": 621,
"text": "SYNTAX : Adding a column to the existing table – "
},
{
"code": null,
"e": 727,
"s": 671,
"text": "ALTER TABLE tableName \nADD columnName columnDefinition;"
},
{
"code": null,
"e": 739,
"s": 727,
"text": "Example – "
},
{
"code": null,
"e": 791,
"s": 739,
"text": "ALTER TABLE Student \nADD marks_obtained Number (3);"
},
{
"code": null,
"e": 815,
"s": 791,
"text": "Before : Student Table "
},
{
"code": null,
"e": 838,
"s": 815,
"text": "After : Student Table "
},
{
"code": null,
"e": 854,
"s": 838,
"text": "marks_obtained "
},
{
"code": null,
"e": 903,
"s": 854,
"text": "SYNTAX : Removing column from existing table – "
},
{
"code": null,
"e": 950,
"s": 903,
"text": "ALTER TABLE tableName \nDROP COLUMN columnName;"
},
{
"code": null,
"e": 962,
"s": 950,
"text": "Example – "
},
{
"code": null,
"e": 1001,
"s": 962,
"text": "ALTER TABLE Student \nDROP COLUMN city;"
},
{
"code": null,
"e": 1026,
"s": 1001,
"text": "Before : Student table "
},
{
"code": null,
"e": 1048,
"s": 1026,
"text": "After: Student table "
},
{
"code": null,
"e": 1058,
"s": 1048,
"text": "SYNTAX : "
},
{
"code": null,
"e": 1105,
"s": 1058,
"text": "Changing column name in the existing table – "
},
{
"code": null,
"e": 1164,
"s": 1105,
"text": "ALTER TABLE tableName \nRENAME COLUMN olderName TO newName;"
},
{
"code": null,
"e": 1176,
"s": 1164,
"text": "Example – "
},
{
"code": null,
"e": 1233,
"s": 1176,
"text": "ALTER TABLE student \nRENAME COLUMN contactTO contact_no;"
},
{
"code": null,
"e": 1258,
"s": 1233,
"text": "Before : Student table "
},
{
"code": null,
"e": 1282,
"s": 1258,
"text": "After : Student table "
},
{
"code": null,
"e": 1303,
"s": 1282,
"text": "2. UPDATE Command : "
},
{
"code": null,
"e": 1505,
"s": 1303,
"text": "UPDATE is an SQL command used in Relational DBMS and is a Data Manipulation Language (DML) statement. It is used to manipulate the data of any existing column. But can’t change the table’s definition. "
},
{
"code": null,
"e": 1550,
"s": 1505,
"text": "SYNTAX : Updating data in existing table – "
},
{
"code": null,
"e": 1631,
"s": 1550,
"text": "UPDATE table_name \nSET column1 = value1, \ncolumn2 = value2, ... WHERE condition;"
},
{
"code": null,
"e": 1643,
"s": 1631,
"text": "Example – "
},
{
"code": null,
"e": 1698,
"s": 1643,
"text": "UPDATE student \nSET contact = 91111. WHERE name =ashu;"
},
{
"code": null,
"e": 1723,
"s": 1698,
"text": "Before : Student table "
},
{
"code": null,
"e": 1792,
"s": 1723,
"text": "Without the WHERE clause, all records in the table will be updated. "
},
{
"code": null,
"e": 1847,
"s": 1792,
"text": "Difference Between ALTER and UPDATE Command in SQL : "
},
{
"code": null,
"e": 1866,
"s": 1849,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1875,
"s": 1866,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1881,
"s": 1875,
"text": "mysql"
},
{
"code": null,
"e": 1885,
"s": 1881,
"text": "SQL"
},
{
"code": null,
"e": 1889,
"s": 1885,
"text": "SQL"
},
{
"code": null,
"e": 1987,
"s": 1889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1998,
"s": 1987,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2029,
"s": 1998,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2095,
"s": 2029,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2119,
"s": 2095,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2131,
"s": 2119,
"text": "SQL | Views"
},
{
"code": null,
"e": 2176,
"s": 2131,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2200,
"s": 2176,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2232,
"s": 2200,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 2247,
"s": 2232,
"text": "SQL | GROUP BY"
}
] |
How to add filter with Portfolio Gallery using HTML, CSS and JavaScript ? | 10 Sep, 2021
The portfolio gallery is useful when your website contains different types of content or so many contents. With the help of a portfolio gallery, you can easily display all the contents on your front page to the user. But if user wants some specific contents then we need to attach filters on the portfolio. In this article, we will add filters using JavaScript. Before proceeding into this article you can see the article ‘how to create a Portfolio Gallery using HTML and CSS?‘. Creating Structure: In this section, we will create the basic website structure of the portfolio. Here, we will attach the title attribute so the user can know what will be the content type on each grid of the portfolio.
HTML code: In this section, we will design the basic structure of Portfolio Gallery.
html
<!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"></head> <body> <!-- Title and tag --> <div class="container"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio of Languages</h2> <!-- Button foreach group --> <div id="filtering"> <button class="bttn active" onclick="geeksportal('all')"> Show all </button> <button class="bttn" onclick="geeksportal('Markup')"> Markup </button> <button class="bttn" onclick="geeksportal('Style')"> Style </button> <button class="bttn" onclick="geeksportal('Scripting')"> Scripting </button> </div> <!-- Portfolio Gallery Grid --> <div class="row"> <div class="column Markup"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html.png" alt="HTML" style="width:100%"> <h3><a href="#"> HTML Tutorials </a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class="column Styleshit"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS.png" alt="CSS" style="width:100%"> <h3><a href="#"> CSS Tutorials </a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class="column Scripting"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/php-1.png" alt="" style="width:100%"> <h3><a href="#"> PHP Tutorials </a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class="column Scripting"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/javascript.png" alt="" style="width:100%"> <h3><a href="#"> JavaScript Tutorials </a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html>
Designing Structure: In the previous section, we have created the structure of the basic website and now we are going to use CSS to design the structure of the web-page.
CSS code:
CSS
<style> /* Wildcard styling */ * { box-sizing: border-box; } /* Padding for whole body */ body { padding: 15px; } .container { max-width: 1200px; margin: auto; } /* Styling h2 tag */ h1 { Color: green; word-break: break-all; } /* Anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } .row { margin: 0px -14px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; display: none; } /* Content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* Paragraph decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } .row:after { content: ""; display: table; clear: both; } .content { background-color: white; padding: 10px; border: 1px solid gray; } .show { display: block; } /* Style the filter buttons */ .bttn { border: none; padding: 8px 14px; background-color: gray; } .bttn:hover { background-color: #007EE5; opacity: 0.8; } .bttn.active { background-color: #007EE5; color: white; } /* Window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* Window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } }</style>
JavaScript code:
javascript
<script> geeksportal("all") function geeksportal(c) { var x, i; x = document.getElementsByClassName("column"); if (c == "all") c = ""; for (i = 0; i < x.length; i++) { w3RemoveClass(x[i], "show"); if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show"); } } function w3AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } function w3RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } // Add active class to the current // button (highlight it) var btnContainer = document.getElementById("filtering"); var btns = btnContainer.getElementsByClassName("bttn"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); }</script>
Combining the HTML, CSS and JavaScript Code: Combining HTML, CSS and JavaScript section code to make a complete Portfolio Gallery with the filter.
html
<!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> /* Wildcard styling */ * { box-sizing: border-box; } /* Padding for whole body */ body { padding: 15px; } .container { max-width: 1200px; margin: auto; } /* Styling h2 tag */ h1 { Color: green; word-break: break-all; } /* Anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } .row { margin: 0px -14px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; display: none; } /* Content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* Paragraph decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } .row:after { content: ""; display: table; clear: both; } .content { background-color: white; padding: 10px; border: 1px solid gray; } .show { display: block; } /* Style the filter buttons */ .bttn { border: none; padding: 8px 14px; background-color: gray; } .bttn:hover { background-color: #007EE5; opacity: 0.8; } .bttn.active { background-color: #007EE5; color: white; } /* Window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* Window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } } </style></head> <body> <!-- Title and tag --> <div class="container"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio of Languages</h2> <!-- button foreach group --> <div id="filtering"> <button class="bttn active" onclick="geeksportal('all')"> Show all </button> <button class="bttn" onclick="geeksportal('Markup')"> Markup </button> <button class="bttn" onclick="geeksportal('Style')"> Style </button> <button class="bttn" onclick="geeksportal('Scripting')"> Scripting </button> </div> <!-- Portfolio Gallery Grid --> <div class="row"> <div class="column Markup"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html.png" alt="HTML" style="width:100%"> <h3><a href="#"> HTML Tutorials </a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class="column Styleshit"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/CSS.png" alt="CSS" style="width:100%"> <h3><a href="#"> CSS Tutorials </a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class="column Scripting"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/php-1.png" alt="" style="width:100%"> <h3><a href="#"> PHP Tutorials </a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class="column Scripting"> <div class="content"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/javascript.png" alt="" style="width:100%"> <h3><a href="#"> JavaScript Tutorials </a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div> <script> geeksportal("all") function geeksportal(c) { var x, i; x = document.getElementsByClassName("column"); if (c == "all") c = ""; for (i = 0; i < x.length; i++) { w3RemoveClass(x[i], "show"); if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show"); } } function w3AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += " " + arr2[i]; } } } function w3RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(" "); arr2 = name.split(" "); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(" "); } // Add active class to the current // button (highlight it) var btnContainer = document.getElementById("filtering"); var btns = btnContainer.getElementsByClassName("bttn"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); } </script></body> </html>
Output:
gabaa406
CSS-Misc
HTML-Misc
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 730,
"s": 28,
"text": "The portfolio gallery is useful when your website contains different types of content or so many contents. With the help of a portfolio gallery, you can easily display all the contents on your front page to the user. But if user wants some specific contents then we need to attach filters on the portfolio. In this article, we will add filters using JavaScript. Before proceeding into this article you can see the article ‘how to create a Portfolio Gallery using HTML and CSS?‘. Creating Structure: In this section, we will create the basic website structure of the portfolio. Here, we will attach the title attribute so the user can know what will be the content type on each grid of the portfolio. "
},
{
"code": null,
"e": 816,
"s": 730,
"text": "HTML code: In this section, we will design the basic structure of Portfolio Gallery. "
},
{
"code": null,
"e": 821,
"s": 816,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"></head> <body> <!-- Title and tag --> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio of Languages</h2> <!-- Button foreach group --> <div id=\"filtering\"> <button class=\"bttn active\" onclick=\"geeksportal('all')\"> Show all </button> <button class=\"bttn\" onclick=\"geeksportal('Markup')\"> Markup </button> <button class=\"bttn\" onclick=\"geeksportal('Style')\"> Style </button> <button class=\"bttn\" onclick=\"geeksportal('Scripting')\"> Scripting </button> </div> <!-- Portfolio Gallery Grid --> <div class=\"row\"> <div class=\"column Markup\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html.png\" alt=\"HTML\" style=\"width:100%\"> <h3><a href=\"#\"> HTML Tutorials </a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class=\"column Styleshit\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS.png\" alt=\"CSS\" style=\"width:100%\"> <h3><a href=\"#\"> CSS Tutorials </a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class=\"column Scripting\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/php-1.png\" alt=\"\" style=\"width:100%\"> <h3><a href=\"#\"> PHP Tutorials </a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class=\"column Scripting\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/javascript.png\" alt=\"\" style=\"width:100%\"> <h3><a href=\"#\"> JavaScript Tutorials </a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div></body> </html>",
"e": 4895,
"s": 821,
"text": null
},
{
"code": null,
"e": 5067,
"s": 4895,
"text": "Designing Structure: In the previous section, we have created the structure of the basic website and now we are going to use CSS to design the structure of the web-page. "
},
{
"code": null,
"e": 5078,
"s": 5067,
"text": "CSS code: "
},
{
"code": null,
"e": 5082,
"s": 5078,
"text": "CSS"
},
{
"code": "<style> /* Wildcard styling */ * { box-sizing: border-box; } /* Padding for whole body */ body { padding: 15px; } .container { max-width: 1200px; margin: auto; } /* Styling h2 tag */ h1 { Color: green; word-break: break-all; } /* Anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } .row { margin: 0px -14px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; display: none; } /* Content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* Paragraph decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } .row:after { content: \"\"; display: table; clear: both; } .content { background-color: white; padding: 10px; border: 1px solid gray; } .show { display: block; } /* Style the filter buttons */ .bttn { border: none; padding: 8px 14px; background-color: gray; } .bttn:hover { background-color: #007EE5; opacity: 0.8; } .bttn.active { background-color: #007EE5; color: white; } /* Window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* Window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } }</style>",
"e": 6964,
"s": 5082,
"text": null
},
{
"code": null,
"e": 6982,
"s": 6964,
"text": "JavaScript code: "
},
{
"code": null,
"e": 6993,
"s": 6982,
"text": "javascript"
},
{
"code": "<script> geeksportal(\"all\") function geeksportal(c) { var x, i; x = document.getElementsByClassName(\"column\"); if (c == \"all\") c = \"\"; for (i = 0; i < x.length; i++) { w3RemoveClass(x[i], \"show\"); if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], \"show\"); } } function w3AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(\" \"); arr2 = name.split(\" \"); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += \" \" + arr2[i]; } } } function w3RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(\" \"); arr2 = name.split(\" \"); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(\" \"); } // Add active class to the current // button (highlight it) var btnContainer = document.getElementById(\"filtering\"); var btns = btnContainer.getElementsByClassName(\"bttn\"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener(\"click\", function() { var current = document.getElementsByClassName(\"active\"); current[0].className = current[0].className.replace(\" active\", \"\"); this.className += \" active\"; }); }</script>",
"e": 8624,
"s": 6993,
"text": null
},
{
"code": null,
"e": 8772,
"s": 8624,
"text": "Combining the HTML, CSS and JavaScript Code: Combining HTML, CSS and JavaScript section code to make a complete Portfolio Gallery with the filter. "
},
{
"code": null,
"e": 8777,
"s": 8772,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> /* Wildcard styling */ * { box-sizing: border-box; } /* Padding for whole body */ body { padding: 15px; } .container { max-width: 1200px; margin: auto; } /* Styling h2 tag */ h1 { Color: green; word-break: break-all; } /* Anchor tag decoration */ a { text-decoration: none; color: #5673C8; } a:hover { color: lightblue; } .row { margin: 0px -14px; padding: 8px; } .row > .column { padding: 6px; } .column { float: left; width: 25%; display: none; } /* Content decoration */ .content { background-color: white; padding: 10px; border: 1px solid gray; } /* Paragraph decoration */ p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; } .row:after { content: \"\"; display: table; clear: both; } .content { background-color: white; padding: 10px; border: 1px solid gray; } .show { display: block; } /* Style the filter buttons */ .bttn { border: none; padding: 8px 14px; background-color: gray; } .bttn:hover { background-color: #007EE5; opacity: 0.8; } .bttn.active { background-color: #007EE5; color: white; } /* Window size 850 width set */ @media screen and (max-width: 850px) { .column { width: 50%; } } /* Window size 400 width set */ @media screen and (max-width: 400px) { .column { width: 100%; } } </style></head> <body> <!-- Title and tag --> <div class=\"container\"> <h1>GeeksforGeeks</h1> <h3>A Computer Science Portal for Geeks</h3> <hr> <!-- Content of the body--> <h2>Portfolio of Languages</h2> <!-- button foreach group --> <div id=\"filtering\"> <button class=\"bttn active\" onclick=\"geeksportal('all')\"> Show all </button> <button class=\"bttn\" onclick=\"geeksportal('Markup')\"> Markup </button> <button class=\"bttn\" onclick=\"geeksportal('Style')\"> Style </button> <button class=\"bttn\" onclick=\"geeksportal('Scripting')\"> Scripting </button> </div> <!-- Portfolio Gallery Grid --> <div class=\"row\"> <div class=\"column Markup\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html.png\" alt=\"HTML\" style=\"width:100%\"> <h3><a href=\"#\"> HTML Tutorials </a> </h3> <p> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. </p> </div> </div> <div class=\"column Styleshit\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/CSS.png\" alt=\"CSS\" style=\"width:100%\"> <h3><a href=\"#\"> CSS Tutorials </a> </h3> <p> Cascading Style Sheets, fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. </p> </div> </div> <div class=\"column Scripting\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/php-1.png\" alt=\"\" style=\"width:100%\"> <h3><a href=\"#\"> PHP Tutorials </a> </h3> <p> The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files. </p> </div> </div> <div class=\"column Scripting\"> <div class=\"content\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/javascript.png\" alt=\"\" style=\"width:100%\"> <h3><a href=\"#\"> JavaScript Tutorials </a> </h3> <p> Javascript was developed by Brendan Eich in 1995. At first, it was called LiveScript but was later name to JavaScript. JavaScript is the muscle of the structure </p> </div> </div> </div> </div> <script> geeksportal(\"all\") function geeksportal(c) { var x, i; x = document.getElementsByClassName(\"column\"); if (c == \"all\") c = \"\"; for (i = 0; i < x.length; i++) { w3RemoveClass(x[i], \"show\"); if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], \"show\"); } } function w3AddClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(\" \"); arr2 = name.split(\" \"); for (i = 0; i < arr2.length; i++) { if (arr1.indexOf(arr2[i]) == -1) { element.className += \" \" + arr2[i]; } } } function w3RemoveClass(element, name) { var i, arr1, arr2; arr1 = element.className.split(\" \"); arr2 = name.split(\" \"); for (i = 0; i < arr2.length; i++) { while (arr1.indexOf(arr2[i]) > -1) { arr1.splice(arr1.indexOf(arr2[i]), 1); } } element.className = arr1.join(\" \"); } // Add active class to the current // button (highlight it) var btnContainer = document.getElementById(\"filtering\"); var btns = btnContainer.getElementsByClassName(\"bttn\"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener(\"click\", function() { var current = document.getElementsByClassName(\"active\"); current[0].className = current[0].className.replace(\" active\", \"\"); this.className += \" active\"; }); } </script></body> </html>",
"e": 17044,
"s": 8777,
"text": null
},
{
"code": null,
"e": 17054,
"s": 17044,
"text": "Output: "
},
{
"code": null,
"e": 17065,
"s": 17056,
"text": "gabaa406"
},
{
"code": null,
"e": 17074,
"s": 17065,
"text": "CSS-Misc"
},
{
"code": null,
"e": 17084,
"s": 17074,
"text": "HTML-Misc"
},
{
"code": null,
"e": 17100,
"s": 17084,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 17111,
"s": 17100,
"text": "JavaScript"
},
{
"code": null,
"e": 17128,
"s": 17111,
"text": "Web Technologies"
},
{
"code": null,
"e": 17155,
"s": 17128,
"text": "Web technologies Questions"
}
] |
Java.net.URI class in Java | 12 Jun, 2017
This class provides methods for creating URI instances from its components or by parsing the string form of those components, for accessing and retrieving different components of a URI instance.What is URI?URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular resource. It enables for the interaction of the representation of the resource over the network using specific protocols.
URI, URL and URN: What is The Difference?
The question that must be coming to your minds must be that if URI identifies a resource, what does URL do? People often use the terms interchangeably but it is not correct. According to Tim Berners Lee
“A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.”“A URI can be further classified as a locator, a name, or both. The term “Uniform Resource Locator” (URL) refers to the subset of URI that identify resources via a representation of their primary access mechanism (e.g., their network “location”), rather than identifying the resource by name or by some other attribute(s) of that resource. The term “Uniform Resource Name” (URN) refers to the subset of URI that are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable.”
For example,
https://www.geeksforgeeks.org/url-class-java-examples/
Represents a URL as it tells the exact location where url class article can be found over the network.
url-class-java-examples
Represents a URN as it does not tell anything about the location but only gives a unique name to the resource.
The difference between an object of URI class and an URL class lies in the fact that a URI string is parsed only with consideration of syntax and no lookups of host is performed on creation. Comparison of two URI objects is done solely on the characters contained in the string. But on the other hand, a URL string is parsed with a certain scheme and comparisons of two URL objects is performed by looking of actual resource on the net.
URI Syntax :
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
scheme : The scheme component lays out the protocols to be associated with the URI. In some schemes the “//” are required while others dont need them.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1authority : Authority component is made of several components- authentication section, a host and optional port number preceded by a ‘:’. Authentication section includes username and password. Host can be any ip-address.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1path : The path represents a string containing the address within the server to the resource.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1query : Query represent a nonhierarchical data usually the query used for searching of a particular resource. They are separated by a ‘?’ from the preceding part.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1fragment : Fragments are used to identify secondary resources as headings or subheadings within a page etc.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
scheme : The scheme component lays out the protocols to be associated with the URI. In some schemes the “//” are required while others dont need them.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
authority : Authority component is made of several components- authentication section, a host and optional port number preceded by a ‘:’. Authentication section includes username and password. Host can be any ip-address.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
path : The path represents a string containing the address within the server to the resource.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
query : Query represent a nonhierarchical data usually the query used for searching of a particular resource. They are separated by a ‘?’ from the preceding part.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
fragment : Fragments are used to identify secondary resources as headings or subheadings within a page etc.abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
abc://admin:[email protected]:1234/path/data
?key=value&key2=value2#fragid1
Constructors :
URI(String str) : Constructs a URI object by parsing the specified string. The grammar used while parsing is the one specified in RFC 2396, Appendix A.Syntax :public URI(String str)
throws URISyntaxException
Parameters :
str : String to be parsed into URI
Throws :
URISyntaxException : If the string violates RFC 2396URI(String scheme, String ssp, String fragment) : Constructs a URI from the given components. A component may be left undefined by passing null. Initially the result string is empty. If scheme is not null it is appended. Similarly the ssp and fragment part is appended if provided.Syntax :public URI(String scheme, String ssp, String fragment)
throws URISyntaxException
Parameters :
scheme : scheme name
ssp : scheme-specific part
fragment : fragment part
Throws :
URISyntaxException : If the URI string constructed from the given
components violates RFC 2396Similarly other constructors are provided based on what components are known at the creation time.URI(String scheme, String userInfo, String host, int port, String path,String query, String fragment)Syntax :public URI(String scheme, String userInfo, String host, int port,
String path, String query, String fragment)
Parameters :
scheme : string representing scheme
userInfo : userinfo of URI
host : host component of URI
port : listening port number
path : path of URI
query : String representing the query part
fragment :optional fragment
URI(String scheme, String host, String path, String fragment)Syntax :public URI(String scheme, String host, String path, String fragment)
Parameters :
scheme : string representing scheme
host : host component of URI
path : path of URI
fragment :optional fragment
URI(String scheme, String authority, String path, String query, String fragment)Syntax :public URI(String scheme, String authority, String path,
String query, String fragment)
Parameters :
scheme : string representing scheme
authority : authority
path : path of URI
query : String representing the query part
URI(String str) : Constructs a URI object by parsing the specified string. The grammar used while parsing is the one specified in RFC 2396, Appendix A.Syntax :public URI(String str)
throws URISyntaxException
Parameters :
str : String to be parsed into URI
Throws :
URISyntaxException : If the string violates RFC 2396
Syntax :public URI(String str)
throws URISyntaxException
Parameters :
str : String to be parsed into URI
Throws :
URISyntaxException : If the string violates RFC 2396
URI(String scheme, String ssp, String fragment) : Constructs a URI from the given components. A component may be left undefined by passing null. Initially the result string is empty. If scheme is not null it is appended. Similarly the ssp and fragment part is appended if provided.Syntax :public URI(String scheme, String ssp, String fragment)
throws URISyntaxException
Parameters :
scheme : scheme name
ssp : scheme-specific part
fragment : fragment part
Throws :
URISyntaxException : If the URI string constructed from the given
components violates RFC 2396
Syntax :public URI(String scheme, String ssp, String fragment)
throws URISyntaxException
Parameters :
scheme : scheme name
ssp : scheme-specific part
fragment : fragment part
Throws :
URISyntaxException : If the URI string constructed from the given
components violates RFC 2396
Similarly other constructors are provided based on what components are known at the creation time.
URI(String scheme, String userInfo, String host, int port, String path,String query, String fragment)Syntax :public URI(String scheme, String userInfo, String host, int port,
String path, String query, String fragment)
Parameters :
scheme : string representing scheme
userInfo : userinfo of URI
host : host component of URI
port : listening port number
path : path of URI
query : String representing the query part
fragment :optional fragment
Syntax :public URI(String scheme, String userInfo, String host, int port,
String path, String query, String fragment)
Parameters :
scheme : string representing scheme
userInfo : userinfo of URI
host : host component of URI
port : listening port number
path : path of URI
query : String representing the query part
fragment :optional fragment
URI(String scheme, String host, String path, String fragment)Syntax :public URI(String scheme, String host, String path, String fragment)
Parameters :
scheme : string representing scheme
host : host component of URI
path : path of URI
fragment :optional fragment
Syntax :public URI(String scheme, String host, String path, String fragment)
Parameters :
scheme : string representing scheme
host : host component of URI
path : path of URI
fragment :optional fragment
URI(String scheme, String authority, String path, String query, String fragment)Syntax :public URI(String scheme, String authority, String path,
String query, String fragment)
Parameters :
scheme : string representing scheme
authority : authority
path : path of URI
query : String representing the query part
Syntax :public URI(String scheme, String authority, String path,
String query, String fragment)
Parameters :
scheme : string representing scheme
authority : authority
path : path of URI
query : String representing the query part
Methods :
create() : creates a new URI object. This method can be called a pseudo constructor. It is provided for use in the situations when it is known for sure that given string will parse as the URI object and it would be considered as a programmers error if it does not parse.Syntax : public static URI create(String str)
Parameters :
str : String to be parsed as URIparseServerAuthority() : This method is used to parse the URI’s authority components if provided into user information, host and port components. This method returns a URI object whose authority field has been parsed as a server based authority.Syntax : public URI parseServerAuthority()normalize() : Normalizes this URI’s path. URI is constructed by normalizing the URI’s path which is consistent with RFC 2396. Returns a normalized URI object.Syntax : public URI normalize()resolve() : Resolves the given URI with this URI. Returns a new hierarchical URI in a manner consistent with RFC 2396.Syntax : public URI resolve(URI uri)
Parameters :
uri : URI to be resolved
Another overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).Syntax : public URI resolve(String str)
Parameters :
str : String to be parsed as URIrelativize() : Relativizes the given URI against this URI.Syntax : public URI relativize(URI uri)Parameters :uri : URI to relativizetoURL() : Constructs a URL from this URI.Syntax : public URL toURL()
throws MalformedURLException
Throws :
MalformedURLException : If error occurs while constructing URLgetScheme() : Returns the scheme component of the URISyntax : public String getScheme()getRawSchemeSpecificPart() : Returns the raw scheme specific component of the URI.Syntax : public String getRawSchemeSpecificPart()getSchemeSpecificPart() : Returns the decoded scheme specific component of the URISyntax : public String getSchemeSpecificPart()getRawAuthority() : Returns the authority component of the URI. If the authority is server based, then further user information, host and port components are returned.Syntax : public String getRawAuthority()getAuthority() : Returns exact similar result as of the above method except in the decoded form.Syntax : public String getAuthority()getRawUserInfo() : Returns the user info component of the URI, or null if it is undefined.Syntax : public String getRawUserInfo()getUserInfo() : Returns the user info component of the URI in decoded form, or null if it is undefined.Syntax : public String getUserInfo()Java Implementation :// Java program to illustrate various// URI class methodsimport java.net.*; class uridemo1{ public static void main(String[] args) throws Exception { String uribase = "https://www.geeksforgeeks.org/"; String urirelative = "languages/../java"; String str = "https://www.google.co.in/?gws_rd=ssl#"+"" + "q=networking+in+java+geeksforgeeks"+"" +"&spf=1496918039682"; // Constructor to create a new URI // by parsing the string URI uriBase = new URI(uribase); // create() method URI uri = URI.create(str); // toString() method System.out.println("Base URI = " + uriBase.toString()); URI uriRelative = new URI(urirelative); System.out.println("Relative URI = " + uriRelative.toString()); // resolve() method URI uriResolved = uriBase.resolve(uriRelative); System.out.println("Resolved URI = " + uriResolved.toString()); // relativized() method URI uriRelativized = uriBase.relativize(uriResolved); System.out.println("Relativized URI = " + uriRelativized.toString()); // normalize() method System.out.println(uri.normalize().toString()); // getScheme() method System.out.println("Scheme = " + uri.getScheme()); // getRawShemeSpecific() method System.out.println("Raw Scheme = " + uri.getRawSchemeSpecificPart()); // getSchemeSpecificPart() method System.out.println("Scheme-specific part = " + uri.getSchemeSpecificPart()); // getRawUserInfo() method System.out.println("Raw User Info = " + uri.getRawUserInfo()); // getUserInfo() method System.out.println("User Info = " + uri.getUserInfo()); // getAuthority() method System.out.println("Authority = " + uri.getAuthority()); // getRawAuthority() method System.out.println("Raw Authority = " + uri.getRawAuthority()); }}Output :Base URI = https://www.geeksforgeeks.org/
Relative URI = languages/../java
Resolved URI = https://www.geeksforgeeks.org/java
Relativized URI = java
https://www.google.co.in/?gws_rd=ssl#q=networking+in+
java+geeksforgeeks&spf=1496918039682
Scheme = https
Raw Scheme = //www.google.co.in/?gws_rd=ssl
Scheme-specific part = //www.google.co.in/?gws_rd=ssl
Raw User Info = null
User Info = null
Authority = www.google.co.in
Raw Authority = www.google.co.in
getHost() : Returns the host component of the URI. As the host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.Syntax : public String getHost()getPort() : Returns the port number of this URI.Syntax : public int getPort()getRawPath() : Returns the raw path of this URI, or null if not defined.Syntax : public String getRawPath()getPath() : Returns the decoded path component of this URI.Syntax : public String getPath()getRawQuery() : Returns the query component of the URI, or null if undefined.Syntax : public String getRawQuery()getQuery() : Returns the query component of the URI in decoded form, or null if undefined.Syntax : public String getQuery()getRawFragment() : Returns the fragment component of the URI, or null if undefined.Syntax : public String getRawFragment()getFragment() : Returns the decoded fragment component of this URI, or null if undefined.Syntax : public String getFragment()compareTo() : Compares this URI object with another URI object. Comparison by performed according to the natural ordering with String.compareTo() methods. If one component is undefined and other is defined than first is considered smaller than second. Components to be parsed are compared in their raw form rather than their encoded form.Syntax : public int compareTo(URI uri)
Parameters :
uri : URI to be compared withequals() : Tests the given object with this URI. Ig the object is not a URI, it returns false. For two URIs to be considered equal requires that either both are opaque or both are hierarchical. When checking for equality of different components, their raw form is considered rather than the encoded form.Syntax : public boolean equals(Object ob)
Parameters :
ob : object to be compared for equalityisAbsolute() : Returns true if this URI is absolute, otherwise false. A URI is absolute if, and only if, it has a scheme component.Syntax : public boolean isAbsolute()isOpaque() : Returns true if this URI is opaque, otherwise false. A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character (‘/’)Syntax : public boolean isOpaque()hashCode() : Returns the hashcode for the this URI object. All the components are taken into account while creating a hashcode for the URI object.Syntax : public int hashCode()toString() : Returns the string representation of this URI object.Syntax : public String toString()toASCIIString() : Returns the string representation in ASCII format.Syntax : public String toASCIIString()Java Implementation ://Java Program to illustrate various//URI class methodsimport java.net.*;class uridemo1 { public static void main(String[] args) throws Exception { String str = "https://www.google.co.in/?gws_rd=ssl#"+"" + "q=networking+in+java+geeksforgeeks"+"" +"&spf=1496918039682"; // Constructor to create a new URI // by parsing the given string. URI uri = new URI(str); // getHost() method System.out.println("Host = " + uri.getHost()); // getPort() method System.out.println("Port = " + uri.getPath()); // getRawPath() method System.out.println("Raw Path = " + uri.getRawPath()); // getPath() method System.out.println("Path = " + uri.getPath()); // getQuery() method System.out.println("Query = " + uri.getQuery()); // getRawQuery() method System.out.println("Raw Query = " + uri.getRawQuery()); // getFragment() method System.out.println("Fragment = " + uri.getFragment()); // getRawFragment() method System.out.println("Raw Fragment = " + uri.getRawFragment()); URI uri2 = new URI(str + "fr"); // compareTo() mrthod System.out.println("CompareTo =" + uri.compareTo(uri2)); // equals() method System.out.println("Equals = " + uri.equals(uri2)); // hashcode() method System.out.println("Hashcode : " + uri.hashCode()); // toString() method System.out.println("toString : " + uri.toString()); // toASCIIString() method System.out.println("toASCIIString : " + uri.toASCIIString()); }}Output :Host = www.google.co.in
Port = /
Raw Path = /
Path = /
Query = gws_rd=ssl
Raw Query = gws_rd=ssl
Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
Raw Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
CompareTo =-2
Equals = false
Hashcode : 480379574
toString : https://www.google.co.in/?gws_rd=ssl#q=networking+
in+java+geeksforgeeks&spf=1496918039682
toASCIIString : https://www.google.co.in/?gws_rd=ssl#q=
networking+in+java+geeksforgeeks&spf=1496918039682
create() : creates a new URI object. This method can be called a pseudo constructor. It is provided for use in the situations when it is known for sure that given string will parse as the URI object and it would be considered as a programmers error if it does not parse.Syntax : public static URI create(String str)
Parameters :
str : String to be parsed as URI
Syntax : public static URI create(String str)
Parameters :
str : String to be parsed as URI
parseServerAuthority() : This method is used to parse the URI’s authority components if provided into user information, host and port components. This method returns a URI object whose authority field has been parsed as a server based authority.Syntax : public URI parseServerAuthority()
Syntax : public URI parseServerAuthority()
normalize() : Normalizes this URI’s path. URI is constructed by normalizing the URI’s path which is consistent with RFC 2396. Returns a normalized URI object.Syntax : public URI normalize()
Syntax : public URI normalize()
resolve() : Resolves the given URI with this URI. Returns a new hierarchical URI in a manner consistent with RFC 2396.Syntax : public URI resolve(URI uri)
Parameters :
uri : URI to be resolved
Another overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).Syntax : public URI resolve(String str)
Parameters :
str : String to be parsed as URI
Syntax : public URI resolve(URI uri)
Parameters :
uri : URI to be resolved
Another overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).
Syntax : public URI resolve(String str)
Parameters :
str : String to be parsed as URI
relativize() : Relativizes the given URI against this URI.Syntax : public URI relativize(URI uri)Parameters :uri : URI to relativize
Syntax : public URI relativize(URI uri)
Parameters :uri : URI to relativize
toURL() : Constructs a URL from this URI.Syntax : public URL toURL()
throws MalformedURLException
Throws :
MalformedURLException : If error occurs while constructing URL
Syntax : public URL toURL()
throws MalformedURLException
Throws :
MalformedURLException : If error occurs while constructing URL
getScheme() : Returns the scheme component of the URISyntax : public String getScheme()
Syntax : public String getScheme()
getRawSchemeSpecificPart() : Returns the raw scheme specific component of the URI.Syntax : public String getRawSchemeSpecificPart()
Syntax : public String getRawSchemeSpecificPart()
getSchemeSpecificPart() : Returns the decoded scheme specific component of the URISyntax : public String getSchemeSpecificPart()
Syntax : public String getSchemeSpecificPart()
getRawAuthority() : Returns the authority component of the URI. If the authority is server based, then further user information, host and port components are returned.Syntax : public String getRawAuthority()
Syntax : public String getRawAuthority()
getAuthority() : Returns exact similar result as of the above method except in the decoded form.Syntax : public String getAuthority()
Syntax : public String getAuthority()
getRawUserInfo() : Returns the user info component of the URI, or null if it is undefined.Syntax : public String getRawUserInfo()
Syntax : public String getRawUserInfo()
getUserInfo() : Returns the user info component of the URI in decoded form, or null if it is undefined.Syntax : public String getUserInfo()
Syntax : public String getUserInfo()
Java Implementation :
// Java program to illustrate various// URI class methodsimport java.net.*; class uridemo1{ public static void main(String[] args) throws Exception { String uribase = "https://www.geeksforgeeks.org/"; String urirelative = "languages/../java"; String str = "https://www.google.co.in/?gws_rd=ssl#"+"" + "q=networking+in+java+geeksforgeeks"+"" +"&spf=1496918039682"; // Constructor to create a new URI // by parsing the string URI uriBase = new URI(uribase); // create() method URI uri = URI.create(str); // toString() method System.out.println("Base URI = " + uriBase.toString()); URI uriRelative = new URI(urirelative); System.out.println("Relative URI = " + uriRelative.toString()); // resolve() method URI uriResolved = uriBase.resolve(uriRelative); System.out.println("Resolved URI = " + uriResolved.toString()); // relativized() method URI uriRelativized = uriBase.relativize(uriResolved); System.out.println("Relativized URI = " + uriRelativized.toString()); // normalize() method System.out.println(uri.normalize().toString()); // getScheme() method System.out.println("Scheme = " + uri.getScheme()); // getRawShemeSpecific() method System.out.println("Raw Scheme = " + uri.getRawSchemeSpecificPart()); // getSchemeSpecificPart() method System.out.println("Scheme-specific part = " + uri.getSchemeSpecificPart()); // getRawUserInfo() method System.out.println("Raw User Info = " + uri.getRawUserInfo()); // getUserInfo() method System.out.println("User Info = " + uri.getUserInfo()); // getAuthority() method System.out.println("Authority = " + uri.getAuthority()); // getRawAuthority() method System.out.println("Raw Authority = " + uri.getRawAuthority()); }}
Output :
Base URI = https://www.geeksforgeeks.org/
Relative URI = languages/../java
Resolved URI = https://www.geeksforgeeks.org/java
Relativized URI = java
https://www.google.co.in/?gws_rd=ssl#q=networking+in+
java+geeksforgeeks&spf=1496918039682
Scheme = https
Raw Scheme = //www.google.co.in/?gws_rd=ssl
Scheme-specific part = //www.google.co.in/?gws_rd=ssl
Raw User Info = null
User Info = null
Authority = www.google.co.in
Raw Authority = www.google.co.in
getHost() : Returns the host component of the URI. As the host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.Syntax : public String getHost()
Syntax : public String getHost()
getPort() : Returns the port number of this URI.Syntax : public int getPort()
Syntax : public int getPort()
getRawPath() : Returns the raw path of this URI, or null if not defined.Syntax : public String getRawPath()
Syntax : public String getRawPath()
getPath() : Returns the decoded path component of this URI.Syntax : public String getPath()
Syntax : public String getPath()
getRawQuery() : Returns the query component of the URI, or null if undefined.Syntax : public String getRawQuery()
Syntax : public String getRawQuery()
getQuery() : Returns the query component of the URI in decoded form, or null if undefined.Syntax : public String getQuery()
Syntax : public String getQuery()
getRawFragment() : Returns the fragment component of the URI, or null if undefined.Syntax : public String getRawFragment()
Syntax : public String getRawFragment()
getFragment() : Returns the decoded fragment component of this URI, or null if undefined.Syntax : public String getFragment()
Syntax : public String getFragment()
compareTo() : Compares this URI object with another URI object. Comparison by performed according to the natural ordering with String.compareTo() methods. If one component is undefined and other is defined than first is considered smaller than second. Components to be parsed are compared in their raw form rather than their encoded form.Syntax : public int compareTo(URI uri)
Parameters :
uri : URI to be compared with
Syntax : public int compareTo(URI uri)
Parameters :
uri : URI to be compared with
equals() : Tests the given object with this URI. Ig the object is not a URI, it returns false. For two URIs to be considered equal requires that either both are opaque or both are hierarchical. When checking for equality of different components, their raw form is considered rather than the encoded form.Syntax : public boolean equals(Object ob)
Parameters :
ob : object to be compared for equality
Syntax : public boolean equals(Object ob)
Parameters :
ob : object to be compared for equality
isAbsolute() : Returns true if this URI is absolute, otherwise false. A URI is absolute if, and only if, it has a scheme component.Syntax : public boolean isAbsolute()
Syntax : public boolean isAbsolute()
isOpaque() : Returns true if this URI is opaque, otherwise false. A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character (‘/’)Syntax : public boolean isOpaque()
Syntax : public boolean isOpaque()
hashCode() : Returns the hashcode for the this URI object. All the components are taken into account while creating a hashcode for the URI object.Syntax : public int hashCode()
Syntax : public int hashCode()
toString() : Returns the string representation of this URI object.Syntax : public String toString()
Syntax : public String toString()
toASCIIString() : Returns the string representation in ASCII format.Syntax : public String toASCIIString()
Syntax : public String toASCIIString()
Java Implementation :
//Java Program to illustrate various//URI class methodsimport java.net.*;class uridemo1 { public static void main(String[] args) throws Exception { String str = "https://www.google.co.in/?gws_rd=ssl#"+"" + "q=networking+in+java+geeksforgeeks"+"" +"&spf=1496918039682"; // Constructor to create a new URI // by parsing the given string. URI uri = new URI(str); // getHost() method System.out.println("Host = " + uri.getHost()); // getPort() method System.out.println("Port = " + uri.getPath()); // getRawPath() method System.out.println("Raw Path = " + uri.getRawPath()); // getPath() method System.out.println("Path = " + uri.getPath()); // getQuery() method System.out.println("Query = " + uri.getQuery()); // getRawQuery() method System.out.println("Raw Query = " + uri.getRawQuery()); // getFragment() method System.out.println("Fragment = " + uri.getFragment()); // getRawFragment() method System.out.println("Raw Fragment = " + uri.getRawFragment()); URI uri2 = new URI(str + "fr"); // compareTo() mrthod System.out.println("CompareTo =" + uri.compareTo(uri2)); // equals() method System.out.println("Equals = " + uri.equals(uri2)); // hashcode() method System.out.println("Hashcode : " + uri.hashCode()); // toString() method System.out.println("toString : " + uri.toString()); // toASCIIString() method System.out.println("toASCIIString : " + uri.toASCIIString()); }}
Output :
Host = www.google.co.in
Port = /
Raw Path = /
Path = /
Query = gws_rd=ssl
Raw Query = gws_rd=ssl
Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
Raw Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
CompareTo =-2
Equals = false
Hashcode : 480379574
toString : https://www.google.co.in/?gws_rd=ssl#q=networking+
in+java+geeksforgeeks&spf=1496918039682
toASCIIString : https://www.google.co.in/?gws_rd=ssl#q=
networking+in+java+geeksforgeeks&spf=1496918039682
References:Official Java Documentation
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.ase write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Jun, 2017"
},
{
"code": null,
"e": 524,
"s": 54,
"text": "This class provides methods for creating URI instances from its components or by parsing the string form of those components, for accessing and retrieving different components of a URI instance.What is URI?URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular resource. It enables for the interaction of the representation of the resource over the network using specific protocols."
},
{
"code": null,
"e": 566,
"s": 524,
"text": "URI, URL and URN: What is The Difference?"
},
{
"code": null,
"e": 769,
"s": 566,
"text": "The question that must be coming to your minds must be that if URI identifies a resource, what does URL do? People often use the terms interchangeably but it is not correct. According to Tim Berners Lee"
},
{
"code": null,
"e": 1422,
"s": 769,
"text": "“A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.”“A URI can be further classified as a locator, a name, or both. The term “Uniform Resource Locator” (URL) refers to the subset of URI that identify resources via a representation of their primary access mechanism (e.g., their network “location”), rather than identifying the resource by name or by some other attribute(s) of that resource. The term “Uniform Resource Name” (URN) refers to the subset of URI that are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable.”"
},
{
"code": null,
"e": 1435,
"s": 1422,
"text": "For example,"
},
{
"code": null,
"e": 1490,
"s": 1435,
"text": "https://www.geeksforgeeks.org/url-class-java-examples/"
},
{
"code": null,
"e": 1593,
"s": 1490,
"text": "Represents a URL as it tells the exact location where url class article can be found over the network."
},
{
"code": null,
"e": 1617,
"s": 1593,
"text": "url-class-java-examples"
},
{
"code": null,
"e": 1728,
"s": 1617,
"text": "Represents a URN as it does not tell anything about the location but only gives a unique name to the resource."
},
{
"code": null,
"e": 2165,
"s": 1728,
"text": "The difference between an object of URI class and an URL class lies in the fact that a URI string is parsed only with consideration of syntax and no lookups of host is performed on creation. Comparison of two URI objects is done solely on the characters contained in the string. But on the other hand, a URL string is parsed with a certain scheme and comparisons of two URL objects is performed by looking of actual resource on the net."
},
{
"code": null,
"e": 2178,
"s": 2165,
"text": "URI Syntax :"
},
{
"code": null,
"e": 2243,
"s": 2178,
"text": "scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]"
},
{
"code": null,
"e": 3446,
"s": 2243,
"text": "scheme : The scheme component lays out the protocols to be associated with the URI. In some schemes the “//” are required while others dont need them.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1authority : Authority component is made of several components- authentication section, a host and optional port number preceded by a ‘:’. Authentication section includes username and password. Host can be any ip-address.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1path : The path represents a string containing the address within the server to the resource.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1query : Query represent a nonhierarchical data usually the query used for searching of a particular resource. They are separated by a ‘?’ from the preceding part.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1fragment : Fragments are used to identify secondary resources as headings or subheadings within a page etc.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 3691,
"s": 3446,
"text": "scheme : The scheme component lays out the protocols to be associated with the URI. In some schemes the “//” are required while others dont need them.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 3786,
"s": 3691,
"text": "abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4101,
"s": 3786,
"text": "authority : Authority component is made of several components- authentication section, a host and optional port number preceded by a ‘:’. Authentication section includes username and password. Host can be any ip-address.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4196,
"s": 4101,
"text": "abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4384,
"s": 4196,
"text": "path : The path represents a string containing the address within the server to the resource.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4479,
"s": 4384,
"text": "abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4736,
"s": 4479,
"text": "query : Query represent a nonhierarchical data usually the query used for searching of a particular resource. They are separated by a ‘?’ from the preceding part.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 4831,
"s": 4736,
"text": "abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 5033,
"s": 4831,
"text": "fragment : Fragments are used to identify secondary resources as headings or subheadings within a page etc.abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 5128,
"s": 5033,
"text": "abc://admin:[email protected]:1234/path/data\n ?key=value&key2=value2#fragid1"
},
{
"code": null,
"e": 5143,
"s": 5128,
"text": "Constructors :"
},
{
"code": null,
"e": 7156,
"s": 5143,
"text": "URI(String str) : Constructs a URI object by parsing the specified string. The grammar used while parsing is the one specified in RFC 2396, Appendix A.Syntax :public URI(String str)\n throws URISyntaxException\nParameters : \nstr : String to be parsed into URI\nThrows : \nURISyntaxException : If the string violates RFC 2396URI(String scheme, String ssp, String fragment) : Constructs a URI from the given components. A component may be left undefined by passing null. Initially the result string is empty. If scheme is not null it is appended. Similarly the ssp and fragment part is appended if provided.Syntax :public URI(String scheme, String ssp, String fragment)\n throws URISyntaxException\nParameters : \nscheme : scheme name\nssp : scheme-specific part\nfragment : fragment part\nThrows : \nURISyntaxException : If the URI string constructed from the given\n components violates RFC 2396Similarly other constructors are provided based on what components are known at the creation time.URI(String scheme, String userInfo, String host, int port, String path,String query, String fragment)Syntax :public URI(String scheme, String userInfo, String host, int port, \n String path, String query, String fragment)\nParameters :\nscheme : string representing scheme\nuserInfo : userinfo of URI\nhost : host component of URI\nport : listening port number\npath : path of URI\nquery : String representing the query part\nfragment :optional fragment \nURI(String scheme, String host, String path, String fragment)Syntax :public URI(String scheme, String host, String path, String fragment)\nParameters :\nscheme : string representing scheme\nhost : host component of URI\npath : path of URI\nfragment :optional fragment \nURI(String scheme, String authority, String path, String query, String fragment)Syntax :public URI(String scheme, String authority, String path,\n String query, String fragment)\nParameters :\nscheme : string representing scheme\nauthority : authority\npath : path of URI\nquery : String representing the query part\n"
},
{
"code": null,
"e": 7480,
"s": 7156,
"text": "URI(String str) : Constructs a URI object by parsing the specified string. The grammar used while parsing is the one specified in RFC 2396, Appendix A.Syntax :public URI(String str)\n throws URISyntaxException\nParameters : \nstr : String to be parsed into URI\nThrows : \nURISyntaxException : If the string violates RFC 2396"
},
{
"code": null,
"e": 7653,
"s": 7480,
"text": "Syntax :public URI(String str)\n throws URISyntaxException\nParameters : \nstr : String to be parsed into URI\nThrows : \nURISyntaxException : If the string violates RFC 2396"
},
{
"code": null,
"e": 8220,
"s": 7653,
"text": "URI(String scheme, String ssp, String fragment) : Constructs a URI from the given components. A component may be left undefined by passing null. Initially the result string is empty. If scheme is not null it is appended. Similarly the ssp and fragment part is appended if provided.Syntax :public URI(String scheme, String ssp, String fragment)\n throws URISyntaxException\nParameters : \nscheme : scheme name\nssp : scheme-specific part\nfragment : fragment part\nThrows : \nURISyntaxException : If the URI string constructed from the given\n components violates RFC 2396"
},
{
"code": null,
"e": 8506,
"s": 8220,
"text": "Syntax :public URI(String scheme, String ssp, String fragment)\n throws URISyntaxException\nParameters : \nscheme : scheme name\nssp : scheme-specific part\nfragment : fragment part\nThrows : \nURISyntaxException : If the URI string constructed from the given\n components violates RFC 2396"
},
{
"code": null,
"e": 8605,
"s": 8506,
"text": "Similarly other constructors are provided based on what components are known at the creation time."
},
{
"code": null,
"e": 9057,
"s": 8605,
"text": "URI(String scheme, String userInfo, String host, int port, String path,String query, String fragment)Syntax :public URI(String scheme, String userInfo, String host, int port, \n String path, String query, String fragment)\nParameters :\nscheme : string representing scheme\nuserInfo : userinfo of URI\nhost : host component of URI\nport : listening port number\npath : path of URI\nquery : String representing the query part\nfragment :optional fragment \n"
},
{
"code": null,
"e": 9408,
"s": 9057,
"text": "Syntax :public URI(String scheme, String userInfo, String host, int port, \n String path, String query, String fragment)\nParameters :\nscheme : string representing scheme\nuserInfo : userinfo of URI\nhost : host component of URI\nport : listening port number\npath : path of URI\nquery : String representing the query part\nfragment :optional fragment \n"
},
{
"code": null,
"e": 9673,
"s": 9408,
"text": "URI(String scheme, String host, String path, String fragment)Syntax :public URI(String scheme, String host, String path, String fragment)\nParameters :\nscheme : string representing scheme\nhost : host component of URI\npath : path of URI\nfragment :optional fragment \n"
},
{
"code": null,
"e": 9877,
"s": 9673,
"text": "Syntax :public URI(String scheme, String host, String path, String fragment)\nParameters :\nscheme : string representing scheme\nhost : host component of URI\npath : path of URI\nfragment :optional fragment \n"
},
{
"code": null,
"e": 10188,
"s": 9877,
"text": "URI(String scheme, String authority, String path, String query, String fragment)Syntax :public URI(String scheme, String authority, String path,\n String query, String fragment)\nParameters :\nscheme : string representing scheme\nauthority : authority\npath : path of URI\nquery : String representing the query part\n"
},
{
"code": null,
"e": 10419,
"s": 10188,
"text": "Syntax :public URI(String scheme, String authority, String path,\n String query, String fragment)\nParameters :\nscheme : string representing scheme\nauthority : authority\npath : path of URI\nquery : String representing the query part\n"
},
{
"code": null,
"e": 10429,
"s": 10419,
"text": "Methods :"
},
{
"code": null,
"e": 20117,
"s": 10429,
"text": "create() : creates a new URI object. This method can be called a pseudo constructor. It is provided for use in the situations when it is known for sure that given string will parse as the URI object and it would be considered as a programmers error if it does not parse.Syntax : public static URI create(String str)\nParameters :\nstr : String to be parsed as URIparseServerAuthority() : This method is used to parse the URI’s authority components if provided into user information, host and port components. This method returns a URI object whose authority field has been parsed as a server based authority.Syntax : public URI parseServerAuthority()normalize() : Normalizes this URI’s path. URI is constructed by normalizing the URI’s path which is consistent with RFC 2396. Returns a normalized URI object.Syntax : public URI normalize()resolve() : Resolves the given URI with this URI. Returns a new hierarchical URI in a manner consistent with RFC 2396.Syntax : public URI resolve(URI uri)\nParameters :\nuri : URI to be resolved\nAnother overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).Syntax : public URI resolve(String str)\nParameters :\nstr : String to be parsed as URIrelativize() : Relativizes the given URI against this URI.Syntax : public URI relativize(URI uri)Parameters :uri : URI to relativizetoURL() : Constructs a URL from this URI.Syntax : public URL toURL()\n throws MalformedURLException\nThrows :\nMalformedURLException : If error occurs while constructing URLgetScheme() : Returns the scheme component of the URISyntax : public String getScheme()getRawSchemeSpecificPart() : Returns the raw scheme specific component of the URI.Syntax : public String getRawSchemeSpecificPart()getSchemeSpecificPart() : Returns the decoded scheme specific component of the URISyntax : public String getSchemeSpecificPart()getRawAuthority() : Returns the authority component of the URI. If the authority is server based, then further user information, host and port components are returned.Syntax : public String getRawAuthority()getAuthority() : Returns exact similar result as of the above method except in the decoded form.Syntax : public String getAuthority()getRawUserInfo() : Returns the user info component of the URI, or null if it is undefined.Syntax : public String getRawUserInfo()getUserInfo() : Returns the user info component of the URI in decoded form, or null if it is undefined.Syntax : public String getUserInfo()Java Implementation :// Java program to illustrate various// URI class methodsimport java.net.*; class uridemo1{ public static void main(String[] args) throws Exception { String uribase = \"https://www.geeksforgeeks.org/\"; String urirelative = \"languages/../java\"; String str = \"https://www.google.co.in/?gws_rd=ssl#\"+\"\" + \"q=networking+in+java+geeksforgeeks\"+\"\" +\"&spf=1496918039682\"; // Constructor to create a new URI // by parsing the string URI uriBase = new URI(uribase); // create() method URI uri = URI.create(str); // toString() method System.out.println(\"Base URI = \" + uriBase.toString()); URI uriRelative = new URI(urirelative); System.out.println(\"Relative URI = \" + uriRelative.toString()); // resolve() method URI uriResolved = uriBase.resolve(uriRelative); System.out.println(\"Resolved URI = \" + uriResolved.toString()); // relativized() method URI uriRelativized = uriBase.relativize(uriResolved); System.out.println(\"Relativized URI = \" + uriRelativized.toString()); // normalize() method System.out.println(uri.normalize().toString()); // getScheme() method System.out.println(\"Scheme = \" + uri.getScheme()); // getRawShemeSpecific() method System.out.println(\"Raw Scheme = \" + uri.getRawSchemeSpecificPart()); // getSchemeSpecificPart() method System.out.println(\"Scheme-specific part = \" + uri.getSchemeSpecificPart()); // getRawUserInfo() method System.out.println(\"Raw User Info = \" + uri.getRawUserInfo()); // getUserInfo() method System.out.println(\"User Info = \" + uri.getUserInfo()); // getAuthority() method System.out.println(\"Authority = \" + uri.getAuthority()); // getRawAuthority() method System.out.println(\"Raw Authority = \" + uri.getRawAuthority()); }}Output :Base URI = https://www.geeksforgeeks.org/\nRelative URI = languages/../java\nResolved URI = https://www.geeksforgeeks.org/java\nRelativized URI = java\nhttps://www.google.co.in/?gws_rd=ssl#q=networking+in+\njava+geeksforgeeks&spf=1496918039682\nScheme = https\nRaw Scheme = //www.google.co.in/?gws_rd=ssl\nScheme-specific part = //www.google.co.in/?gws_rd=ssl\nRaw User Info = null\nUser Info = null\nAuthority = www.google.co.in\nRaw Authority = www.google.co.in\n\ngetHost() : Returns the host component of the URI. As the host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.Syntax : public String getHost()getPort() : Returns the port number of this URI.Syntax : public int getPort()getRawPath() : Returns the raw path of this URI, or null if not defined.Syntax : public String getRawPath()getPath() : Returns the decoded path component of this URI.Syntax : public String getPath()getRawQuery() : Returns the query component of the URI, or null if undefined.Syntax : public String getRawQuery()getQuery() : Returns the query component of the URI in decoded form, or null if undefined.Syntax : public String getQuery()getRawFragment() : Returns the fragment component of the URI, or null if undefined.Syntax : public String getRawFragment()getFragment() : Returns the decoded fragment component of this URI, or null if undefined.Syntax : public String getFragment()compareTo() : Compares this URI object with another URI object. Comparison by performed according to the natural ordering with String.compareTo() methods. If one component is undefined and other is defined than first is considered smaller than second. Components to be parsed are compared in their raw form rather than their encoded form.Syntax : public int compareTo(URI uri)\nParameters :\nuri : URI to be compared withequals() : Tests the given object with this URI. Ig the object is not a URI, it returns false. For two URIs to be considered equal requires that either both are opaque or both are hierarchical. When checking for equality of different components, their raw form is considered rather than the encoded form.Syntax : public boolean equals(Object ob)\nParameters :\nob : object to be compared for equalityisAbsolute() : Returns true if this URI is absolute, otherwise false. A URI is absolute if, and only if, it has a scheme component.Syntax : public boolean isAbsolute()isOpaque() : Returns true if this URI is opaque, otherwise false. A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character (‘/’)Syntax : public boolean isOpaque()hashCode() : Returns the hashcode for the this URI object. All the components are taken into account while creating a hashcode for the URI object.Syntax : public int hashCode()toString() : Returns the string representation of this URI object.Syntax : public String toString()toASCIIString() : Returns the string representation in ASCII format.Syntax : public String toASCIIString()Java Implementation ://Java Program to illustrate various//URI class methodsimport java.net.*;class uridemo1 { public static void main(String[] args) throws Exception { String str = \"https://www.google.co.in/?gws_rd=ssl#\"+\"\" + \"q=networking+in+java+geeksforgeeks\"+\"\" +\"&spf=1496918039682\"; // Constructor to create a new URI // by parsing the given string. URI uri = new URI(str); // getHost() method System.out.println(\"Host = \" + uri.getHost()); // getPort() method System.out.println(\"Port = \" + uri.getPath()); // getRawPath() method System.out.println(\"Raw Path = \" + uri.getRawPath()); // getPath() method System.out.println(\"Path = \" + uri.getPath()); // getQuery() method System.out.println(\"Query = \" + uri.getQuery()); // getRawQuery() method System.out.println(\"Raw Query = \" + uri.getRawQuery()); // getFragment() method System.out.println(\"Fragment = \" + uri.getFragment()); // getRawFragment() method System.out.println(\"Raw Fragment = \" + uri.getRawFragment()); URI uri2 = new URI(str + \"fr\"); // compareTo() mrthod System.out.println(\"CompareTo =\" + uri.compareTo(uri2)); // equals() method System.out.println(\"Equals = \" + uri.equals(uri2)); // hashcode() method System.out.println(\"Hashcode : \" + uri.hashCode()); // toString() method System.out.println(\"toString : \" + uri.toString()); // toASCIIString() method System.out.println(\"toASCIIString : \" + uri.toASCIIString()); }}Output :Host = www.google.co.in\nPort = /\nRaw Path = /\nPath = /\nQuery = gws_rd=ssl\nRaw Query = gws_rd=ssl\nFragment = q=networking+in+java+geeksforgeeks&spf=1496918039682\nRaw Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682\nCompareTo =-2\nEquals = false\nHashcode : 480379574\ntoString : https://www.google.co.in/?gws_rd=ssl#q=networking+\nin+java+geeksforgeeks&spf=1496918039682\ntoASCIIString : https://www.google.co.in/?gws_rd=ssl#q=\nnetworking+in+java+geeksforgeeks&spf=1496918039682\n"
},
{
"code": null,
"e": 20479,
"s": 20117,
"text": "create() : creates a new URI object. This method can be called a pseudo constructor. It is provided for use in the situations when it is known for sure that given string will parse as the URI object and it would be considered as a programmers error if it does not parse.Syntax : public static URI create(String str)\nParameters :\nstr : String to be parsed as URI"
},
{
"code": null,
"e": 20571,
"s": 20479,
"text": "Syntax : public static URI create(String str)\nParameters :\nstr : String to be parsed as URI"
},
{
"code": null,
"e": 20859,
"s": 20571,
"text": "parseServerAuthority() : This method is used to parse the URI’s authority components if provided into user information, host and port components. This method returns a URI object whose authority field has been parsed as a server based authority.Syntax : public URI parseServerAuthority()"
},
{
"code": null,
"e": 20902,
"s": 20859,
"text": "Syntax : public URI parseServerAuthority()"
},
{
"code": null,
"e": 21092,
"s": 20902,
"text": "normalize() : Normalizes this URI’s path. URI is constructed by normalizing the URI’s path which is consistent with RFC 2396. Returns a normalized URI object.Syntax : public URI normalize()"
},
{
"code": null,
"e": 21124,
"s": 21092,
"text": "Syntax : public URI normalize()"
},
{
"code": null,
"e": 21514,
"s": 21124,
"text": "resolve() : Resolves the given URI with this URI. Returns a new hierarchical URI in a manner consistent with RFC 2396.Syntax : public URI resolve(URI uri)\nParameters :\nuri : URI to be resolved\nAnother overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).Syntax : public URI resolve(String str)\nParameters :\nstr : String to be parsed as URI"
},
{
"code": null,
"e": 21590,
"s": 21514,
"text": "Syntax : public URI resolve(URI uri)\nParameters :\nuri : URI to be resolved\n"
},
{
"code": null,
"e": 21702,
"s": 21590,
"text": "Another overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str))."
},
{
"code": null,
"e": 21788,
"s": 21702,
"text": "Syntax : public URI resolve(String str)\nParameters :\nstr : String to be parsed as URI"
},
{
"code": null,
"e": 21921,
"s": 21788,
"text": "relativize() : Relativizes the given URI against this URI.Syntax : public URI relativize(URI uri)Parameters :uri : URI to relativize"
},
{
"code": null,
"e": 21961,
"s": 21921,
"text": "Syntax : public URI relativize(URI uri)"
},
{
"code": null,
"e": 21997,
"s": 21961,
"text": "Parameters :uri : URI to relativize"
},
{
"code": null,
"e": 22177,
"s": 21997,
"text": "toURL() : Constructs a URL from this URI.Syntax : public URL toURL()\n throws MalformedURLException\nThrows :\nMalformedURLException : If error occurs while constructing URL"
},
{
"code": null,
"e": 22316,
"s": 22177,
"text": "Syntax : public URL toURL()\n throws MalformedURLException\nThrows :\nMalformedURLException : If error occurs while constructing URL"
},
{
"code": null,
"e": 22404,
"s": 22316,
"text": "getScheme() : Returns the scheme component of the URISyntax : public String getScheme()"
},
{
"code": null,
"e": 22439,
"s": 22404,
"text": "Syntax : public String getScheme()"
},
{
"code": null,
"e": 22571,
"s": 22439,
"text": "getRawSchemeSpecificPart() : Returns the raw scheme specific component of the URI.Syntax : public String getRawSchemeSpecificPart()"
},
{
"code": null,
"e": 22621,
"s": 22571,
"text": "Syntax : public String getRawSchemeSpecificPart()"
},
{
"code": null,
"e": 22750,
"s": 22621,
"text": "getSchemeSpecificPart() : Returns the decoded scheme specific component of the URISyntax : public String getSchemeSpecificPart()"
},
{
"code": null,
"e": 22797,
"s": 22750,
"text": "Syntax : public String getSchemeSpecificPart()"
},
{
"code": null,
"e": 23005,
"s": 22797,
"text": "getRawAuthority() : Returns the authority component of the URI. If the authority is server based, then further user information, host and port components are returned.Syntax : public String getRawAuthority()"
},
{
"code": null,
"e": 23046,
"s": 23005,
"text": "Syntax : public String getRawAuthority()"
},
{
"code": null,
"e": 23180,
"s": 23046,
"text": "getAuthority() : Returns exact similar result as of the above method except in the decoded form.Syntax : public String getAuthority()"
},
{
"code": null,
"e": 23218,
"s": 23180,
"text": "Syntax : public String getAuthority()"
},
{
"code": null,
"e": 23348,
"s": 23218,
"text": "getRawUserInfo() : Returns the user info component of the URI, or null if it is undefined.Syntax : public String getRawUserInfo()"
},
{
"code": null,
"e": 23388,
"s": 23348,
"text": "Syntax : public String getRawUserInfo()"
},
{
"code": null,
"e": 23528,
"s": 23388,
"text": "getUserInfo() : Returns the user info component of the URI in decoded form, or null if it is undefined.Syntax : public String getUserInfo()"
},
{
"code": null,
"e": 23565,
"s": 23528,
"text": "Syntax : public String getUserInfo()"
},
{
"code": null,
"e": 23587,
"s": 23565,
"text": "Java Implementation :"
},
{
"code": "// Java program to illustrate various// URI class methodsimport java.net.*; class uridemo1{ public static void main(String[] args) throws Exception { String uribase = \"https://www.geeksforgeeks.org/\"; String urirelative = \"languages/../java\"; String str = \"https://www.google.co.in/?gws_rd=ssl#\"+\"\" + \"q=networking+in+java+geeksforgeeks\"+\"\" +\"&spf=1496918039682\"; // Constructor to create a new URI // by parsing the string URI uriBase = new URI(uribase); // create() method URI uri = URI.create(str); // toString() method System.out.println(\"Base URI = \" + uriBase.toString()); URI uriRelative = new URI(urirelative); System.out.println(\"Relative URI = \" + uriRelative.toString()); // resolve() method URI uriResolved = uriBase.resolve(uriRelative); System.out.println(\"Resolved URI = \" + uriResolved.toString()); // relativized() method URI uriRelativized = uriBase.relativize(uriResolved); System.out.println(\"Relativized URI = \" + uriRelativized.toString()); // normalize() method System.out.println(uri.normalize().toString()); // getScheme() method System.out.println(\"Scheme = \" + uri.getScheme()); // getRawShemeSpecific() method System.out.println(\"Raw Scheme = \" + uri.getRawSchemeSpecificPart()); // getSchemeSpecificPart() method System.out.println(\"Scheme-specific part = \" + uri.getSchemeSpecificPart()); // getRawUserInfo() method System.out.println(\"Raw User Info = \" + uri.getRawUserInfo()); // getUserInfo() method System.out.println(\"User Info = \" + uri.getUserInfo()); // getAuthority() method System.out.println(\"Authority = \" + uri.getAuthority()); // getRawAuthority() method System.out.println(\"Raw Authority = \" + uri.getRawAuthority()); }}",
"e": 25586,
"s": 23587,
"text": null
},
{
"code": null,
"e": 25595,
"s": 25586,
"text": "Output :"
},
{
"code": null,
"e": 26049,
"s": 25595,
"text": "Base URI = https://www.geeksforgeeks.org/\nRelative URI = languages/../java\nResolved URI = https://www.geeksforgeeks.org/java\nRelativized URI = java\nhttps://www.google.co.in/?gws_rd=ssl#q=networking+in+\njava+geeksforgeeks&spf=1496918039682\nScheme = https\nRaw Scheme = //www.google.co.in/?gws_rd=ssl\nScheme-specific part = //www.google.co.in/?gws_rd=ssl\nRaw User Info = null\nUser Info = null\nAuthority = www.google.co.in\nRaw Authority = www.google.co.in\n\n"
},
{
"code": null,
"e": 26243,
"s": 26049,
"text": "getHost() : Returns the host component of the URI. As the host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.Syntax : public String getHost()"
},
{
"code": null,
"e": 26276,
"s": 26243,
"text": "Syntax : public String getHost()"
},
{
"code": null,
"e": 26354,
"s": 26276,
"text": "getPort() : Returns the port number of this URI.Syntax : public int getPort()"
},
{
"code": null,
"e": 26384,
"s": 26354,
"text": "Syntax : public int getPort()"
},
{
"code": null,
"e": 26492,
"s": 26384,
"text": "getRawPath() : Returns the raw path of this URI, or null if not defined.Syntax : public String getRawPath()"
},
{
"code": null,
"e": 26528,
"s": 26492,
"text": "Syntax : public String getRawPath()"
},
{
"code": null,
"e": 26620,
"s": 26528,
"text": "getPath() : Returns the decoded path component of this URI.Syntax : public String getPath()"
},
{
"code": null,
"e": 26653,
"s": 26620,
"text": "Syntax : public String getPath()"
},
{
"code": null,
"e": 26767,
"s": 26653,
"text": "getRawQuery() : Returns the query component of the URI, or null if undefined.Syntax : public String getRawQuery()"
},
{
"code": null,
"e": 26804,
"s": 26767,
"text": "Syntax : public String getRawQuery()"
},
{
"code": null,
"e": 26928,
"s": 26804,
"text": "getQuery() : Returns the query component of the URI in decoded form, or null if undefined.Syntax : public String getQuery()"
},
{
"code": null,
"e": 26962,
"s": 26928,
"text": "Syntax : public String getQuery()"
},
{
"code": null,
"e": 27085,
"s": 26962,
"text": "getRawFragment() : Returns the fragment component of the URI, or null if undefined.Syntax : public String getRawFragment()"
},
{
"code": null,
"e": 27125,
"s": 27085,
"text": "Syntax : public String getRawFragment()"
},
{
"code": null,
"e": 27251,
"s": 27125,
"text": "getFragment() : Returns the decoded fragment component of this URI, or null if undefined.Syntax : public String getFragment()"
},
{
"code": null,
"e": 27288,
"s": 27251,
"text": "Syntax : public String getFragment()"
},
{
"code": null,
"e": 27708,
"s": 27288,
"text": "compareTo() : Compares this URI object with another URI object. Comparison by performed according to the natural ordering with String.compareTo() methods. If one component is undefined and other is defined than first is considered smaller than second. Components to be parsed are compared in their raw form rather than their encoded form.Syntax : public int compareTo(URI uri)\nParameters :\nuri : URI to be compared with"
},
{
"code": null,
"e": 27790,
"s": 27708,
"text": "Syntax : public int compareTo(URI uri)\nParameters :\nuri : URI to be compared with"
},
{
"code": null,
"e": 28189,
"s": 27790,
"text": "equals() : Tests the given object with this URI. Ig the object is not a URI, it returns false. For two URIs to be considered equal requires that either both are opaque or both are hierarchical. When checking for equality of different components, their raw form is considered rather than the encoded form.Syntax : public boolean equals(Object ob)\nParameters :\nob : object to be compared for equality"
},
{
"code": null,
"e": 28284,
"s": 28189,
"text": "Syntax : public boolean equals(Object ob)\nParameters :\nob : object to be compared for equality"
},
{
"code": null,
"e": 28452,
"s": 28284,
"text": "isAbsolute() : Returns true if this URI is absolute, otherwise false. A URI is absolute if, and only if, it has a scheme component.Syntax : public boolean isAbsolute()"
},
{
"code": null,
"e": 28489,
"s": 28452,
"text": "Syntax : public boolean isAbsolute()"
},
{
"code": null,
"e": 28710,
"s": 28489,
"text": "isOpaque() : Returns true if this URI is opaque, otherwise false. A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character (‘/’)Syntax : public boolean isOpaque()"
},
{
"code": null,
"e": 28745,
"s": 28710,
"text": "Syntax : public boolean isOpaque()"
},
{
"code": null,
"e": 28922,
"s": 28745,
"text": "hashCode() : Returns the hashcode for the this URI object. All the components are taken into account while creating a hashcode for the URI object.Syntax : public int hashCode()"
},
{
"code": null,
"e": 28953,
"s": 28922,
"text": "Syntax : public int hashCode()"
},
{
"code": null,
"e": 29053,
"s": 28953,
"text": "toString() : Returns the string representation of this URI object.Syntax : public String toString()"
},
{
"code": null,
"e": 29087,
"s": 29053,
"text": "Syntax : public String toString()"
},
{
"code": null,
"e": 29194,
"s": 29087,
"text": "toASCIIString() : Returns the string representation in ASCII format.Syntax : public String toASCIIString()"
},
{
"code": null,
"e": 29233,
"s": 29194,
"text": "Syntax : public String toASCIIString()"
},
{
"code": null,
"e": 29255,
"s": 29233,
"text": "Java Implementation :"
},
{
"code": "//Java Program to illustrate various//URI class methodsimport java.net.*;class uridemo1 { public static void main(String[] args) throws Exception { String str = \"https://www.google.co.in/?gws_rd=ssl#\"+\"\" + \"q=networking+in+java+geeksforgeeks\"+\"\" +\"&spf=1496918039682\"; // Constructor to create a new URI // by parsing the given string. URI uri = new URI(str); // getHost() method System.out.println(\"Host = \" + uri.getHost()); // getPort() method System.out.println(\"Port = \" + uri.getPath()); // getRawPath() method System.out.println(\"Raw Path = \" + uri.getRawPath()); // getPath() method System.out.println(\"Path = \" + uri.getPath()); // getQuery() method System.out.println(\"Query = \" + uri.getQuery()); // getRawQuery() method System.out.println(\"Raw Query = \" + uri.getRawQuery()); // getFragment() method System.out.println(\"Fragment = \" + uri.getFragment()); // getRawFragment() method System.out.println(\"Raw Fragment = \" + uri.getRawFragment()); URI uri2 = new URI(str + \"fr\"); // compareTo() mrthod System.out.println(\"CompareTo =\" + uri.compareTo(uri2)); // equals() method System.out.println(\"Equals = \" + uri.equals(uri2)); // hashcode() method System.out.println(\"Hashcode : \" + uri.hashCode()); // toString() method System.out.println(\"toString : \" + uri.toString()); // toASCIIString() method System.out.println(\"toASCIIString : \" + uri.toASCIIString()); }}",
"e": 30919,
"s": 29255,
"text": null
},
{
"code": null,
"e": 30928,
"s": 30919,
"text": "Output :"
},
{
"code": null,
"e": 31417,
"s": 30928,
"text": "Host = www.google.co.in\nPort = /\nRaw Path = /\nPath = /\nQuery = gws_rd=ssl\nRaw Query = gws_rd=ssl\nFragment = q=networking+in+java+geeksforgeeks&spf=1496918039682\nRaw Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682\nCompareTo =-2\nEquals = false\nHashcode : 480379574\ntoString : https://www.google.co.in/?gws_rd=ssl#q=networking+\nin+java+geeksforgeeks&spf=1496918039682\ntoASCIIString : https://www.google.co.in/?gws_rd=ssl#q=\nnetworking+in+java+geeksforgeeks&spf=1496918039682\n"
},
{
"code": null,
"e": 31456,
"s": 31417,
"text": "References:Official Java Documentation"
},
{
"code": null,
"e": 31759,
"s": 31456,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 32005,
"s": 31759,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.ase write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32021,
"s": 32005,
"text": "Java-Networking"
},
{
"code": null,
"e": 32026,
"s": 32021,
"text": "Java"
},
{
"code": null,
"e": 32031,
"s": 32026,
"text": "Java"
},
{
"code": null,
"e": 32129,
"s": 32031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32180,
"s": 32129,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32211,
"s": 32180,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32230,
"s": 32211,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32260,
"s": 32230,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32278,
"s": 32260,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32298,
"s": 32278,
"text": "Collections in Java"
},
{
"code": null,
"e": 32313,
"s": 32298,
"text": "Stream In Java"
},
{
"code": null,
"e": 32345,
"s": 32313,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32365,
"s": 32345,
"text": "Stack Class in Java"
}
] |
File handling in Java using FileWriter and FileReader | 23 Feb, 2022
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes.
FileWriterFileWriter is useful to create a file writing characters into it.
This class inherits from the OutputStream class.
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
FileWriter creates the output file if it is not present already.
Constructors:
FileWriter(File file) – Constructs a FileWriter object given a File object.
FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
FileWriter (String fileName) – constructs a FileWriter object given a file name.
FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.
Methods:
public void write (int c) throws IOException – Writes a single character.
public void write (char [] stir) throws IOException – Writes an array of characters.
public void write(String str)throws IOException – Writes a string.
public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here off is offset from which to start writing characters and len is the number of characters to write.
public void flush() throws IOException flushes the stream
public void close() throws IOException flushes the stream first and then closes the writer.
Reading and writing take place character by character, which increases the number of I/O operations and affects the performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.The following program depicts how to create a text file using FileWriter
Java
// Creating a text File using FileWriterimport java.io.FileWriter;import java.io.IOException;class CreateFile{ public static void main(String[] args) throws IOException { // Accept a string String str = "File Handling in Java using "+ " FileWriter and FileReader"; // attach a file to FileWriter FileWriter fw=new FileWriter("output.txt"); // read character wise from string and write // into FileWriter for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); System.out.println("Writing successful"); //close the file fw.close(); }}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
This class inherited from the InputStreamReader Class.
The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
Constructors:
FileReader(File file) – Creates a FileReader , given the File to read from
FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from
FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from
Methods:
public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. Parameters: cbuf – Destination buffer off – Offset at which to start storing characters len – Maximum number of characters to read
public void close() throws IOException closes the reader.
public long skip(long n) throws IOException –Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. Parameters: n – The number of characters to skip
The following program depicts how to read from the ‘text’ file using FileReader
Java
// Reading data from a file using FileReaderimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;class ReadFile{ public static void main(String[] args) throws IOException { // variable declaration int ch; // check if File exists or not FileReader fr=null; try { fr = new FileReader("text"); } catch (FileNotFoundException fe) { System.out.println("File not found"); } // read from FileReader till the end of file while ((ch=fr.read())!=-1) System.out.print((char)ch); // close the file fr.close(); }}
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SandySharma
shubhamvora05
java-file-handling
Java-I/O
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 345,
"s": 54,
"text": "Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes. "
},
{
"code": null,
"e": 422,
"s": 345,
"text": "FileWriterFileWriter is useful to create a file writing characters into it. "
},
{
"code": null,
"e": 471,
"s": 422,
"text": "This class inherits from the OutputStream class."
},
{
"code": null,
"e": 685,
"s": 471,
"text": "The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream. "
},
{
"code": null,
"e": 809,
"s": 685,
"text": "FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream."
},
{
"code": null,
"e": 874,
"s": 809,
"text": "FileWriter creates the output file if it is not present already."
},
{
"code": null,
"e": 889,
"s": 874,
"text": "Constructors: "
},
{
"code": null,
"e": 965,
"s": 889,
"text": "FileWriter(File file) – Constructs a FileWriter object given a File object."
},
{
"code": null,
"e": 1058,
"s": 965,
"text": "FileWriter (File file, boolean append) – constructs a FileWriter object given a File object."
},
{
"code": null,
"e": 1157,
"s": 1058,
"text": "FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor."
},
{
"code": null,
"e": 1238,
"s": 1157,
"text": "FileWriter (String fileName) – constructs a FileWriter object given a file name."
},
{
"code": null,
"e": 1403,
"s": 1238,
"text": "FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written."
},
{
"code": null,
"e": 1413,
"s": 1403,
"text": "Methods: "
},
{
"code": null,
"e": 1487,
"s": 1413,
"text": "public void write (int c) throws IOException – Writes a single character."
},
{
"code": null,
"e": 1572,
"s": 1487,
"text": "public void write (char [] stir) throws IOException – Writes an array of characters."
},
{
"code": null,
"e": 1639,
"s": 1572,
"text": "public void write(String str)throws IOException – Writes a string."
},
{
"code": null,
"e": 1841,
"s": 1639,
"text": "public void write(String str, int off, int len)throws IOException – Writes a portion of a string. Here off is offset from which to start writing characters and len is the number of characters to write."
},
{
"code": null,
"e": 1899,
"s": 1841,
"text": "public void flush() throws IOException flushes the stream"
},
{
"code": null,
"e": 1991,
"s": 1899,
"text": "public void close() throws IOException flushes the stream first and then closes the writer."
},
{
"code": null,
"e": 2290,
"s": 1991,
"text": "Reading and writing take place character by character, which increases the number of I/O operations and affects the performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.The following program depicts how to create a text file using FileWriter "
},
{
"code": null,
"e": 2295,
"s": 2290,
"text": "Java"
},
{
"code": "// Creating a text File using FileWriterimport java.io.FileWriter;import java.io.IOException;class CreateFile{ public static void main(String[] args) throws IOException { // Accept a string String str = \"File Handling in Java using \"+ \" FileWriter and FileReader\"; // attach a file to FileWriter FileWriter fw=new FileWriter(\"output.txt\"); // read character wise from string and write // into FileWriter for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); System.out.println(\"Writing successful\"); //close the file fw.close(); }}",
"e": 2945,
"s": 2295,
"text": null
},
{
"code": null,
"e": 2956,
"s": 2945,
"text": "FileReader"
},
{
"code": null,
"e": 3037,
"s": 2956,
"text": "FileReader is useful to read data in the form of characters from a ‘text’ file. "
},
{
"code": null,
"e": 3092,
"s": 3037,
"text": "This class inherited from the InputStreamReader Class."
},
{
"code": null,
"e": 3305,
"s": 3092,
"text": "The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream. "
},
{
"code": null,
"e": 3428,
"s": 3305,
"text": "FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream."
},
{
"code": null,
"e": 3443,
"s": 3428,
"text": "Constructors: "
},
{
"code": null,
"e": 3518,
"s": 3443,
"text": "FileReader(File file) – Creates a FileReader , given the File to read from"
},
{
"code": null,
"e": 3615,
"s": 3518,
"text": "FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from"
},
{
"code": null,
"e": 3712,
"s": 3615,
"text": "FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from"
},
{
"code": null,
"e": 3722,
"s": 3712,
"text": "Methods: "
},
{
"code": null,
"e": 3901,
"s": 3722,
"text": "public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached."
},
{
"code": null,
"e": 4096,
"s": 3901,
"text": "public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached."
},
{
"code": null,
"e": 4462,
"s": 4096,
"text": "public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. Parameters: cbuf – Destination buffer off – Offset at which to start storing characters len – Maximum number of characters to read "
},
{
"code": null,
"e": 4520,
"s": 4462,
"text": "public void close() throws IOException closes the reader."
},
{
"code": null,
"e": 4751,
"s": 4520,
"text": "public long skip(long n) throws IOException –Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. Parameters: n – The number of characters to skip "
},
{
"code": null,
"e": 4832,
"s": 4751,
"text": "The following program depicts how to read from the ‘text’ file using FileReader "
},
{
"code": null,
"e": 4837,
"s": 4832,
"text": "Java"
},
{
"code": "// Reading data from a file using FileReaderimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;class ReadFile{ public static void main(String[] args) throws IOException { // variable declaration int ch; // check if File exists or not FileReader fr=null; try { fr = new FileReader(\"text\"); } catch (FileNotFoundException fe) { System.out.println(\"File not found\"); } // read from FileReader till the end of file while ((ch=fr.read())!=-1) System.out.print((char)ch); // close the file fr.close(); }}",
"e": 5518,
"s": 4837,
"text": null
},
{
"code": null,
"e": 5941,
"s": 5518,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5953,
"s": 5941,
"text": "SandySharma"
},
{
"code": null,
"e": 5967,
"s": 5953,
"text": "shubhamvora05"
},
{
"code": null,
"e": 5986,
"s": 5967,
"text": "java-file-handling"
},
{
"code": null,
"e": 5995,
"s": 5986,
"text": "Java-I/O"
},
{
"code": null,
"e": 6008,
"s": 5995,
"text": "Java-Library"
},
{
"code": null,
"e": 6013,
"s": 6008,
"text": "Java"
},
{
"code": null,
"e": 6018,
"s": 6013,
"text": "Java"
},
{
"code": null,
"e": 6116,
"s": 6018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6167,
"s": 6116,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6198,
"s": 6167,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6217,
"s": 6198,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6247,
"s": 6217,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6265,
"s": 6247,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6280,
"s": 6265,
"text": "Stream In Java"
},
{
"code": null,
"e": 6300,
"s": 6280,
"text": "Collections in Java"
},
{
"code": null,
"e": 6324,
"s": 6300,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6356,
"s": 6324,
"text": "Multidimensional Arrays in Java"
}
] |
Subarrays with distinct elements | 11 Jul, 2022
Given an array, the task is to calculate the sum of lengths of contiguous subarrays having all elements distinct.
Examples:
Input : arr[] = {1, 2, 3}
Output : 10
{1, 2, 3} is a subarray of length 3 with
distinct elements. Total length of length
three = 3.
{1, 2}, {2, 3} are 2 subarray of length 2
with distinct elements. Total length of
lengths two = 2 + 2 = 4
{1}, {2}, {3} are 3 subarrays of length 1
with distinct element. Total lengths of
length one = 1 + 1 + 1 = 3
Sum of lengths = 3 + 4 + 3 = 10
Input : arr[] = {1, 2, 1}
Output : 7
Input : arr[] = {1, 2, 3, 4}
Output : 20
A simple solution is to consider all subarrays and for every subarray check if it has distinct elements or not using hashing. And add lengths of all subarrays having distinct elements. If we use hashing to find distinct elements, then this approach takes O(n2) time under the assumption that hashing search and insert operations take O(1) time.
An efficient solution is based on the fact that if we know all elements in a subarray arr[i..j] are distinct, sum of all lengths of distinct element subarrays in this sub array is ((j-i+1)*(j-i+2))/2. How? the possible lengths of subarrays are 1, 2, 3,......, j – i +1. So, the sum will be ((j – i +1)*(j – i +2))/2.
We first find largest subarray (with distinct elements) starting from first element. We count sum of lengths in this subarray using above formula. For finding next subarray of the distinct element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If not possible, then we increment i again and move forward the same way.
Below is the implementation of this approach:
C++
Java
Python 3
C#
Javascript
// C++ program to calculate sum of lengths of subarrays// of distinct elements.#include<bits/stdc++.h>using namespace std; // Returns sum of lengths of all subarrays with distinct// elements.int sumoflength(int arr[], int n){ // For maintaining distinct elements. unordered_set<int> s; // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i=0; i<n; i++) { // Find ending point for current subarray with // distinct elements. while (j < n && s.find(arr[j]) == s.end()) { s.insert(arr[j]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1))/2; // Remove arr[i] as we pick new starting point // from next s.erase(arr[i]); } return ans;} // Driven Codeint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << sumoflength(arr, n) << endl; return 0;}
// Java program to calculate sum of lengths of subarrays// of distinct elements.import java.util.*; class geeks{ // Returns sum of lengths of all subarrays // with distinct elements. public static int sumoflength(int[] arr, int n) { // For maintaining distinct elements. Set<Integer> s = new HashSet<>(); // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i = 0; i < n; i++) { while (j < n && !s.contains(arr[j])) { s.add(arr[j]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) / 2; // Remove arr[i] as we pick new starting point // from next s.remove(arr[i]); } return ans; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(sumoflength(arr, n)); }} // This code is contributed by// sanjeev2552
# Python 3 program to calculate sum of# lengths of subarrays of distinct elements. # Returns sum of lengths of all subarrays# with distinct elements.def sumoflength(arr, n): # For maintaining distinct elements. s = [] # Initialize ending point and result j = 0 ans = 0 # Fix starting point for i in range(n): # Find ending point for current # subarray with distinct elements. while (j < n and (arr[j] not in s)): s.append(arr[j]) j += 1 # Calculating and adding all possible # length subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) // 2 # Remove arr[i] as we pick new # starting point from next s.remove(arr[i]) return ans # Driven Codeif __name__=="__main__": arr = [1, 2, 3, 4] n = len(arr) print(sumoflength(arr, n)) # This code is contributed by ita_c
// C# program to calculate sum of lengths of subarrays// of distinct elementsusing System;using System.Collections.Generic; public class geeks{ // Returns sum of lengths of all subarrays // with distinct elements. public static int sumoflength(int[] arr, int n) { // For maintaining distinct elements. HashSet<int> s = new HashSet<int>(); // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i = 0; i < n; i++) { while (j < n && !s.Contains(arr[j])) { s.Add(arr[i]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) / 2; // Remove arr[i] as we pick new starting point // from next s.Remove(arr[i]); } return ans; } // Driver Code public static void Main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.WriteLine(sumoflength(arr, n)); }} /* This code is contributed by PrinciRaj1992 */
<script> // Javascript program to calculate sum of lengths of subarrays// of distinct elements. // Returns sum of lengths of all subarrays // with distinct elements. function sumoflength(arr,n) { // For maintaining distinct elements. let s=new Set(); // Initialize ending point and result let j = 0, ans = 0; // Fix starting point for (let i = 0; i < n; i++) { while (j < n && !s.has(arr[j])) { s.add(arr[i]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += Math.floor(((j - i) * (j - i + 1)) / 2); // Remove arr[i] as we pick new starting point // from next s.delete(arr[i]); } return ans; } // Driver Code let arr=[1, 2, 3, 4]; let n = arr.length; document.write(sumoflength(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
20
Time Complexity of this solution is O(n). Note that the inner loop runs n times in total as j goes from 0 to n across all outer loops. So we do O(2n) operations which is same as O(n).Space Complexity: O(n), since n extra space has been added
This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
ukasp
sanjeev2552
princiraj1992
avanitrachhadiya2155
simmytarika5
rohitmishra051000
hardikkoriintern
rishavpgl4
subarray
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 166,
"s": 52,
"text": "Given an array, the task is to calculate the sum of lengths of contiguous subarrays having all elements distinct."
},
{
"code": null,
"e": 177,
"s": 166,
"text": "Examples: "
},
{
"code": null,
"e": 643,
"s": 177,
"text": "Input : arr[] = {1, 2, 3}\nOutput : 10\n{1, 2, 3} is a subarray of length 3 with \ndistinct elements. Total length of length\nthree = 3.\n{1, 2}, {2, 3} are 2 subarray of length 2 \nwith distinct elements. Total length of \nlengths two = 2 + 2 = 4\n{1}, {2}, {3} are 3 subarrays of length 1\nwith distinct element. Total lengths of \nlength one = 1 + 1 + 1 = 3\nSum of lengths = 3 + 4 + 3 = 10\n\nInput : arr[] = {1, 2, 1}\nOutput : 7\n\nInput : arr[] = {1, 2, 3, 4}\nOutput : 20"
},
{
"code": null,
"e": 988,
"s": 643,
"text": "A simple solution is to consider all subarrays and for every subarray check if it has distinct elements or not using hashing. And add lengths of all subarrays having distinct elements. If we use hashing to find distinct elements, then this approach takes O(n2) time under the assumption that hashing search and insert operations take O(1) time."
},
{
"code": null,
"e": 1305,
"s": 988,
"text": "An efficient solution is based on the fact that if we know all elements in a subarray arr[i..j] are distinct, sum of all lengths of distinct element subarrays in this sub array is ((j-i+1)*(j-i+2))/2. How? the possible lengths of subarrays are 1, 2, 3,......, j – i +1. So, the sum will be ((j – i +1)*(j – i +2))/2."
},
{
"code": null,
"e": 1658,
"s": 1305,
"text": "We first find largest subarray (with distinct elements) starting from first element. We count sum of lengths in this subarray using above formula. For finding next subarray of the distinct element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If not possible, then we increment i again and move forward the same way."
},
{
"code": null,
"e": 1704,
"s": 1658,
"text": "Below is the implementation of this approach:"
},
{
"code": null,
"e": 1708,
"s": 1704,
"text": "C++"
},
{
"code": null,
"e": 1713,
"s": 1708,
"text": "Java"
},
{
"code": null,
"e": 1722,
"s": 1713,
"text": "Python 3"
},
{
"code": null,
"e": 1725,
"s": 1722,
"text": "C#"
},
{
"code": null,
"e": 1736,
"s": 1725,
"text": "Javascript"
},
{
"code": "// C++ program to calculate sum of lengths of subarrays// of distinct elements.#include<bits/stdc++.h>using namespace std; // Returns sum of lengths of all subarrays with distinct// elements.int sumoflength(int arr[], int n){ // For maintaining distinct elements. unordered_set<int> s; // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i=0; i<n; i++) { // Find ending point for current subarray with // distinct elements. while (j < n && s.find(arr[j]) == s.end()) { s.insert(arr[j]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1))/2; // Remove arr[i] as we pick new starting point // from next s.erase(arr[i]); } return ans;} // Driven Codeint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << sumoflength(arr, n) << endl; return 0;}",
"e": 2744,
"s": 1736,
"text": null
},
{
"code": "// Java program to calculate sum of lengths of subarrays// of distinct elements.import java.util.*; class geeks{ // Returns sum of lengths of all subarrays // with distinct elements. public static int sumoflength(int[] arr, int n) { // For maintaining distinct elements. Set<Integer> s = new HashSet<>(); // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i = 0; i < n; i++) { while (j < n && !s.contains(arr[j])) { s.add(arr[j]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) / 2; // Remove arr[i] as we pick new starting point // from next s.remove(arr[i]); } return ans; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(sumoflength(arr, n)); }} // This code is contributed by// sanjeev2552",
"e": 3864,
"s": 2744,
"text": null
},
{
"code": "# Python 3 program to calculate sum of# lengths of subarrays of distinct elements. # Returns sum of lengths of all subarrays# with distinct elements.def sumoflength(arr, n): # For maintaining distinct elements. s = [] # Initialize ending point and result j = 0 ans = 0 # Fix starting point for i in range(n): # Find ending point for current # subarray with distinct elements. while (j < n and (arr[j] not in s)): s.append(arr[j]) j += 1 # Calculating and adding all possible # length subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) // 2 # Remove arr[i] as we pick new # starting point from next s.remove(arr[i]) return ans # Driven Codeif __name__==\"__main__\": arr = [1, 2, 3, 4] n = len(arr) print(sumoflength(arr, n)) # This code is contributed by ita_c",
"e": 4764,
"s": 3864,
"text": null
},
{
"code": "// C# program to calculate sum of lengths of subarrays// of distinct elementsusing System;using System.Collections.Generic; public class geeks{ // Returns sum of lengths of all subarrays // with distinct elements. public static int sumoflength(int[] arr, int n) { // For maintaining distinct elements. HashSet<int> s = new HashSet<int>(); // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i = 0; i < n; i++) { while (j < n && !s.Contains(arr[j])) { s.Add(arr[i]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1)) / 2; // Remove arr[i] as we pick new starting point // from next s.Remove(arr[i]); } return ans; } // Driver Code public static void Main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.WriteLine(sumoflength(arr, n)); }} /* This code is contributed by PrinciRaj1992 */",
"e": 5924,
"s": 4764,
"text": null
},
{
"code": "<script> // Javascript program to calculate sum of lengths of subarrays// of distinct elements. // Returns sum of lengths of all subarrays // with distinct elements. function sumoflength(arr,n) { // For maintaining distinct elements. let s=new Set(); // Initialize ending point and result let j = 0, ans = 0; // Fix starting point for (let i = 0; i < n; i++) { while (j < n && !s.has(arr[j])) { s.add(arr[i]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += Math.floor(((j - i) * (j - i + 1)) / 2); // Remove arr[i] as we pick new starting point // from next s.delete(arr[i]); } return ans; } // Driver Code let arr=[1, 2, 3, 4]; let n = arr.length; document.write(sumoflength(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 6964,
"s": 5924,
"text": null
},
{
"code": null,
"e": 6973,
"s": 6964,
"text": "Output: "
},
{
"code": null,
"e": 6976,
"s": 6973,
"text": "20"
},
{
"code": null,
"e": 7218,
"s": 6976,
"text": "Time Complexity of this solution is O(n). Note that the inner loop runs n times in total as j goes from 0 to n across all outer loops. So we do O(2n) operations which is same as O(n).Space Complexity: O(n), since n extra space has been added"
},
{
"code": null,
"e": 7525,
"s": 7218,
"text": "This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 7531,
"s": 7525,
"text": "ukasp"
},
{
"code": null,
"e": 7543,
"s": 7531,
"text": "sanjeev2552"
},
{
"code": null,
"e": 7557,
"s": 7543,
"text": "princiraj1992"
},
{
"code": null,
"e": 7578,
"s": 7557,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7591,
"s": 7578,
"text": "simmytarika5"
},
{
"code": null,
"e": 7609,
"s": 7591,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 7626,
"s": 7609,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7637,
"s": 7626,
"text": "rishavpgl4"
},
{
"code": null,
"e": 7646,
"s": 7637,
"text": "subarray"
},
{
"code": null,
"e": 7653,
"s": 7646,
"text": "Arrays"
},
{
"code": null,
"e": 7658,
"s": 7653,
"text": "Hash"
},
{
"code": null,
"e": 7665,
"s": 7658,
"text": "Arrays"
},
{
"code": null,
"e": 7670,
"s": 7665,
"text": "Hash"
}
] |
Zeller’s Congruence | Find the Day for a Date | 14 Mar, 2022
Zeller’s congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any Julian or Gregorian calendar date. It can be considered to be based on the conversion between Julian day and the calendar date. It is an algorithm to find the day of the week for any date. For the Gregorian calendar it is: For the Julian calendar it is: where,
h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday)q is the day of the monthm is the month (3 = March, 4 = April, 5 = May, ..., 14 = February)K is the year of the century (year % 100).J is the zero-based century (actually ⌊ year/100 ⌋) For example, the zero-based centuries for 1995 and 2000 are 19 and 20 respectively (to not be confused with the common ordinal century enumeration which indicates 20th for both cases).
h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday)
q is the day of the month
m is the month (3 = March, 4 = April, 5 = May, ..., 14 = February)
K is the year of the century (year % 100).
J is the zero-based century (actually ⌊ year/100 ⌋) For example, the zero-based centuries for 1995 and 2000 are 19 and 20 respectively (to not be confused with the common ordinal century enumeration which indicates 20th for both cases).
NOTE: In this algorithm January and February are
counted as months 13 and 14 of the previous
year.E.g. if it is 2 February 2010, the
algorithm counts the date as the second day
of the fourteenth month of 2009 (02/14/2009
in DD/MM/YYYY format)
For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use
d = ((h+5)%7) + 1
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Find the Day// for a Date#include <cmath>#include <cstring>#include <iostream>using namespace std; int Zellercongruence(int day, int month, int year){ if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0: cout << "Saturday \n"; break; case 1: cout << "Sunday \n"; break; case 2: cout << "Monday \n"; break; case 3: cout << "Tuesday \n"; break; case 4: cout << "Wednesday \n"; break; case 5: cout << "Thursday \n"; break; case 6: cout << "Friday \n"; break; } return 0;} // Driver codeint main(){ Zellercongruence(22, 10, 2017); // date (dd/mm/yyyy) return 0;}
// Java program to Find the Day// for a Dateimport java.util.*; class GFG{ // Print Day for a Date static void Zellercongruence(int day, int month, int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : System.out.println("Saturday"); break; case 1 : System.out.println("Sunday"); break; case 2 : System.out.println("Monday"); break; case 3 : System.out.println("Tuesday"); break; case 4 : System.out.println("Wednesday"); break; case 5 : System.out.println("Thursday"); break; case 6 : System.out.println("Friday"); break; } } // Driver code public static void main(String[] args) { Zellercongruence(22, 10, 2017); //date (dd/mm/yyyy) }} /* This code is contributed by Mr. Somesh Awasthi */
# Python3 program to Find the Day# for a Date def switch(h) : return { 0 : "Saturday", 1 : "Sunday", 2 : "Monday", 3 : "Tuesday", 4 : "Wednesday", 5 : "Thursday", 6 : "Friday", }[h] def Zellercongruence(day, month, year) : if (month == 1) : month = 13 year = year - 1 if (month == 2) : month = 14 year = year - 1 q = day m = month k = year % 100; j = year // 100; h = q + 13 * (m + 1) // 5 + k + k // 4 + j // 4 + 5 * j h = h % 7 print(switch (h)) # Driver codeZellercongruence(22, 10, 2017) #date (dd/mm/yyyy) # This code is contributed by Nikita Tiwari
// C# program to Find the Day// for a Dateusing System; class GFG { // Print Day for a Date static void Zellercongruence(int day, int month, int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : Console.WriteLine("Saturday"); break; case 1 : Console.WriteLine("Sunday"); break; case 2 : Console.WriteLine("Monday"); break; case 3 : Console.WriteLine("Tuesday"); break; case 4 : Console.WriteLine("Wednesday"); break; case 5 : Console.WriteLine("Thursday"); break; case 6 : Console.WriteLine("Friday"); break; } } // Driver code public static void Main() { //date (dd/mm/yyyy) Zellercongruence(22, 10, 2017); }} /* This code is contributed by vt_m */
<?php// PHP program to Find the Day// for a Date function Zellercongruence($day, $month, $year){ if ($month == 1) { $month = 13; $year--; } if ($month == 2) { $month = 14; $year--; } $q = $day; $m = $month; $k = $year % 100; $j = $year / 100; $h = $q + 13*($m + 1) / 5 + $k + $k / 4 + $j / 4 + 5 * $j; $h = $h % 7; switch ($h) { case 1 : echo "Saturday \n"; break; case 2 : echo "Sunday \n"; break; case 3 : echo "Monday \n"; break; case 4 : echo "Tuesday \n"; break; case 5 : echo "Wednesday \n"; break; case 6 : echo "Thursday \n"; break; case 7 : echo "Friday \n"; break; }} // Driver code//date (dd/mm/yyyy)Zellercongruence(22, 10, 2017); // This code is contributed by ajit.?>
<script> // Javascript program to Find the Day for a Date // Print Day for a Date function Zellercongruence(day, month, year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } let q = day; let m = month; let k = year % 100; let j = parseInt(year / 100, 10); let h = q + parseInt(13 * (m + 1) / 5, 10) + k + parseInt(k / 4, 10) + parseInt(j / 4, 10) + 5 * j; h = h % 7; switch (h) { case 0 : document.write("Saturday"); break; case 1 : document.write("Sunday"); break; case 2 : document.write("Monday"); break; case 3 : document.write("Tuesday"); break; case 4 : document.write("Wednesday"); break; case 5 : document.write("Thursday"); break; case 6 : document.write("Friday"); break; } } //date (dd/mm/yyyy) Zellercongruence(22, 10, 2017); </script>
Output:
Sunday
This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
18bhupenderyadav18
decode2207
simmytarika5
date-time-program
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Merge two sorted arrays with O(1) extra space | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 421,
"s": 54,
"text": "Zeller’s congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any Julian or Gregorian calendar date. It can be considered to be based on the conversion between Julian day and the calendar date. It is an algorithm to find the day of the week for any date. For the Gregorian calendar it is: For the Julian calendar it is: where, "
},
{
"code": null,
"e": 871,
"s": 421,
"text": "h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday)q is the day of the monthm is the month (3 = March, 4 = April, 5 = May, ..., 14 = February)K is the year of the century (year % 100).J is the zero-based century (actually ⌊ year/100 ⌋) For example, the zero-based centuries for 1995 and 2000 are 19 and 20 respectively (to not be confused with the common ordinal century enumeration which indicates 20th for both cases)."
},
{
"code": null,
"e": 952,
"s": 871,
"text": "h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday)"
},
{
"code": null,
"e": 978,
"s": 952,
"text": "q is the day of the month"
},
{
"code": null,
"e": 1045,
"s": 978,
"text": "m is the month (3 = March, 4 = April, 5 = May, ..., 14 = February)"
},
{
"code": null,
"e": 1088,
"s": 1045,
"text": "K is the year of the century (year % 100)."
},
{
"code": null,
"e": 1325,
"s": 1088,
"text": "J is the zero-based century (actually ⌊ year/100 ⌋) For example, the zero-based centuries for 1995 and 2000 are 19 and 20 respectively (to not be confused with the common ordinal century enumeration which indicates 20th for both cases)."
},
{
"code": null,
"e": 1601,
"s": 1325,
"text": "NOTE: In this algorithm January and February are\n counted as months 13 and 14 of the previous\n year.E.g. if it is 2 February 2010, the \n algorithm counts the date as the second day \n of the fourteenth month of 2009 (02/14/2009 \n in DD/MM/YYYY format)"
},
{
"code": null,
"e": 1670,
"s": 1601,
"text": "For an ISO week date Day-of-Week d (1 = Monday to 7 = Sunday), use "
},
{
"code": null,
"e": 1690,
"s": 1670,
"text": " d = ((h+5)%7) + 1 "
},
{
"code": null,
"e": 1694,
"s": 1690,
"text": "C++"
},
{
"code": null,
"e": 1699,
"s": 1694,
"text": "Java"
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Python3"
},
{
"code": null,
"e": 1710,
"s": 1707,
"text": "C#"
},
{
"code": null,
"e": 1714,
"s": 1710,
"text": "PHP"
},
{
"code": null,
"e": 1725,
"s": 1714,
"text": "Javascript"
},
{
"code": "// C++ program to Find the Day// for a Date#include <cmath>#include <cstring>#include <iostream>using namespace std; int Zellercongruence(int day, int month, int year){ if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0: cout << \"Saturday \\n\"; break; case 1: cout << \"Sunday \\n\"; break; case 2: cout << \"Monday \\n\"; break; case 3: cout << \"Tuesday \\n\"; break; case 4: cout << \"Wednesday \\n\"; break; case 5: cout << \"Thursday \\n\"; break; case 6: cout << \"Friday \\n\"; break; } return 0;} // Driver codeint main(){ Zellercongruence(22, 10, 2017); // date (dd/mm/yyyy) return 0;}",
"e": 2715,
"s": 1725,
"text": null
},
{
"code": "// Java program to Find the Day// for a Dateimport java.util.*; class GFG{ // Print Day for a Date static void Zellercongruence(int day, int month, int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : System.out.println(\"Saturday\"); break; case 1 : System.out.println(\"Sunday\"); break; case 2 : System.out.println(\"Monday\"); break; case 3 : System.out.println(\"Tuesday\"); break; case 4 : System.out.println(\"Wednesday\"); break; case 5 : System.out.println(\"Thursday\"); break; case 6 : System.out.println(\"Friday\"); break; } } // Driver code public static void main(String[] args) { Zellercongruence(22, 10, 2017); //date (dd/mm/yyyy) }} /* This code is contributed by Mr. Somesh Awasthi */",
"e": 3896,
"s": 2715,
"text": null
},
{
"code": "# Python3 program to Find the Day# for a Date def switch(h) : return { 0 : \"Saturday\", 1 : \"Sunday\", 2 : \"Monday\", 3 : \"Tuesday\", 4 : \"Wednesday\", 5 : \"Thursday\", 6 : \"Friday\", }[h] def Zellercongruence(day, month, year) : if (month == 1) : month = 13 year = year - 1 if (month == 2) : month = 14 year = year - 1 q = day m = month k = year % 100; j = year // 100; h = q + 13 * (m + 1) // 5 + k + k // 4 + j // 4 + 5 * j h = h % 7 print(switch (h)) # Driver codeZellercongruence(22, 10, 2017) #date (dd/mm/yyyy) # This code is contributed by Nikita Tiwari",
"e": 4577,
"s": 3896,
"text": null
},
{
"code": "// C# program to Find the Day// for a Dateusing System; class GFG { // Print Day for a Date static void Zellercongruence(int day, int month, int year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : Console.WriteLine(\"Saturday\"); break; case 1 : Console.WriteLine(\"Sunday\"); break; case 2 : Console.WriteLine(\"Monday\"); break; case 3 : Console.WriteLine(\"Tuesday\"); break; case 4 : Console.WriteLine(\"Wednesday\"); break; case 5 : Console.WriteLine(\"Thursday\"); break; case 6 : Console.WriteLine(\"Friday\"); break; } } // Driver code public static void Main() { //date (dd/mm/yyyy) Zellercongruence(22, 10, 2017); }} /* This code is contributed by vt_m */",
"e": 6033,
"s": 4577,
"text": null
},
{
"code": "<?php// PHP program to Find the Day// for a Date function Zellercongruence($day, $month, $year){ if ($month == 1) { $month = 13; $year--; } if ($month == 2) { $month = 14; $year--; } $q = $day; $m = $month; $k = $year % 100; $j = $year / 100; $h = $q + 13*($m + 1) / 5 + $k + $k / 4 + $j / 4 + 5 * $j; $h = $h % 7; switch ($h) { case 1 : echo \"Saturday \\n\"; break; case 2 : echo \"Sunday \\n\"; break; case 3 : echo \"Monday \\n\"; break; case 4 : echo \"Tuesday \\n\"; break; case 5 : echo \"Wednesday \\n\"; break; case 6 : echo \"Thursday \\n\"; break; case 7 : echo \"Friday \\n\"; break; }} // Driver code//date (dd/mm/yyyy)Zellercongruence(22, 10, 2017); // This code is contributed by ajit.?>",
"e": 6934,
"s": 6033,
"text": null
},
{
"code": "<script> // Javascript program to Find the Day for a Date // Print Day for a Date function Zellercongruence(day, month, year) { if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } let q = day; let m = month; let k = year % 100; let j = parseInt(year / 100, 10); let h = q + parseInt(13 * (m + 1) / 5, 10) + k + parseInt(k / 4, 10) + parseInt(j / 4, 10) + 5 * j; h = h % 7; switch (h) { case 0 : document.write(\"Saturday\"); break; case 1 : document.write(\"Sunday\"); break; case 2 : document.write(\"Monday\"); break; case 3 : document.write(\"Tuesday\"); break; case 4 : document.write(\"Wednesday\"); break; case 5 : document.write(\"Thursday\"); break; case 6 : document.write(\"Friday\"); break; } } //date (dd/mm/yyyy) Zellercongruence(22, 10, 2017); </script>",
"e": 8323,
"s": 6934,
"text": null
},
{
"code": null,
"e": 8332,
"s": 8323,
"text": "Output: "
},
{
"code": null,
"e": 8339,
"s": 8332,
"text": "Sunday"
},
{
"code": null,
"e": 8774,
"s": 8339,
"text": "This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8780,
"s": 8774,
"text": "jit_t"
},
{
"code": null,
"e": 8799,
"s": 8780,
"text": "18bhupenderyadav18"
},
{
"code": null,
"e": 8810,
"s": 8799,
"text": "decode2207"
},
{
"code": null,
"e": 8823,
"s": 8810,
"text": "simmytarika5"
},
{
"code": null,
"e": 8841,
"s": 8823,
"text": "date-time-program"
},
{
"code": null,
"e": 8854,
"s": 8841,
"text": "Mathematical"
},
{
"code": null,
"e": 8867,
"s": 8854,
"text": "Mathematical"
},
{
"code": null,
"e": 8965,
"s": 8867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8989,
"s": 8965,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 9010,
"s": 8989,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9024,
"s": 9010,
"text": "Prime Numbers"
},
{
"code": null,
"e": 9061,
"s": 9024,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 9114,
"s": 9061,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9157,
"s": 9114,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 9189,
"s": 9157,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9232,
"s": 9189,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 9281,
"s": 9232,
"text": "Program to find sum of elements in a given array"
}
] |
How to change the Background Color of Text in C# Console | To change the background color of text in Console, use the Console.BackgroundColor
Property in C#.
Let us now see an example −
using System;
class Demo {
public static void Main (string[] args) {
Console.BackgroundColor = ConsoleColor.Blue;
Console.WriteLine("Background color changed = "+Console.BackgroundColor);
}
}
This will produce the following output − | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To change the background color of text in Console, use the Console.BackgroundColor\nProperty in C#."
},
{
"code": null,
"e": 1189,
"s": 1161,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1399,
"s": 1189,
"text": "using System;\nclass Demo {\n public static void Main (string[] args) {\n Console.BackgroundColor = ConsoleColor.Blue;\n Console.WriteLine(\"Background color changed = \"+Console.BackgroundColor);\n }\n}"
},
{
"code": null,
"e": 1440,
"s": 1399,
"text": "This will produce the following output −"
}
] |
SELU — Make FNNs Great Again (SNN) | by Elior Cohen | Towards Data Science | Last month I came across a recent article (published June 22nd, 2017) presenting a new concept called Self Normalizing Networks (SNN).In this post I will review what’s different about them and show some comparisons.Link to the article —Klambauer et al.Code for this post is taken from bioinf-jku’s github.
Before we get into what are SNN lets speak about the motivation to create them.Right in the abstract of the article the writer mentions a good point; while neural networks are gaining success at many domains it seems like the main stage belongs to convolution networks and recurrent networks (LSTM, GRU) while the feed forward neural networks (FNNs) are left behind in the beginner tutorial sections.Also noted is that the FNNs that did manage to get winning results at Kaggle were at most 4 layers deep.
When using very deep architectures, networks become prone to gradient issues which is exactly why batch normalization came to be standard — this is where the writer puts FNNs weak link, in its sensitivity to normalization in training.SNNs are a way to instead use external normalization techniques (like batch norm), the normalization occurs inside the activation function.To make it clear, instead of normalizing the output of the activation function — the activation function suggested (SELU — scaled exponential linear units) outputs normalized values.For SNNs to work, they need two things, a custom weight initialization method and the SELU activation function.
Before we explain it, lets take a look what it’s all about.
SELU is some kind of ELU but with a little twist.α and λ are two fixed parameters, meaning we don’t backpropagate through them and they are not hyperparameters to make decisions about.α and λ are derived from the inputs — I will not go into this, but you can see the math for yourself in the article (which has 93 pages appendix :O, for math).For standard scaled inputs (mean 0, stddev 1), the values are α=1.6732~, λ=1.0507~.Lets plot and see what it looks like for these values.
Looks pretty similar to leaky ReLU, but wait to see its magic.
SELU can’t make it work alone, so a custom weight initialization technique is being used.SNNs initialize weights with zero mean and use standard deviation of the squared root of 1/(size of input).In code this looks as follows (taken from the github mentioned in the opening)
# Standard layertf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=np.sqrt(1 / n_input))# Convolution layertf.Variable(tf.random_normal([5, 5, 1, 32], stddev=np.sqrt(1/25)))
So now that we understand the initialization and activation methods, lets put it to work.
Lets examine how SNNs, using the specified initialization and the SELU activation function, does on the MNIST and CIFAR-10 datasets.First lets see if it really does keep the outputs normalized, using TensorBoard, on a 2 layer SNN (both hidden layers, are of 784 nodes, MNIST).Plotting the activation function outputs of layer 1, and the weights of layer 2.The plotting of layer1_act is not present in the github code, I added it for the sake of this histogram.
Keeps up to the expectations, both the activations of the first and the resulting weights on the second layer are almost perfect zero mean (I got 0.000201 on my run).Trust me that the histogram is pretty much the same on the first layers weights.
More important, SNNs seem to be able to perform better, as you can see from the plots taken from the mentioned github, comparing 3 convolutional networks with identical architecture only different by their activation function and initialization.SELU vs ELU vs ReLU.
Seems like SELU converges better and gets better accuracy on the test set.
Notice that using SELU + the mentioned initialization we got improved accuracy and faster convergence on a CNN network — so don’t hesitate to try it on architectures that are not pure FNNs as it seems to be able to boost performance in other architectures as well.
It does seem like SNNs can find their place in the world of neural networks, maybe pushing a bit extra accuracy in a bit less time — but we’ll have to wait and see what result they’ll yield by themselves and more importantly incorporated into joint architectures (like the conv-snn above).Maybe we’ll meet them in competition winning architectures, who knows.
There are some things I didn’t go over here which are in the article, like the proposed “alpha dropout” which is a dropout technique that fits the SNNs’ concept which is also implemented in the mentioned github, so your’e more than welcome to go into that.
Whether SNNs are a thing or not I really can’t tell but they are another tool to add to your kit. Hope you enjoyed this reading and learnt something new :) | [
{
"code": null,
"e": 478,
"s": 172,
"text": "Last month I came across a recent article (published June 22nd, 2017) presenting a new concept called Self Normalizing Networks (SNN).In this post I will review what’s different about them and show some comparisons.Link to the article —Klambauer et al.Code for this post is taken from bioinf-jku’s github."
},
{
"code": null,
"e": 983,
"s": 478,
"text": "Before we get into what are SNN lets speak about the motivation to create them.Right in the abstract of the article the writer mentions a good point; while neural networks are gaining success at many domains it seems like the main stage belongs to convolution networks and recurrent networks (LSTM, GRU) while the feed forward neural networks (FNNs) are left behind in the beginner tutorial sections.Also noted is that the FNNs that did manage to get winning results at Kaggle were at most 4 layers deep."
},
{
"code": null,
"e": 1650,
"s": 983,
"text": "When using very deep architectures, networks become prone to gradient issues which is exactly why batch normalization came to be standard — this is where the writer puts FNNs weak link, in its sensitivity to normalization in training.SNNs are a way to instead use external normalization techniques (like batch norm), the normalization occurs inside the activation function.To make it clear, instead of normalizing the output of the activation function — the activation function suggested (SELU — scaled exponential linear units) outputs normalized values.For SNNs to work, they need two things, a custom weight initialization method and the SELU activation function."
},
{
"code": null,
"e": 1710,
"s": 1650,
"text": "Before we explain it, lets take a look what it’s all about."
},
{
"code": null,
"e": 2191,
"s": 1710,
"text": "SELU is some kind of ELU but with a little twist.α and λ are two fixed parameters, meaning we don’t backpropagate through them and they are not hyperparameters to make decisions about.α and λ are derived from the inputs — I will not go into this, but you can see the math for yourself in the article (which has 93 pages appendix :O, for math).For standard scaled inputs (mean 0, stddev 1), the values are α=1.6732~, λ=1.0507~.Lets plot and see what it looks like for these values."
},
{
"code": null,
"e": 2254,
"s": 2191,
"text": "Looks pretty similar to leaky ReLU, but wait to see its magic."
},
{
"code": null,
"e": 2529,
"s": 2254,
"text": "SELU can’t make it work alone, so a custom weight initialization technique is being used.SNNs initialize weights with zero mean and use standard deviation of the squared root of 1/(size of input).In code this looks as follows (taken from the github mentioned in the opening)"
},
{
"code": null,
"e": 2711,
"s": 2529,
"text": "# Standard layertf.Variable(tf.random_normal([n_input, n_hidden_1], stddev=np.sqrt(1 / n_input))# Convolution layertf.Variable(tf.random_normal([5, 5, 1, 32], stddev=np.sqrt(1/25)))"
},
{
"code": null,
"e": 2801,
"s": 2711,
"text": "So now that we understand the initialization and activation methods, lets put it to work."
},
{
"code": null,
"e": 3262,
"s": 2801,
"text": "Lets examine how SNNs, using the specified initialization and the SELU activation function, does on the MNIST and CIFAR-10 datasets.First lets see if it really does keep the outputs normalized, using TensorBoard, on a 2 layer SNN (both hidden layers, are of 784 nodes, MNIST).Plotting the activation function outputs of layer 1, and the weights of layer 2.The plotting of layer1_act is not present in the github code, I added it for the sake of this histogram."
},
{
"code": null,
"e": 3509,
"s": 3262,
"text": "Keeps up to the expectations, both the activations of the first and the resulting weights on the second layer are almost perfect zero mean (I got 0.000201 on my run).Trust me that the histogram is pretty much the same on the first layers weights."
},
{
"code": null,
"e": 3775,
"s": 3509,
"text": "More important, SNNs seem to be able to perform better, as you can see from the plots taken from the mentioned github, comparing 3 convolutional networks with identical architecture only different by their activation function and initialization.SELU vs ELU vs ReLU."
},
{
"code": null,
"e": 3850,
"s": 3775,
"text": "Seems like SELU converges better and gets better accuracy on the test set."
},
{
"code": null,
"e": 4115,
"s": 3850,
"text": "Notice that using SELU + the mentioned initialization we got improved accuracy and faster convergence on a CNN network — so don’t hesitate to try it on architectures that are not pure FNNs as it seems to be able to boost performance in other architectures as well."
},
{
"code": null,
"e": 4475,
"s": 4115,
"text": "It does seem like SNNs can find their place in the world of neural networks, maybe pushing a bit extra accuracy in a bit less time — but we’ll have to wait and see what result they’ll yield by themselves and more importantly incorporated into joint architectures (like the conv-snn above).Maybe we’ll meet them in competition winning architectures, who knows."
},
{
"code": null,
"e": 4732,
"s": 4475,
"text": "There are some things I didn’t go over here which are in the article, like the proposed “alpha dropout” which is a dropout technique that fits the SNNs’ concept which is also implemented in the mentioned github, so your’e more than welcome to go into that."
}
] |
Wikipedia Data Science: Working with the World’s Largest Encyclopedia | by Will Koehrsen | Towards Data Science | Wikipedia is one of modern humanity’s most impressive creations. Who would have thought that in just a few years, anonymous contributors working for free could create the greatest source of online knowledge the world has ever seen? Not only is Wikipedia the best place to get information for writing your college papers, but it’s also an extremely rich source of data that can fuel numerous data science projects from natural language processing to supervised machine learning.
The size of Wikipedia makes it both the world’s largest encyclopedia and slightly intimidating to work with. However, size is not an issue with the right tools, and in this article, we’ll walk through how we can programmatically download and parse through all of the English language Wikipedia.
Along the way, we’ll cover a number of useful topics in data science:
Finding and programmatically downloading data from the webParsing web data (HTML, XML, MediaWiki) using Python librariesRunning operations in parallel with multiprocessing/multithreadingBenchmarking methods to find the optimal solution to a problem
Finding and programmatically downloading data from the web
Parsing web data (HTML, XML, MediaWiki) using Python libraries
Running operations in parallel with multiprocessing/multithreading
Benchmarking methods to find the optimal solution to a problem
The original impetus for this project was to collect information on every single book on Wikipedia, but I soon realized the solutions involved were more broadly applicable. The techniques covered here and presented in the accompanying Jupyter Notebook will let you efficiently work with any articles on Wikipedia and can be extended to other sources of web data.
If you’d like to see more about utilizing the data in this article, I wrote a post using neural network embeddings to build a book recommendation system.
The notebook containing the Python code for this article is available on GitHub. This project was inspired by the excellent Deep Learning Cookbook by Douwe Osinga and much of the code is adapted from the book. The book is well worth it and you can access the Jupyter Notebooks at no cost on GitHub.
The first step in any data science project is accessing your data! While we could make individual requests to Wikipedia pages and scrape the results, we’d quickly run into rate limits and unnecessarily tax Wikipedia’s servers. Instead, we can access a dump of all of Wikipedia through Wikimedia at dumps.wikimedia.org. (A dump refers to a periodic snapshot of a database).
The English version is at dumps.wikimedia.org/enwiki. We view the available versions of the database using the following code.
import requests# Library for parsing HTMLfrom bs4 import BeautifulSoupbase_url = 'https://dumps.wikimedia.org/enwiki/'index = requests.get(base_url).textsoup_index = BeautifulSoup(index, 'html.parser')# Find the links on the pagedumps = [a['href'] for a in soup_index.find_all('a') if a.has_attr('href')]dumps['../', '20180620/', '20180701/', '20180720/', '20180801/', '20180820/', '20180901/', '20180920/', 'latest/']
This code makes use of the BeautifulSoup library for parsing HTML. Given that HTML is the standard markup language for web pages, this is an invaluable library for working with web data.
For this project, we’ll take the dump on September 1, 2018 (some of the dumps are incomplete so make sure to choose one with the data you need). To find all the available files in the dump, we use the following code:
dump_url = base_url + '20180901/'# Retrieve the htmldump_html = requests.get(dump_url).text# Convert to a soupsoup_dump = BeautifulSoup(dump_html, 'html.parser')# Find list elements with the class filesoup_dump.find_all('li', {'class': 'file'})[:3][<li class="file"><a href="/enwiki/20180901/enwiki-20180901-pages-articles-multistream.xml.bz2">enwiki-20180901-pages-articles-multistream.xml.bz2</a> 15.2 GB</li>, <li class="file"><a href="/enwiki/20180901/enwiki-20180901-pages-articles-multistream-index.txt.bz2">enwiki-20180901-pages-articles-multistream-index.txt.bz2</a> 195.6 MB</li>, <li class="file"><a href="/enwiki/20180901/enwiki-20180901-pages-meta-history1.xml-p10p2101.7z">enwiki-20180901-pages-meta-history1.xml-p10p2101.7z</a> 320.6 MB</li>]
Again, we parse the webpage using BeautifulSoup to find the files. We could go to https://dumps.wikimedia.org/enwiki/20180901/ and look for the files to download manually, but that would be inefficient. Knowing how to parse HTML and interact with websites in a program is an extremely useful skill considering how much data is on the web. Learn a little web scraping and vast new data sources become accessible. (Here’s a tutorial to get you started).
The above code finds all of the files in the dump. This includes several options for download: the current version of only the articles, the articles along with the current discussion, or the articles along with all past edits and discussion. If we go with the latter option, we are looking at several terabytes of data! For this project, we’ll stick to the most recent version of only the articles. This page is useful for determining which files to get given your needs.
The current version of all the articles is available as a single file. However, if we get the single file, then when we parse it, we’ll be stuck going through all the articles sequentially — one at a time — a very inefficient approach. A better option is to download partitioned files, each of which contains a subset of the articles. Then, as we’ll see, we can parse through multiple files at a time through parallelization, speeding up the process significantly.
When I’m dealing with files, I would rather have many small files than one large file because then I can parallelize operations on the files.
The partitioned files are available as bz2-compressed XML (eXtended Markup Language). Each partition is around 300–400 MB in size with a total compressed size of 15.4 GB. We won’t need to decompress the files, but if you choose to do so, the entire size is around 58 GB. This actually doesn’t seem too large for all of human knowledge! (Okay, not all knowledge, but still).
To actually download the files, the Keras utility get_file is extremely useful. This downloads a file at a link and saves it to disk.
from keras.utils import get_filesaved_file_path = get_file(file, url)
The files are saved in ~/.keras/datasets/, the default save location for Keras. Downloading all of the files one at a time takes a little over 2 hours. (You can try to download in parallel, but I ran into rate limits when I tried to make multiple requests at the same time.)
It might seem like the first thing we want to do is decompress the files. However, it turns out we won’t ever actually need to do this to access all the data in the articles! Instead, we can iteratively work with the files by decompressing and processing lines one at a time. Iterating through files is often the only option if we work with large datasets that do not fit in memory.
To iterate through a bz2 compressed file we could use the bz2 library. In testing though, I found that a faster option (by a factor of 2) is to call the system utility bzcat with the subprocess Python module. This illustrates a critical point: often, there are multiple solutions to a problem and the only way to find what is most efficient is to benchmark the options. This can be as simple as using the %%timeit Jupyter cell magic to time the methods.
For the complete details, see the notebook, but the basic format of iteratively decompressing a file is:
data_path = '~/.keras/datasets/enwiki-20180901-pages-articles15.xml-p7744803p9244803.bz2# Iterate through compressed file one line at a timefor line in subprocess.Popen(['bzcat'], stdin = open(data_path), stdout = subprocess.PIPE).stdout: # process line
If we simply read in the XML data and append it to a list, we get something that looks like this:
This shows the XML from a single Wikipedia article. The files we have downloaded contain millions of lines like this, with thousands of articles in each file. If we really wanted to make things difficult, we could go through this using regular expressions and string matching to find each article. Given this is extraordinarily inefficient, we’ll take a better approach using tools custom built for parsing both XML and Wikipedia-style articles.
We need to parse the files on two levels:
Extract the article titles and text from the XMLExtract relevant information from the article text
Extract the article titles and text from the XML
Extract relevant information from the article text
Fortunately, there are good options for both of these operations in Python.
To solve the first problem of locating articles, we’ll use the SAX parser, which is “The Simple API for XML.” BeautifulSoup can also be used for parsing XML, but this requires loading the entire file into memory and building a Document Object Model (DOM). SAX, on the other hand, processes XML one line at a time, which fits our approach perfectly.
The basic idea we need to execute is to search through the XML and extract the information between specific tags (If you need an introduction to XML, I’d recommend starting here). For example, given the XML below:
<title>Carroll F. Knicely</title><text xml:space="preserve">\'\'\'Carroll F. Knicely\'\'\' (born c. 1929 in [[Staunton, Virginia]] - died November 2, 2006 in [[Glasgow, Kentucky]]) was [[Editing|editor]] and [[Publishing|publisher]] of the \'\'[[Glasgow Daily Times]]\'\' for nearly 20 years (and later, its owner) and served under three [[Governor of Kentucky|Kentucky Governors]] as commissioner and later Commerce Secretary.\n'</text>
We want to select the content between the <title> and <text> tags. (The title is simply the Wikipedia page title and the text is the content of the article). SAX will let us do exactly this using a parser and a ContentHandler which controls how the information passed to the parser is handled. We pass the XML to the parser one line at a time and the Content Handler lets us extract the relevant information.
This is a little difficult to follow without trying it out yourself, but the idea is that the Content handler looks for certain start tags, and when it finds one, it adds characters to a buffer until it encounters the same end tag. Then it saves the buffer content to a dictionary with the tag as the key. The result is that we get a dictionary where the keys are the tags and the values are the content between the tags. We can then send this dictionary to another function that will parse the values in the dictionary.
The only part of SAX we need to write is the Content Handler. This is shown in its entirety below:
In this code, we are looking for the tags title and text . Every time the parser encounters one of these, it will save characters to the buffer until it encounters the same end tag (identified by </tag>). At this point it will save the buffer contents to a dictionary — self._values . Articles are separated by <page> tags, so if the content handler encounters an ending </page> tag, then it should add the self._values to the list of articles, self._pages. If this is a little confusing, then perhaps seeing it in action will help.
The code below shows how we use this to search through the XML file to find articles. For now we’re just saving them to the handler._pages attribute, but later we’ll send the articles to another function for parsing.
# Object for handling xmlhandler = WikiXmlHandler()# Parsing objectparser = xml.sax.make_parser()parser.setContentHandler(handler)# Iteratively process filefor line in subprocess.Popen(['bzcat'], stdin = open(data_path), stdout = subprocess.PIPE).stdout: parser.feed(line) # Stop when 3 articles have been found if len(handler._pages) > 2: break
If we inspect handler._pages , we’ll see a list, each element of which is a tuple with the title and text of one article:
handler._pages[0][('Carroll Knicely', "'''Carroll F. Knicely''' (born c. 1929 in [[Staunton, Virginia]] - died November 2, 2006 in [[Glasgow, Kentucky]]) was [[Editing|editor]] and [[Publishing|publisher]] ...)]
At this point we have written code that can successfully identify articles within the XML. This gets us halfway through the process of parsing the files and the next step is to process the articles themselves to find specific pages and information. Once again, we’ll turn to a tool purpose built for the task.
Wikipedia runs on a software for building wikis known as MediaWiki. This means that articles follow a standard format that makes programmatically accessing the information within them simple. While the text of an article may look like just a string, it encodes far more information due to the formatting. To efficiently get at this information, we bring in the powerful mwparserfromhell , a library built to work with MediaWiki content.
If we pass the text of a Wikipedia article to the mwparserfromhell , we get a Wikicode object which comes with many methods for sorting through the data. For example, the following code creates a wikicode object from an article (about KENZ FM) and retrieves the wikilinks() within the article. These are all of the links that point to other Wikipedia articles:
import mwparserfromhell# Create the wiki articlewiki = mwparserfromhell.parse(handler._pages[6][1])# Find the wikilinkswikilinks = [x.title for x in wiki.filter_wikilinks()]wikilinks[:5]['Provo, Utah', 'Wasatch Front', 'Megahertz', 'Contemporary hit radio', 'watt']
There are a number of useful methods that can be applied to the wikicode such as finding comments or searching for a specific keyword. If you want to get a clean version of the article text, then call:
wiki.strip_code().strip()'KENZ (94.9 FM, " Power 94.9 " ) is a top 40/CHR radio station broadcasting to Salt Lake City, Utah '
Since my ultimate goal was to find all the articles about books, the question arises if there is a way to use this parser to identify articles in a certain category? Fortunately, the answer is yes, using MediaWiki templates.
Templates are standard ways of recording information. There are numerous templates for everything on Wikipedia, but the most relevant for our purposes are Infoboxes . These are templates that encode summary information for an article. For instance, the infobox for War and Peace is:
Each category of articles on Wikipedia, such as films, books, or radio stations, has its own type of infobox. In the case of books, the infobox template is helpfully named Infobox book. Just as helpful, the wiki object has a method called filter_templates() that allows us to extract a specific template from an article. Therefore, if we want to know whether an article is about a book, we can filter it for the book infobox. This is shown below:
# Filter article for book templatewiki.filter_templates('Infobox book')
If there’s a match, then we’ve found a book! To find the Infobox template for the category of articles you are interested in, refer to the list of infoboxes.
How do we combine the mwparserfromhell for parsing articles with the SAX parser we wrote? Well, we modify the endElement method in the Content Handler to send the dictionary of values containing the title and text of an article to a function that searches the article text for specified template. If the function finds an article we want, it extracts information from the article and then returns it to the handler. First, I’ll show the updated endElement :
def endElement(self, name): """Closing tag of element""" if name == self._current_tag: self._values[name] = ' '.join(self._buffer) if name == 'page': self._article_count += 1 # Send the page to the process article function book = process_article(**self._values, template = 'Infobox book') # If article is a book append to the list of books if book: self._books.append(book)
Now, once the parser has hit the end of an article, we send the article on to the function process_article which is shown below:
Although I’m looking for books, this function can be used to search for any category of article on Wikipedia. Just replace the template with the template for the category (such as Infobox language to find languages) and it will only return the information from articles within the category.
We can test this function and the new ContentHandler on one file.
Searched through 427481 articles.Found 1426 books in 1055 seconds.
Let’s take a look at the output for one book:
books[10]['War and Peace', {'name': 'War and Peace', 'author': 'Leo Tolstoy', 'language': 'Russian, with some French', 'country': 'Russia', 'genre': 'Novel (Historical novel)', 'publisher': 'The Russian Messenger (serial)', 'title_orig': 'Война и миръ', 'orig_lang_code': 'ru', 'translator': 'The first translation of War and Peace into English was by American Nathan Haskell Dole, in 1899', 'image': 'Tolstoy - War and Peace - first edition, 1869.jpg', 'caption': 'Front page of War and Peace, first edition, 1869 (Russian)', 'release_date': 'Serialised 1865–1867; book 1869', 'media_type': 'Print', 'pages': '1,225 (first published edition)'}, ['Leo Tolstoy', 'Novel', 'Historical novel', 'The Russian Messenger', 'Serial (publishing)', 'Category:1869 Russian novels', 'Category:Epic novels', 'Category:Novels set in 19th-century Russia', 'Category:Russian novels adapted into films', 'Category:Russian philosophical novels'], ['https://books.google.com/?id=c4HEAN-ti1MC', 'https://www.britannica.com/art/English-literature', 'https://books.google.com/books?id=xf7umXHGDPcC', 'https://books.google.com/?id=E5fotqsglPEC', 'https://books.google.com/?id=9sHebfZIXFAC'], '2018-08-29T02:37:35Z']
For every single book on Wikipedia, we have the information from the Infobox as a dictionary, the internal wikilinks, the external links, and the timestamp of the most recent edit. (I’m concentrating on these pieces of information to build a book recommendation system for my next project). You can modify the process_article function and WikiXmlHandler class to find whatever information and articles you need!
If you look at the time to process just one file, 1055 seconds, and multiply that by 55, you get over 15 hours of processing time for all files! Granted, we could just run that overnight, but I’d rather not waste the extra time if I don’t have to. This brings us to our final technique we’ll cover in this project: parallelization using multiprocessing and multithreading.
Instead of parsing through the files one at a time, we want to process several of them at once (which is why we downloaded the partitions). We can do this using parallelization, either through multithreading or multiprocessing.
Multithreading and multiprocessing are ways to carry out many tasks on a computer — or multiple computers — simultaneously. We many files on disk, each of which needs to be parsed in the same way. A naive approach would be to parse one file at a time, but that is not taking full advantage of our resources. Instead, we use either multithreading or multiprocessing to parse many files at the same time, significantly speeding up the entire process.
Generally, multithreading works better (is faster) for input / output bound tasks, such as reading in files or making requests. Multiprocessing works better (is faster) for cpu-bound tasks (source). For the process of parsing articles, I wasn’t sure which method would be optimal, so again I benchmarked both of them with different parameters.
Learning how to set up tests and seek out different ways to solve a problem will get you far in a data science or any technical career.
(The code for testing multithreading and multiprocessing appears at the end of the notebook). When I ran the tests, I found multiprocessing was almost 10 times faster indicating this process is probably CPU bound (limited).
Learning multithreading / multiprocessing is essential for making your data science workflows more efficient. I’d recommend this article to get started with the concepts. (We’ll stick to the built-in multiprocessing library, but you can also using Dask for parallelization as in this project).
After running a number of tests, I found the fastest way to process the files was using 16 processes, one for each core of my computer. This means we can process 16 files at a time instead of 1! I’d encourage anyone to test out a few options for multiprocessing / multithreading and let me know the results! I’m still not sure I did things in the best way, and I’m always willing to learn.
To run an operation in parallel, we need a service and a set of tasks . A service is just a function and tasks are in an iterable — such as a list — each of which we send to the function. For the purpose of parsing the XML files, each task is one file, and the function will take in the file, find all the books, and save them to disk. The pseudo-code for the function is below:
def find_books(data_path, save = True): """Find and save all the book articles from a compressed wikipedia XML file. """ # Parse file for books if save: # Save all books to a file based on the data path name
The end result of running this function is a saved list of books from the file sent to the function. The files are saved as json, a machine readable format for writing nested information such as lists of lists and dictionaries. The tasks that we want to send to this function are all the compressed files.
# List of compressed files to processpartitions = [keras_home + file for file in os.listdir(keras_home) if 'xml-p' in file]len(partitions), partitions[-1](55, '/home/ubuntu/.keras/datasets/enwiki-20180901-pages-articles17.xml-p11539268p13039268.bz2')
For each file, we want to send it to find_books to be parsed.
The final code to search through every article on Wikipedia is below:
from multiprocessing import Pool# Create a pool of workers to execute processespool = Pool(processes = 16)# Map (service, tasks), applies function to each partitionresults = pool.map(find_books, partitions)pool.close()pool.join()
We map each task to the service, the function that finds the books (map refers to applying a function to each item in an iterable). Running with 16 processes in parallel, we can search all of Wikipedia in under 3 hours! After running the code, the books from each file are saved on disk in separate json files.
For practice writing parallelized code, we’ll read the separate files in with multiple processes, this time using threads. The multiprocessing.dummy library provides a wrapper around the threading module. This time the service is read_data and the tasks are the saved files on disk:
The multithreaded code works in the exact same way, mapping tasks in an iterable to function. Once we have the list of lists, we flatten it to a single list.
print(f'Found {len(book_list)} books.')Found 37861 books.
Wikipedia has nearly 38,000 articles on books according to our count. The size of the final json file with all the book information is only about 55 MB meaning we searched through over 50 GB (uncompressed) of total files to find 55 MB worth of books! Given that we are only keeping a limited subset of the book information, that makes sense.
We now have information on every single book on Wikipedia. You can use the same code to find articles for any category of your choosing, or modify the functions to search for different information. Using some fairly simple Python code, we are able to search through an incredible amount of information.
In this article, we saw how to download and parse the entire English language version of Wikipedia. Having a ton of data is not useful unless we can make sense of it, and so we developed a set of methods for efficiently processing all of the articles for the information we need for our projects.
Throughout this project, we covered a number of important topics:
Finding and downloading data programmaticallyParsing through data in an efficient mannerRunning operations in parallel to get the most from our hardwareSetting up and running benchmarking tests to find efficient solutions
Finding and downloading data programmatically
Parsing through data in an efficient manner
Running operations in parallel to get the most from our hardware
Setting up and running benchmarking tests to find efficient solutions
The skills developed in this project are well-suited to Wikipedia data but are also broadly applicable to any information from the web. I’d encourage you to apply these methods for your own projects or try analyzing a different category of articles. There’s plenty of information for everyone to do their own project! (I am working on making a book recommendation system with the Wikipedia articles using entity embeddings from neural networks.)
Wikipedia is an incredible source of human-curated information, and we now know how to use this monumental achievement by accessing and processing it programmatically. I look forward to writing about and doing more Wikipedia Data Science. In the meantime, the techniques presented here are broadly applicable so get out there and find a problem to solve!
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or on my personal website at willk.online.
Some rights reserved | [
{
"code": null,
"e": 650,
"s": 172,
"text": "Wikipedia is one of modern humanity’s most impressive creations. Who would have thought that in just a few years, anonymous contributors working for free could create the greatest source of online knowledge the world has ever seen? Not only is Wikipedia the best place to get information for writing your college papers, but it’s also an extremely rich source of data that can fuel numerous data science projects from natural language processing to supervised machine learning."
},
{
"code": null,
"e": 945,
"s": 650,
"text": "The size of Wikipedia makes it both the world’s largest encyclopedia and slightly intimidating to work with. However, size is not an issue with the right tools, and in this article, we’ll walk through how we can programmatically download and parse through all of the English language Wikipedia."
},
{
"code": null,
"e": 1015,
"s": 945,
"text": "Along the way, we’ll cover a number of useful topics in data science:"
},
{
"code": null,
"e": 1264,
"s": 1015,
"text": "Finding and programmatically downloading data from the webParsing web data (HTML, XML, MediaWiki) using Python librariesRunning operations in parallel with multiprocessing/multithreadingBenchmarking methods to find the optimal solution to a problem"
},
{
"code": null,
"e": 1323,
"s": 1264,
"text": "Finding and programmatically downloading data from the web"
},
{
"code": null,
"e": 1386,
"s": 1323,
"text": "Parsing web data (HTML, XML, MediaWiki) using Python libraries"
},
{
"code": null,
"e": 1453,
"s": 1386,
"text": "Running operations in parallel with multiprocessing/multithreading"
},
{
"code": null,
"e": 1516,
"s": 1453,
"text": "Benchmarking methods to find the optimal solution to a problem"
},
{
"code": null,
"e": 1879,
"s": 1516,
"text": "The original impetus for this project was to collect information on every single book on Wikipedia, but I soon realized the solutions involved were more broadly applicable. The techniques covered here and presented in the accompanying Jupyter Notebook will let you efficiently work with any articles on Wikipedia and can be extended to other sources of web data."
},
{
"code": null,
"e": 2033,
"s": 1879,
"text": "If you’d like to see more about utilizing the data in this article, I wrote a post using neural network embeddings to build a book recommendation system."
},
{
"code": null,
"e": 2332,
"s": 2033,
"text": "The notebook containing the Python code for this article is available on GitHub. This project was inspired by the excellent Deep Learning Cookbook by Douwe Osinga and much of the code is adapted from the book. The book is well worth it and you can access the Jupyter Notebooks at no cost on GitHub."
},
{
"code": null,
"e": 2705,
"s": 2332,
"text": "The first step in any data science project is accessing your data! While we could make individual requests to Wikipedia pages and scrape the results, we’d quickly run into rate limits and unnecessarily tax Wikipedia’s servers. Instead, we can access a dump of all of Wikipedia through Wikimedia at dumps.wikimedia.org. (A dump refers to a periodic snapshot of a database)."
},
{
"code": null,
"e": 2832,
"s": 2705,
"text": "The English version is at dumps.wikimedia.org/enwiki. We view the available versions of the database using the following code."
},
{
"code": null,
"e": 3260,
"s": 2832,
"text": "import requests# Library for parsing HTMLfrom bs4 import BeautifulSoupbase_url = 'https://dumps.wikimedia.org/enwiki/'index = requests.get(base_url).textsoup_index = BeautifulSoup(index, 'html.parser')# Find the links on the pagedumps = [a['href'] for a in soup_index.find_all('a') if a.has_attr('href')]dumps['../', '20180620/', '20180701/', '20180720/', '20180801/', '20180820/', '20180901/', '20180920/', 'latest/']"
},
{
"code": null,
"e": 3447,
"s": 3260,
"text": "This code makes use of the BeautifulSoup library for parsing HTML. Given that HTML is the standard markup language for web pages, this is an invaluable library for working with web data."
},
{
"code": null,
"e": 3664,
"s": 3447,
"text": "For this project, we’ll take the dump on September 1, 2018 (some of the dumps are incomplete so make sure to choose one with the data you need). To find all the available files in the dump, we use the following code:"
},
{
"code": null,
"e": 4421,
"s": 3664,
"text": "dump_url = base_url + '20180901/'# Retrieve the htmldump_html = requests.get(dump_url).text# Convert to a soupsoup_dump = BeautifulSoup(dump_html, 'html.parser')# Find list elements with the class filesoup_dump.find_all('li', {'class': 'file'})[:3][<li class=\"file\"><a href=\"/enwiki/20180901/enwiki-20180901-pages-articles-multistream.xml.bz2\">enwiki-20180901-pages-articles-multistream.xml.bz2</a> 15.2 GB</li>, <li class=\"file\"><a href=\"/enwiki/20180901/enwiki-20180901-pages-articles-multistream-index.txt.bz2\">enwiki-20180901-pages-articles-multistream-index.txt.bz2</a> 195.6 MB</li>, <li class=\"file\"><a href=\"/enwiki/20180901/enwiki-20180901-pages-meta-history1.xml-p10p2101.7z\">enwiki-20180901-pages-meta-history1.xml-p10p2101.7z</a> 320.6 MB</li>]"
},
{
"code": null,
"e": 4873,
"s": 4421,
"text": "Again, we parse the webpage using BeautifulSoup to find the files. We could go to https://dumps.wikimedia.org/enwiki/20180901/ and look for the files to download manually, but that would be inefficient. Knowing how to parse HTML and interact with websites in a program is an extremely useful skill considering how much data is on the web. Learn a little web scraping and vast new data sources become accessible. (Here’s a tutorial to get you started)."
},
{
"code": null,
"e": 5346,
"s": 4873,
"text": "The above code finds all of the files in the dump. This includes several options for download: the current version of only the articles, the articles along with the current discussion, or the articles along with all past edits and discussion. If we go with the latter option, we are looking at several terabytes of data! For this project, we’ll stick to the most recent version of only the articles. This page is useful for determining which files to get given your needs."
},
{
"code": null,
"e": 5811,
"s": 5346,
"text": "The current version of all the articles is available as a single file. However, if we get the single file, then when we parse it, we’ll be stuck going through all the articles sequentially — one at a time — a very inefficient approach. A better option is to download partitioned files, each of which contains a subset of the articles. Then, as we’ll see, we can parse through multiple files at a time through parallelization, speeding up the process significantly."
},
{
"code": null,
"e": 5953,
"s": 5811,
"text": "When I’m dealing with files, I would rather have many small files than one large file because then I can parallelize operations on the files."
},
{
"code": null,
"e": 6327,
"s": 5953,
"text": "The partitioned files are available as bz2-compressed XML (eXtended Markup Language). Each partition is around 300–400 MB in size with a total compressed size of 15.4 GB. We won’t need to decompress the files, but if you choose to do so, the entire size is around 58 GB. This actually doesn’t seem too large for all of human knowledge! (Okay, not all knowledge, but still)."
},
{
"code": null,
"e": 6461,
"s": 6327,
"text": "To actually download the files, the Keras utility get_file is extremely useful. This downloads a file at a link and saves it to disk."
},
{
"code": null,
"e": 6531,
"s": 6461,
"text": "from keras.utils import get_filesaved_file_path = get_file(file, url)"
},
{
"code": null,
"e": 6806,
"s": 6531,
"text": "The files are saved in ~/.keras/datasets/, the default save location for Keras. Downloading all of the files one at a time takes a little over 2 hours. (You can try to download in parallel, but I ran into rate limits when I tried to make multiple requests at the same time.)"
},
{
"code": null,
"e": 7189,
"s": 6806,
"text": "It might seem like the first thing we want to do is decompress the files. However, it turns out we won’t ever actually need to do this to access all the data in the articles! Instead, we can iteratively work with the files by decompressing and processing lines one at a time. Iterating through files is often the only option if we work with large datasets that do not fit in memory."
},
{
"code": null,
"e": 7643,
"s": 7189,
"text": "To iterate through a bz2 compressed file we could use the bz2 library. In testing though, I found that a faster option (by a factor of 2) is to call the system utility bzcat with the subprocess Python module. This illustrates a critical point: often, there are multiple solutions to a problem and the only way to find what is most efficient is to benchmark the options. This can be as simple as using the %%timeit Jupyter cell magic to time the methods."
},
{
"code": null,
"e": 7748,
"s": 7643,
"text": "For the complete details, see the notebook, but the basic format of iteratively decompressing a file is:"
},
{
"code": null,
"e": 8065,
"s": 7748,
"text": "data_path = '~/.keras/datasets/enwiki-20180901-pages-articles15.xml-p7744803p9244803.bz2# Iterate through compressed file one line at a timefor line in subprocess.Popen(['bzcat'], stdin = open(data_path), stdout = subprocess.PIPE).stdout: # process line"
},
{
"code": null,
"e": 8163,
"s": 8065,
"text": "If we simply read in the XML data and append it to a list, we get something that looks like this:"
},
{
"code": null,
"e": 8609,
"s": 8163,
"text": "This shows the XML from a single Wikipedia article. The files we have downloaded contain millions of lines like this, with thousands of articles in each file. If we really wanted to make things difficult, we could go through this using regular expressions and string matching to find each article. Given this is extraordinarily inefficient, we’ll take a better approach using tools custom built for parsing both XML and Wikipedia-style articles."
},
{
"code": null,
"e": 8651,
"s": 8609,
"text": "We need to parse the files on two levels:"
},
{
"code": null,
"e": 8750,
"s": 8651,
"text": "Extract the article titles and text from the XMLExtract relevant information from the article text"
},
{
"code": null,
"e": 8799,
"s": 8750,
"text": "Extract the article titles and text from the XML"
},
{
"code": null,
"e": 8850,
"s": 8799,
"text": "Extract relevant information from the article text"
},
{
"code": null,
"e": 8926,
"s": 8850,
"text": "Fortunately, there are good options for both of these operations in Python."
},
{
"code": null,
"e": 9275,
"s": 8926,
"text": "To solve the first problem of locating articles, we’ll use the SAX parser, which is “The Simple API for XML.” BeautifulSoup can also be used for parsing XML, but this requires loading the entire file into memory and building a Document Object Model (DOM). SAX, on the other hand, processes XML one line at a time, which fits our approach perfectly."
},
{
"code": null,
"e": 9489,
"s": 9275,
"text": "The basic idea we need to execute is to search through the XML and extract the information between specific tags (If you need an introduction to XML, I’d recommend starting here). For example, given the XML below:"
},
{
"code": null,
"e": 9927,
"s": 9489,
"text": "<title>Carroll F. Knicely</title><text xml:space=\"preserve\">\\'\\'\\'Carroll F. Knicely\\'\\'\\' (born c. 1929 in [[Staunton, Virginia]] - died November 2, 2006 in [[Glasgow, Kentucky]]) was [[Editing|editor]] and [[Publishing|publisher]] of the \\'\\'[[Glasgow Daily Times]]\\'\\' for nearly 20 years (and later, its owner) and served under three [[Governor of Kentucky|Kentucky Governors]] as commissioner and later Commerce Secretary.\\n'</text>"
},
{
"code": null,
"e": 10336,
"s": 9927,
"text": "We want to select the content between the <title> and <text> tags. (The title is simply the Wikipedia page title and the text is the content of the article). SAX will let us do exactly this using a parser and a ContentHandler which controls how the information passed to the parser is handled. We pass the XML to the parser one line at a time and the Content Handler lets us extract the relevant information."
},
{
"code": null,
"e": 10857,
"s": 10336,
"text": "This is a little difficult to follow without trying it out yourself, but the idea is that the Content handler looks for certain start tags, and when it finds one, it adds characters to a buffer until it encounters the same end tag. Then it saves the buffer content to a dictionary with the tag as the key. The result is that we get a dictionary where the keys are the tags and the values are the content between the tags. We can then send this dictionary to another function that will parse the values in the dictionary."
},
{
"code": null,
"e": 10956,
"s": 10857,
"text": "The only part of SAX we need to write is the Content Handler. This is shown in its entirety below:"
},
{
"code": null,
"e": 11489,
"s": 10956,
"text": "In this code, we are looking for the tags title and text . Every time the parser encounters one of these, it will save characters to the buffer until it encounters the same end tag (identified by </tag>). At this point it will save the buffer contents to a dictionary — self._values . Articles are separated by <page> tags, so if the content handler encounters an ending </page> tag, then it should add the self._values to the list of articles, self._pages. If this is a little confusing, then perhaps seeing it in action will help."
},
{
"code": null,
"e": 11706,
"s": 11489,
"text": "The code below shows how we use this to search through the XML file to find articles. For now we’re just saving them to the handler._pages attribute, but later we’ll send the articles to another function for parsing."
},
{
"code": null,
"e": 12132,
"s": 11706,
"text": "# Object for handling xmlhandler = WikiXmlHandler()# Parsing objectparser = xml.sax.make_parser()parser.setContentHandler(handler)# Iteratively process filefor line in subprocess.Popen(['bzcat'], stdin = open(data_path), stdout = subprocess.PIPE).stdout: parser.feed(line) # Stop when 3 articles have been found if len(handler._pages) > 2: break"
},
{
"code": null,
"e": 12254,
"s": 12132,
"text": "If we inspect handler._pages , we’ll see a list, each element of which is a tuple with the title and text of one article:"
},
{
"code": null,
"e": 12467,
"s": 12254,
"text": "handler._pages[0][('Carroll Knicely', \"'''Carroll F. Knicely''' (born c. 1929 in [[Staunton, Virginia]] - died November 2, 2006 in [[Glasgow, Kentucky]]) was [[Editing|editor]] and [[Publishing|publisher]] ...)]"
},
{
"code": null,
"e": 12777,
"s": 12467,
"text": "At this point we have written code that can successfully identify articles within the XML. This gets us halfway through the process of parsing the files and the next step is to process the articles themselves to find specific pages and information. Once again, we’ll turn to a tool purpose built for the task."
},
{
"code": null,
"e": 13214,
"s": 12777,
"text": "Wikipedia runs on a software for building wikis known as MediaWiki. This means that articles follow a standard format that makes programmatically accessing the information within them simple. While the text of an article may look like just a string, it encodes far more information due to the formatting. To efficiently get at this information, we bring in the powerful mwparserfromhell , a library built to work with MediaWiki content."
},
{
"code": null,
"e": 13575,
"s": 13214,
"text": "If we pass the text of a Wikipedia article to the mwparserfromhell , we get a Wikicode object which comes with many methods for sorting through the data. For example, the following code creates a wikicode object from an article (about KENZ FM) and retrieves the wikilinks() within the article. These are all of the links that point to other Wikipedia articles:"
},
{
"code": null,
"e": 13841,
"s": 13575,
"text": "import mwparserfromhell# Create the wiki articlewiki = mwparserfromhell.parse(handler._pages[6][1])# Find the wikilinkswikilinks = [x.title for x in wiki.filter_wikilinks()]wikilinks[:5]['Provo, Utah', 'Wasatch Front', 'Megahertz', 'Contemporary hit radio', 'watt']"
},
{
"code": null,
"e": 14043,
"s": 13841,
"text": "There are a number of useful methods that can be applied to the wikicode such as finding comments or searching for a specific keyword. If you want to get a clean version of the article text, then call:"
},
{
"code": null,
"e": 14171,
"s": 14043,
"text": "wiki.strip_code().strip()'KENZ (94.9 FM, \" Power 94.9 \" ) is a top 40/CHR radio station broadcasting to Salt Lake City, Utah '"
},
{
"code": null,
"e": 14396,
"s": 14171,
"text": "Since my ultimate goal was to find all the articles about books, the question arises if there is a way to use this parser to identify articles in a certain category? Fortunately, the answer is yes, using MediaWiki templates."
},
{
"code": null,
"e": 14679,
"s": 14396,
"text": "Templates are standard ways of recording information. There are numerous templates for everything on Wikipedia, but the most relevant for our purposes are Infoboxes . These are templates that encode summary information for an article. For instance, the infobox for War and Peace is:"
},
{
"code": null,
"e": 15126,
"s": 14679,
"text": "Each category of articles on Wikipedia, such as films, books, or radio stations, has its own type of infobox. In the case of books, the infobox template is helpfully named Infobox book. Just as helpful, the wiki object has a method called filter_templates() that allows us to extract a specific template from an article. Therefore, if we want to know whether an article is about a book, we can filter it for the book infobox. This is shown below:"
},
{
"code": null,
"e": 15198,
"s": 15126,
"text": "# Filter article for book templatewiki.filter_templates('Infobox book')"
},
{
"code": null,
"e": 15356,
"s": 15198,
"text": "If there’s a match, then we’ve found a book! To find the Infobox template for the category of articles you are interested in, refer to the list of infoboxes."
},
{
"code": null,
"e": 15814,
"s": 15356,
"text": "How do we combine the mwparserfromhell for parsing articles with the SAX parser we wrote? Well, we modify the endElement method in the Content Handler to send the dictionary of values containing the title and text of an article to a function that searches the article text for specified template. If the function finds an article we want, it extracts information from the article and then returns it to the handler. First, I’ll show the updated endElement :"
},
{
"code": null,
"e": 16282,
"s": 15814,
"text": "def endElement(self, name): \"\"\"Closing tag of element\"\"\" if name == self._current_tag: self._values[name] = ' '.join(self._buffer) if name == 'page': self._article_count += 1 # Send the page to the process article function book = process_article(**self._values, template = 'Infobox book') # If article is a book append to the list of books if book: self._books.append(book)"
},
{
"code": null,
"e": 16411,
"s": 16282,
"text": "Now, once the parser has hit the end of an article, we send the article on to the function process_article which is shown below:"
},
{
"code": null,
"e": 16702,
"s": 16411,
"text": "Although I’m looking for books, this function can be used to search for any category of article on Wikipedia. Just replace the template with the template for the category (such as Infobox language to find languages) and it will only return the information from articles within the category."
},
{
"code": null,
"e": 16768,
"s": 16702,
"text": "We can test this function and the new ContentHandler on one file."
},
{
"code": null,
"e": 16835,
"s": 16768,
"text": "Searched through 427481 articles.Found 1426 books in 1055 seconds."
},
{
"code": null,
"e": 16881,
"s": 16835,
"text": "Let’s take a look at the output for one book:"
},
{
"code": null,
"e": 18101,
"s": 16881,
"text": "books[10]['War and Peace', {'name': 'War and Peace', 'author': 'Leo Tolstoy', 'language': 'Russian, with some French', 'country': 'Russia', 'genre': 'Novel (Historical novel)', 'publisher': 'The Russian Messenger (serial)', 'title_orig': 'Война и миръ', 'orig_lang_code': 'ru', 'translator': 'The first translation of War and Peace into English was by American Nathan Haskell Dole, in 1899', 'image': 'Tolstoy - War and Peace - first edition, 1869.jpg', 'caption': 'Front page of War and Peace, first edition, 1869 (Russian)', 'release_date': 'Serialised 1865–1867; book 1869', 'media_type': 'Print', 'pages': '1,225 (first published edition)'}, ['Leo Tolstoy', 'Novel', 'Historical novel', 'The Russian Messenger', 'Serial (publishing)', 'Category:1869 Russian novels', 'Category:Epic novels', 'Category:Novels set in 19th-century Russia', 'Category:Russian novels adapted into films', 'Category:Russian philosophical novels'], ['https://books.google.com/?id=c4HEAN-ti1MC', 'https://www.britannica.com/art/English-literature', 'https://books.google.com/books?id=xf7umXHGDPcC', 'https://books.google.com/?id=E5fotqsglPEC', 'https://books.google.com/?id=9sHebfZIXFAC'], '2018-08-29T02:37:35Z']"
},
{
"code": null,
"e": 18513,
"s": 18101,
"text": "For every single book on Wikipedia, we have the information from the Infobox as a dictionary, the internal wikilinks, the external links, and the timestamp of the most recent edit. (I’m concentrating on these pieces of information to build a book recommendation system for my next project). You can modify the process_article function and WikiXmlHandler class to find whatever information and articles you need!"
},
{
"code": null,
"e": 18886,
"s": 18513,
"text": "If you look at the time to process just one file, 1055 seconds, and multiply that by 55, you get over 15 hours of processing time for all files! Granted, we could just run that overnight, but I’d rather not waste the extra time if I don’t have to. This brings us to our final technique we’ll cover in this project: parallelization using multiprocessing and multithreading."
},
{
"code": null,
"e": 19114,
"s": 18886,
"text": "Instead of parsing through the files one at a time, we want to process several of them at once (which is why we downloaded the partitions). We can do this using parallelization, either through multithreading or multiprocessing."
},
{
"code": null,
"e": 19563,
"s": 19114,
"text": "Multithreading and multiprocessing are ways to carry out many tasks on a computer — or multiple computers — simultaneously. We many files on disk, each of which needs to be parsed in the same way. A naive approach would be to parse one file at a time, but that is not taking full advantage of our resources. Instead, we use either multithreading or multiprocessing to parse many files at the same time, significantly speeding up the entire process."
},
{
"code": null,
"e": 19907,
"s": 19563,
"text": "Generally, multithreading works better (is faster) for input / output bound tasks, such as reading in files or making requests. Multiprocessing works better (is faster) for cpu-bound tasks (source). For the process of parsing articles, I wasn’t sure which method would be optimal, so again I benchmarked both of them with different parameters."
},
{
"code": null,
"e": 20043,
"s": 19907,
"text": "Learning how to set up tests and seek out different ways to solve a problem will get you far in a data science or any technical career."
},
{
"code": null,
"e": 20267,
"s": 20043,
"text": "(The code for testing multithreading and multiprocessing appears at the end of the notebook). When I ran the tests, I found multiprocessing was almost 10 times faster indicating this process is probably CPU bound (limited)."
},
{
"code": null,
"e": 20561,
"s": 20267,
"text": "Learning multithreading / multiprocessing is essential for making your data science workflows more efficient. I’d recommend this article to get started with the concepts. (We’ll stick to the built-in multiprocessing library, but you can also using Dask for parallelization as in this project)."
},
{
"code": null,
"e": 20951,
"s": 20561,
"text": "After running a number of tests, I found the fastest way to process the files was using 16 processes, one for each core of my computer. This means we can process 16 files at a time instead of 1! I’d encourage anyone to test out a few options for multiprocessing / multithreading and let me know the results! I’m still not sure I did things in the best way, and I’m always willing to learn."
},
{
"code": null,
"e": 21330,
"s": 20951,
"text": "To run an operation in parallel, we need a service and a set of tasks . A service is just a function and tasks are in an iterable — such as a list — each of which we send to the function. For the purpose of parsing the XML files, each task is one file, and the function will take in the file, find all the books, and save them to disk. The pseudo-code for the function is below:"
},
{
"code": null,
"e": 21561,
"s": 21330,
"text": "def find_books(data_path, save = True): \"\"\"Find and save all the book articles from a compressed wikipedia XML file. \"\"\" # Parse file for books if save: # Save all books to a file based on the data path name"
},
{
"code": null,
"e": 21867,
"s": 21561,
"text": "The end result of running this function is a saved list of books from the file sent to the function. The files are saved as json, a machine readable format for writing nested information such as lists of lists and dictionaries. The tasks that we want to send to this function are all the compressed files."
},
{
"code": null,
"e": 22118,
"s": 21867,
"text": "# List of compressed files to processpartitions = [keras_home + file for file in os.listdir(keras_home) if 'xml-p' in file]len(partitions), partitions[-1](55, '/home/ubuntu/.keras/datasets/enwiki-20180901-pages-articles17.xml-p11539268p13039268.bz2')"
},
{
"code": null,
"e": 22180,
"s": 22118,
"text": "For each file, we want to send it to find_books to be parsed."
},
{
"code": null,
"e": 22250,
"s": 22180,
"text": "The final code to search through every article on Wikipedia is below:"
},
{
"code": null,
"e": 22480,
"s": 22250,
"text": "from multiprocessing import Pool# Create a pool of workers to execute processespool = Pool(processes = 16)# Map (service, tasks), applies function to each partitionresults = pool.map(find_books, partitions)pool.close()pool.join()"
},
{
"code": null,
"e": 22791,
"s": 22480,
"text": "We map each task to the service, the function that finds the books (map refers to applying a function to each item in an iterable). Running with 16 processes in parallel, we can search all of Wikipedia in under 3 hours! After running the code, the books from each file are saved on disk in separate json files."
},
{
"code": null,
"e": 23074,
"s": 22791,
"text": "For practice writing parallelized code, we’ll read the separate files in with multiple processes, this time using threads. The multiprocessing.dummy library provides a wrapper around the threading module. This time the service is read_data and the tasks are the saved files on disk:"
},
{
"code": null,
"e": 23232,
"s": 23074,
"text": "The multithreaded code works in the exact same way, mapping tasks in an iterable to function. Once we have the list of lists, we flatten it to a single list."
},
{
"code": null,
"e": 23290,
"s": 23232,
"text": "print(f'Found {len(book_list)} books.')Found 37861 books."
},
{
"code": null,
"e": 23632,
"s": 23290,
"text": "Wikipedia has nearly 38,000 articles on books according to our count. The size of the final json file with all the book information is only about 55 MB meaning we searched through over 50 GB (uncompressed) of total files to find 55 MB worth of books! Given that we are only keeping a limited subset of the book information, that makes sense."
},
{
"code": null,
"e": 23935,
"s": 23632,
"text": "We now have information on every single book on Wikipedia. You can use the same code to find articles for any category of your choosing, or modify the functions to search for different information. Using some fairly simple Python code, we are able to search through an incredible amount of information."
},
{
"code": null,
"e": 24232,
"s": 23935,
"text": "In this article, we saw how to download and parse the entire English language version of Wikipedia. Having a ton of data is not useful unless we can make sense of it, and so we developed a set of methods for efficiently processing all of the articles for the information we need for our projects."
},
{
"code": null,
"e": 24298,
"s": 24232,
"text": "Throughout this project, we covered a number of important topics:"
},
{
"code": null,
"e": 24520,
"s": 24298,
"text": "Finding and downloading data programmaticallyParsing through data in an efficient mannerRunning operations in parallel to get the most from our hardwareSetting up and running benchmarking tests to find efficient solutions"
},
{
"code": null,
"e": 24566,
"s": 24520,
"text": "Finding and downloading data programmatically"
},
{
"code": null,
"e": 24610,
"s": 24566,
"text": "Parsing through data in an efficient manner"
},
{
"code": null,
"e": 24675,
"s": 24610,
"text": "Running operations in parallel to get the most from our hardware"
},
{
"code": null,
"e": 24745,
"s": 24675,
"text": "Setting up and running benchmarking tests to find efficient solutions"
},
{
"code": null,
"e": 25191,
"s": 24745,
"text": "The skills developed in this project are well-suited to Wikipedia data but are also broadly applicable to any information from the web. I’d encourage you to apply these methods for your own projects or try analyzing a different category of articles. There’s plenty of information for everyone to do their own project! (I am working on making a book recommendation system with the Wikipedia articles using entity embeddings from neural networks.)"
},
{
"code": null,
"e": 25546,
"s": 25191,
"text": "Wikipedia is an incredible source of human-curated information, and we now know how to use this monumental achievement by accessing and processing it programmatically. I look forward to writing about and doing more Wikipedia Data Science. In the meantime, the techniques presented here are broadly applicable so get out there and find a problem to solve!"
},
{
"code": null,
"e": 25690,
"s": 25546,
"text": "As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or on my personal website at willk.online."
}
] |
Machine Learning: Autoencoders. Using autoencoders to fit high... | by Anuradha Wickramarachchi | Towards Data Science | I found the simplest definition for an autoencoder through Wikipedia, which translates itself into “A machine learning model that learns a lower-dimensional encoding of data”. This is one of the smartest ways of reducing the dimensionality of a dataset, just by using the capabilities of the differentiation ending (Tensorflow, PyTorch, etc). Indeed, we should have a specific neural network architecture in order to achieve this. However, before we start, let’s have a brief overview of dimensionality reduction.
Both PCA and Autoencoders intend to learn a lower-dimensional representation thus reducing the reconstruction error of original dimensionality by the lower dimensional representations. However, as you might know, PCA translates the original data to a lower set of dimensions that are orthogonal to each other. We call this a linear transformation into another space. The problem comes with the linear part. The information loss could be higher. In contrast with Autoencoders, the neural networks use gradient descent to estimate the best possible parameters for a hidden layer with lower dimensions.
Autoencoders take an architecture of a stream of data passing through a bottleneck. This bottleneck represents the lower dimension. The autoencoder is expected to learn this lower dimension thus minimizing the error score defined between the input and the output.
Let us have a look at a simple autoencoder (from Wikipedia).
As you can see we have a middle element which is a narrow passage. Input and Output for the training are usually the same since we intend to learn a lower-dimensional representation.
Our usual imports will be;
import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt # for plots
Processing data; taking MNIST handwriting dataset as an example.
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_train = x_train.astype('float32') / 255x_test = x_test.astype('float32') / 255x_train = np.round(x_train, 0)x_test = np.round(x_test, 0)x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))print(x_train.shape)
Note that we round up data. This is because this dataset is grayscale, we only consider strictly black pixels and strictly white pixels. This helps us form a binary cross-entropy as the loss function.
Let us create the network using Keras functional API.
inputs = tf.keras.layers.Input(784)encoded_1 = tf.keras.layers.Dense(128)(inputs)encoded = tf.keras.layers.Dense(64, activation='relu')(encoded_1)decoded_1 = tf.keras.layers.Dense(128)(encoded)decoded = tf.keras.layers.Dense(784, activation='sigmoid')(decoded_1)auto_encoder = tf.keras.Model(inputs, decoded)auto_encoder.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])auto_encoder.summary()tf.keras.utils.plot_model(auto_encoder, show_shapes=True, to_file='autoenc.png', dpi=200)
Note that I use binary_crossentropy since our data is in binary format (either zeros or ones). The complete set of layers is the autoencoder (encodes and decodes to give the same output). Let us have a look at our encoder. We can build it using the layers from inputs to encoded just as follows.
encoder = tf.keras.Model(inputs, encoded)encoder.summary()tf.keras.utils.plot_model(encoder, show_shapes=True, to_file='enc.png', dpi=200)
Although you can make this using the Sequential Keras API, I find the functional API more elegant (just the opinion, you might see why in the future articles).
Now that we have built our autoencoder, we can fit our training data.
auto_encoder.fit(x_train, x_train, epochs=10, batch_size=256, shuffle=True)
Once trained I obtained an accuracy of 0.9851 which is not so bad!. So we could expect a good performance in terms of dimension reduction.
Let us see the estimated lowed dimension and reconstructed images of the MNIST test dataset.
predicted_2dim = encoder.predict(x_test)predicted_original = auto_encoder.predict(x_test)
Note that for the decoded values, I straightaway feed the raw data to the complete autoencoder, which does the reconstruction straightaway after encoding. For the encodings, I use the encoder component.
The input data without being adjusted looks like below;
The encoded images look like this;
Reconstruction looks like this;
Note that the reconstructed image looks blurred. This happens since our last layer is activated by the sigmoid function. This function returns values in the range 0 and 1.
We use relu activation function because, in the middle layers, the chance of values getting diminished is higher when we use the sigmoid function.
When we decrease the hidden dimension the accuracy of reconstruction diminishes. The reconstruction looks like this. It only had the distinguishable features of characters, not the exact character.
We can see that in the above images 9 and 4 are almost similar. Much more information is lost.
My plotting function for characters (One might find useful)
shown = {}fig = plt.figure(figsize=(20, 10))fig.subplots_adjust(hspace=1, wspace=0.1)i = 0for data, y in zip(predicted_original, y_test): if y not in shown and y==len(shown): i += 1 ax = fig.add_subplot(1, 10, i) ax.text(1, -1, str(y), fontsize=25, ha='center', c='g') ax.imshow(np.array(data).reshape(28, 28), cmap='gray')shown[y] = True if len(shown) == 10: break
Feel free to change code and run. Hope this article was useful. I will introduce variational autoencoders in future articles(s)! | [
{
"code": null,
"e": 686,
"s": 172,
"text": "I found the simplest definition for an autoencoder through Wikipedia, which translates itself into “A machine learning model that learns a lower-dimensional encoding of data”. This is one of the smartest ways of reducing the dimensionality of a dataset, just by using the capabilities of the differentiation ending (Tensorflow, PyTorch, etc). Indeed, we should have a specific neural network architecture in order to achieve this. However, before we start, let’s have a brief overview of dimensionality reduction."
},
{
"code": null,
"e": 1286,
"s": 686,
"text": "Both PCA and Autoencoders intend to learn a lower-dimensional representation thus reducing the reconstruction error of original dimensionality by the lower dimensional representations. However, as you might know, PCA translates the original data to a lower set of dimensions that are orthogonal to each other. We call this a linear transformation into another space. The problem comes with the linear part. The information loss could be higher. In contrast with Autoencoders, the neural networks use gradient descent to estimate the best possible parameters for a hidden layer with lower dimensions."
},
{
"code": null,
"e": 1550,
"s": 1286,
"text": "Autoencoders take an architecture of a stream of data passing through a bottleneck. This bottleneck represents the lower dimension. The autoencoder is expected to learn this lower dimension thus minimizing the error score defined between the input and the output."
},
{
"code": null,
"e": 1611,
"s": 1550,
"text": "Let us have a look at a simple autoencoder (from Wikipedia)."
},
{
"code": null,
"e": 1794,
"s": 1611,
"text": "As you can see we have a middle element which is a narrow passage. Input and Output for the training are usually the same since we intend to learn a lower-dimensional representation."
},
{
"code": null,
"e": 1821,
"s": 1794,
"text": "Our usual imports will be;"
},
{
"code": null,
"e": 1906,
"s": 1821,
"text": "import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt # for plots"
},
{
"code": null,
"e": 1971,
"s": 1906,
"text": "Processing data; taking MNIST handwriting dataset as an example."
},
{
"code": null,
"e": 2338,
"s": 1971,
"text": "(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_train = x_train.astype('float32') / 255x_test = x_test.astype('float32') / 255x_train = np.round(x_train, 0)x_test = np.round(x_test, 0)x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))print(x_train.shape)"
},
{
"code": null,
"e": 2539,
"s": 2338,
"text": "Note that we round up data. This is because this dataset is grayscale, we only consider strictly black pixels and strictly white pixels. This helps us form a binary cross-entropy as the loss function."
},
{
"code": null,
"e": 2593,
"s": 2539,
"text": "Let us create the network using Keras functional API."
},
{
"code": null,
"e": 3143,
"s": 2593,
"text": "inputs = tf.keras.layers.Input(784)encoded_1 = tf.keras.layers.Dense(128)(inputs)encoded = tf.keras.layers.Dense(64, activation='relu')(encoded_1)decoded_1 = tf.keras.layers.Dense(128)(encoded)decoded = tf.keras.layers.Dense(784, activation='sigmoid')(decoded_1)auto_encoder = tf.keras.Model(inputs, decoded)auto_encoder.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])auto_encoder.summary()tf.keras.utils.plot_model(auto_encoder, show_shapes=True, to_file='autoenc.png', dpi=200)"
},
{
"code": null,
"e": 3439,
"s": 3143,
"text": "Note that I use binary_crossentropy since our data is in binary format (either zeros or ones). The complete set of layers is the autoencoder (encodes and decodes to give the same output). Let us have a look at our encoder. We can build it using the layers from inputs to encoded just as follows."
},
{
"code": null,
"e": 3578,
"s": 3439,
"text": "encoder = tf.keras.Model(inputs, encoded)encoder.summary()tf.keras.utils.plot_model(encoder, show_shapes=True, to_file='enc.png', dpi=200)"
},
{
"code": null,
"e": 3738,
"s": 3578,
"text": "Although you can make this using the Sequential Keras API, I find the functional API more elegant (just the opinion, you might see why in the future articles)."
},
{
"code": null,
"e": 3808,
"s": 3738,
"text": "Now that we have built our autoencoder, we can fit our training data."
},
{
"code": null,
"e": 3933,
"s": 3808,
"text": "auto_encoder.fit(x_train, x_train, epochs=10, batch_size=256, shuffle=True)"
},
{
"code": null,
"e": 4072,
"s": 3933,
"text": "Once trained I obtained an accuracy of 0.9851 which is not so bad!. So we could expect a good performance in terms of dimension reduction."
},
{
"code": null,
"e": 4165,
"s": 4072,
"text": "Let us see the estimated lowed dimension and reconstructed images of the MNIST test dataset."
},
{
"code": null,
"e": 4255,
"s": 4165,
"text": "predicted_2dim = encoder.predict(x_test)predicted_original = auto_encoder.predict(x_test)"
},
{
"code": null,
"e": 4458,
"s": 4255,
"text": "Note that for the decoded values, I straightaway feed the raw data to the complete autoencoder, which does the reconstruction straightaway after encoding. For the encodings, I use the encoder component."
},
{
"code": null,
"e": 4514,
"s": 4458,
"text": "The input data without being adjusted looks like below;"
},
{
"code": null,
"e": 4549,
"s": 4514,
"text": "The encoded images look like this;"
},
{
"code": null,
"e": 4581,
"s": 4549,
"text": "Reconstruction looks like this;"
},
{
"code": null,
"e": 4753,
"s": 4581,
"text": "Note that the reconstructed image looks blurred. This happens since our last layer is activated by the sigmoid function. This function returns values in the range 0 and 1."
},
{
"code": null,
"e": 4900,
"s": 4753,
"text": "We use relu activation function because, in the middle layers, the chance of values getting diminished is higher when we use the sigmoid function."
},
{
"code": null,
"e": 5098,
"s": 4900,
"text": "When we decrease the hidden dimension the accuracy of reconstruction diminishes. The reconstruction looks like this. It only had the distinguishable features of characters, not the exact character."
},
{
"code": null,
"e": 5193,
"s": 5098,
"text": "We can see that in the above images 9 and 4 are almost similar. Much more information is lost."
},
{
"code": null,
"e": 5253,
"s": 5193,
"text": "My plotting function for characters (One might find useful)"
},
{
"code": null,
"e": 5660,
"s": 5253,
"text": "shown = {}fig = plt.figure(figsize=(20, 10))fig.subplots_adjust(hspace=1, wspace=0.1)i = 0for data, y in zip(predicted_original, y_test): if y not in shown and y==len(shown): i += 1 ax = fig.add_subplot(1, 10, i) ax.text(1, -1, str(y), fontsize=25, ha='center', c='g') ax.imshow(np.array(data).reshape(28, 28), cmap='gray')shown[y] = True if len(shown) == 10: break"
}
] |
Largest BST | Practice | GeeksforGeeks | Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.
Note: Here Size is equal to the number of nodes in the subtree.
Example 1:
Input:
1
/ \
4 4
/ \
6 8
Output: 1
Explanation: There's no sub-tree with size
greater than 1 which forms a BST. All the
leaf Nodes are the BSTs with size equal
to 1.
Example 2:
Input: 6 6 3 N 2 9 3 N 8 8 2
6
/ \
6 3
\ / \
2 9 3
\ / \
8 8 2
Output: 2
Explanation: The following sub-tree is a
BST of size 2:
2
/ \
N 8
Your Task:
You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 106
0
spideyyy1091 week ago
c++ code ,using DP on Trees concept
bool isBST(Node * root,int mini, int maxi){
if(!root) return true;
if(root->data <= mini || root->data >= maxi) return false;
return isBST(root->left,mini,root->data)&&isBST(root->right,root->data,maxi);
}
int max_size = INT_MIN; //declared globally
int maxsumDPonTrees(Node * root ){
if(!root) return 0;
int l = maxsumDPonTrees(root->left);
int r= maxsumDPonTrees(root->right);
int temp = l+r+1;
max_size = max(max_size , temp);
return temp;
}
void helper(Node * root){
if(!root) return;
//if i have a BST then i will get the maxsize using DP on trees
if(isBST(root,INT_MIN,INT_MAX))
maxsumDPonTrees(root);
else{ //if its not a BST then we still have to check for left and the right subtrees
helper(root->left);
helper(root->right);
}
}
/*You are required to complete this method */
// Return the size of the largest sub-tree which is also a BST
int largestBst(Node *root)
{
//Your code here
max_size = 0;
helper(root);
return max_size;
}
0
arbaazmakandar981 week ago
class info{ public: int mini; int maxi; bool isBST; int size;};info solve(Node* root, int &ans){ //base case if(!root){ return {INT_MIN, INT_MAX, true, 0}; } info left = solve(root->left, ans); info right = solve(root->right, ans); info currNode; currNode.size = left.size + right.size + 1; currNode.maxi = max(root->data, right.maxi); currNode.mini = min(root->data, left.mini); if(left.isBST && right.isBST && (root->data > left.maxi && root->data < right.mini)){ currNode.isBST = true; ans = max(ans, currNode.size); } else{ currNode.isBST = false; } //update ans // if(currNode.isBST){ // } return currNode;}
class Solution{ public: /*You are required to complete this method */ // Return the size of the largest sub-tree which is also a BST int largestBst(Node *root) { //Your code here int ans = 0; info temp = solve(root, ans); return ans; }};
//WHY MY CODE IS NOT WORKING?????
//please help
+1
800dheerajmaurya2 weeks ago
Easiest approach:
Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not.Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not).If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size.Refer to the following code.Thanks. :)
Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not.
Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not).
If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size.
Refer to the following code.
Thanks. :)
class quad{ public: int size; int min; int max; bool isBST;};
quad check(Node* root){ if(root==NULL) return {0,INT_MAX,INT_MIN,true}; quad x=check(root->left); quad y=check(root->right); if(root->data>x.max&&root->data<y.min&&x.isBST&&y.isBST) return {x.size+y.size+1,min(root->data,x.min),max(root->data,y.max),true}; return {max(x.size,y.size),min(root->data,x.min),max(root->data,y.max),false};}
class Solution{ public: int largestBst(Node *root) { return check(root).size; }};
0
amishasahu3282 weeks ago
class NodeValue
{
public: int maxSize, maxValue, minValue;
public:
NodeValue(int minValue, int maxValue, int maxSize)
{
this->minValue = minValue;
this->maxValue = maxValue;
this->maxSize = maxSize;
}
};
class Solution{
private:
NodeValue largestBSTHelper(Node *root)
{
// An empty tree is a BST of size 0.
// maxValue to be the extream small
// minValue to be the extream larger
// To make it comparable
if(!root)
return NodeValue(INT_MAX, INT_MIN, 0);
// Get values from left and right subtree of current tree.
auto left = largestBSTHelper(root->left);
auto right = largestBSTHelper(root->right);
// Current node is greater than max value in left AND smaller than min value in right, it is a BST.
if(left.maxValue < root->data && root->data < right.minValue)
{
return NodeValue(min(root->data, left.minValue), max(root->data, right.maxValue), left.maxSize + right.maxSize + 1);
}
// Otherwise, return [-inf, inf] so that parent can't be valid BST
return NodeValue(INT_MIN, INT_MAX, max(left.maxSize, right.maxSize));
}
public:
/*You are required to complete this method */
// Return the size of the largest sub-tree which is also a BST
int largestBst(Node *root)
{
//Your code here
return largestBSTHelper(root).maxSize;
}
};
0
nitansshujain
This comment was deleted.
+2
raghavbansal44 weeks ago
Easy JAVA Solution, TC - O(N) , SC - O(1)
class newNode{
int size;
int min;
int max;
}
class Solution{
// Return the size of the largest sub-tree which is also a BST
static newNode getSize(Node node){
if(node == null){
newNode a = new newNode();
a.size = 0;
a.min = Integer.MAX_VALUE;
a.max = Integer.MIN_VALUE;
return a;
}
newNode np = new newNode();
newNode l = getSize(node.left);
newNode r = getSize(node.right);
if(l.max < node.data && node.data < r.min){
np.size = l.size + r.size + 1;
np.min = Math.min(node.data,l.min);
np.max = Math.max(node.data,r.max);
}
else{
np.size = Math.max(l.size,r.size);
np.min = Integer.MIN_VALUE;
np.max = Integer.MAX_VALUE;
}
return np;
}
static int largestBst(Node root)
{
return getSize(root).size;
}
}
+1
sandeep55211 month ago
C++ O(n) post-order Solution (0.0 time Taken)
pair<pair<int,int>,int> func(Node *root){
if(!root) return {{0,INT_MIN},INT_MAX};
if(!(root->left) and !(root->right)) return {{1,root->data},root->data};
auto a=func(root->left);
auto b=func(root->right);
if(a.first.second<root->data and b.second>root->data)
return {{1+a.first.first+b.first.first,max(root->data,b.first.second)},min(root->data,a.second)};
return {{max(a.first.first,b.first.first),INT_MAX},INT_MIN};
}
int largestBst(Node *root)
{
auto c=func(root);
return c.first.first;
//Your code here
}
0
abrajput15061 month ago
void helper(Node* root,vector<int> &v){
if(!root)
return;
helper(root->left,v);
v.push_back(root->data);
helper(root->right,v);
}
bool isBST(Node* root){
vector<int> v;
helper(root,v);
for(int i = 1;i<v.size();i++){
if(v[i]<=v[i-1])
return false;
}
return true;
}
int noOfnodes(Node* root){
if(!root)
return 0;
return 1+noOfnodes(root->left)+noOfnodes(root->right);
}
int largestBst(Node *root)
{
//Your code here
if(!root)
return 0;
if(isBST(root))
return noOfnodes(root);
return max(largestBst(root->left),largestBst(root->right));
}
0
terusrihitha9871 month ago
//INORDER APPROACH
void solve1(Node*temp,vector<int>&v,int &cnt){ if(temp==NULL) return; solve1(temp->left,v,cnt); v.push_back(temp->data); cnt++; solve1(temp->right,v,cnt);}int maxi=INT_MIN;void solve(Node *root){ if(root==NULL) return; else { vector<int>v; int cnt=0; solve1(root,v,cnt); int flag=0; for(int j=1;j<v.size();j++) { if(v[j]<=v[j-1]) { flag=1; break; } } if(flag==0) { maxi=max(maxi,cnt); } v.clear(); solve(root->left); solve(root->right); }} int largestBst(Node *root) { solve(root); return maxi; }
0
kambojabhishek0611 month ago
// here anyone clear me why its not given a correct output
class Solution{ class NodeValue{ public int minNode,maxNode,maxsize; NodeValue(int mixNode,int maxNode,int maxsize){ this.minNode=maxNode; this.maxNode=minNode; this.maxsize=maxsize; } } // Return the size of the largest sub-tree which is also a BST public NodeValue solve(Node root){ if(root==null) { return new NodeValue(Integer.MAX_VALUE,Integer.MIN_VALUE,0); } NodeValue left=solve(root.left); NodeValue right=solve(root.right); if(left.maxNode<root.data&&right.minNode>root.data){ return new NodeValue(Math.min(left.minNode,root.data),Math.max(right.maxNode,root.data),1+left.maxsize+right.maxsize); } else return new NodeValue(Integer.MIN_VALUE,Integer.MAX_VALUE,Math.max(left.maxsize,right.maxsize)); } public int largestBst(Node root) { // Write your code here return solve(root).maxsize; //if(NodeValue max.size==0) 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": 390,
"s": 238,
"text": "Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree.\nNote: Here Size is equal to the number of nodes in the subtree."
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Example 1:"
},
{
"code": null,
"e": 604,
"s": 401,
"text": "Input:\n 1\n / \\\n 4 4\n / \\\n 6 8\nOutput: 1\nExplanation: There's no sub-tree with size\ngreater than 1 which forms a BST. All the\nleaf Nodes are the BSTs with size equal\nto 1.\n"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Example 2:"
},
{
"code": null,
"e": 876,
"s": 615,
"text": "Input: 6 6 3 N 2 9 3 N 8 8 2\n 6\n / \\\n 6 3\n \\ / \\\n 2 9 3\n \\ / \\\n 8 8 2 \nOutput: 2\nExplanation: The following sub-tree is a\nBST of size 2: \n 2\n / \\ \n N 8"
},
{
"code": null,
"e": 1194,
"s": 876,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree. "
},
{
"code": null,
"e": 1274,
"s": 1194,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the BST)."
},
{
"code": null,
"e": 1338,
"s": 1274,
"text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 106"
},
{
"code": null,
"e": 1340,
"s": 1338,
"text": "0"
},
{
"code": null,
"e": 1362,
"s": 1340,
"text": "spideyyy1091 week ago"
},
{
"code": null,
"e": 1398,
"s": 1362,
"text": "c++ code ,using DP on Trees concept"
},
{
"code": null,
"e": 2540,
"s": 1398,
"text": "bool isBST(Node * root,int mini, int maxi){\n if(!root) return true;\n if(root->data <= mini || root->data >= maxi) return false;\n return isBST(root->left,mini,root->data)&&isBST(root->right,root->data,maxi);\n }\n \n int max_size = INT_MIN; //declared globally\n int maxsumDPonTrees(Node * root ){\n \n if(!root) return 0;\n int l = maxsumDPonTrees(root->left);\n int r= maxsumDPonTrees(root->right);\n int temp = l+r+1;\n max_size = max(max_size , temp);\n return temp; \n }\n \n void helper(Node * root){\n \n if(!root) return;\n //if i have a BST then i will get the maxsize using DP on trees\n if(isBST(root,INT_MIN,INT_MAX)) \n maxsumDPonTrees(root);\n else{ //if its not a BST then we still have to check for left and the right subtrees\n helper(root->left);\n helper(root->right);\n }\n }\n /*You are required to complete this method */\n // Return the size of the largest sub-tree which is also a BST\n int largestBst(Node *root)\n {\n //Your code here\n max_size = 0;\n helper(root);\n return max_size;\n }"
},
{
"code": null,
"e": 2542,
"s": 2540,
"text": "0"
},
{
"code": null,
"e": 2569,
"s": 2542,
"text": "arbaazmakandar981 week ago"
},
{
"code": null,
"e": 3275,
"s": 2569,
"text": "class info{ public: int mini; int maxi; bool isBST; int size;};info solve(Node* root, int &ans){ //base case if(!root){ return {INT_MIN, INT_MAX, true, 0}; } info left = solve(root->left, ans); info right = solve(root->right, ans); info currNode; currNode.size = left.size + right.size + 1; currNode.maxi = max(root->data, right.maxi); currNode.mini = min(root->data, left.mini); if(left.isBST && right.isBST && (root->data > left.maxi && root->data < right.mini)){ currNode.isBST = true; ans = max(ans, currNode.size); } else{ currNode.isBST = false; } //update ans // if(currNode.isBST){ // } return currNode;}"
},
{
"code": null,
"e": 3543,
"s": 3275,
"text": "class Solution{ public: /*You are required to complete this method */ // Return the size of the largest sub-tree which is also a BST int largestBst(Node *root) { //Your code here int ans = 0; info temp = solve(root, ans); return ans; }};"
},
{
"code": null,
"e": 3581,
"s": 3547,
"text": "//WHY MY CODE IS NOT WORKING?????"
},
{
"code": null,
"e": 3595,
"s": 3581,
"text": "//please help"
},
{
"code": null,
"e": 3598,
"s": 3595,
"text": "+1"
},
{
"code": null,
"e": 3626,
"s": 3598,
"text": "800dheerajmaurya2 weeks ago"
},
{
"code": null,
"e": 3644,
"s": 3626,
"text": "Easiest approach:"
},
{
"code": null,
"e": 4251,
"s": 3644,
"text": "Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not.Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not).If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size.Refer to the following code.Thanks. :)"
},
{
"code": null,
"e": 4374,
"s": 4251,
"text": "Recur form bottom to top, so that you can give info to the parent node whether the left and right subtree is a BST or not."
},
{
"code": null,
"e": 4552,
"s": 4374,
"text": "Make a class/struct of 4 members i.e. size(your final answer), min(minimum value in that subtree), max(maximum value in that subtree), isBST(whether this subtree is BST or not)."
},
{
"code": null,
"e": 4822,
"s": 4552,
"text": "If the left and right child is BST and value of current node is greater than the maximum value of left subtree and is less than the minimum value of the right subtree then, the node and left subtree and right subtree comparises a whole new BST. Now update the max size."
},
{
"code": null,
"e": 4851,
"s": 4822,
"text": "Refer to the following code."
},
{
"code": null,
"e": 4862,
"s": 4851,
"text": "Thanks. :)"
},
{
"code": null,
"e": 4936,
"s": 4864,
"text": "class quad{ public: int size; int min; int max; bool isBST;};"
},
{
"code": null,
"e": 5297,
"s": 4938,
"text": "quad check(Node* root){ if(root==NULL) return {0,INT_MAX,INT_MIN,true}; quad x=check(root->left); quad y=check(root->right); if(root->data>x.max&&root->data<y.min&&x.isBST&&y.isBST) return {x.size+y.size+1,min(root->data,x.min),max(root->data,y.max),true}; return {max(x.size,y.size),min(root->data,x.min),max(root->data,y.max),false};}"
},
{
"code": null,
"e": 5392,
"s": 5299,
"text": "class Solution{ public: int largestBst(Node *root) { return check(root).size; }};"
},
{
"code": null,
"e": 5394,
"s": 5392,
"text": "0"
},
{
"code": null,
"e": 5419,
"s": 5394,
"text": "amishasahu3282 weeks ago"
},
{
"code": null,
"e": 6895,
"s": 5419,
"text": "class NodeValue\n{\n public: int maxSize, maxValue, minValue;\n public:\n NodeValue(int minValue, int maxValue, int maxSize)\n {\n this->minValue = minValue;\n this->maxValue = maxValue;\n this->maxSize = maxSize;\n }\n};\nclass Solution{\n private:\n NodeValue largestBSTHelper(Node *root)\n {\n // An empty tree is a BST of size 0.\n // maxValue to be the extream small\n // minValue to be the extream larger\n // To make it comparable\n if(!root)\n return NodeValue(INT_MAX, INT_MIN, 0);\n \n // Get values from left and right subtree of current tree.\n auto left = largestBSTHelper(root->left);\n auto right = largestBSTHelper(root->right);\n \n // Current node is greater than max value in left AND smaller than min value in right, it is a BST.\n if(left.maxValue < root->data && root->data < right.minValue)\n {\n return NodeValue(min(root->data, left.minValue), max(root->data, right.maxValue), left.maxSize + right.maxSize + 1);\n }\n // Otherwise, return [-inf, inf] so that parent can't be valid BST\n return NodeValue(INT_MIN, INT_MAX, max(left.maxSize, right.maxSize));\n }\n public:\n /*You are required to complete this method */\n // Return the size of the largest sub-tree which is also a BST\n int largestBst(Node *root)\n {\n \t//Your code here\n \treturn largestBSTHelper(root).maxSize;\n }\n};"
},
{
"code": null,
"e": 6897,
"s": 6895,
"text": "0"
},
{
"code": null,
"e": 6911,
"s": 6897,
"text": "nitansshujain"
},
{
"code": null,
"e": 6937,
"s": 6911,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6940,
"s": 6937,
"text": "+2"
},
{
"code": null,
"e": 6965,
"s": 6940,
"text": "raghavbansal44 weeks ago"
},
{
"code": null,
"e": 7007,
"s": 6965,
"text": "Easy JAVA Solution, TC - O(N) , SC - O(1)"
},
{
"code": null,
"e": 8119,
"s": 7007,
"text": "class newNode{\n int size;\n int min;\n int max;\n }\nclass Solution{\n \n // Return the size of the largest sub-tree which is also a BST\n \n static newNode getSize(Node node){\n if(node == null){\n newNode a = new newNode();\n a.size = 0;\n a.min = Integer.MAX_VALUE;\n a.max = Integer.MIN_VALUE;\n return a;\n }\n \n newNode np = new newNode();\n newNode l = getSize(node.left);\n newNode r = getSize(node.right);\n \n if(l.max < node.data && node.data < r.min){\n np.size = l.size + r.size + 1;\n np.min = Math.min(node.data,l.min);\n np.max = Math.max(node.data,r.max);\n }\n else{\n np.size = Math.max(l.size,r.size);\n np.min = Integer.MIN_VALUE;\n np.max = Integer.MAX_VALUE;\n }\n return np;\n }\n static int largestBst(Node root)\n {\n return getSize(root).size;\n \n }\n \n}"
},
{
"code": null,
"e": 8122,
"s": 8119,
"text": "+1"
},
{
"code": null,
"e": 8145,
"s": 8122,
"text": "sandeep55211 month ago"
},
{
"code": null,
"e": 8191,
"s": 8145,
"text": "C++ O(n) post-order Solution (0.0 time Taken)"
},
{
"code": null,
"e": 8788,
"s": 8191,
"text": "pair<pair<int,int>,int> func(Node *root){\n if(!root) return {{0,INT_MIN},INT_MAX};\n if(!(root->left) and !(root->right)) return {{1,root->data},root->data};\n auto a=func(root->left);\n auto b=func(root->right);\n if(a.first.second<root->data and b.second>root->data)\n return {{1+a.first.first+b.first.first,max(root->data,b.first.second)},min(root->data,a.second)};\n return {{max(a.first.first,b.first.first),INT_MAX},INT_MIN};\n } \n int largestBst(Node *root)\n {\n auto c=func(root);\n return c.first.first;\n //Your code here\n } "
},
{
"code": null,
"e": 8790,
"s": 8788,
"text": "0"
},
{
"code": null,
"e": 8814,
"s": 8790,
"text": "abrajput15061 month ago"
},
{
"code": null,
"e": 9560,
"s": 8814,
"text": "void helper(Node* root,vector<int> &v){\n if(!root)\n return;\n helper(root->left,v);\n v.push_back(root->data);\n helper(root->right,v);\n }\n bool isBST(Node* root){\n vector<int> v;\n helper(root,v);\n for(int i = 1;i<v.size();i++){\n if(v[i]<=v[i-1])\n return false;\n }\n return true;\n }\n int noOfnodes(Node* root){\n if(!root)\n return 0;\n return 1+noOfnodes(root->left)+noOfnodes(root->right);\n }\n int largestBst(Node *root)\n {\n \t//Your code here\n \tif(!root)\n \t return 0;\n \tif(isBST(root))\n \t return noOfnodes(root);\n\t return max(largestBst(root->left),largestBst(root->right));\n }"
},
{
"code": null,
"e": 9562,
"s": 9560,
"text": "0"
},
{
"code": null,
"e": 9589,
"s": 9562,
"text": "terusrihitha9871 month ago"
},
{
"code": null,
"e": 9608,
"s": 9589,
"text": "//INORDER APPROACH"
},
{
"code": null,
"e": 10357,
"s": 9610,
"text": "void solve1(Node*temp,vector<int>&v,int &cnt){ if(temp==NULL) return; solve1(temp->left,v,cnt); v.push_back(temp->data); cnt++; solve1(temp->right,v,cnt);}int maxi=INT_MIN;void solve(Node *root){ if(root==NULL) return; else { vector<int>v; int cnt=0; solve1(root,v,cnt); int flag=0; for(int j=1;j<v.size();j++) { if(v[j]<=v[j-1]) { flag=1; break; } } if(flag==0) { maxi=max(maxi,cnt); } v.clear(); solve(root->left); solve(root->right); }} int largestBst(Node *root) { solve(root); return maxi; }"
},
{
"code": null,
"e": 10363,
"s": 10361,
"text": "0"
},
{
"code": null,
"e": 10392,
"s": 10363,
"text": "kambojabhishek0611 month ago"
},
{
"code": null,
"e": 10452,
"s": 10392,
"text": "// here anyone clear me why its not given a correct output"
},
{
"code": null,
"e": 11459,
"s": 10452,
"text": "class Solution{ class NodeValue{ public int minNode,maxNode,maxsize; NodeValue(int mixNode,int maxNode,int maxsize){ this.minNode=maxNode; this.maxNode=minNode; this.maxsize=maxsize; } } // Return the size of the largest sub-tree which is also a BST public NodeValue solve(Node root){ if(root==null) { return new NodeValue(Integer.MAX_VALUE,Integer.MIN_VALUE,0); } NodeValue left=solve(root.left); NodeValue right=solve(root.right); if(left.maxNode<root.data&&right.minNode>root.data){ return new NodeValue(Math.min(left.minNode,root.data),Math.max(right.maxNode,root.data),1+left.maxsize+right.maxsize); } else return new NodeValue(Integer.MIN_VALUE,Integer.MAX_VALUE,Math.max(left.maxsize,right.maxsize)); } public int largestBst(Node root) { // Write your code here return solve(root).maxsize; //if(NodeValue max.size==0) return 1; } }"
},
{
"code": null,
"e": 11605,
"s": 11459,
"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": 11641,
"s": 11605,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11651,
"s": 11641,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11661,
"s": 11651,
"text": "\nContest\n"
},
{
"code": null,
"e": 11724,
"s": 11661,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11872,
"s": 11724,
"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": 12080,
"s": 11872,
"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": 12186,
"s": 12080,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Valid Palindrome III in C++ | Suppose we have a string s and another number k; we have to check whether the given string is a K-Palindrome or not.
A string is said to be K-Palindrome if it can be transformed into a palindrome by removing at most k characters from it.
So, if the input is like s = "abcdeca", k = 2, then the output will be true as by removing 'b' and 'e' characters, it will be palindrome.
To solve this, we will follow these steps −
Define a function lcs(), this will take s, t,
Define a function lcs(), this will take s, t,
n := size of s
n := size of s
add one blank space before s
add one blank space before s
add one blank space before t
add one blank space before t
Define one 2D array dp of size (n + 1) x (n + 1)
Define one 2D array dp of size (n + 1) x (n + 1)
for initialize i := 1, when i <= n, update (increase i by 1), do −for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
for initialize i := 1, when i <= n, update (increase i by 1), do −
for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
for initialize j := 1, when j <= n, update (increase j by 1), do −
dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]
dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]
if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
if s[i] is same as t[j], then −
dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]
return dp[n, n]
return dp[n, n]
From the main method do the following −
From the main method do the following −
if not size of s, then −return true
if not size of s, then −
return true
return true
x := blank space
x := blank space
for initialize i := size of s, when i >= 0, update (decrease i by 1), do −x := x + s[i]
for initialize i := size of s, when i >= 0, update (decrease i by 1), do −
x := x + s[i]
x := x + s[i]
return size of s
return size of s
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lcs(string s, string t){
int n = s.size();
s = " " + s;
t = " " + t;
vector<vector<int> > dp(n + 1, vector<int>(n + 1));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if (s[i] == t[j])
dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
}
}
return dp[n][n];
}
bool isValidPalindrome(string s, int k) {
if (!s.size())
return true;
string x = "";
for (int i = s.size() - 1; i >= 0; i--)
x += s[i];
return s.size() - lcs(s, x) <= k;
}
};
main(){
Solution ob;
cout << (ob.isValidPalindrome("abcdeca", 2));
}
"abcdeca", 2
1 | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "Suppose we have a string s and another number k; we have to check whether the given string is a K-Palindrome or not."
},
{
"code": null,
"e": 1300,
"s": 1179,
"text": "A string is said to be K-Palindrome if it can be transformed into a palindrome by removing at most k characters from it."
},
{
"code": null,
"e": 1438,
"s": 1300,
"text": "So, if the input is like s = \"abcdeca\", k = 2, then the output will be true as by removing 'b' and 'e' characters, it will be palindrome."
},
{
"code": null,
"e": 1482,
"s": 1438,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1528,
"s": 1482,
"text": "Define a function lcs(), this will take s, t,"
},
{
"code": null,
"e": 1574,
"s": 1528,
"text": "Define a function lcs(), this will take s, t,"
},
{
"code": null,
"e": 1589,
"s": 1574,
"text": "n := size of s"
},
{
"code": null,
"e": 1604,
"s": 1589,
"text": "n := size of s"
},
{
"code": null,
"e": 1633,
"s": 1604,
"text": "add one blank space before s"
},
{
"code": null,
"e": 1662,
"s": 1633,
"text": "add one blank space before s"
},
{
"code": null,
"e": 1691,
"s": 1662,
"text": "add one blank space before t"
},
{
"code": null,
"e": 1720,
"s": 1691,
"text": "add one blank space before t"
},
{
"code": null,
"e": 1769,
"s": 1720,
"text": "Define one 2D array dp of size (n + 1) x (n + 1)"
},
{
"code": null,
"e": 1818,
"s": 1769,
"text": "Define one 2D array dp of size (n + 1) x (n + 1)"
},
{
"code": null,
"e": 2090,
"s": 1818,
"text": "for initialize i := 1, when i <= n, update (increase i by 1), do −for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]"
},
{
"code": null,
"e": 2157,
"s": 2090,
"text": "for initialize i := 1, when i <= n, update (increase i by 1), do −"
},
{
"code": null,
"e": 2363,
"s": 2157,
"text": "for initialize j := 1, when j <= n, update (increase j by 1), do −dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]"
},
{
"code": null,
"e": 2430,
"s": 2363,
"text": "for initialize j := 1, when j <= n, update (increase j by 1), do −"
},
{
"code": null,
"e": 2483,
"s": 2430,
"text": "dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]"
},
{
"code": null,
"e": 2536,
"s": 2483,
"text": "dp[i, j] := maximum of dp[i - 1, j] and dp[i, j - 1]"
},
{
"code": null,
"e": 2624,
"s": 2536,
"text": "if s[i] is same as t[j], then −dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]"
},
{
"code": null,
"e": 2656,
"s": 2624,
"text": "if s[i] is same as t[j], then −"
},
{
"code": null,
"e": 2713,
"s": 2656,
"text": "dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]"
},
{
"code": null,
"e": 2770,
"s": 2713,
"text": "dp[i, j] := maximum of dp[i, j] and 1 + dp[i - 1, j - 1]"
},
{
"code": null,
"e": 2786,
"s": 2770,
"text": "return dp[n, n]"
},
{
"code": null,
"e": 2802,
"s": 2786,
"text": "return dp[n, n]"
},
{
"code": null,
"e": 2842,
"s": 2802,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 2882,
"s": 2842,
"text": "From the main method do the following −"
},
{
"code": null,
"e": 2918,
"s": 2882,
"text": "if not size of s, then −return true"
},
{
"code": null,
"e": 2943,
"s": 2918,
"text": "if not size of s, then −"
},
{
"code": null,
"e": 2955,
"s": 2943,
"text": "return true"
},
{
"code": null,
"e": 2967,
"s": 2955,
"text": "return true"
},
{
"code": null,
"e": 2984,
"s": 2967,
"text": "x := blank space"
},
{
"code": null,
"e": 3001,
"s": 2984,
"text": "x := blank space"
},
{
"code": null,
"e": 3089,
"s": 3001,
"text": "for initialize i := size of s, when i >= 0, update (decrease i by 1), do −x := x + s[i]"
},
{
"code": null,
"e": 3164,
"s": 3089,
"text": "for initialize i := size of s, when i >= 0, update (decrease i by 1), do −"
},
{
"code": null,
"e": 3178,
"s": 3164,
"text": "x := x + s[i]"
},
{
"code": null,
"e": 3192,
"s": 3178,
"text": "x := x + s[i]"
},
{
"code": null,
"e": 3209,
"s": 3192,
"text": "return size of s"
},
{
"code": null,
"e": 3226,
"s": 3209,
"text": "return size of s"
},
{
"code": null,
"e": 3296,
"s": 3226,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3307,
"s": 3296,
"text": " Live Demo"
},
{
"code": null,
"e": 4098,
"s": 3307,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int lcs(string s, string t){\n int n = s.size();\n s = \" \" + s;\n t = \" \" + t;\n vector<vector<int> > dp(n + 1, vector<int>(n + 1));\n for (int i = 1; i <= n; i++) {\n for (int j = 1; j <= n; j++) {\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);\n if (s[i] == t[j])\n dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);\n }\n }\n return dp[n][n];\n }\n bool isValidPalindrome(string s, int k) {\n if (!s.size())\n return true;\n string x = \"\";\n for (int i = s.size() - 1; i >= 0; i--)\n x += s[i];\n return s.size() - lcs(s, x) <= k;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.isValidPalindrome(\"abcdeca\", 2));\n}"
},
{
"code": null,
"e": 4111,
"s": 4098,
"text": "\"abcdeca\", 2"
},
{
"code": null,
"e": 4113,
"s": 4111,
"text": "1"
}
] |
Python module Newspaper for Article scraping & curation? | We can extract content in web pages from a variety of domains such as data mining, information retrieval etc. To extract information from the websites of newspapers and magazines we are going to use newspaper library.
The main purpose of this library is to extract and curates the articles from the newspapers and similar websites.
To Newspaper library installation, run in your terminal:
To Newspaper library installation, run in your terminal:
$ pip install newspaper3k
For lxml dependencies, run below command in your terminal
For lxml dependencies, run below command in your terminal
$pip install lxml
To install PIL, run
To install PIL, run
$pip install Pillow
The NLP corpora will be downloaded:
The NLP corpora will be downloaded:
$ curl https://raw.githubusercontent.com/codelucas/newspaper/master/download_corpora.py | python
The python newpaper library is used to collect information associated with articles. This includes author name, major images in the article, publication dates, video present in the article, key words describing the article and the summary of the article.
#Import required library
from newspaper import Article
# url link-which you want to extract
url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"
# Download the article
>>> from newspaper import Article
>>> url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"
>>> article = Article(url)
>>> article.download()
# Parse the article and fetch authors name
>>> article.parse()
>>> print(article.authors)
['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']
# Extract Publication date
>>> print("Article Publication Date:")
>>> print(article.publish_date)
# Extract URL of the major images
>>> print(article.top_image)
https://images.wsj.net/im-51122/social
# Extract keywords using NLP
print ("Keywords in the article", article.keywords)
# Extract summary of the article
print("Article Summary", article.summary)
Below is the complete program:
from newspaper import Article
url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"
article = Article(url)
article.download()
article.parse()
print(article.authors)
print("Article Publication Date:")
print(article.publish_date)
print("Major Image in the article:")
print(article.top_image)
article.nlp()
print ("Keywords in the article")
print(article.keywords)
print("Article Summary")
print(article.summary)
['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']
Article Publication Date:
None
Major Image in the article:
https://images.wsj.net/im-51122/social
Keywords in the article
['state', 'spending', 'sweeping', 'southern', 'security', 'border', 'principle', 'lawmakers', 'avoid', 'shutdown', 'reach', 'weekendthe', 'fund', 'trump', 'union', 'agreement', 'wall']
Article Summary
President Trump made the case in his State of the Union address for the construction of a wall along the southern U.S. border, calling it a “moral issue."
Photo: GettyWASHINGTON—Senior lawmakers said Monday night they had reached an agreement in principle on a sweeping deal to end a monthslong fight over border security and avoid a partial government shutdown this weekend.
The top four lawmakers on the House and Senate Appropriations Committees emerged after three closed-door meetings Monday and announced that they had agreed to a framework for all seven spending bills whose funding expires at 12:01 a.m. Saturday. | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "We can extract content in web pages from a variety of domains such as data mining, information retrieval etc. To extract information from the websites of newspapers and magazines we are going to use newspaper library."
},
{
"code": null,
"e": 1394,
"s": 1280,
"text": "The main purpose of this library is to extract and curates the articles from the newspapers and similar websites."
},
{
"code": null,
"e": 1451,
"s": 1394,
"text": "To Newspaper library installation, run in your terminal:"
},
{
"code": null,
"e": 1508,
"s": 1451,
"text": "To Newspaper library installation, run in your terminal:"
},
{
"code": null,
"e": 1534,
"s": 1508,
"text": "$ pip install newspaper3k"
},
{
"code": null,
"e": 1592,
"s": 1534,
"text": "For lxml dependencies, run below command in your terminal"
},
{
"code": null,
"e": 1650,
"s": 1592,
"text": "For lxml dependencies, run below command in your terminal"
},
{
"code": null,
"e": 1668,
"s": 1650,
"text": "$pip install lxml"
},
{
"code": null,
"e": 1688,
"s": 1668,
"text": "To install PIL, run"
},
{
"code": null,
"e": 1708,
"s": 1688,
"text": "To install PIL, run"
},
{
"code": null,
"e": 1728,
"s": 1708,
"text": "$pip install Pillow"
},
{
"code": null,
"e": 1764,
"s": 1728,
"text": "The NLP corpora will be downloaded:"
},
{
"code": null,
"e": 1800,
"s": 1764,
"text": "The NLP corpora will be downloaded:"
},
{
"code": null,
"e": 1897,
"s": 1800,
"text": "$ curl https://raw.githubusercontent.com/codelucas/newspaper/master/download_corpora.py | python"
},
{
"code": null,
"e": 2152,
"s": 1897,
"text": "The python newpaper library is used to collect information associated with articles. This includes author name, major images in the article, publication dates, video present in the article, key words describing the article and the summary of the article."
},
{
"code": null,
"e": 2643,
"s": 2152,
"text": "#Import required library\nfrom newspaper import Article\n# url link-which you want to extract\nurl = \"https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117\"\n# Download the article\n>>> from newspaper import Article\n>>> url = \"https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117\"\n>>> article = Article(url)\n>>> article.download()\n# Parse the article and fetch authors name\n>>> article.parse()\n>>> print(article.authors)"
},
{
"code": null,
"e": 2948,
"s": 2643,
"text": "['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']\n\n# Extract Publication date\n>>> print(\"Article Publication Date:\")\n>>> print(article.publish_date)\n\n# Extract URL of the major images\n\n>>> print(article.top_image)"
},
{
"code": null,
"e": 3147,
"s": 2948,
"text": "https://images.wsj.net/im-51122/social\n\n# Extract keywords using NLP\n\nprint (\"Keywords in the article\", article.keywords)\n\n# Extract summary of the article\n\nprint(\"Article Summary\", article.summary)"
},
{
"code": null,
"e": 3178,
"s": 3147,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 3633,
"s": 3178,
"text": "from newspaper import Article\nurl = \"https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117\"\narticle = Article(url)\narticle.download()\narticle.parse()\nprint(article.authors)\nprint(\"Article Publication Date:\")\nprint(article.publish_date)\nprint(\"Major Image in the article:\")\nprint(article.top_image)\narticle.nlp()\nprint (\"Keywords in the article\")\nprint(article.keywords)\nprint(\"Article Summary\")\nprint(article.summary)"
},
{
"code": null,
"e": 4719,
"s": 3633,
"text": "['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']\nArticle Publication Date:\nNone\nMajor Image in the article:\nhttps://images.wsj.net/im-51122/social\nKeywords in the article\n['state', 'spending', 'sweeping', 'southern', 'security', 'border', 'principle', 'lawmakers', 'avoid', 'shutdown', 'reach', 'weekendthe', 'fund', 'trump', 'union', 'agreement', 'wall']\nArticle Summary\nPresident Trump made the case in his State of the Union address for the construction of a wall along the southern U.S. border, calling it a “moral issue.\"\nPhoto: GettyWASHINGTON—Senior lawmakers said Monday night they had reached an agreement in principle on a sweeping deal to end a monthslong fight over border security and avoid a partial government shutdown this weekend.\nThe top four lawmakers on the House and Senate Appropriations Committees emerged after three closed-door meetings Monday and announced that they had agreed to a framework for all seven spending bills whose funding expires at 12:01 a.m. Saturday."
}
] |
Remove character | Practice | GeeksforGeeks | Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.
NOTE: Size of first string is always greater than the size of second string( |string1| > |string2|).
Example 1:
Input:
string1 = "computer"
string2 = "cat"
Output: "ompuer"
Explanation: After removing characters(c, a, t)
from string1 we get "ompuer".
Example 2:
Input:
string1 = "occurrence"
string2 = "car"
Output: "ouene"
Explanation: After removing characters
(c, a, r) from string1 we get "ouene".
Your Task:
You dont need to read input or print anything. Complete the function removeChars() which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1.
Expected Time Complexity:O( |String1| + |String2| )
Expected Auxiliary Space: O(K),Where K = Constant
Constraints:
1 <= |String1| , |String2| <= 50
0
manavkanjiyanijobupdate2 weeks ago
JAVA ALL CODE TEST CASE PASSED
class Solution{ static String removeChars(String string1, String string2){ String s = ""; for(int i = 0 ; i < string1.length() ; i++) { if(!string2.contains(String.valueOf(string1.charAt(i)))) { s = s + string1.charAt(i); } } return s; }}
0
nishraut72 weeks ago
python code:
class Solution: def removeChars (ob, string1, string2): # code here for i in string1: for j in string2: if i == j: string1 = string1.replace(i,"") return string1
0
nithinkirthick3 weeks ago
Python : 0/0.4
def removeChars (ob, string1, string2): # code here elist=[] for i in string1: if i not in string2: elist.append(i) return "".join(elist)
0
princejee20191 month ago
C++ || USING STL || 0.0 ms || 3 LINE CODE
string removeChars(string s1, string s2) { for(int i =0;i<s2.size();i++){ s1.erase(remove(s1.begin(),s1.end(),s2[i]),s1.end()); } return s1; }
0
pradeepshillare1 month ago
............java(0.2)...
String v= ""; Stack<Character> s = new Stack<>(); for(int i=0;i<string2.length();i++) { s.add(string2.charAt(i));
} for(int i=0;i<string1.length();i++) { char c = string1.charAt(i); if(!s.contains(c)) { v = v + c; } } return v;
0
arjunaryagupta2031 month ago
#USING ANAGRAM CONCEPT
#Code in Python # code here box=[0]*26 for i in range(len(string1)): box[ord(string1[i])-ord('a')]=box[ord(string1[i])-ord('a')]+1 for j in range(len(string2)): if box[ord(string2[j])-ord('a')]!=0: box[ord(string2[j])-ord('a')]=0 strng="" for i in range(len(string1)): if box[ord(string1[i])-ord('a')]!=0: strng=strng+string1[i] #print(strng) return strng
0
meghanareddygopidiPremium1 month ago
class Solution: def removeChars (ob, string1, string2): l=[] for i in string1: if i not in string2: l.append(i) str1 = "" for ele in l: str1 += ele return str1
0
raghavendra7771 month ago
class Solution: def removeChars (ob, string1, string2): # code here s=list(string1) #print(s) for ch in string2: for i in range(0,1000): if ch in s: s.remove(ch) return ''.join(s)
0
adira42004
This comment was deleted.
0
rahulrs2 months ago
JAVA CODE..................................
static String removeChars(String string1, String string2){ // code here
HashSet<Character> s2 = new HashSet<>();
// storing all elements of string2 into s2. for(int i=0;i<string2.length();i++){ s2.add(string2.charAt(i)); } String str = ""; for(int i=0;i<string1.length();i++){ if(!s2.contains(string1.charAt(i))){ str+=string1.charAt(i); } } return str; }
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": 536,
"s": 226,
"text": "Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters.\nNOTE: Size of first string is always greater than the size of second string( |string1| > |string2|).\n "
},
{
"code": null,
"e": 547,
"s": 536,
"text": "Example 1:"
},
{
"code": null,
"e": 686,
"s": 547,
"text": "Input:\nstring1 = \"computer\"\nstring2 = \"cat\"\nOutput: \"ompuer\"\nExplanation: After removing characters(c, a, t)\nfrom string1 we get \"ompuer\"."
},
{
"code": null,
"e": 697,
"s": 686,
"text": "Example 2:"
},
{
"code": null,
"e": 837,
"s": 697,
"text": "Input:\nstring1 = \"occurrence\"\nstring2 = \"car\"\nOutput: \"ouene\"\nExplanation: After removing characters\n(c, a, r) from string1 we get \"ouene\"."
},
{
"code": null,
"e": 1070,
"s": 839,
"text": "Your Task: \nYou dont need to read input or print anything. Complete the function removeChars() which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1."
},
{
"code": null,
"e": 1176,
"s": 1070,
"text": "\nExpected Time Complexity:O( |String1| + |String2| )\nExpected Auxiliary Space: O(K),Where K = Constant "
},
{
"code": null,
"e": 1223,
"s": 1176,
"text": "\nConstraints:\n1 <= |String1| , |String2| <= 50"
},
{
"code": null,
"e": 1225,
"s": 1223,
"text": "0"
},
{
"code": null,
"e": 1260,
"s": 1225,
"text": "manavkanjiyanijobupdate2 weeks ago"
},
{
"code": null,
"e": 1292,
"s": 1260,
"text": "JAVA ALL CODE TEST CASE PASSED "
},
{
"code": null,
"e": 1611,
"s": 1292,
"text": "class Solution{ static String removeChars(String string1, String string2){ String s = \"\"; for(int i = 0 ; i < string1.length() ; i++) { if(!string2.contains(String.valueOf(string1.charAt(i)))) { s = s + string1.charAt(i); } } return s; }}"
},
{
"code": null,
"e": 1613,
"s": 1611,
"text": "0"
},
{
"code": null,
"e": 1634,
"s": 1613,
"text": "nishraut72 weeks ago"
},
{
"code": null,
"e": 1647,
"s": 1634,
"text": "python code:"
},
{
"code": null,
"e": 1881,
"s": 1649,
"text": "class Solution: def removeChars (ob, string1, string2): # code here for i in string1: for j in string2: if i == j: string1 = string1.replace(i,\"\") return string1"
},
{
"code": null,
"e": 1885,
"s": 1883,
"text": "0"
},
{
"code": null,
"e": 1911,
"s": 1885,
"text": "nithinkirthick3 weeks ago"
},
{
"code": null,
"e": 1926,
"s": 1911,
"text": "Python : 0/0.4"
},
{
"code": null,
"e": 2112,
"s": 1926,
"text": " def removeChars (ob, string1, string2): # code here elist=[] for i in string1: if i not in string2: elist.append(i) return \"\".join(elist)"
},
{
"code": null,
"e": 2114,
"s": 2112,
"text": "0"
},
{
"code": null,
"e": 2139,
"s": 2114,
"text": "princejee20191 month ago"
},
{
"code": null,
"e": 2181,
"s": 2139,
"text": "C++ || USING STL || 0.0 ms || 3 LINE CODE"
},
{
"code": null,
"e": 2353,
"s": 2181,
"text": "string removeChars(string s1, string s2) { for(int i =0;i<s2.size();i++){ s1.erase(remove(s1.begin(),s1.end(),s2[i]),s1.end()); } return s1; }"
},
{
"code": null,
"e": 2355,
"s": 2353,
"text": "0"
},
{
"code": null,
"e": 2382,
"s": 2355,
"text": "pradeepshillare1 month ago"
},
{
"code": null,
"e": 2407,
"s": 2382,
"text": "............java(0.2)..."
},
{
"code": null,
"e": 2556,
"s": 2407,
"text": " String v= \"\"; Stack<Character> s = new Stack<>(); for(int i=0;i<string2.length();i++) { s.add(string2.charAt(i));"
},
{
"code": null,
"e": 2755,
"s": 2556,
"text": " } for(int i=0;i<string1.length();i++) { char c = string1.charAt(i); if(!s.contains(c)) { v = v + c; } } return v;"
},
{
"code": null,
"e": 2757,
"s": 2755,
"text": "0"
},
{
"code": null,
"e": 2786,
"s": 2757,
"text": "arjunaryagupta2031 month ago"
},
{
"code": null,
"e": 2817,
"s": 2786,
"text": " #USING ANAGRAM CONCEPT"
},
{
"code": null,
"e": 3302,
"s": 2817,
"text": " #Code in Python # code here box=[0]*26 for i in range(len(string1)): box[ord(string1[i])-ord('a')]=box[ord(string1[i])-ord('a')]+1 for j in range(len(string2)): if box[ord(string2[j])-ord('a')]!=0: box[ord(string2[j])-ord('a')]=0 strng=\"\" for i in range(len(string1)): if box[ord(string1[i])-ord('a')]!=0: strng=strng+string1[i] #print(strng) return strng"
},
{
"code": null,
"e": 3304,
"s": 3302,
"text": "0"
},
{
"code": null,
"e": 3341,
"s": 3304,
"text": "meghanareddygopidiPremium1 month ago"
},
{
"code": null,
"e": 3573,
"s": 3341,
"text": "class Solution: def removeChars (ob, string1, string2): l=[] for i in string1: if i not in string2: l.append(i) str1 = \"\" for ele in l: str1 += ele return str1"
},
{
"code": null,
"e": 3575,
"s": 3573,
"text": "0"
},
{
"code": null,
"e": 3601,
"s": 3575,
"text": "raghavendra7771 month ago"
},
{
"code": null,
"e": 3863,
"s": 3601,
"text": "class Solution: def removeChars (ob, string1, string2): # code here s=list(string1) #print(s) for ch in string2: for i in range(0,1000): if ch in s: s.remove(ch) return ''.join(s)"
},
{
"code": null,
"e": 3865,
"s": 3863,
"text": "0"
},
{
"code": null,
"e": 3876,
"s": 3865,
"text": "adira42004"
},
{
"code": null,
"e": 3902,
"s": 3876,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3904,
"s": 3902,
"text": "0"
},
{
"code": null,
"e": 3924,
"s": 3904,
"text": "rahulrs2 months ago"
},
{
"code": null,
"e": 3968,
"s": 3924,
"text": "JAVA CODE.................................."
},
{
"code": null,
"e": 4046,
"s": 3968,
"text": "static String removeChars(String string1, String string2){ // code here"
},
{
"code": null,
"e": 4094,
"s": 4046,
"text": " HashSet<Character> s2 = new HashSet<>();"
},
{
"code": null,
"e": 4433,
"s": 4094,
"text": " // storing all elements of string2 into s2. for(int i=0;i<string2.length();i++){ s2.add(string2.charAt(i)); } String str = \"\"; for(int i=0;i<string1.length();i++){ if(!s2.contains(string1.charAt(i))){ str+=string1.charAt(i); } } return str; }"
},
{
"code": null,
"e": 4579,
"s": 4433,
"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": 4615,
"s": 4579,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4625,
"s": 4615,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4635,
"s": 4625,
"text": "\nContest\n"
},
{
"code": null,
"e": 4698,
"s": 4635,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4846,
"s": 4698,
"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": 5054,
"s": 4846,
"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": 5160,
"s": 5054,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Microsoft Expression Web - Blank Web Page | As we have already created our website, now we will need to create our Home Page. In the previous chapter, we have created a one-page website, and our Home Page was created at that time automatically by Expression Web. So, if you have created a blank website, then you will need to create a Home Page for your site.
Microsoft Expression Web can create the following types of pages −
HTML
ASPX
ASP
PHP
CSS
Master Page
Dynamic Web Template
JavaScript
XML
Text File
In this chapter, we will create an HTML page and its corresponding style sheet.
To create a blank page, you can simply go to File menu and select New → Page... menu option.
From the new dialog, you can create different types of blank pages such as HTML page, ASPX page, CSS page, etc. and click OK.
As you can see here, the default code is already added by Microsoft Expression Web.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<h1>
This is a blank web page
</h1>
</body>
</html>
As you can see, your newly created page has the file name Untitled_1.html or Untitled_1.htm. You will need to save the page by pressing Ctrl + S and specify the name.
As our website already contains an index.html page, we don’t need another one. However, if you have created an Empty website, then name this page index.html.
To see your web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say Internet Explorer.
Let’s take you through the step-by-step process of creating a CSS page.
Step 1 − To create a CSS page, go to the File menu and select New → Page... menu option.
Step 2 − Select General → CSS and click OK.
Step 3 − Save the page and type a name for the style-sheet.
Step 4 − Click the Save button.
Step 5 − Now, let’s go to the index.html page.
Step 6 − In the Manage Styles Panel, click Attach Style Sheet.
Step 7 − Browse to your style-sheet and select the Current page from “Attach to” and Link from “Attach as” and click OK.
Step 8 − Now, you will see that a new line is added automatically in the index.html page.
<link href = "sample.css" rel = "stylesheet" type = "text/css" />
Step 9 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First, select the body tag in Design View and then click on the New Style... in Apply Styles panel or Manage Styles panel, which will open the New Style dialog.
Here, you can define the different options for your style. The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” dropdown list.
Step 10 − From the URL, select the sample.css file. On the left side, there is a Category list like font, background, etc. and currently the Font is highlighted. Set the Font related information as per your requirements as shown in the above screenshot and click Ok.
Step 11 − Now you can see in the design view that the background color and the font has changed to what we have selected. Now, if you open the sample.css file, you will see that all the information is automatically stored in the CSS file.
Let’s preview our web page in a browser. You will observe that the style is applied from the CSS file.
16 Lectures
11.5 hours
SHIVPRASAD KOIRALA
33 Lectures
3 hours
Abhishek And Pukhraj
33 Lectures
5.5 hours
Abhishek And Pukhraj
40 Lectures
6.5 hours
Syed Raza
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2512,
"s": 2196,
"text": "As we have already created our website, now we will need to create our Home Page. In the previous chapter, we have created a one-page website, and our Home Page was created at that time automatically by Expression Web. So, if you have created a blank website, then you will need to create a Home Page for your site."
},
{
"code": null,
"e": 2579,
"s": 2512,
"text": "Microsoft Expression Web can create the following types of pages −"
},
{
"code": null,
"e": 2584,
"s": 2579,
"text": "HTML"
},
{
"code": null,
"e": 2589,
"s": 2584,
"text": "ASPX"
},
{
"code": null,
"e": 2593,
"s": 2589,
"text": "ASP"
},
{
"code": null,
"e": 2597,
"s": 2593,
"text": "PHP"
},
{
"code": null,
"e": 2601,
"s": 2597,
"text": "CSS"
},
{
"code": null,
"e": 2613,
"s": 2601,
"text": "Master Page"
},
{
"code": null,
"e": 2634,
"s": 2613,
"text": "Dynamic Web Template"
},
{
"code": null,
"e": 2645,
"s": 2634,
"text": "JavaScript"
},
{
"code": null,
"e": 2649,
"s": 2645,
"text": "XML"
},
{
"code": null,
"e": 2659,
"s": 2649,
"text": "Text File"
},
{
"code": null,
"e": 2739,
"s": 2659,
"text": "In this chapter, we will create an HTML page and its corresponding style sheet."
},
{
"code": null,
"e": 2832,
"s": 2739,
"text": "To create a blank page, you can simply go to File menu and select New → Page... menu option."
},
{
"code": null,
"e": 2958,
"s": 2832,
"text": "From the new dialog, you can create different types of blank pages such as HTML page, ASPX page, CSS page, etc. and click OK."
},
{
"code": null,
"e": 3042,
"s": 2958,
"text": "As you can see here, the default code is already added by Microsoft Expression Web."
},
{
"code": null,
"e": 3450,
"s": 3042,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <title>Untitled 1</title> \n </head> \n\n <body> \n <h1> \n This is a blank web page \n </h1> \n </body> \n</html> "
},
{
"code": null,
"e": 3617,
"s": 3450,
"text": "As you can see, your newly created page has the file name Untitled_1.html or Untitled_1.htm. You will need to save the page by pressing Ctrl + S and specify the name."
},
{
"code": null,
"e": 3775,
"s": 3617,
"text": "As our website already contains an index.html page, we don’t need another one. However, if you have created an Empty website, then name this page index.html."
},
{
"code": null,
"e": 3909,
"s": 3775,
"text": "To see your web in a browser, let’s go to the File menu and select the Preview in Browser → Any browser, let’s say Internet Explorer."
},
{
"code": null,
"e": 3981,
"s": 3909,
"text": "Let’s take you through the step-by-step process of creating a CSS page."
},
{
"code": null,
"e": 4070,
"s": 3981,
"text": "Step 1 − To create a CSS page, go to the File menu and select New → Page... menu option."
},
{
"code": null,
"e": 4114,
"s": 4070,
"text": "Step 2 − Select General → CSS and click OK."
},
{
"code": null,
"e": 4174,
"s": 4114,
"text": "Step 3 − Save the page and type a name for the style-sheet."
},
{
"code": null,
"e": 4206,
"s": 4174,
"text": "Step 4 − Click the Save button."
},
{
"code": null,
"e": 4253,
"s": 4206,
"text": "Step 5 − Now, let’s go to the index.html page."
},
{
"code": null,
"e": 4316,
"s": 4253,
"text": "Step 6 − In the Manage Styles Panel, click Attach Style Sheet."
},
{
"code": null,
"e": 4437,
"s": 4316,
"text": "Step 7 − Browse to your style-sheet and select the Current page from “Attach to” and Link from “Attach as” and click OK."
},
{
"code": null,
"e": 4527,
"s": 4437,
"text": "Step 8 − Now, you will see that a new line is added automatically in the index.html page."
},
{
"code": null,
"e": 4594,
"s": 4527,
"text": "<link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" /> "
},
{
"code": null,
"e": 4866,
"s": 4594,
"text": "Step 9 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First, select the body tag in Design View and then click on the New Style... in Apply Styles panel or Manage Styles panel, which will open the New Style dialog."
},
{
"code": null,
"e": 5067,
"s": 4866,
"text": "Here, you can define the different options for your style. The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” dropdown list."
},
{
"code": null,
"e": 5334,
"s": 5067,
"text": "Step 10 − From the URL, select the sample.css file. On the left side, there is a Category list like font, background, etc. and currently the Font is highlighted. Set the Font related information as per your requirements as shown in the above screenshot and click Ok."
},
{
"code": null,
"e": 5573,
"s": 5334,
"text": "Step 11 − Now you can see in the design view that the background color and the font has changed to what we have selected. Now, if you open the sample.css file, you will see that all the information is automatically stored in the CSS file."
},
{
"code": null,
"e": 5676,
"s": 5573,
"text": "Let’s preview our web page in a browser. You will observe that the style is applied from the CSS file."
},
{
"code": null,
"e": 5712,
"s": 5676,
"text": "\n 16 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 5732,
"s": 5712,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5765,
"s": 5732,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5787,
"s": 5765,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5822,
"s": 5787,
"text": "\n 33 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5844,
"s": 5822,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5879,
"s": 5844,
"text": "\n 40 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5890,
"s": 5879,
"text": " Syed Raza"
},
{
"code": null,
"e": 5923,
"s": 5890,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5963,
"s": 5923,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 5998,
"s": 5963,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6038,
"s": 5998,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 6045,
"s": 6038,
"text": " Print"
},
{
"code": null,
"e": 6056,
"s": 6045,
"text": " Add Notes"
}
] |
Explicitly assigning port number to client in Socket - GeeksforGeeks | 09 Nov, 2021
Prerequisite: Socket programming in C/C++.In socket programming, when server and client are connected then the client is provided any random port number by an operating system to run and generally, we don’t care about it, But in some cases, there may be a firewall on the client-side that only allows outgoing connections on certain port numbers. So, it is highly probable that the port number provided to the client by the operating system may have been blocked by the client firewall. In that case, we need to explicitly or forcefully assign any port number to the client on which it can operate.
Some protocol like NFS protocol requires the client program to run on only a certain port number and so in this case, the client needs to forcefully assign that port number only as it runs on port number either on 111 or on 2049. This can be done using a bind() system call specifying a particular port number in a client-side socket.
Below is the implementation Server and Client program where a client will be forcefully get assigned a port number.
Server Side Program
C
// C program to demonstrate// socket programming in finding ip address// and port number of connected client// on Server Side#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<string.h>#include<netdb.h>#include<netinet/in.h>#include<arpa/inet.h>#include<string.h> int main(){ // Two buffers for message communication char buffer1[256], buffer2[256]; int server = socket(AF_INET, SOCK_STREAM, 0); if (server < 0) printf("Error in server creating\n"); else printf("Server Created\n"); struct sockaddr_in my_addr, peer_addr; my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; // This ip address will change according to the machine my_addr.sin_addr.s_addr = inet_addr("10.32.40.213"); my_addr.sin_port = htons(12000); if (bind(server, (struct sockaddr*) &my_addr, sizeof(my_addr)) == 0) printf("Binded Correctly\n"); else printf("Unable to bind\n"); if (listen(server, 3) == 0) printf("Listening ...\n"); else printf("Unable to listen\n"); socklen_t addr_size; addr_size = sizeof(struct sockaddr_in); // Ip character array will store the ip address of client char *ip; // while loop is iterated infinitely to // accept infinite connection one by one while (1) { int acc = accept(server, (struct sockaddr*) &peer_addr, &addr_size); printf("Connection Established\n"); char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(peer_addr.sin_addr), ip, INET_ADDRSTRLEN); // "ntohs(peer_addr.sin_port)" function is // for finding port number of client printf("connection established with IP : %s and PORT : %d\n", ip, ntohs(peer_addr.sin_port)); recv(acc, buffer2, 256, 0); printf("Client : %s\n", buffer2); strcpy(buffer1, "Hello"); send(acc, buffer1, 256, 0); } return 0;}
Output:
Server Created
Binded Correctly
Listening ...
Connection Established
connection established with IP : 10.32.40.213 and PORT : 12010
Client : Hello
Client-Side Program
C
// C program to demonstrate socket programming// as well as explicitly assigning a port number// on Client Side#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<string.h>#include<netdb.h>#include<netinet/in.h>#include<arpa/inet.h>#include<stdlib.h> int main(){ // Two buffer are for message communication char buffer1[256], buffer2[256]; struct sockaddr_in my_addr, my_addr1; int client = socket(AF_INET, SOCK_STREAM, 0); if (client < 0) printf("Error in client creating\n"); else printf("Client Created\n"); my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_port = htons(12000); // This ip address will change according to the machine my_addr.sin_addr.s_addr = inet_addr("10.32.40.213"); // Explicitly assigning port number 12010 by // binding client with that port my_addr1.sin_family = AF_INET; my_addr1.sin_addr.s_addr = INADDR_ANY; my_addr1.sin_port = htons(12010); // This ip address will change according to the machine my_addr1.sin_addr.s_addr = inet_addr("10.32.40.213"); if (bind(client, (struct sockaddr*) &my_addr1, sizeof(struct sockaddr_in)) == 0) printf("Binded Correctly\n"); else printf("Unable to bind\n"); socklen_t addr_size = sizeof my_addr; int con = connect(client, (struct sockaddr*) &my_addr, sizeof my_addr); if (con == 0) printf("Client Connected\n"); else printf("Error in Connection\n"); strcpy(buffer2, "Hello"); send(client, buffer2, 256, 0); recv(client, buffer1, 256, 0); printf("Server : %s\n", buffer1); return 0;}
Output:
Client Created
Binded Correctly
Client Connected
Server : Hello
Reference: https://stackoverflow.com/questions/4118241/what-client-side-situations-need-bind
This article is contributed by Aditya 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
marcosarcticseal
C-Library
C Language
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Layers of OSI Model
TCP/IP Model
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 24831,
"s": 24232,
"text": "Prerequisite: Socket programming in C/C++.In socket programming, when server and client are connected then the client is provided any random port number by an operating system to run and generally, we don’t care about it, But in some cases, there may be a firewall on the client-side that only allows outgoing connections on certain port numbers. So, it is highly probable that the port number provided to the client by the operating system may have been blocked by the client firewall. In that case, we need to explicitly or forcefully assign any port number to the client on which it can operate."
},
{
"code": null,
"e": 25166,
"s": 24831,
"text": "Some protocol like NFS protocol requires the client program to run on only a certain port number and so in this case, the client needs to forcefully assign that port number only as it runs on port number either on 111 or on 2049. This can be done using a bind() system call specifying a particular port number in a client-side socket."
},
{
"code": null,
"e": 25282,
"s": 25166,
"text": "Below is the implementation Server and Client program where a client will be forcefully get assigned a port number."
},
{
"code": null,
"e": 25303,
"s": 25282,
"text": "Server Side Program "
},
{
"code": null,
"e": 25305,
"s": 25303,
"text": "C"
},
{
"code": "// C program to demonstrate// socket programming in finding ip address// and port number of connected client// on Server Side#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<string.h>#include<netdb.h>#include<netinet/in.h>#include<arpa/inet.h>#include<string.h> int main(){ // Two buffers for message communication char buffer1[256], buffer2[256]; int server = socket(AF_INET, SOCK_STREAM, 0); if (server < 0) printf(\"Error in server creating\\n\"); else printf(\"Server Created\\n\"); struct sockaddr_in my_addr, peer_addr; my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; // This ip address will change according to the machine my_addr.sin_addr.s_addr = inet_addr(\"10.32.40.213\"); my_addr.sin_port = htons(12000); if (bind(server, (struct sockaddr*) &my_addr, sizeof(my_addr)) == 0) printf(\"Binded Correctly\\n\"); else printf(\"Unable to bind\\n\"); if (listen(server, 3) == 0) printf(\"Listening ...\\n\"); else printf(\"Unable to listen\\n\"); socklen_t addr_size; addr_size = sizeof(struct sockaddr_in); // Ip character array will store the ip address of client char *ip; // while loop is iterated infinitely to // accept infinite connection one by one while (1) { int acc = accept(server, (struct sockaddr*) &peer_addr, &addr_size); printf(\"Connection Established\\n\"); char ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(peer_addr.sin_addr), ip, INET_ADDRSTRLEN); // \"ntohs(peer_addr.sin_port)\" function is // for finding port number of client printf(\"connection established with IP : %s and PORT : %d\\n\", ip, ntohs(peer_addr.sin_port)); recv(acc, buffer2, 256, 0); printf(\"Client : %s\\n\", buffer2); strcpy(buffer1, \"Hello\"); send(acc, buffer1, 256, 0); } return 0;}",
"e": 27302,
"s": 25305,
"text": null
},
{
"code": null,
"e": 27311,
"s": 27302,
"text": "Output: "
},
{
"code": null,
"e": 27458,
"s": 27311,
"text": "Server Created\nBinded Correctly\nListening ...\nConnection Established\nconnection established with IP : 10.32.40.213 and PORT : 12010\nClient : Hello"
},
{
"code": null,
"e": 27479,
"s": 27458,
"text": "Client-Side Program "
},
{
"code": null,
"e": 27481,
"s": 27479,
"text": "C"
},
{
"code": "// C program to demonstrate socket programming// as well as explicitly assigning a port number// on Client Side#include<stdio.h>#include<sys/types.h>#include<sys/socket.h>#include<sys/un.h>#include<string.h>#include<netdb.h>#include<netinet/in.h>#include<arpa/inet.h>#include<stdlib.h> int main(){ // Two buffer are for message communication char buffer1[256], buffer2[256]; struct sockaddr_in my_addr, my_addr1; int client = socket(AF_INET, SOCK_STREAM, 0); if (client < 0) printf(\"Error in client creating\\n\"); else printf(\"Client Created\\n\"); my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_port = htons(12000); // This ip address will change according to the machine my_addr.sin_addr.s_addr = inet_addr(\"10.32.40.213\"); // Explicitly assigning port number 12010 by // binding client with that port my_addr1.sin_family = AF_INET; my_addr1.sin_addr.s_addr = INADDR_ANY; my_addr1.sin_port = htons(12010); // This ip address will change according to the machine my_addr1.sin_addr.s_addr = inet_addr(\"10.32.40.213\"); if (bind(client, (struct sockaddr*) &my_addr1, sizeof(struct sockaddr_in)) == 0) printf(\"Binded Correctly\\n\"); else printf(\"Unable to bind\\n\"); socklen_t addr_size = sizeof my_addr; int con = connect(client, (struct sockaddr*) &my_addr, sizeof my_addr); if (con == 0) printf(\"Client Connected\\n\"); else printf(\"Error in Connection\\n\"); strcpy(buffer2, \"Hello\"); send(client, buffer2, 256, 0); recv(client, buffer1, 256, 0); printf(\"Server : %s\\n\", buffer1); return 0;}",
"e": 29149,
"s": 27481,
"text": null
},
{
"code": null,
"e": 29158,
"s": 29149,
"text": "Output: "
},
{
"code": null,
"e": 29222,
"s": 29158,
"text": "Client Created\nBinded Correctly\nClient Connected\nServer : Hello"
},
{
"code": null,
"e": 29315,
"s": 29222,
"text": "Reference: https://stackoverflow.com/questions/4118241/what-client-side-situations-need-bind"
},
{
"code": null,
"e": 29736,
"s": 29315,
"text": "This article is contributed by Aditya 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29753,
"s": 29736,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 29763,
"s": 29753,
"text": "C-Library"
},
{
"code": null,
"e": 29774,
"s": 29763,
"text": "C Language"
},
{
"code": null,
"e": 29792,
"s": 29774,
"text": "Computer Networks"
},
{
"code": null,
"e": 29810,
"s": 29792,
"text": "Computer Networks"
},
{
"code": null,
"e": 29908,
"s": 29810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29946,
"s": 29908,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29966,
"s": 29946,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29992,
"s": 29966,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 30014,
"s": 29992,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 30055,
"s": 30014,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30075,
"s": 30055,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 30088,
"s": 30075,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 30118,
"s": 30088,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 30156,
"s": 30118,
"text": "TCP Server-Client implementation in C"
}
] |
Kotlin - Basic Types | In this chapter, we will learn about the basic data types available in Kotlin programming language.
The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Following table lists different variable lengths for different numbers.
In the following example, we will see how Kotlin works with different data types. Please enter the following set of code in our coding ground.
fun main(args: Array<String>) {
val a: Int = 10000
val d: Double = 100.00
val f: Float = 100.00f
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("Your Int Value is "+a);
println("Your Double Value is "+d);
println("Your Float Value is "+f);
println("Your Long Value is "+l);
println("Your Short Value is "+s);
println("Your Byte Value is "+b);
}
When you run the above piece of code in the coding ground, it will generate the following output in the web console.
Your Int Value is 10000
Your Double Value is 100.0
Your Float Value is 100.0
Your Long Value is 1000000004
Your Short Value is 10
Your Byte Value is 1
Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interprets the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”.
fun main(args: Array<String>) {
val letter: Char // defining a variable
letter = 'A' // Assigning a value to it
println("$letter")
}
The above piece of code will yield the following output in the browser output window.
A
Boolean is very simple like other programming languages. We have only two values for Boolean – either true or false. In the following example, we will see how Kotlin interprets Boolean.
fun main(args: Array<String>) {
val letter: Boolean // defining a variable
letter = true // Assinging a value to it
println("Your character value is "+"$letter")
}
The above piece of code will yield the following output in the browser.
Your character value is true
Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings.
fun main(args: Array<String>) {
var rawString :String = "I am Raw String!"
val escapedString : String = "I am escaped String!\n"
println("Hello!"+escapedString)
println("Hey!!"+rawString)
}
The above example of escaped String allows to provide extra line space after the first print statement. Following will be the output in the browser.
Hello!I am escaped String!
Hey!!I am Raw String!
Arrays are a collection of homogeneous data. Like Java, Kotlin supports arrays of different data types. In the following example, we will make use of different arrays.
fun main(args: Array<String>) {
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Hey!! I am array Example"+numbers[2])
}
The above piece of code yields the following output. The indexing of the array is similar to other programming languages. Here, we are searching for a second index, whose value is “3”.
Hey!! I am array Example3
Collection is a very important part of the data structure, which makes the software development easy for engineers. Kotlin has two types of collection - one is immutable collection (which means lists, maps and sets that cannot be editable) and another is mutable collection (this type of collection is editable). It is very important to keep in mind the type of collection used in your application, as Kotlin system does not represent any specific difference in them.
fun main(args: Array<String>) {
val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List
val readOnlyView: List<Int> = numbers // immutable list
println("my mutable list--"+numbers) // prints "[1, 2, 3]"
numbers.add(4)
println("my mutable list after addition --"+numbers) // prints "[1, 2, 3, 4]"
println(readOnlyView)
readOnlyView.clear() // ⇒ does not compile
// gives error
}
The above piece of code will yield the following output in the browser. It gives an error when we try to clear the mutable list of collection.
main.kt:9:18: error: unresolved reference: clear
readOnlyView.clear() // -> does not compile
^
In collection, Kotlin provides some useful methods such as first(), last(), filter(), etc. All these methods are self-descriptive and easy to implement. Moreover, Kotlin follows the same structure such as Java while implementing collection. You are free to implement any collection of your choice such as Map and Set.
In the following example, we have implemented Map and Set using different built-in methods.
fun main(args: Array<String>) {
val items = listOf(1, 2, 3, 4)
println("First Element of our list----"+items.first())
println("Last Element of our list----"+items.last())
println("Even Numbers of our List----"+items.
filter { it % 2 = = 0 }) // returns [2, 4]
val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
println(readWriteMap["foo"]) // prints "1"
val strings = hashSetOf("a", "b", "c", "c")
println("My Set Values are"+strings)
}
The above piece of code yields the following output in the browser.
First Element of our list----1
Last Element of our list----4
Even Numbers of our List----[2, 4]
1
My Set Values are[a, b, c]
Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..).
In the following example, we will see how Kotlin interprets this range operator.
fun main(args: Array<String>) {
val i:Int = 2
for (j in 1..4)
print(j) // prints "1234"
if (i in 1..10) { // equivalent of 1 < = i && i < = 10
println("we found your number --"+i)
}
}
The above piece of code yields the following output in the browser.
1234we found your number --2
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2525,
"s": 2425,
"text": "In this chapter, we will learn about the basic data types available in Kotlin programming language."
},
{
"code": null,
"e": 2740,
"s": 2525,
"text": "The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not allow internal conversion of different data types. Following table lists different variable lengths for different numbers."
},
{
"code": null,
"e": 2883,
"s": 2740,
"text": "In the following example, we will see how Kotlin works with different data types. Please enter the following set of code in our coding ground."
},
{
"code": null,
"e": 3289,
"s": 2883,
"text": "fun main(args: Array<String>) {\n val a: Int = 10000\n val d: Double = 100.00\n val f: Float = 100.00f\n val l: Long = 1000000004\n val s: Short = 10\n val b: Byte = 1\n \n println(\"Your Int Value is \"+a);\n println(\"Your Double Value is \"+d);\n println(\"Your Float Value is \"+f);\n println(\"Your Long Value is \"+l);\n println(\"Your Short Value is \"+s);\n println(\"Your Byte Value is \"+b);\n}"
},
{
"code": null,
"e": 3406,
"s": 3289,
"text": "When you run the above piece of code in the coding ground, it will generate the following output in the web console."
},
{
"code": null,
"e": 3559,
"s": 3406,
"text": "Your Int Value is 10000\nYour Double Value is 100.0\nYour Float Value is 100.0\nYour Long Value is 1000000004\nYour Short Value is 10\nYour Byte Value is 1\n"
},
{
"code": null,
"e": 3911,
"s": 3559,
"text": "Kotlin represents character using char. Character should be declared in a single quote like ‘c’. Please enter the following code in our coding ground and see how Kotlin interprets the character variable. Character variable cannot be declared like number variables. Kotlin variable can be declared in two ways - one using “var” and another using “val”."
},
{
"code": null,
"e": 4065,
"s": 3911,
"text": "fun main(args: Array<String>) {\n val letter: Char // defining a variable \n letter = 'A' // Assigning a value to it \n println(\"$letter\")\n}"
},
{
"code": null,
"e": 4151,
"s": 4065,
"text": "The above piece of code will yield the following output in the browser output window."
},
{
"code": null,
"e": 4154,
"s": 4151,
"text": "A\n"
},
{
"code": null,
"e": 4340,
"s": 4154,
"text": "Boolean is very simple like other programming languages. We have only two values for Boolean – either true or false. In the following example, we will see how Kotlin interprets Boolean."
},
{
"code": null,
"e": 4525,
"s": 4340,
"text": "fun main(args: Array<String>) {\n val letter: Boolean // defining a variable \n letter = true // Assinging a value to it \n println(\"Your character value is \"+\"$letter\")\n}"
},
{
"code": null,
"e": 4597,
"s": 4525,
"text": "The above piece of code will yield the following output in the browser."
},
{
"code": null,
"e": 4627,
"s": 4597,
"text": "Your character value is true\n"
},
{
"code": null,
"e": 4872,
"s": 4627,
"text": "Strings are character arrays. Like Java, they are immutable in nature. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. In the following example, we will make use of these strings."
},
{
"code": null,
"e": 5083,
"s": 4872,
"text": "fun main(args: Array<String>) {\n var rawString :String = \"I am Raw String!\"\n val escapedString : String = \"I am escaped String!\\n\"\n \n println(\"Hello!\"+escapedString)\n println(\"Hey!!\"+rawString) \n}"
},
{
"code": null,
"e": 5232,
"s": 5083,
"text": "The above example of escaped String allows to provide extra line space after the first print statement. Following will be the output in the browser."
},
{
"code": null,
"e": 5283,
"s": 5232,
"text": "Hello!I am escaped String!\n\nHey!!I am Raw String!\n"
},
{
"code": null,
"e": 5451,
"s": 5283,
"text": "Arrays are a collection of homogeneous data. Like Java, Kotlin supports arrays of different data types. In the following example, we will make use of different arrays."
},
{
"code": null,
"e": 5588,
"s": 5451,
"text": "fun main(args: Array<String>) {\n val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)\n println(\"Hey!! I am array Example\"+numbers[2])\n}"
},
{
"code": null,
"e": 5773,
"s": 5588,
"text": "The above piece of code yields the following output. The indexing of the array is similar to other programming languages. Here, we are searching for a second index, whose value is “3”."
},
{
"code": null,
"e": 5800,
"s": 5773,
"text": "Hey!! I am array Example3\n"
},
{
"code": null,
"e": 6268,
"s": 5800,
"text": "Collection is a very important part of the data structure, which makes the software development easy for engineers. Kotlin has two types of collection - one is immutable collection (which means lists, maps and sets that cannot be editable) and another is mutable collection (this type of collection is editable). It is very important to keep in mind the type of collection used in your application, as Kotlin system does not represent any specific difference in them."
},
{
"code": null,
"e": 6730,
"s": 6268,
"text": "fun main(args: Array<String>) { \n val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //mutable List \n val readOnlyView: List<Int> = numbers // immutable list \n println(\"my mutable list--\"+numbers) // prints \"[1, 2, 3]\" \n numbers.add(4) \n println(\"my mutable list after addition --\"+numbers) // prints \"[1, 2, 3, 4]\" \n println(readOnlyView) \n readOnlyView.clear() // ⇒ does not compile \n// gives error \n}"
},
{
"code": null,
"e": 6873,
"s": 6730,
"text": "The above piece of code will yield the following output in the browser. It gives an error when we try to clear the mutable list of collection."
},
{
"code": null,
"e": 6994,
"s": 6873,
"text": "main.kt:9:18: error: unresolved reference: clear\n readOnlyView.clear() // -> does not compile \n ^\n"
},
{
"code": null,
"e": 7312,
"s": 6994,
"text": "In collection, Kotlin provides some useful methods such as first(), last(), filter(), etc. All these methods are self-descriptive and easy to implement. Moreover, Kotlin follows the same structure such as Java while implementing collection. You are free to implement any collection of your choice such as Map and Set."
},
{
"code": null,
"e": 7404,
"s": 7312,
"text": "In the following example, we have implemented Map and Set using different built-in methods."
},
{
"code": null,
"e": 7884,
"s": 7404,
"text": "fun main(args: Array<String>) {\n val items = listOf(1, 2, 3, 4)\n println(\"First Element of our list----\"+items.first())\n println(\"Last Element of our list----\"+items.last())\n println(\"Even Numbers of our List----\"+items.\n filter { it % 2 = = 0 }) // returns [2, 4]\n \n val readWriteMap = hashMapOf(\"foo\" to 1, \"bar\" to 2)\n println(readWriteMap[\"foo\"]) // prints \"1\"\n \n val strings = hashSetOf(\"a\", \"b\", \"c\", \"c\")\n println(\"My Set Values are\"+strings)\n}"
},
{
"code": null,
"e": 7952,
"s": 7884,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 8078,
"s": 7952,
"text": "First Element of our list----1\nLast Element of our list----4\nEven Numbers of our List----[2, 4]\n1\nMy Set Values are[a, b, c]\n"
},
{
"code": null,
"e": 8285,
"s": 8078,
"text": "Ranges is another unique characteristic of Kotlin. Like Haskell, it provides an operator that helps you iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..)."
},
{
"code": null,
"e": 8366,
"s": 8285,
"text": "In the following example, we will see how Kotlin interprets this range operator."
},
{
"code": null,
"e": 8577,
"s": 8366,
"text": "fun main(args: Array<String>) {\n val i:Int = 2\n for (j in 1..4) \n print(j) // prints \"1234\"\n \n if (i in 1..10) { // equivalent of 1 < = i && i < = 10\n println(\"we found your number --\"+i)\n }\n}"
},
{
"code": null,
"e": 8645,
"s": 8577,
"text": "The above piece of code yields the following output in the browser."
},
{
"code": null,
"e": 8675,
"s": 8645,
"text": "1234we found your number --2\n"
},
{
"code": null,
"e": 8710,
"s": 8675,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8729,
"s": 8710,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8764,
"s": 8729,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8781,
"s": 8764,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8816,
"s": 8781,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8833,
"s": 8816,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 8866,
"s": 8833,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8882,
"s": 8866,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 8917,
"s": 8882,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8937,
"s": 8917,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8970,
"s": 8937,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8987,
"s": 8970,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 8994,
"s": 8987,
"text": " Print"
},
{
"code": null,
"e": 9005,
"s": 8994,
"text": " Add Notes"
}
] |
Longest Repeating Substring in C++ | Suppose we have a string S, we have to find the length of the longest repeating substring(s). We will return 0 if no repeating substring is present. So if the string is like “abbaba”, then the output will be 2. As the longest repeating substring is “ab” or “ba”.
Return all words that can be formed in this manner, in lexicographical order.
To solve this, we will follow these steps −
n := size of S
n := size of S
set S := one blank space concatenated with S
set S := one blank space concatenated with S
set ret := 0
set ret := 0
create one matrix dp of size (n + 1) x (n + 1)
create one matrix dp of size (n + 1) x (n + 1)
for i in range 1 to nfor j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
for i in range 1 to n
for j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
for j in range i + 1 to n
if S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]
if S[i] = S[j]
dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]
dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]
ret := max of ret and dp[i, j]
ret := max of ret and dp[i, j]
return ret
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestRepeatingSubstring(string S) {
int n = S.size();
S = " " + S;
int ret = 0;
vector < vector <int> > dp(n + 1, vector <int> (n + 1));
for(int i = 1; i <= n; i++){
for(int j = i + 1; j <= n; j++){
if(S[i] == S[j]){
dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
ret = max(ret, dp[i][j]);
}
}
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.longestRepeatingSubstring("abbaba"));
}
"abbaba"
2 | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "Suppose we have a string S, we have to find the length of the longest repeating substring(s). We will return 0 if no repeating substring is present. So if the string is like “abbaba”, then the output will be 2. As the longest repeating substring is “ab” or “ba”."
},
{
"code": null,
"e": 1403,
"s": 1325,
"text": "Return all words that can be formed in this manner, in lexicographical order."
},
{
"code": null,
"e": 1447,
"s": 1403,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1462,
"s": 1447,
"text": "n := size of S"
},
{
"code": null,
"e": 1477,
"s": 1462,
"text": "n := size of S"
},
{
"code": null,
"e": 1522,
"s": 1477,
"text": "set S := one blank space concatenated with S"
},
{
"code": null,
"e": 1567,
"s": 1522,
"text": "set S := one blank space concatenated with S"
},
{
"code": null,
"e": 1580,
"s": 1567,
"text": "set ret := 0"
},
{
"code": null,
"e": 1593,
"s": 1580,
"text": "set ret := 0"
},
{
"code": null,
"e": 1640,
"s": 1593,
"text": "create one matrix dp of size (n + 1) x (n + 1)"
},
{
"code": null,
"e": 1687,
"s": 1640,
"text": "create one matrix dp of size (n + 1) x (n + 1)"
},
{
"code": null,
"e": 1830,
"s": 1687,
"text": "for i in range 1 to nfor j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]"
},
{
"code": null,
"e": 1852,
"s": 1830,
"text": "for i in range 1 to n"
},
{
"code": null,
"e": 1974,
"s": 1852,
"text": "for j in range i + 1 to nif S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]"
},
{
"code": null,
"e": 2000,
"s": 1974,
"text": "for j in range i + 1 to n"
},
{
"code": null,
"e": 2097,
"s": 2000,
"text": "if S[i] = S[j]dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]ret := max of ret and dp[i, j]"
},
{
"code": null,
"e": 2112,
"s": 2097,
"text": "if S[i] = S[j]"
},
{
"code": null,
"e": 2165,
"s": 2112,
"text": "dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]"
},
{
"code": null,
"e": 2218,
"s": 2165,
"text": "dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j - 1]"
},
{
"code": null,
"e": 2249,
"s": 2218,
"text": "ret := max of ret and dp[i, j]"
},
{
"code": null,
"e": 2280,
"s": 2249,
"text": "ret := max of ret and dp[i, j]"
},
{
"code": null,
"e": 2291,
"s": 2280,
"text": "return ret"
},
{
"code": null,
"e": 2302,
"s": 2291,
"text": "return ret"
},
{
"code": null,
"e": 2372,
"s": 2302,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": " Live Demo"
},
{
"code": null,
"e": 2976,
"s": 2383,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int longestRepeatingSubstring(string S) {\n int n = S.size();\n S = \" \" + S;\n int ret = 0;\n vector < vector <int> > dp(n + 1, vector <int> (n + 1));\n for(int i = 1; i <= n; i++){\n for(int j = i + 1; j <= n; j++){\n if(S[i] == S[j]){\n dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);\n ret = max(ret, dp[i][j]);\n }\n }\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.longestRepeatingSubstring(\"abbaba\"));\n}"
},
{
"code": null,
"e": 2985,
"s": 2976,
"text": "\"abbaba\""
},
{
"code": null,
"e": 2987,
"s": 2985,
"text": "2"
}
] |
Serve a TensorFlow 2 Deep Learning Classifier as a REST API (with GPU support), Part I | by Hamed ZITOUN | Towards Data Science | This series of articles will help you to move from notebooks to real-world use cases of Data Science techniques! We’ll take a Deep Learning classifier from zero to production 🚀!
Disclaimer: You should have prior knowledge and experience with CNN-Convolutional Neural Networks.
The dataset we will use to train our Convolutional Neural Networks classifier is CIFAR-10 (don’t download it yet). The CIFAR-10 dataset comprises 60000 32x32 color images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images.
Here are the classes in the dataset, and 10 random images from each:
Ready? Let’s go!
Too much inspired by the cookiecutter-data-science open-source template, here is my favorite Data Science project structure:
In the data/raw, I copy my original data and in data/processed; I keep the pre-processed data.
In the deploy folder, you can find the Dockerfile and either requirements.txt or environment.yml (holding only production libs)
In the models’ folder, I store the saved models.
In the notebooks folder, I have my notebooks (.ipynb files)
In the references folder, I put the metadata and all references to resources I’m using in the project (pdf, notes... etc)
In the reports folder, I put all the graphs, and reports (png, pdf, slides) containing insights to share with my team
In the src folder, there are my Python scripts grouped in the following manner: src/api folder for scripts aiming to create a REST API, src/data folder contains scripts for processing the data, src/dags folder contains my Airflow DAGs, src/models folder for scripts dealing with our ML/DL models and finally, src/visualization folder holds scripts for data viz and reports exporting.
The tests folder contains the python script for testing my app
logging.yaml where I configure my Python logger
db_config.json just a JSON file holding some database access configs
For simplification reason, let us ease off a bit our project structure by only creating (keep everything empty for the moment):
data folder
deploy folder
models folder
notebooks folder
src folder within src/model and src/api sub-folders
environment.yml file
logging.yml file
Just like me, you end up with these folders
Great! You got a clean project structure ready! Let us set up our working environment!
Follow these steps to create a virtual Python 3 work environment defined in environment.yml file and configure your GPU:
2.1 — Install Miniconda 3 (or Anaconda 3)
2.2 — Make sure that conda is on your path (otherwise add the bin file to your $PATH):
$ which conda~/anaconda3/bin/conda
2.3 — If you have a NVIDIA® GPU card with CUDA® Compute Capability 3.5 or higher, enable TensorFlow GPU support by following these steps https://www.tensorflow.org/install/gpu#software_requirements (don’t pip install tensorflow yet! configure CUDA first we’ll install tf2 in the next step 2.4)
2.4 — We now call our virtual environment tf2-image-classifier-api and then specify the required packages in environment.yml file (copy-paste the following code): tensorflow-gpu, numpy, seaborn, and jupyter are for image classifier creation. Flask and waitress are for REST API creation. tqdm for getting a pleasant progress bar and finally, opencv-python is for image pre-processing!
2.5 — Now go to the project root and create a virtual environment:
$ conda env create -f environment.yml
2.6 — Activate the virtual environment
conda activate tf2-image-classifier-api
You should now have your virtual environment activated!
Bonus (FYI only not needed now):
To entirely remove the environment
conda env remove — name tf2-image-classifier-api
To update the environment packages to the latest compatible version
conda env update -f environment.yml
2.7 — Download CIFAR-10 Dataset but in png format from here
2.8 — Copy the downloaded cifar.tgz file to the data/raw folder and unzip it there (you should get the train folder, the test folder and the labels.txt file)
Great! Now your environment and your dataset are ready for our image classifier training and predicting!
Start by running jupyter notebook command in the project’s root:
$ jupyter notebook
Now navigate to http://localhost:8888/tree/notebooks
Create a new notebook
And follow these steps:
For the first time, it would take a few minutes to load the required cuDNN libs (help TensorFlow discover your GPU device). If everything is ok, you’ll get similar results to mine (except that I have a GTX 960M/CUDA v10.2).
But before we need to define two methods; read_image & load_dataset
Read an image using OpenCV
Test the method by visualizing some images
Results
Load dataset and return images and targets as numpy arrays
Now we are ready to load our training & test datasets!
Check your training data & test data shapes
If everything is OK, you’ll get results similar to mine.
Great! Now we have loaded our libs, and our datasets are ready! Let’s create our CNN architecture!
We do not need to re-invent the wheel, we will use this CNN architecture but in TensorFlow 2.2!
The entire model comprises 16 layers in total:
Batch NormalizationConvolution with 64 different filters in size of (3x3)Max Pooling by 2
Batch Normalization
Convolution with 64 different filters in size of (3x3)
Max Pooling by 2
ReLU activation function
Batch Normalization
4. Convolution with 128 different filters in size of (3x3)
5. Max Pooling by 2
ReLU activation function
Batch Normalization
6. Convolution with 256 different filters in size of (3x3)
7. Max Pooling by 2
ReLU activation function
Batch Normalization
8. Convolution with 512 different filters in size of (3x3)
9. Max Pooling by 2
ReLU activation function
Batch Normalization
10. Flattening the 3-D output of the last convolutional operations.
11. Fully Connected Layer with 128 units
Dropout
Batch Normalization
12. Fully Connected Layer with 256 units
Dropout
Batch Normalization
13. Fully Connected Layer with 512 units
Dropout
Batch Normalization
14. Fully Connected Layer with 1024 units
Dropout
Batch Normalization
15. Fully Connected Layer with 10 units (number of image classes)
16. Softmax
Cool! Now we have our helper functions ready to create our CNN!
Now we can define our training hyper-parameters:
Everything is OK now to instantiate our model. Also, let’s check its summary.
That should print
Model: "keras_image_classification_model"_________________________________________________________________Layer (type) Output Shape Param # =================================================================inputs (InputLayer) [(None, 32, 32, 3)] 0 _________________________________________________________________batch_normalization_15 (Batc (None, 32, 32, 3) 12 _________________________________________________________________conv_1_features (Conv2D) (None, 32, 32, 64) 1792 _________________________________________________________________max_pooling2d_8 (MaxPooling2 (None, 16, 16, 64) 0 _________________________________________________________________batch_normalization_16 (Batc (None, 16, 16, 64) 256 _________________________________________________________________conv_2_features (Conv2D) (None, 16, 16, 128) 73856 _________________________________________________________________max_pooling2d_9 (MaxPooling2 (None, 8, 8, 128) 0 _________________________________________________________________batch_normalization_17 (Batc (None, 8, 8, 128) 512 _________________________________________________________________conv_3_features (Conv2D) (None, 8, 8, 256) 819456 _________________________________________________________________max_pooling2d_10 (MaxPooling (None, 4, 4, 256) 0 _________________________________________________________________batch_normalization_18 (Batc (None, 4, 4, 256) 1024 _________________________________________________________________conv_4_features (Conv2D) (None, 4, 4, 512) 3277312 _________________________________________________________________max_pooling2d_11 (MaxPooling (None, 2, 2, 512) 0 _________________________________________________________________batch_normalization_19 (Batc (None, 2, 2, 512) 2048 _________________________________________________________________flatten_2 (Flatten) (None, 2048) 0 _________________________________________________________________dense_1_features (Dense) (None, 128) 262272 _________________________________________________________________dropout_4 (Dropout) (None, 128) 0 _________________________________________________________________batch_normalization_20 (Batc (None, 128) 512 _________________________________________________________________dense_2_features (Dense) (None, 256) 33024 _________________________________________________________________dropout_5 (Dropout) (None, 256) 0 _________________________________________________________________batch_normalization_21 (Batc (None, 256) 1024 _________________________________________________________________dense_3_features (Dense) (None, 512) 131584 _________________________________________________________________dropout_6 (Dropout) (None, 512) 0 _________________________________________________________________batch_normalization_22 (Batc (None, 512) 2048 _________________________________________________________________dense_4_features (Dense) (None, 1024) 525312 _________________________________________________________________dropout_7 (Dropout) (None, 1024) 0 _________________________________________________________________batch_normalization_23 (Batc (None, 1024) 4096 _________________________________________________________________dense_1 (Dense) (None, 10) 10250 _________________________________________________________________softmax (Softmax) (None, 10) 0 =================================================================Total params: 5,146,390Trainable params: 5,140,624Non-trainable params: 5,766
Wonderful! 5,140,624 params to train!
To train our model, we will use RMSprop as an optimizer & SparseCategoricalCrossentropy as a loss function. Why SparseCategoricalCrossentropy not just CategoricalCrossentropy? Good question! Here is why!
Now we are good to compile our model!
Everything is ready to train our model. Let us, however, define three callbacks:
EarlyStopping to stop training when no our metric has stopped improving
TensorBoard callback to check our model’s training history
TqdmCallback tqdm keras callback for epoch and batch progress
If everything is OK, your model should start training! You should get results similar to mine.
Great! Your GPU is burning now 🔥! Leave it training your model and we’ll get back when training finishes! (Here a screenshot of my GPU working hard)
Take snap if you want like Tom!
Cool! Our classifier has finished training! Time to evaluate it, right? How is it working on the test images? We can check that by launching the tensorboard interface in our notebook using the following command.
%tensorboard --logdir logs
This command should start tensorboard with accuracy & loss graphs for training and validation:
But wait, accuracy is not a good evaluation metric for a classifier! Let us check precision, recall, and f1 score on each class! We can do that thanks to scikit-learn’s classification_report method:
These are my results:
precision recall f1-score support airplane 0.84 0.86 0.85 1000 automobile 0.92 0.92 0.92 1000 bird 0.76 0.72 0.74 1000 cat 0.63 0.67 0.65 1000 deer 0.80 0.81 0.80 1000 dog 0.74 0.72 0.73 1000 frog 0.86 0.86 0.86 1000 horse 0.87 0.86 0.86 1000 ship 0.91 0.90 0.91 1000 truck 0.88 0.89 0.88 1000 accuracy 0.82 10000 macro avg 0.82 0.82 0.82 10000weighted avg 0.82 0.82 0.82 10000
Nice as a first try, right? 0.82 precision & 0.82 recall! We can tune our hyper-parameters and retrain the model to get better results!
Respond to the story with your results! I would be happy to check them! 😊
Let us make an inference test. Giving an image from the test set, let us discover what our model sees!
Result
Nice! Our model is performing pretty well on test data, we can now export it to disk. Our saved model is for making inferences and will get exposed as a REST API!
Finally, let us check if the saved model works fine by loading it!
Wonderful! Wonderful! Wonderful! You have successfully created, trained (on GPU), tested, and saved a TensorFlow 2 Deep Learning Image classifier!
Now we are ready to expose it as a REST API with Flask and Waitress and later Dockerize everything!
Ready? Go!
But wait, this is already too much for one Medium story 😔! Stay tuned for PART II! 🚀
All the source code is on my GitHub 👇 I’ll keep pushing everything!
github.com
Great! Thank you for reading! I’m eager to see you in Part II (coming soon)!
I hope I’ve helped you create a Deep Learning Image Classifier using TensorFlow 2.2. In Part II, we will expose our saved model as a REST API and later we’ll dockerize everything!
Please consider sharing the story if you enjoyed it. That would help a lot. | [
{
"code": null,
"e": 350,
"s": 172,
"text": "This series of articles will help you to move from notebooks to real-world use cases of Data Science techniques! We’ll take a Deep Learning classifier from zero to production 🚀!"
},
{
"code": null,
"e": 449,
"s": 350,
"text": "Disclaimer: You should have prior knowledge and experience with CNN-Convolutional Neural Networks."
},
{
"code": null,
"e": 718,
"s": 449,
"text": "The dataset we will use to train our Convolutional Neural Networks classifier is CIFAR-10 (don’t download it yet). The CIFAR-10 dataset comprises 60000 32x32 color images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images."
},
{
"code": null,
"e": 787,
"s": 718,
"text": "Here are the classes in the dataset, and 10 random images from each:"
},
{
"code": null,
"e": 804,
"s": 787,
"text": "Ready? Let’s go!"
},
{
"code": null,
"e": 929,
"s": 804,
"text": "Too much inspired by the cookiecutter-data-science open-source template, here is my favorite Data Science project structure:"
},
{
"code": null,
"e": 1024,
"s": 929,
"text": "In the data/raw, I copy my original data and in data/processed; I keep the pre-processed data."
},
{
"code": null,
"e": 1152,
"s": 1024,
"text": "In the deploy folder, you can find the Dockerfile and either requirements.txt or environment.yml (holding only production libs)"
},
{
"code": null,
"e": 1201,
"s": 1152,
"text": "In the models’ folder, I store the saved models."
},
{
"code": null,
"e": 1261,
"s": 1201,
"text": "In the notebooks folder, I have my notebooks (.ipynb files)"
},
{
"code": null,
"e": 1383,
"s": 1261,
"text": "In the references folder, I put the metadata and all references to resources I’m using in the project (pdf, notes... etc)"
},
{
"code": null,
"e": 1501,
"s": 1383,
"text": "In the reports folder, I put all the graphs, and reports (png, pdf, slides) containing insights to share with my team"
},
{
"code": null,
"e": 1885,
"s": 1501,
"text": "In the src folder, there are my Python scripts grouped in the following manner: src/api folder for scripts aiming to create a REST API, src/data folder contains scripts for processing the data, src/dags folder contains my Airflow DAGs, src/models folder for scripts dealing with our ML/DL models and finally, src/visualization folder holds scripts for data viz and reports exporting."
},
{
"code": null,
"e": 1948,
"s": 1885,
"text": "The tests folder contains the python script for testing my app"
},
{
"code": null,
"e": 1996,
"s": 1948,
"text": "logging.yaml where I configure my Python logger"
},
{
"code": null,
"e": 2065,
"s": 1996,
"text": "db_config.json just a JSON file holding some database access configs"
},
{
"code": null,
"e": 2193,
"s": 2065,
"text": "For simplification reason, let us ease off a bit our project structure by only creating (keep everything empty for the moment):"
},
{
"code": null,
"e": 2205,
"s": 2193,
"text": "data folder"
},
{
"code": null,
"e": 2219,
"s": 2205,
"text": "deploy folder"
},
{
"code": null,
"e": 2233,
"s": 2219,
"text": "models folder"
},
{
"code": null,
"e": 2250,
"s": 2233,
"text": "notebooks folder"
},
{
"code": null,
"e": 2302,
"s": 2250,
"text": "src folder within src/model and src/api sub-folders"
},
{
"code": null,
"e": 2323,
"s": 2302,
"text": "environment.yml file"
},
{
"code": null,
"e": 2340,
"s": 2323,
"text": "logging.yml file"
},
{
"code": null,
"e": 2384,
"s": 2340,
"text": "Just like me, you end up with these folders"
},
{
"code": null,
"e": 2471,
"s": 2384,
"text": "Great! You got a clean project structure ready! Let us set up our working environment!"
},
{
"code": null,
"e": 2592,
"s": 2471,
"text": "Follow these steps to create a virtual Python 3 work environment defined in environment.yml file and configure your GPU:"
},
{
"code": null,
"e": 2634,
"s": 2592,
"text": "2.1 — Install Miniconda 3 (or Anaconda 3)"
},
{
"code": null,
"e": 2721,
"s": 2634,
"text": "2.2 — Make sure that conda is on your path (otherwise add the bin file to your $PATH):"
},
{
"code": null,
"e": 2756,
"s": 2721,
"text": "$ which conda~/anaconda3/bin/conda"
},
{
"code": null,
"e": 3050,
"s": 2756,
"text": "2.3 — If you have a NVIDIA® GPU card with CUDA® Compute Capability 3.5 or higher, enable TensorFlow GPU support by following these steps https://www.tensorflow.org/install/gpu#software_requirements (don’t pip install tensorflow yet! configure CUDA first we’ll install tf2 in the next step 2.4)"
},
{
"code": null,
"e": 3435,
"s": 3050,
"text": "2.4 — We now call our virtual environment tf2-image-classifier-api and then specify the required packages in environment.yml file (copy-paste the following code): tensorflow-gpu, numpy, seaborn, and jupyter are for image classifier creation. Flask and waitress are for REST API creation. tqdm for getting a pleasant progress bar and finally, opencv-python is for image pre-processing!"
},
{
"code": null,
"e": 3502,
"s": 3435,
"text": "2.5 — Now go to the project root and create a virtual environment:"
},
{
"code": null,
"e": 3540,
"s": 3502,
"text": "$ conda env create -f environment.yml"
},
{
"code": null,
"e": 3579,
"s": 3540,
"text": "2.6 — Activate the virtual environment"
},
{
"code": null,
"e": 3619,
"s": 3579,
"text": "conda activate tf2-image-classifier-api"
},
{
"code": null,
"e": 3675,
"s": 3619,
"text": "You should now have your virtual environment activated!"
},
{
"code": null,
"e": 3708,
"s": 3675,
"text": "Bonus (FYI only not needed now):"
},
{
"code": null,
"e": 3743,
"s": 3708,
"text": "To entirely remove the environment"
},
{
"code": null,
"e": 3792,
"s": 3743,
"text": "conda env remove — name tf2-image-classifier-api"
},
{
"code": null,
"e": 3860,
"s": 3792,
"text": "To update the environment packages to the latest compatible version"
},
{
"code": null,
"e": 3896,
"s": 3860,
"text": "conda env update -f environment.yml"
},
{
"code": null,
"e": 3956,
"s": 3896,
"text": "2.7 — Download CIFAR-10 Dataset but in png format from here"
},
{
"code": null,
"e": 4114,
"s": 3956,
"text": "2.8 — Copy the downloaded cifar.tgz file to the data/raw folder and unzip it there (you should get the train folder, the test folder and the labels.txt file)"
},
{
"code": null,
"e": 4219,
"s": 4114,
"text": "Great! Now your environment and your dataset are ready for our image classifier training and predicting!"
},
{
"code": null,
"e": 4284,
"s": 4219,
"text": "Start by running jupyter notebook command in the project’s root:"
},
{
"code": null,
"e": 4303,
"s": 4284,
"text": "$ jupyter notebook"
},
{
"code": null,
"e": 4356,
"s": 4303,
"text": "Now navigate to http://localhost:8888/tree/notebooks"
},
{
"code": null,
"e": 4378,
"s": 4356,
"text": "Create a new notebook"
},
{
"code": null,
"e": 4402,
"s": 4378,
"text": "And follow these steps:"
},
{
"code": null,
"e": 4626,
"s": 4402,
"text": "For the first time, it would take a few minutes to load the required cuDNN libs (help TensorFlow discover your GPU device). If everything is ok, you’ll get similar results to mine (except that I have a GTX 960M/CUDA v10.2)."
},
{
"code": null,
"e": 4694,
"s": 4626,
"text": "But before we need to define two methods; read_image & load_dataset"
},
{
"code": null,
"e": 4721,
"s": 4694,
"text": "Read an image using OpenCV"
},
{
"code": null,
"e": 4764,
"s": 4721,
"text": "Test the method by visualizing some images"
},
{
"code": null,
"e": 4772,
"s": 4764,
"text": "Results"
},
{
"code": null,
"e": 4831,
"s": 4772,
"text": "Load dataset and return images and targets as numpy arrays"
},
{
"code": null,
"e": 4886,
"s": 4831,
"text": "Now we are ready to load our training & test datasets!"
},
{
"code": null,
"e": 4930,
"s": 4886,
"text": "Check your training data & test data shapes"
},
{
"code": null,
"e": 4987,
"s": 4930,
"text": "If everything is OK, you’ll get results similar to mine."
},
{
"code": null,
"e": 5086,
"s": 4987,
"text": "Great! Now we have loaded our libs, and our datasets are ready! Let’s create our CNN architecture!"
},
{
"code": null,
"e": 5182,
"s": 5086,
"text": "We do not need to re-invent the wheel, we will use this CNN architecture but in TensorFlow 2.2!"
},
{
"code": null,
"e": 5229,
"s": 5182,
"text": "The entire model comprises 16 layers in total:"
},
{
"code": null,
"e": 5319,
"s": 5229,
"text": "Batch NormalizationConvolution with 64 different filters in size of (3x3)Max Pooling by 2"
},
{
"code": null,
"e": 5339,
"s": 5319,
"text": "Batch Normalization"
},
{
"code": null,
"e": 5394,
"s": 5339,
"text": "Convolution with 64 different filters in size of (3x3)"
},
{
"code": null,
"e": 5411,
"s": 5394,
"text": "Max Pooling by 2"
},
{
"code": null,
"e": 5436,
"s": 5411,
"text": "ReLU activation function"
},
{
"code": null,
"e": 5456,
"s": 5436,
"text": "Batch Normalization"
},
{
"code": null,
"e": 5515,
"s": 5456,
"text": "4. Convolution with 128 different filters in size of (3x3)"
},
{
"code": null,
"e": 5535,
"s": 5515,
"text": "5. Max Pooling by 2"
},
{
"code": null,
"e": 5560,
"s": 5535,
"text": "ReLU activation function"
},
{
"code": null,
"e": 5580,
"s": 5560,
"text": "Batch Normalization"
},
{
"code": null,
"e": 5639,
"s": 5580,
"text": "6. Convolution with 256 different filters in size of (3x3)"
},
{
"code": null,
"e": 5659,
"s": 5639,
"text": "7. Max Pooling by 2"
},
{
"code": null,
"e": 5684,
"s": 5659,
"text": "ReLU activation function"
},
{
"code": null,
"e": 5704,
"s": 5684,
"text": "Batch Normalization"
},
{
"code": null,
"e": 5763,
"s": 5704,
"text": "8. Convolution with 512 different filters in size of (3x3)"
},
{
"code": null,
"e": 5783,
"s": 5763,
"text": "9. Max Pooling by 2"
},
{
"code": null,
"e": 5808,
"s": 5783,
"text": "ReLU activation function"
},
{
"code": null,
"e": 5828,
"s": 5808,
"text": "Batch Normalization"
},
{
"code": null,
"e": 5896,
"s": 5828,
"text": "10. Flattening the 3-D output of the last convolutional operations."
},
{
"code": null,
"e": 5937,
"s": 5896,
"text": "11. Fully Connected Layer with 128 units"
},
{
"code": null,
"e": 5945,
"s": 5937,
"text": "Dropout"
},
{
"code": null,
"e": 5965,
"s": 5945,
"text": "Batch Normalization"
},
{
"code": null,
"e": 6006,
"s": 5965,
"text": "12. Fully Connected Layer with 256 units"
},
{
"code": null,
"e": 6014,
"s": 6006,
"text": "Dropout"
},
{
"code": null,
"e": 6034,
"s": 6014,
"text": "Batch Normalization"
},
{
"code": null,
"e": 6075,
"s": 6034,
"text": "13. Fully Connected Layer with 512 units"
},
{
"code": null,
"e": 6083,
"s": 6075,
"text": "Dropout"
},
{
"code": null,
"e": 6103,
"s": 6083,
"text": "Batch Normalization"
},
{
"code": null,
"e": 6145,
"s": 6103,
"text": "14. Fully Connected Layer with 1024 units"
},
{
"code": null,
"e": 6153,
"s": 6145,
"text": "Dropout"
},
{
"code": null,
"e": 6173,
"s": 6153,
"text": "Batch Normalization"
},
{
"code": null,
"e": 6239,
"s": 6173,
"text": "15. Fully Connected Layer with 10 units (number of image classes)"
},
{
"code": null,
"e": 6251,
"s": 6239,
"text": "16. Softmax"
},
{
"code": null,
"e": 6315,
"s": 6251,
"text": "Cool! Now we have our helper functions ready to create our CNN!"
},
{
"code": null,
"e": 6364,
"s": 6315,
"text": "Now we can define our training hyper-parameters:"
},
{
"code": null,
"e": 6442,
"s": 6364,
"text": "Everything is OK now to instantiate our model. Also, let’s check its summary."
},
{
"code": null,
"e": 6460,
"s": 6442,
"text": "That should print"
},
{
"code": null,
"e": 10544,
"s": 6460,
"text": "Model: \"keras_image_classification_model\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================inputs (InputLayer) [(None, 32, 32, 3)] 0 _________________________________________________________________batch_normalization_15 (Batc (None, 32, 32, 3) 12 _________________________________________________________________conv_1_features (Conv2D) (None, 32, 32, 64) 1792 _________________________________________________________________max_pooling2d_8 (MaxPooling2 (None, 16, 16, 64) 0 _________________________________________________________________batch_normalization_16 (Batc (None, 16, 16, 64) 256 _________________________________________________________________conv_2_features (Conv2D) (None, 16, 16, 128) 73856 _________________________________________________________________max_pooling2d_9 (MaxPooling2 (None, 8, 8, 128) 0 _________________________________________________________________batch_normalization_17 (Batc (None, 8, 8, 128) 512 _________________________________________________________________conv_3_features (Conv2D) (None, 8, 8, 256) 819456 _________________________________________________________________max_pooling2d_10 (MaxPooling (None, 4, 4, 256) 0 _________________________________________________________________batch_normalization_18 (Batc (None, 4, 4, 256) 1024 _________________________________________________________________conv_4_features (Conv2D) (None, 4, 4, 512) 3277312 _________________________________________________________________max_pooling2d_11 (MaxPooling (None, 2, 2, 512) 0 _________________________________________________________________batch_normalization_19 (Batc (None, 2, 2, 512) 2048 _________________________________________________________________flatten_2 (Flatten) (None, 2048) 0 _________________________________________________________________dense_1_features (Dense) (None, 128) 262272 _________________________________________________________________dropout_4 (Dropout) (None, 128) 0 _________________________________________________________________batch_normalization_20 (Batc (None, 128) 512 _________________________________________________________________dense_2_features (Dense) (None, 256) 33024 _________________________________________________________________dropout_5 (Dropout) (None, 256) 0 _________________________________________________________________batch_normalization_21 (Batc (None, 256) 1024 _________________________________________________________________dense_3_features (Dense) (None, 512) 131584 _________________________________________________________________dropout_6 (Dropout) (None, 512) 0 _________________________________________________________________batch_normalization_22 (Batc (None, 512) 2048 _________________________________________________________________dense_4_features (Dense) (None, 1024) 525312 _________________________________________________________________dropout_7 (Dropout) (None, 1024) 0 _________________________________________________________________batch_normalization_23 (Batc (None, 1024) 4096 _________________________________________________________________dense_1 (Dense) (None, 10) 10250 _________________________________________________________________softmax (Softmax) (None, 10) 0 =================================================================Total params: 5,146,390Trainable params: 5,140,624Non-trainable params: 5,766"
},
{
"code": null,
"e": 10582,
"s": 10544,
"text": "Wonderful! 5,140,624 params to train!"
},
{
"code": null,
"e": 10786,
"s": 10582,
"text": "To train our model, we will use RMSprop as an optimizer & SparseCategoricalCrossentropy as a loss function. Why SparseCategoricalCrossentropy not just CategoricalCrossentropy? Good question! Here is why!"
},
{
"code": null,
"e": 10824,
"s": 10786,
"text": "Now we are good to compile our model!"
},
{
"code": null,
"e": 10905,
"s": 10824,
"text": "Everything is ready to train our model. Let us, however, define three callbacks:"
},
{
"code": null,
"e": 10977,
"s": 10905,
"text": "EarlyStopping to stop training when no our metric has stopped improving"
},
{
"code": null,
"e": 11036,
"s": 10977,
"text": "TensorBoard callback to check our model’s training history"
},
{
"code": null,
"e": 11098,
"s": 11036,
"text": "TqdmCallback tqdm keras callback for epoch and batch progress"
},
{
"code": null,
"e": 11193,
"s": 11098,
"text": "If everything is OK, your model should start training! You should get results similar to mine."
},
{
"code": null,
"e": 11342,
"s": 11193,
"text": "Great! Your GPU is burning now 🔥! Leave it training your model and we’ll get back when training finishes! (Here a screenshot of my GPU working hard)"
},
{
"code": null,
"e": 11374,
"s": 11342,
"text": "Take snap if you want like Tom!"
},
{
"code": null,
"e": 11586,
"s": 11374,
"text": "Cool! Our classifier has finished training! Time to evaluate it, right? How is it working on the test images? We can check that by launching the tensorboard interface in our notebook using the following command."
},
{
"code": null,
"e": 11613,
"s": 11586,
"text": "%tensorboard --logdir logs"
},
{
"code": null,
"e": 11708,
"s": 11613,
"text": "This command should start tensorboard with accuracy & loss graphs for training and validation:"
},
{
"code": null,
"e": 11907,
"s": 11708,
"text": "But wait, accuracy is not a good evaluation metric for a classifier! Let us check precision, recall, and f1 score on each class! We can do that thanks to scikit-learn’s classification_report method:"
},
{
"code": null,
"e": 11929,
"s": 11907,
"text": "These are my results:"
},
{
"code": null,
"e": 12658,
"s": 11929,
"text": "precision recall f1-score support airplane 0.84 0.86 0.85 1000 automobile 0.92 0.92 0.92 1000 bird 0.76 0.72 0.74 1000 cat 0.63 0.67 0.65 1000 deer 0.80 0.81 0.80 1000 dog 0.74 0.72 0.73 1000 frog 0.86 0.86 0.86 1000 horse 0.87 0.86 0.86 1000 ship 0.91 0.90 0.91 1000 truck 0.88 0.89 0.88 1000 accuracy 0.82 10000 macro avg 0.82 0.82 0.82 10000weighted avg 0.82 0.82 0.82 10000"
},
{
"code": null,
"e": 12794,
"s": 12658,
"text": "Nice as a first try, right? 0.82 precision & 0.82 recall! We can tune our hyper-parameters and retrain the model to get better results!"
},
{
"code": null,
"e": 12868,
"s": 12794,
"text": "Respond to the story with your results! I would be happy to check them! 😊"
},
{
"code": null,
"e": 12971,
"s": 12868,
"text": "Let us make an inference test. Giving an image from the test set, let us discover what our model sees!"
},
{
"code": null,
"e": 12978,
"s": 12971,
"text": "Result"
},
{
"code": null,
"e": 13141,
"s": 12978,
"text": "Nice! Our model is performing pretty well on test data, we can now export it to disk. Our saved model is for making inferences and will get exposed as a REST API!"
},
{
"code": null,
"e": 13208,
"s": 13141,
"text": "Finally, let us check if the saved model works fine by loading it!"
},
{
"code": null,
"e": 13355,
"s": 13208,
"text": "Wonderful! Wonderful! Wonderful! You have successfully created, trained (on GPU), tested, and saved a TensorFlow 2 Deep Learning Image classifier!"
},
{
"code": null,
"e": 13455,
"s": 13355,
"text": "Now we are ready to expose it as a REST API with Flask and Waitress and later Dockerize everything!"
},
{
"code": null,
"e": 13466,
"s": 13455,
"text": "Ready? Go!"
},
{
"code": null,
"e": 13551,
"s": 13466,
"text": "But wait, this is already too much for one Medium story 😔! Stay tuned for PART II! 🚀"
},
{
"code": null,
"e": 13619,
"s": 13551,
"text": "All the source code is on my GitHub 👇 I’ll keep pushing everything!"
},
{
"code": null,
"e": 13630,
"s": 13619,
"text": "github.com"
},
{
"code": null,
"e": 13707,
"s": 13630,
"text": "Great! Thank you for reading! I’m eager to see you in Part II (coming soon)!"
},
{
"code": null,
"e": 13887,
"s": 13707,
"text": "I hope I’ve helped you create a Deep Learning Image Classifier using TensorFlow 2.2. In Part II, we will expose our saved model as a REST API and later we’ll dockerize everything!"
}
] |
AWT Window Class | The class Window is a top level window with no border and no menubar. It uses BorderLayout as default layout manager.
Following is the declaration for java.awt.Window class:
public class Window
extends Container
implements Accessible
Window(Frame owner)
Constructs a new, initially invisible window with the specified Frame as its owner.
Window(Window owner)
Constructs a new, initially invisible window with the specified Window as its owner.
Window(Window owner, GraphicsConfiguration gc)
Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device.
void addNotify()
Makes this Window displayable by creating the connection to its native screen resource.
void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
void add Property ChangeListener(String property Name, Property Change Listener listener)
Adds a PropertyChangeListener to the listener list for a specific property.
void addWindowFocusListener(WindowFocusListener l)
Adds the specified window focus listener to receive window events from this window.
void addWindowListener(WindowListener l)
Adds the specified window listener to receive window events from this window.
void addWindowStateListener(WindowStateListener l)
Adds the specified window state listener to receive window events from this window.
void applyResourceBundle(ResourceBundle rb)
Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation.
void applyResourceBundle(String rbName)
Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation.
void createBufferStrategy(int numBuffers)
Creates a new strategy for multi-buffering on this component.
void createBufferStrategy(int numBuffers, BufferCapabilities caps)
Creates a new strategy for multi-buffering on this component with the required buffer capabilities.
void dispose()
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Window.
BufferStrategy getBufferStrategy()
Returns the BufferStrategy used by this component.
boolean getFocusableWindowState()
Returns whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.
Container getFocusCycleRootAncestor()
Always returns null because Windows have no ancestors; they represent the top of the Component hierarchy.
Component getFocusOwner()
Returns the child Component of this Window that has focus if this Window is focused; returns null otherwise.
Set<AWTKeyStroke> getFocusTraversalKeys(int id)
Gets a focus traversal key for this Window.
GraphicsConfiguration getGraphicsConfiguration()
This method returns the GraphicsConfiguration used by this Window.
List<Image> getIconImages()
Returns the sequence of images to be displayed as the icon for this window.
InputContext getInputContext()
Gets the input context for this window.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Window.
Locale getLocale()
Gets the Locale object that is associated with this window, if the locale has been set.
Dialog.ModalExclusionType getModalExclusionType()
Returns the modal exclusion type of this window.
Component getMostRecentFocusOwner()
Returns the child Component of this Window that will receive the focus when this Window is focused.
Window[] getOwnedWindows()
Return an array containing all the windows this window currently owns.
Window getOwner()
Returns the owner of this window.
static Window[] getOwnerlessWindows()
Returns an array of all Windows created by this application that have no owner.
Toolkit getToolkit()
Returns the toolkit of this frame.
String getWarningString()
Gets the warning string that is displayed with this window.
WindowFocusListener[] getWindowFocusListeners()
Returns an array of all the window focus listeners registered on this window.
WindowListener[] getWindowListeners()
Returns an array of all the window listeners registered on this window.
static Window[] getWindows()
Returns an array of all Windows, both owned and ownerless, created by this application.
WindowStateListener[] getWindowStateListeners()
Returns an array of all the window state listeners registered on this window.
void hide()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
boolean isActive()
Returns whether this Window is active.
boolean isAlwaysOnTop()
Returns whether this window is an always-on-top window.
boolean isAlwaysOnTopSupported()
Returns whether the always-on-top mode is supported for this window.
boolean isFocusableWindow()
Returns whether this Window can become the focused Window, that is, whether this Window or any of its subcomponents can become the focus owner.
boolean isFocusCycleRoot()
Always returns true because all Windows must be roots of a focus traversal cycle.
boolean isFocused()
Returns whether this Window is focused.
boolean isLocationByPlatform()
Returns true if this Window will appear at the default location for the native windowing system the next time this Window is made visible.
boolean isShowing()
Checks if this Window is showing on screen.
void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
void paint(Graphics g)
Paints the container.
boolean postEvent(Event e)
Deprecated. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).
protected void processEvent(AWTEvent e)
Processes events on this window.
protected void processWindowEvent(WindowEvent e)
Processes window events occurring on this window by dispatching them to any registered WindowListener objects.
protected void processWindowFocusEvent(WindowEvent e)
Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects.
protected void processWindowStateEvent(WindowEvent e)
Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects.
void removeNotify()
Makes this Container undisplayable by removing its connection to its native screen resource.
void removeWindowFocusListener(WindowFocusListener l)
Removes the specified window focus listener so that it no longer receives window events from this window.
void removeWindowListener(WindowListener l)
Removes the specified window listener so that it no longer receives window events from this window.
void removeWindowStateListener(WindowStateListener l)
Removes the specified window state listener so that it no longer receives window events from this window.
void reshape(int x, int y, int width, int height)
Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).
void setAlwaysOnTop(boolean alwaysOnTop)
Sets whether this window should always be above other windows.
void setBounds(int x, int y, int width, int height)
Moves and resizes this component.
void setBounds(Rectangle r)
Moves and resizes this component to conform to the new bounding rectangle r.
void setCursor(Cursor cursor)
Set the cursor image to a specified cursor.
void setFocusableWindowState(boolean focusableWindowState)
Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.
void setFocusCycleRoot(boolean focusCycleRoot)
Does nothing because Windows must always be roots of a focus traversal cycle.
void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
void setIconImages(List<? extends Image> icons)
Sets the sequence of images to be displayed as the icon for this window.
void setLocationByPlatform(boolean locationByPlatform)
Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible.
void setLocationRelativeTo(Component c)
Sets the location of the window relative to the specified component.
void setMinimumSize(Dimension minimumSize)
Sets the minimum size of this window to a constant value.
void setModalExclusionType(Dialog.ModalExclusionType exclusionType)
Specifies the modal exclusion type for this window.
void setSize(Dimension d)
Resizes this component so that it has width d.width and height d.height.
void setSize(int width, int height)
Resizes this component so that it has width width and height height.
void setVisible(boolean b)
Shows or hides this Window depending on the value of parameter b.
void show()
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
void toBack()
If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.
void toFront()
If this Window is visible, brings this Window to the front and may make it the focused Window.
This class inherits methods from the following classes:
java.awt.Window
java.awt.Window
java.awt.Container
java.awt.Container
java.awt.Component
java.awt.Component
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtContainerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtContainerDemo awtContainerDemo = new AwtContainerDemo();
awtContainerDemo.showFrameDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showWindowDemo(){
headerLabel.setText("Container in action: Window");
final MessageWindow window =
new MessageWindow(mainFrame,
"Welcome to TutorialsPoint AWT Tutorial.");
Button okButton = new Button("Open a Window");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.setVisible(true);
statusLabel.setText("A Window shown to the user.");
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
class MessageWindow extends Window{
private String message;
public MessageWindow(Frame parent, String message) {
super(parent);
this.message = message;
setSize(300, 300);
setLocationRelativeTo(parent);
setBackground(Color.gray);
}
public void paint(Graphics g) {
super.paint(g);
g.drawRect(0,0,getSize().width - 1,getSize().height - 1);
g.drawString(message,50,150);
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1865,
"s": 1747,
"text": "The class Window is a top level window with no border and no menubar. It uses BorderLayout as default layout manager."
},
{
"code": null,
"e": 1921,
"s": 1865,
"text": "Following is the declaration for java.awt.Window class:"
},
{
"code": null,
"e": 1990,
"s": 1921,
"text": "public class Window\n extends Container\n implements Accessible"
},
{
"code": null,
"e": 2011,
"s": 1990,
"text": "Window(Frame owner) "
},
{
"code": null,
"e": 2095,
"s": 2011,
"text": "Constructs a new, initially invisible window with the specified Frame as its owner."
},
{
"code": null,
"e": 2117,
"s": 2095,
"text": "Window(Window owner) "
},
{
"code": null,
"e": 2202,
"s": 2117,
"text": "Constructs a new, initially invisible window with the specified Window as its owner."
},
{
"code": null,
"e": 2250,
"s": 2202,
"text": "Window(Window owner, GraphicsConfiguration gc) "
},
{
"code": null,
"e": 2375,
"s": 2250,
"text": "Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device."
},
{
"code": null,
"e": 2393,
"s": 2375,
"text": "void addNotify() "
},
{
"code": null,
"e": 2481,
"s": 2393,
"text": "Makes this Window displayable by creating the connection to its native screen resource."
},
{
"code": null,
"e": 2546,
"s": 2481,
"text": "void addPropertyChangeListener(PropertyChangeListener listener) "
},
{
"code": null,
"e": 2598,
"s": 2546,
"text": "Adds a PropertyChangeListener to the listener list."
},
{
"code": null,
"e": 2689,
"s": 2598,
"text": "void add Property ChangeListener(String property Name, Property Change Listener listener) "
},
{
"code": null,
"e": 2765,
"s": 2689,
"text": "Adds a PropertyChangeListener to the listener list for a specific property."
},
{
"code": null,
"e": 2817,
"s": 2765,
"text": "void addWindowFocusListener(WindowFocusListener l) "
},
{
"code": null,
"e": 2901,
"s": 2817,
"text": "Adds the specified window focus listener to receive window events from this window."
},
{
"code": null,
"e": 2943,
"s": 2901,
"text": "void addWindowListener(WindowListener l) "
},
{
"code": null,
"e": 3021,
"s": 2943,
"text": "Adds the specified window listener to receive window events from this window."
},
{
"code": null,
"e": 3073,
"s": 3021,
"text": "void addWindowStateListener(WindowStateListener l) "
},
{
"code": null,
"e": 3157,
"s": 3073,
"text": "Adds the specified window state listener to receive window events from this window."
},
{
"code": null,
"e": 3202,
"s": 3157,
"text": "void applyResourceBundle(ResourceBundle rb) "
},
{
"code": null,
"e": 3279,
"s": 3202,
"text": "Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation."
},
{
"code": null,
"e": 3320,
"s": 3279,
"text": "void applyResourceBundle(String rbName) "
},
{
"code": null,
"e": 3397,
"s": 3320,
"text": "Deprecated. As of J2SE 1.4, replaced by Component.applyComponentOrientation."
},
{
"code": null,
"e": 3440,
"s": 3397,
"text": "void createBufferStrategy(int numBuffers) "
},
{
"code": null,
"e": 3502,
"s": 3440,
"text": "Creates a new strategy for multi-buffering on this component."
},
{
"code": null,
"e": 3570,
"s": 3502,
"text": "void createBufferStrategy(int numBuffers, BufferCapabilities caps) "
},
{
"code": null,
"e": 3670,
"s": 3570,
"text": "Creates a new strategy for multi-buffering on this component with the required buffer capabilities."
},
{
"code": null,
"e": 3686,
"s": 3670,
"text": "void dispose() "
},
{
"code": null,
"e": 3801,
"s": 3686,
"text": "Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children."
},
{
"code": null,
"e": 3843,
"s": 3801,
"text": "AccessibleContext getAccessibleContext() "
},
{
"code": null,
"e": 3899,
"s": 3843,
"text": "Gets the AccessibleContext associated with this Window."
},
{
"code": null,
"e": 3935,
"s": 3899,
"text": "BufferStrategy\tgetBufferStrategy() "
},
{
"code": null,
"e": 3986,
"s": 3935,
"text": "Returns the BufferStrategy used by this component."
},
{
"code": null,
"e": 4021,
"s": 3986,
"text": "boolean getFocusableWindowState() "
},
{
"code": null,
"e": 4145,
"s": 4021,
"text": "Returns whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow."
},
{
"code": null,
"e": 4184,
"s": 4145,
"text": "Container getFocusCycleRootAncestor() "
},
{
"code": null,
"e": 4290,
"s": 4184,
"text": "Always returns null because Windows have no ancestors; they represent the top of the Component hierarchy."
},
{
"code": null,
"e": 4317,
"s": 4290,
"text": "Component getFocusOwner() "
},
{
"code": null,
"e": 4426,
"s": 4317,
"text": "Returns the child Component of this Window that has focus if this Window is focused; returns null otherwise."
},
{
"code": null,
"e": 4475,
"s": 4426,
"text": "Set<AWTKeyStroke> getFocusTraversalKeys(int id) "
},
{
"code": null,
"e": 4519,
"s": 4475,
"text": "Gets a focus traversal key for this Window."
},
{
"code": null,
"e": 4569,
"s": 4519,
"text": "GraphicsConfiguration\tgetGraphicsConfiguration() "
},
{
"code": null,
"e": 4636,
"s": 4569,
"text": "This method returns the GraphicsConfiguration used by this Window."
},
{
"code": null,
"e": 4665,
"s": 4636,
"text": "List<Image> getIconImages() "
},
{
"code": null,
"e": 4741,
"s": 4665,
"text": "Returns the sequence of images to be displayed as the icon for this window."
},
{
"code": null,
"e": 4773,
"s": 4741,
"text": "InputContext getInputContext() "
},
{
"code": null,
"e": 4813,
"s": 4773,
"text": "Gets the input context for this window."
},
{
"code": null,
"e": 4880,
"s": 4813,
"text": "<T extends EventListener> T[] getListeners(Class<T> listenerType) "
},
{
"code": null,
"e": 4971,
"s": 4880,
"text": "Returns an array of all the objects currently registered as FooListeners upon this Window."
},
{
"code": null,
"e": 4991,
"s": 4971,
"text": "Locale\tgetLocale() "
},
{
"code": null,
"e": 5079,
"s": 4991,
"text": "Gets the Locale object that is associated with this window, if the locale has been set."
},
{
"code": null,
"e": 5130,
"s": 5079,
"text": "Dialog.ModalExclusionType\tgetModalExclusionType() "
},
{
"code": null,
"e": 5180,
"s": 5130,
"text": " Returns the modal exclusion type of this window."
},
{
"code": null,
"e": 5217,
"s": 5180,
"text": "Component getMostRecentFocusOwner() "
},
{
"code": null,
"e": 5317,
"s": 5217,
"text": "Returns the child Component of this Window that will receive the focus when this Window is focused."
},
{
"code": null,
"e": 5345,
"s": 5317,
"text": "Window[] getOwnedWindows() "
},
{
"code": null,
"e": 5416,
"s": 5345,
"text": "Return an array containing all the windows this window currently owns."
},
{
"code": null,
"e": 5435,
"s": 5416,
"text": "Window\tgetOwner() "
},
{
"code": null,
"e": 5469,
"s": 5435,
"text": "Returns the owner of this window."
},
{
"code": null,
"e": 5508,
"s": 5469,
"text": "static Window[]\tgetOwnerlessWindows() "
},
{
"code": null,
"e": 5588,
"s": 5508,
"text": "Returns an array of all Windows created by this application that have no owner."
},
{
"code": null,
"e": 5610,
"s": 5588,
"text": "Toolkit getToolkit() "
},
{
"code": null,
"e": 5645,
"s": 5610,
"text": "Returns the toolkit of this frame."
},
{
"code": null,
"e": 5672,
"s": 5645,
"text": "String\tgetWarningString() "
},
{
"code": null,
"e": 5732,
"s": 5672,
"text": "Gets the warning string that is displayed with this window."
},
{
"code": null,
"e": 5781,
"s": 5732,
"text": "WindowFocusListener[] getWindowFocusListeners() "
},
{
"code": null,
"e": 5859,
"s": 5781,
"text": "Returns an array of all the window focus listeners registered on this window."
},
{
"code": null,
"e": 5898,
"s": 5859,
"text": "WindowListener[] getWindowListeners() "
},
{
"code": null,
"e": 5970,
"s": 5898,
"text": "Returns an array of all the window listeners registered on this window."
},
{
"code": null,
"e": 6000,
"s": 5970,
"text": "static Window[] getWindows() "
},
{
"code": null,
"e": 6088,
"s": 6000,
"text": "Returns an array of all Windows, both owned and ownerless, created by this application."
},
{
"code": null,
"e": 6137,
"s": 6088,
"text": "WindowStateListener[] getWindowStateListeners() "
},
{
"code": null,
"e": 6215,
"s": 6137,
"text": "Returns an array of all the window state listeners registered on this window."
},
{
"code": null,
"e": 6228,
"s": 6215,
"text": "void hide() "
},
{
"code": null,
"e": 6296,
"s": 6228,
"text": "Deprecated. As of JDK version 1.5, replaced by setVisible(boolean)."
},
{
"code": null,
"e": 6316,
"s": 6296,
"text": "boolean isActive() "
},
{
"code": null,
"e": 6355,
"s": 6316,
"text": "Returns whether this Window is active."
},
{
"code": null,
"e": 6380,
"s": 6355,
"text": "boolean isAlwaysOnTop() "
},
{
"code": null,
"e": 6436,
"s": 6380,
"text": "Returns whether this window is an always-on-top window."
},
{
"code": null,
"e": 6470,
"s": 6436,
"text": "boolean isAlwaysOnTopSupported() "
},
{
"code": null,
"e": 6539,
"s": 6470,
"text": "Returns whether the always-on-top mode is supported for this window."
},
{
"code": null,
"e": 6568,
"s": 6539,
"text": "boolean isFocusableWindow() "
},
{
"code": null,
"e": 6712,
"s": 6568,
"text": "Returns whether this Window can become the focused Window, that is, whether this Window or any of its subcomponents can become the focus owner."
},
{
"code": null,
"e": 6740,
"s": 6712,
"text": "boolean isFocusCycleRoot() "
},
{
"code": null,
"e": 6822,
"s": 6740,
"text": "Always returns true because all Windows must be roots of a focus traversal cycle."
},
{
"code": null,
"e": 6843,
"s": 6822,
"text": "boolean isFocused() "
},
{
"code": null,
"e": 6883,
"s": 6843,
"text": "Returns whether this Window is focused."
},
{
"code": null,
"e": 6915,
"s": 6883,
"text": "boolean isLocationByPlatform() "
},
{
"code": null,
"e": 7054,
"s": 6915,
"text": "Returns true if this Window will appear at the default location for the native windowing system the next time this Window is made visible."
},
{
"code": null,
"e": 7075,
"s": 7054,
"text": "boolean isShowing() "
},
{
"code": null,
"e": 7119,
"s": 7075,
"text": "Checks if this Window is showing on screen."
},
{
"code": null,
"e": 7132,
"s": 7119,
"text": "void pack() "
},
{
"code": null,
"e": 7223,
"s": 7132,
"text": "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents."
},
{
"code": null,
"e": 7247,
"s": 7223,
"text": "void paint(Graphics g) "
},
{
"code": null,
"e": 7269,
"s": 7247,
"text": "Paints the container."
},
{
"code": null,
"e": 7297,
"s": 7269,
"text": "boolean postEvent(Event e) "
},
{
"code": null,
"e": 7368,
"s": 7297,
"text": "Deprecated. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent)."
},
{
"code": null,
"e": 7409,
"s": 7368,
"text": "protected void processEvent(AWTEvent e) "
},
{
"code": null,
"e": 7442,
"s": 7409,
"text": "Processes events on this window."
},
{
"code": null,
"e": 7492,
"s": 7442,
"text": "protected void processWindowEvent(WindowEvent e) "
},
{
"code": null,
"e": 7603,
"s": 7492,
"text": "Processes window events occurring on this window by dispatching them to any registered WindowListener objects."
},
{
"code": null,
"e": 7658,
"s": 7603,
"text": "protected void processWindowFocusEvent(WindowEvent e) "
},
{
"code": null,
"e": 7778,
"s": 7658,
"text": "Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects."
},
{
"code": null,
"e": 7833,
"s": 7778,
"text": "protected void processWindowStateEvent(WindowEvent e) "
},
{
"code": null,
"e": 7953,
"s": 7833,
"text": "Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects."
},
{
"code": null,
"e": 7974,
"s": 7953,
"text": "void removeNotify() "
},
{
"code": null,
"e": 8067,
"s": 7974,
"text": "Makes this Container undisplayable by removing its connection to its native screen resource."
},
{
"code": null,
"e": 8122,
"s": 8067,
"text": "void removeWindowFocusListener(WindowFocusListener l) "
},
{
"code": null,
"e": 8228,
"s": 8122,
"text": "Removes the specified window focus listener so that it no longer receives window events from this window."
},
{
"code": null,
"e": 8273,
"s": 8228,
"text": "void removeWindowListener(WindowListener l) "
},
{
"code": null,
"e": 8373,
"s": 8273,
"text": "Removes the specified window listener so that it no longer receives window events from this window."
},
{
"code": null,
"e": 8428,
"s": 8373,
"text": "void removeWindowStateListener(WindowStateListener l) "
},
{
"code": null,
"e": 8534,
"s": 8428,
"text": "Removes the specified window state listener so that it no longer receives window events from this window."
},
{
"code": null,
"e": 8585,
"s": 8534,
"text": "void reshape(int x, int y, int width, int height) "
},
{
"code": null,
"e": 8663,
"s": 8585,
"text": "Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int)."
},
{
"code": null,
"e": 8705,
"s": 8663,
"text": "void setAlwaysOnTop(boolean alwaysOnTop) "
},
{
"code": null,
"e": 8768,
"s": 8705,
"text": "Sets whether this window should always be above other windows."
},
{
"code": null,
"e": 8821,
"s": 8768,
"text": "void setBounds(int x, int y, int width, int height) "
},
{
"code": null,
"e": 8855,
"s": 8821,
"text": "Moves and resizes this component."
},
{
"code": null,
"e": 8884,
"s": 8855,
"text": "void setBounds(Rectangle r) "
},
{
"code": null,
"e": 8961,
"s": 8884,
"text": "Moves and resizes this component to conform to the new bounding rectangle r."
},
{
"code": null,
"e": 8992,
"s": 8961,
"text": "void setCursor(Cursor cursor) "
},
{
"code": null,
"e": 9036,
"s": 8992,
"text": "Set the cursor image to a specified cursor."
},
{
"code": null,
"e": 9096,
"s": 9036,
"text": "void setFocusableWindowState(boolean focusableWindowState) "
},
{
"code": null,
"e": 9217,
"s": 9096,
"text": "Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow."
},
{
"code": null,
"e": 9265,
"s": 9217,
"text": "void setFocusCycleRoot(boolean focusCycleRoot) "
},
{
"code": null,
"e": 9343,
"s": 9265,
"text": "Does nothing because Windows must always be roots of a focus traversal cycle."
},
{
"code": null,
"e": 9375,
"s": 9343,
"text": "void setIconImage(Image image) "
},
{
"code": null,
"e": 9435,
"s": 9375,
"text": "Sets the image to be displayed as the icon for this window."
},
{
"code": null,
"e": 9484,
"s": 9435,
"text": "void setIconImages(List<? extends Image> icons) "
},
{
"code": null,
"e": 9557,
"s": 9484,
"text": "Sets the sequence of images to be displayed as the icon for this window."
},
{
"code": null,
"e": 9613,
"s": 9557,
"text": "void setLocationByPlatform(boolean locationByPlatform) "
},
{
"code": null,
"e": 9803,
"s": 9613,
"text": "Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible."
},
{
"code": null,
"e": 9844,
"s": 9803,
"text": "void setLocationRelativeTo(Component c) "
},
{
"code": null,
"e": 9914,
"s": 9844,
"text": " Sets the location of the window relative to the specified component."
},
{
"code": null,
"e": 9958,
"s": 9914,
"text": "void setMinimumSize(Dimension minimumSize) "
},
{
"code": null,
"e": 10016,
"s": 9958,
"text": "Sets the minimum size of this window to a constant value."
},
{
"code": null,
"e": 10085,
"s": 10016,
"text": "void setModalExclusionType(Dialog.ModalExclusionType exclusionType) "
},
{
"code": null,
"e": 10137,
"s": 10085,
"text": "Specifies the modal exclusion type for this window."
},
{
"code": null,
"e": 10164,
"s": 10137,
"text": "void setSize(Dimension d) "
},
{
"code": null,
"e": 10237,
"s": 10164,
"text": "Resizes this component so that it has width d.width and height d.height."
},
{
"code": null,
"e": 10274,
"s": 10237,
"text": "void setSize(int width, int height) "
},
{
"code": null,
"e": 10343,
"s": 10274,
"text": "Resizes this component so that it has width width and height height."
},
{
"code": null,
"e": 10371,
"s": 10343,
"text": "void setVisible(boolean b) "
},
{
"code": null,
"e": 10437,
"s": 10371,
"text": "Shows or hides this Window depending on the value of parameter b."
},
{
"code": null,
"e": 10450,
"s": 10437,
"text": "void show() "
},
{
"code": null,
"e": 10518,
"s": 10450,
"text": "Deprecated. As of JDK version 1.5, replaced by setVisible(boolean)."
},
{
"code": null,
"e": 10533,
"s": 10518,
"text": "void toBack() "
},
{
"code": null,
"e": 10674,
"s": 10533,
"text": "If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window."
},
{
"code": null,
"e": 10690,
"s": 10674,
"text": "void toFront() "
},
{
"code": null,
"e": 10785,
"s": 10690,
"text": "If this Window is visible, brings this Window to the front and may make it the focused Window."
},
{
"code": null,
"e": 10841,
"s": 10785,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 10857,
"s": 10841,
"text": "java.awt.Window"
},
{
"code": null,
"e": 10873,
"s": 10857,
"text": "java.awt.Window"
},
{
"code": null,
"e": 10892,
"s": 10873,
"text": "java.awt.Container"
},
{
"code": null,
"e": 10911,
"s": 10892,
"text": "java.awt.Container"
},
{
"code": null,
"e": 10930,
"s": 10911,
"text": "java.awt.Component"
},
{
"code": null,
"e": 10949,
"s": 10930,
"text": "java.awt.Component"
},
{
"code": null,
"e": 10966,
"s": 10949,
"text": "java.lang.Object"
},
{
"code": null,
"e": 10983,
"s": 10966,
"text": "java.lang.Object"
},
{
"code": null,
"e": 11097,
"s": 10983,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 13607,
"s": 11097,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtContainerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtContainerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtContainerDemo awtContainerDemo = new AwtContainerDemo(); \n awtContainerDemo.showFrameDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n \n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n \n private void showWindowDemo(){\n headerLabel.setText(\"Container in action: Window\"); \n final MessageWindow window = \n new MessageWindow(mainFrame,\n \"Welcome to TutorialsPoint AWT Tutorial.\");\n\n Button okButton = new Button(\"Open a Window\");\n okButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n window.setVisible(true);\n statusLabel.setText(\"A Window shown to the user.\"); \n }\n });\n controlPanel.add(okButton);\n mainFrame.setVisible(true); \n }\n\n class MessageWindow extends Window{\n private String message; \n\n public MessageWindow(Frame parent, String message) { \n super(parent); \n this.message = message; \n setSize(300, 300); \n setLocationRelativeTo(parent);\n setBackground(Color.gray);\n }\n\n public void paint(Graphics g) { \n super.paint(g);\n g.drawRect(0,0,getSize().width - 1,getSize().height - 1); \n g.drawString(message,50,150); \n } \n }\n}"
},
{
"code": null,
"e": 13698,
"s": 13607,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 13756,
"s": 13698,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtContainerDemo.java"
},
{
"code": null,
"e": 13853,
"s": 13756,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 13905,
"s": 13853,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtContainerDemo"
},
{
"code": null,
"e": 13933,
"s": 13905,
"text": "Verify the following output"
},
{
"code": null,
"e": 13966,
"s": 13933,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13974,
"s": 13966,
"text": " EduOLC"
},
{
"code": null,
"e": 13981,
"s": 13974,
"text": " Print"
},
{
"code": null,
"e": 13992,
"s": 13981,
"text": " Add Notes"
}
] |
WebGL - Context | To write a WebGL application, first step is to get the WebGL rendering context object. This object interacts with the WebGL drawing buffer and can call all the WebGL methods. The following operations are performed to obtain the WebGL context −
Create an HTML-5 canvas
Get the canvas ID
Obtain WebGL
In Chapter 5, we discussed how to create an HTML-5 canvas element. Within the body of the HTML-5 document, write a canvas, give it a name, and pass it as a parameter to the attribute id. You can define the dimensions of the canvas using the width and height attributes (optional).
The following example shows how to create a canvas element with the dimensions 500 × 500. We have created a border to the canvas using CSS for visibility. Copy and paste the following code in a file with the name my_canvas.html.
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas{border:1px solid blue;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "300" height = "300"></canvas>
</body>
</html>
It will produce the following result −
After creating the canvas, you have to get the WebGL context. The first thing to do to obtain a WebGL drawing context is to get the id of the current canvas element.
Canvas ID is acquired by calling the DOM (Document Object Model) method getElementById(). This method accepts a string value as parameter, so we pass the name of the current canvas to it.
For example, if the canvas name is my_canvas, then canvas ID is obtained as shown below−
var canvas = document.getElementById('my_Canvas');
To get the WebGLRenderingContext object (or WebGL Drawing context object or simply WebGL context), call the getContext() method of the current HTMLCanvasElement. The syntax of getContext() is as follows −
canvas.getContext(contextType, contextAttributes);
Pass the strings webgl or experimental-webgl as the contentType. The contextAttributes parameter is optional. (While proceeding with this step, make sure your browser implements WebGL version 1 (OpenGL ES 2.0)).
The following code snippet shows how to obtain the WebGL rendering context. Here gl is the reference variable to the obtained context object.
var canvas = document.getElementById('my_Canvas');
var gl = canvas.getContext('experimental-webgl');
The parameter WebGLContextAttributes is not mandatory. This parameter provides various options that accept Boolean values as listed below −
Alpha
If its value is true, it provides an alpha buffer to the canvas.
By default, its value is true.
depth
If its value is true, you will get a drawing buffer which contains a depth buffer of at least 16 bits.
By default, its value is true.
stencil
If its value is true, you will get a drawing buffer which contains a stencil buffer of at least 8 bits.
By default, its value is false.
antialias
If its value is true, you will get a drawing buffer which performs anti-aliasing.
By default, its value is true.
premultipliedAlpha
If its value is true, you will get a drawing buffer which contains colors with pre-multiplied alpha.
By default, its value is true.
preserveDrawingBuffer
If its value is true, the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
By default, its value is false.
The following code snippet shows how to create a WebGL context with a stencil buffer, which will not perform anti-aliasing.
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('webgl', { antialias: false, stencil: true });
At the time of creating the WebGLRenderingContext, a drawing buffer is created. The Context object manages OpenGL state and renders to the drawing buffer.
It is the principal interface in WebGL. It represents the WebGL drawing context. This interface contains all the methods used to perform various tasks on the Drawing buffer. The attributes of this interface are given in the following table.
Canvas
This is a reference to the canvas element that created this context.
drawingBufferWidth
This attribute represents the actual width of the drawing buffer. It may differ from the width attribute of the HTMLCanvasElement.
drawingBufferHeight
This attribute represents the actual height of the drawing buffer. It may differ from the height attribute of the HTMLCanvasElement.
10 Lectures
1 hours
Frahaan Hussain
28 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2291,
"s": 2047,
"text": "To write a WebGL application, first step is to get the WebGL rendering context object. This object interacts with the WebGL drawing buffer and can call all the WebGL methods. The following operations are performed to obtain the WebGL context −"
},
{
"code": null,
"e": 2315,
"s": 2291,
"text": "Create an HTML-5 canvas"
},
{
"code": null,
"e": 2333,
"s": 2315,
"text": "Get the canvas ID"
},
{
"code": null,
"e": 2346,
"s": 2333,
"text": "Obtain WebGL"
},
{
"code": null,
"e": 2627,
"s": 2346,
"text": "In Chapter 5, we discussed how to create an HTML-5 canvas element. Within the body of the HTML-5 document, write a canvas, give it a name, and pass it as a parameter to the attribute id. You can define the dimensions of the canvas using the width and height attributes (optional)."
},
{
"code": null,
"e": 2856,
"s": 2627,
"text": "The following example shows how to create a canvas element with the dimensions 500 × 500. We have created a border to the canvas using CSS for visibility. Copy and paste the following code in a file with the name my_canvas.html."
},
{
"code": null,
"e": 3070,
"s": 2856,
"text": "<!DOCTYPE HTML>\n<html>\n <head>\n <style>\n #mycanvas{border:1px solid blue;}\n </style>\n </head>\n <body>\n <canvas id = \"mycanvas\" width = \"300\" height = \"300\"></canvas>\n </body>\n</html>"
},
{
"code": null,
"e": 3109,
"s": 3070,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3275,
"s": 3109,
"text": "After creating the canvas, you have to get the WebGL context. The first thing to do to obtain a WebGL drawing context is to get the id of the current canvas element."
},
{
"code": null,
"e": 3463,
"s": 3275,
"text": "Canvas ID is acquired by calling the DOM (Document Object Model) method getElementById(). This method accepts a string value as parameter, so we pass the name of the current canvas to it."
},
{
"code": null,
"e": 3552,
"s": 3463,
"text": "For example, if the canvas name is my_canvas, then canvas ID is obtained as shown below−"
},
{
"code": null,
"e": 3604,
"s": 3552,
"text": "var canvas = document.getElementById('my_Canvas');\n"
},
{
"code": null,
"e": 3809,
"s": 3604,
"text": "To get the WebGLRenderingContext object (or WebGL Drawing context object or simply WebGL context), call the getContext() method of the current HTMLCanvasElement. The syntax of getContext() is as follows −"
},
{
"code": null,
"e": 3861,
"s": 3809,
"text": "canvas.getContext(contextType, contextAttributes);\n"
},
{
"code": null,
"e": 4073,
"s": 3861,
"text": "Pass the strings webgl or experimental-webgl as the contentType. The contextAttributes parameter is optional. (While proceeding with this step, make sure your browser implements WebGL version 1 (OpenGL ES 2.0))."
},
{
"code": null,
"e": 4215,
"s": 4073,
"text": "The following code snippet shows how to obtain the WebGL rendering context. Here gl is the reference variable to the obtained context object."
},
{
"code": null,
"e": 4317,
"s": 4215,
"text": "var canvas = document.getElementById('my_Canvas');\nvar gl = canvas.getContext('experimental-webgl');\n"
},
{
"code": null,
"e": 4457,
"s": 4317,
"text": "The parameter WebGLContextAttributes is not mandatory. This parameter provides various options that accept Boolean values as listed below −"
},
{
"code": null,
"e": 4463,
"s": 4457,
"text": "Alpha"
},
{
"code": null,
"e": 4528,
"s": 4463,
"text": "If its value is true, it provides an alpha buffer to the canvas."
},
{
"code": null,
"e": 4559,
"s": 4528,
"text": "By default, its value is true."
},
{
"code": null,
"e": 4565,
"s": 4559,
"text": "depth"
},
{
"code": null,
"e": 4668,
"s": 4565,
"text": "If its value is true, you will get a drawing buffer which contains a depth buffer of at least 16 bits."
},
{
"code": null,
"e": 4699,
"s": 4668,
"text": "By default, its value is true."
},
{
"code": null,
"e": 4707,
"s": 4699,
"text": "stencil"
},
{
"code": null,
"e": 4811,
"s": 4707,
"text": "If its value is true, you will get a drawing buffer which contains a stencil buffer of at least 8 bits."
},
{
"code": null,
"e": 4843,
"s": 4811,
"text": "By default, its value is false."
},
{
"code": null,
"e": 4853,
"s": 4843,
"text": "antialias"
},
{
"code": null,
"e": 4935,
"s": 4853,
"text": "If its value is true, you will get a drawing buffer which performs anti-aliasing."
},
{
"code": null,
"e": 4966,
"s": 4935,
"text": "By default, its value is true."
},
{
"code": null,
"e": 4985,
"s": 4966,
"text": "premultipliedAlpha"
},
{
"code": null,
"e": 5086,
"s": 4985,
"text": "If its value is true, you will get a drawing buffer which contains colors with pre-multiplied alpha."
},
{
"code": null,
"e": 5117,
"s": 5086,
"text": "By default, its value is true."
},
{
"code": null,
"e": 5139,
"s": 5117,
"text": "preserveDrawingBuffer"
},
{
"code": null,
"e": 5268,
"s": 5139,
"text": "If its value is true, the buffers will not be cleared and will preserve their values until cleared or overwritten by the author."
},
{
"code": null,
"e": 5300,
"s": 5268,
"text": "By default, its value is false."
},
{
"code": null,
"e": 5424,
"s": 5300,
"text": "The following code snippet shows how to create a WebGL context with a stencil buffer, which will not perform anti-aliasing."
},
{
"code": null,
"e": 5553,
"s": 5424,
"text": "var canvas = document.getElementById('canvas1');\nvar context = canvas.getContext('webgl', { antialias: false, stencil: true });\n"
},
{
"code": null,
"e": 5708,
"s": 5553,
"text": "At the time of creating the WebGLRenderingContext, a drawing buffer is created. The Context object manages OpenGL state and renders to the drawing buffer."
},
{
"code": null,
"e": 5949,
"s": 5708,
"text": "It is the principal interface in WebGL. It represents the WebGL drawing context. This interface contains all the methods used to perform various tasks on the Drawing buffer. The attributes of this interface are given in the following table."
},
{
"code": null,
"e": 5956,
"s": 5949,
"text": "Canvas"
},
{
"code": null,
"e": 6025,
"s": 5956,
"text": "This is a reference to the canvas element that created this context."
},
{
"code": null,
"e": 6044,
"s": 6025,
"text": "drawingBufferWidth"
},
{
"code": null,
"e": 6175,
"s": 6044,
"text": "This attribute represents the actual width of the drawing buffer. It may differ from the width attribute of the HTMLCanvasElement."
},
{
"code": null,
"e": 6195,
"s": 6175,
"text": "drawingBufferHeight"
},
{
"code": null,
"e": 6328,
"s": 6195,
"text": "This attribute represents the actual height of the drawing buffer. It may differ from the height attribute of the HTMLCanvasElement."
},
{
"code": null,
"e": 6361,
"s": 6328,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6378,
"s": 6361,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6411,
"s": 6378,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6428,
"s": 6411,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6435,
"s": 6428,
"text": " Print"
},
{
"code": null,
"e": 6446,
"s": 6435,
"text": " Add Notes"
}
] |
MySQL add “prefix” to every column? | To create a view only if it does not already exist, you can use the following syntax −
CREATE OR REPLACE VIEW yourViewName AS SELECT *FROM yourTableName;
To understand the above syntax, let us create a table.
The query to create a table is as follows −
mysql> create table createViewDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command.
The query is as follows −
mysql> insert into createViewDemo(Name) values('John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into createViewDemo(Name) values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> insert into createViewDemo(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into createViewDemo(Name) values('Sam');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement.
The query is as follows −
mysql> select *from createViewDemo;
Here is the output −
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | Carol |
| 3 | Bob |
| 4 | Sam |
+----+-------+
4 rows in set (0.00 sec)
Here is the query to create a view only if it does not already exist −
mysql> CREATE OR REPLACE VIEW New_ViewDemo AS select *from createViewDemo;
Query OK, 0 rows affected (0.13 sec)
Let us check the records of view.
The query is as follows −
mysql> select *from New_ViewDemo;
The following is The output −
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | Carol |
| 3 | Bob |
| 4 | Sam |
+----+-------+
4 rows in set (0.02 sec) | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To create a view only if it does not already exist, you can use the following syntax −"
},
{
"code": null,
"e": 1216,
"s": 1149,
"text": "CREATE OR REPLACE VIEW yourViewName AS SELECT *FROM yourTableName;"
},
{
"code": null,
"e": 1272,
"s": 1216,
"text": "To understand the above syntax, let us create a table. "
},
{
"code": null,
"e": 1316,
"s": 1272,
"text": "The query to create a table is as follows −"
},
{
"code": null,
"e": 1478,
"s": 1316,
"text": "mysql> create table createViewDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1534,
"s": 1478,
"text": "Insert some records in the table using insert command. "
},
{
"code": null,
"e": 1560,
"s": 1534,
"text": "The query is as follows −"
},
{
"code": null,
"e": 1927,
"s": 1560,
"text": "mysql> insert into createViewDemo(Name) values('John');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into createViewDemo(Name) values('Carol');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into createViewDemo(Name) values('Bob');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into createViewDemo(Name) values('Sam');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1987,
"s": 1927,
"text": "Display all records from the table using select statement. "
},
{
"code": null,
"e": 2013,
"s": 1987,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2049,
"s": 2013,
"text": "mysql> select *from createViewDemo;"
},
{
"code": null,
"e": 2070,
"s": 2049,
"text": "Here is the output −"
},
{
"code": null,
"e": 2215,
"s": 2070,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | Sam |\n+----+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2286,
"s": 2215,
"text": "Here is the query to create a view only if it does not already exist −"
},
{
"code": null,
"e": 2398,
"s": 2286,
"text": "mysql> CREATE OR REPLACE VIEW New_ViewDemo AS select *from createViewDemo;\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 2433,
"s": 2398,
"text": "Let us check the records of view. "
},
{
"code": null,
"e": 2459,
"s": 2433,
"text": "The query is as follows −"
},
{
"code": null,
"e": 2493,
"s": 2459,
"text": "mysql> select *from New_ViewDemo;"
},
{
"code": null,
"e": 2523,
"s": 2493,
"text": "The following is The output −"
},
{
"code": null,
"e": 2668,
"s": 2523,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | Sam |\n+----+-------+\n4 rows in set (0.02 sec)"
}
] |
Predicting Stock Price with LSTM. Machine learning has found its... | by Asutosh Nayak | Towards Data Science | Machine learning has found its applications in many interesting fields over these years. Taming stock market is one of them. I had been thinking of giving it a shot for quite some time now; mostly to solidify my working knowledge of LSTMs. And finally I have finished the project and quite excited to share my experience.
I will write about my experience over a series of blogs. The purpose of this series is not to explain the basics of LSTM or Machine Learning concepts. Hence, I will assume the reader has begun his/her journey with Machine Learning and has the basics like Python, familiarity with SkLearn, Keras, LSTM etc. The reason is that there are already excellent articles on topics like “How LSTMs work?” by people who are much more qualified to explain the maths behind it. But I will be sharing links to such articles, wherever I feel like background knowledge might be missing. While there are lots of articles out there to tell you how to predict stock prices given a dataset, mostly authors don’t reveal/explain how they reached that particular configuration for a Neural Network or how did they select that particular set of Hyperparameters. So the real purpose of this article is to share such steps, my mistakes and some steps that I found very helpful. As such, this article is not limited to Stock Price Prediction problem.
Here are the things we will look at :
Reading and analyzing data. (Pandas)Normalizing the data. (SkLearn)Converting data to time-series and supervised learning problem.Creating model (Keras)Fine tuning the model (in the next article)Training, predicting and visualizing the result.Tips & tools that I found very helpful (last article of the series)
Reading and analyzing data. (Pandas)
Normalizing the data. (SkLearn)
Converting data to time-series and supervised learning problem.
Creating model (Keras)
Fine tuning the model (in the next article)
Training, predicting and visualizing the result.
Tips & tools that I found very helpful (last article of the series)
Please note that this first article talks about preprocessing steps and terminologies of LSTM. If you are fairly confident about these steps, you can skip to next article.
Let’s begin!
I will be using the historical stock price data for GE for this post. You can find the data in my kaggle site here. I don’t remember the source of data since I had downloaded it long back. We can read the data into frame as shown below :
df_ge = pd.read_csv(os.path.join(INPUT_PATH, "us.ge.txt"), engine='python')df_ge.tail()
As you can see there are around 14060 items, each representing a day’s stock market attributes for the company. Lets see how does it look on a plot :
from matplotlib import pyplot as pltplt.figure()plt.plot(df_ge["Open"])plt.plot(df_ge["High"])plt.plot(df_ge["Low"])plt.plot(df_ge["Close"])plt.title('GE stock price history')plt.ylabel('Price (USD)')plt.xlabel('Days')plt.legend(['Open','High','Low','Close'], loc='upper left')plt.show()
It seems the prices — Open, Close, Low, High — don’t vary too much from each other except for occasional slight drops in Low price.
Now let’s check out the plot for volume :
plt.figure()plt.plot(df_ge["Volume"])plt.title('GE stock volume history')plt.ylabel('Volume')plt.xlabel('Days')plt.show()
Huh. Did you see something interesting? There is quite a surge in the number of transactions around 12000th day on the timeline, which happens to coincide with the sudden drop of stock price. May be we can go back to that particular date and dig up old news articles to find what caused it.
Now let’s see if we have any null/Nan values to worry about. As it turns out we don’t have any null values. Great!
print("checking if any null values are present\n", df_ge.isna().sum())
The data is not normalized and the range for each column varies, especially Volume. Normalizing data helps the algorithm in converging i.e. to find local/ global minimum efficiently. I will use MinMaxScaler from Sci-kit Learn. But before that we have to split the dataset into training and testing datasets. Also I will convert the DataFrame to ndarray in the process.
This is quite important and somewhat tricky. This is where the knowledge LSTM is needed. I would give a brief description of key concepts that are needed here but I strongly recommend reading Andre karpathy’s blog here, which is considered one of the best resources on LSTM out there and this. Or you can watch Andrew Ng’s video too (which by the way mentions Andre’s blog too).
LSTMs consume input in format [ batch_size, time_steps, Features ]; a 3- dimensional array.
Batch Size says how many samples of input do you want your Neural Net to see before updating the weights. So let’s say you have 100 samples (input dataset) and you want to update weights every time your NN has seen an input. In that case batch size would be 1 and total number of batches would be 100. Like wise if you wanted your network to update weights after it has seen all the samples, batch size would be 100 and number of batches would be 1. As it turns out using very small batch size reduces the speed of training and on the other hand using too big batch size (like whole dataset) reduces the models ability to generalize to different data and it also consumes more memory. But it takes fewer steps to find the minima for your objective function. So you have to try out various values on your data and find the sweet spot. It’s quite a big topic. We will see how to search these in somewhat smarter way in the next article.
Time Steps define how many units back in time you want your network to see. For example if you were working on a character prediction problem where you have a text corpus to train on and you decide to feed your network 6 characters at a time. Then your time step is 6. In our case we will be using 60 as time step i.e. we will look into 2 months of data to predict next days price. More on this later.
Features is the number of attributes used to represent each time step. Consider the character prediction example above, and assume that you use a one-hot encoded vector of size 100 to represent each character. Then feature size here is 100.
Now that we have some what cleared up terminologies out of the way, let’s convert our stock data into a suitable format. Let’s assume, for simplicity, that we chose 3 as time our time step (we want our network to look back on 3 days of data to predict price on 4th day) then we would form our dataset like this:
Samples 0 to 2 would be our first input and Close price of sample 3 would be its corresponding output value; both enclosed by green rectangle. Similarly samples 1 to 3 would be our second input and Close price of sample 4 would be output value; represented by blue rectangle. And so on. So till now we have a matrix of shape (3, 5), 3 being the time step and 5 being the number of features. Now think how many such input-output pairs are possible in the image above? 4.
Also mix the batch size with this. Let’s assume we choose batch size of 2. Then input-output pair 1 (green rectangle) and pair 2 (blue rectangle) would constitute batch one. And so on. Here is the python code snippet to do this:
‘y_col_index’ is the index of your output column. Now suppose after converting data into supervised learning format, like shown above, you have 41 samples in your training dataset but your batch size is 20 then you will have to trim your training set to remove the odd samples left out. I will look for a better way to go around this, but for now this is what I have done:
Now using the above functions lets form our train, validation and test datasets
x_t, y_t = build_timeseries(x_train, 3)x_t = trim_dataset(x_t, BATCH_SIZE)y_t = trim_dataset(y_t, BATCH_SIZE)x_temp, y_temp = build_timeseries(x_test, 3)x_val, x_test_t = np.split(trim_dataset(x_temp, BATCH_SIZE),2)y_val, y_test_t = np.split(trim_dataset(y_temp, BATCH_SIZE),2)
Now that our data is ready we can concentrate on building the model.
We will be using LSTM for this task, which is a variation of Recurrent Neural Network. Creating LSTM model is as simple as this:
Now that you have your model compiled and ready to be trained, train it like shown below. If you are wondering about what values to use for parameters like epochs, batch size etc., don’t worry we will see how to figure those out in the next article.
Training this model (with fine tuned hyperparameters) gave best error of 3.27e-4 and best validation error of 3.7e-4. Here is what the Training loss vs Validation loss looked like:
This is how the prediction looked with above model:
I have found that this configuration for LSTM works the best out of all the combinations I have tried (for this dataset), and I have tried more than 100! So the question is how do you land on the perfect (or in almost all the cases, close to perfect) architecture for your neural network? This leads us to our next and important section, to be continued in the next article.
You can find all the complete programs on my Github profile here.
NOTE: A humble request to the readers — You all are welcome to connect with me on LinkedIn or Twitter, but if you have a query regarding my blogs please post it on comments section of respective blog instead of personal messaging, so that if someone else has the same query, they would find it here itself, and I wouldn’t have to explain it individually. However, you are still welcome to send queries unrelated to blogs or general tech queries, to me personally. Thanks :-)
UPDATE 13/4/19
It has come to my knowledge, since I have written this article, that my model used for this blog may have been overfitted. While I have not confirmed it, it’s likely. So please be careful while implementing this in your projects. You could try out things like lesser epochs, smaller network, more dropout etc.I have used Sigmoid activation for last layer which may suffer from limitation of not being able to predict a price greater than ‘max’ price in dataset. You could try ‘Linear’ activation for last layer to solve this.Fixed a typo in “converting data to time-series” section.
It has come to my knowledge, since I have written this article, that my model used for this blog may have been overfitted. While I have not confirmed it, it’s likely. So please be careful while implementing this in your projects. You could try out things like lesser epochs, smaller network, more dropout etc.
I have used Sigmoid activation for last layer which may suffer from limitation of not being able to predict a price greater than ‘max’ price in dataset. You could try ‘Linear’ activation for last layer to solve this.
Fixed a typo in “converting data to time-series” section.
Thanks to the readers for bringing these to my attention.
UPDATE 21/1/2020
As mentioned in some of the comments, I was exploring other ways to approach the stock prediction problem. I have finally got it working. Interested readers can read about that here. | [
{
"code": null,
"e": 494,
"s": 172,
"text": "Machine learning has found its applications in many interesting fields over these years. Taming stock market is one of them. I had been thinking of giving it a shot for quite some time now; mostly to solidify my working knowledge of LSTMs. And finally I have finished the project and quite excited to share my experience."
},
{
"code": null,
"e": 1518,
"s": 494,
"text": "I will write about my experience over a series of blogs. The purpose of this series is not to explain the basics of LSTM or Machine Learning concepts. Hence, I will assume the reader has begun his/her journey with Machine Learning and has the basics like Python, familiarity with SkLearn, Keras, LSTM etc. The reason is that there are already excellent articles on topics like “How LSTMs work?” by people who are much more qualified to explain the maths behind it. But I will be sharing links to such articles, wherever I feel like background knowledge might be missing. While there are lots of articles out there to tell you how to predict stock prices given a dataset, mostly authors don’t reveal/explain how they reached that particular configuration for a Neural Network or how did they select that particular set of Hyperparameters. So the real purpose of this article is to share such steps, my mistakes and some steps that I found very helpful. As such, this article is not limited to Stock Price Prediction problem."
},
{
"code": null,
"e": 1556,
"s": 1518,
"text": "Here are the things we will look at :"
},
{
"code": null,
"e": 1867,
"s": 1556,
"text": "Reading and analyzing data. (Pandas)Normalizing the data. (SkLearn)Converting data to time-series and supervised learning problem.Creating model (Keras)Fine tuning the model (in the next article)Training, predicting and visualizing the result.Tips & tools that I found very helpful (last article of the series)"
},
{
"code": null,
"e": 1904,
"s": 1867,
"text": "Reading and analyzing data. (Pandas)"
},
{
"code": null,
"e": 1936,
"s": 1904,
"text": "Normalizing the data. (SkLearn)"
},
{
"code": null,
"e": 2000,
"s": 1936,
"text": "Converting data to time-series and supervised learning problem."
},
{
"code": null,
"e": 2023,
"s": 2000,
"text": "Creating model (Keras)"
},
{
"code": null,
"e": 2067,
"s": 2023,
"text": "Fine tuning the model (in the next article)"
},
{
"code": null,
"e": 2116,
"s": 2067,
"text": "Training, predicting and visualizing the result."
},
{
"code": null,
"e": 2184,
"s": 2116,
"text": "Tips & tools that I found very helpful (last article of the series)"
},
{
"code": null,
"e": 2356,
"s": 2184,
"text": "Please note that this first article talks about preprocessing steps and terminologies of LSTM. If you are fairly confident about these steps, you can skip to next article."
},
{
"code": null,
"e": 2369,
"s": 2356,
"text": "Let’s begin!"
},
{
"code": null,
"e": 2607,
"s": 2369,
"text": "I will be using the historical stock price data for GE for this post. You can find the data in my kaggle site here. I don’t remember the source of data since I had downloaded it long back. We can read the data into frame as shown below :"
},
{
"code": null,
"e": 2695,
"s": 2607,
"text": "df_ge = pd.read_csv(os.path.join(INPUT_PATH, \"us.ge.txt\"), engine='python')df_ge.tail()"
},
{
"code": null,
"e": 2845,
"s": 2695,
"text": "As you can see there are around 14060 items, each representing a day’s stock market attributes for the company. Lets see how does it look on a plot :"
},
{
"code": null,
"e": 3133,
"s": 2845,
"text": "from matplotlib import pyplot as pltplt.figure()plt.plot(df_ge[\"Open\"])plt.plot(df_ge[\"High\"])plt.plot(df_ge[\"Low\"])plt.plot(df_ge[\"Close\"])plt.title('GE stock price history')plt.ylabel('Price (USD)')plt.xlabel('Days')plt.legend(['Open','High','Low','Close'], loc='upper left')plt.show()"
},
{
"code": null,
"e": 3265,
"s": 3133,
"text": "It seems the prices — Open, Close, Low, High — don’t vary too much from each other except for occasional slight drops in Low price."
},
{
"code": null,
"e": 3307,
"s": 3265,
"text": "Now let’s check out the plot for volume :"
},
{
"code": null,
"e": 3429,
"s": 3307,
"text": "plt.figure()plt.plot(df_ge[\"Volume\"])plt.title('GE stock volume history')plt.ylabel('Volume')plt.xlabel('Days')plt.show()"
},
{
"code": null,
"e": 3720,
"s": 3429,
"text": "Huh. Did you see something interesting? There is quite a surge in the number of transactions around 12000th day on the timeline, which happens to coincide with the sudden drop of stock price. May be we can go back to that particular date and dig up old news articles to find what caused it."
},
{
"code": null,
"e": 3835,
"s": 3720,
"text": "Now let’s see if we have any null/Nan values to worry about. As it turns out we don’t have any null values. Great!"
},
{
"code": null,
"e": 3906,
"s": 3835,
"text": "print(\"checking if any null values are present\\n\", df_ge.isna().sum())"
},
{
"code": null,
"e": 4275,
"s": 3906,
"text": "The data is not normalized and the range for each column varies, especially Volume. Normalizing data helps the algorithm in converging i.e. to find local/ global minimum efficiently. I will use MinMaxScaler from Sci-kit Learn. But before that we have to split the dataset into training and testing datasets. Also I will convert the DataFrame to ndarray in the process."
},
{
"code": null,
"e": 4654,
"s": 4275,
"text": "This is quite important and somewhat tricky. This is where the knowledge LSTM is needed. I would give a brief description of key concepts that are needed here but I strongly recommend reading Andre karpathy’s blog here, which is considered one of the best resources on LSTM out there and this. Or you can watch Andrew Ng’s video too (which by the way mentions Andre’s blog too)."
},
{
"code": null,
"e": 4746,
"s": 4654,
"text": "LSTMs consume input in format [ batch_size, time_steps, Features ]; a 3- dimensional array."
},
{
"code": null,
"e": 5681,
"s": 4746,
"text": "Batch Size says how many samples of input do you want your Neural Net to see before updating the weights. So let’s say you have 100 samples (input dataset) and you want to update weights every time your NN has seen an input. In that case batch size would be 1 and total number of batches would be 100. Like wise if you wanted your network to update weights after it has seen all the samples, batch size would be 100 and number of batches would be 1. As it turns out using very small batch size reduces the speed of training and on the other hand using too big batch size (like whole dataset) reduces the models ability to generalize to different data and it also consumes more memory. But it takes fewer steps to find the minima for your objective function. So you have to try out various values on your data and find the sweet spot. It’s quite a big topic. We will see how to search these in somewhat smarter way in the next article."
},
{
"code": null,
"e": 6083,
"s": 5681,
"text": "Time Steps define how many units back in time you want your network to see. For example if you were working on a character prediction problem where you have a text corpus to train on and you decide to feed your network 6 characters at a time. Then your time step is 6. In our case we will be using 60 as time step i.e. we will look into 2 months of data to predict next days price. More on this later."
},
{
"code": null,
"e": 6324,
"s": 6083,
"text": "Features is the number of attributes used to represent each time step. Consider the character prediction example above, and assume that you use a one-hot encoded vector of size 100 to represent each character. Then feature size here is 100."
},
{
"code": null,
"e": 6636,
"s": 6324,
"text": "Now that we have some what cleared up terminologies out of the way, let’s convert our stock data into a suitable format. Let’s assume, for simplicity, that we chose 3 as time our time step (we want our network to look back on 3 days of data to predict price on 4th day) then we would form our dataset like this:"
},
{
"code": null,
"e": 7106,
"s": 6636,
"text": "Samples 0 to 2 would be our first input and Close price of sample 3 would be its corresponding output value; both enclosed by green rectangle. Similarly samples 1 to 3 would be our second input and Close price of sample 4 would be output value; represented by blue rectangle. And so on. So till now we have a matrix of shape (3, 5), 3 being the time step and 5 being the number of features. Now think how many such input-output pairs are possible in the image above? 4."
},
{
"code": null,
"e": 7335,
"s": 7106,
"text": "Also mix the batch size with this. Let’s assume we choose batch size of 2. Then input-output pair 1 (green rectangle) and pair 2 (blue rectangle) would constitute batch one. And so on. Here is the python code snippet to do this:"
},
{
"code": null,
"e": 7708,
"s": 7335,
"text": "‘y_col_index’ is the index of your output column. Now suppose after converting data into supervised learning format, like shown above, you have 41 samples in your training dataset but your batch size is 20 then you will have to trim your training set to remove the odd samples left out. I will look for a better way to go around this, but for now this is what I have done:"
},
{
"code": null,
"e": 7788,
"s": 7708,
"text": "Now using the above functions lets form our train, validation and test datasets"
},
{
"code": null,
"e": 8066,
"s": 7788,
"text": "x_t, y_t = build_timeseries(x_train, 3)x_t = trim_dataset(x_t, BATCH_SIZE)y_t = trim_dataset(y_t, BATCH_SIZE)x_temp, y_temp = build_timeseries(x_test, 3)x_val, x_test_t = np.split(trim_dataset(x_temp, BATCH_SIZE),2)y_val, y_test_t = np.split(trim_dataset(y_temp, BATCH_SIZE),2)"
},
{
"code": null,
"e": 8135,
"s": 8066,
"text": "Now that our data is ready we can concentrate on building the model."
},
{
"code": null,
"e": 8264,
"s": 8135,
"text": "We will be using LSTM for this task, which is a variation of Recurrent Neural Network. Creating LSTM model is as simple as this:"
},
{
"code": null,
"e": 8514,
"s": 8264,
"text": "Now that you have your model compiled and ready to be trained, train it like shown below. If you are wondering about what values to use for parameters like epochs, batch size etc., don’t worry we will see how to figure those out in the next article."
},
{
"code": null,
"e": 8695,
"s": 8514,
"text": "Training this model (with fine tuned hyperparameters) gave best error of 3.27e-4 and best validation error of 3.7e-4. Here is what the Training loss vs Validation loss looked like:"
},
{
"code": null,
"e": 8747,
"s": 8695,
"text": "This is how the prediction looked with above model:"
},
{
"code": null,
"e": 9122,
"s": 8747,
"text": "I have found that this configuration for LSTM works the best out of all the combinations I have tried (for this dataset), and I have tried more than 100! So the question is how do you land on the perfect (or in almost all the cases, close to perfect) architecture for your neural network? This leads us to our next and important section, to be continued in the next article."
},
{
"code": null,
"e": 9188,
"s": 9122,
"text": "You can find all the complete programs on my Github profile here."
},
{
"code": null,
"e": 9663,
"s": 9188,
"text": "NOTE: A humble request to the readers — You all are welcome to connect with me on LinkedIn or Twitter, but if you have a query regarding my blogs please post it on comments section of respective blog instead of personal messaging, so that if someone else has the same query, they would find it here itself, and I wouldn’t have to explain it individually. However, you are still welcome to send queries unrelated to blogs or general tech queries, to me personally. Thanks :-)"
},
{
"code": null,
"e": 9678,
"s": 9663,
"text": "UPDATE 13/4/19"
},
{
"code": null,
"e": 10261,
"s": 9678,
"text": "It has come to my knowledge, since I have written this article, that my model used for this blog may have been overfitted. While I have not confirmed it, it’s likely. So please be careful while implementing this in your projects. You could try out things like lesser epochs, smaller network, more dropout etc.I have used Sigmoid activation for last layer which may suffer from limitation of not being able to predict a price greater than ‘max’ price in dataset. You could try ‘Linear’ activation for last layer to solve this.Fixed a typo in “converting data to time-series” section."
},
{
"code": null,
"e": 10571,
"s": 10261,
"text": "It has come to my knowledge, since I have written this article, that my model used for this blog may have been overfitted. While I have not confirmed it, it’s likely. So please be careful while implementing this in your projects. You could try out things like lesser epochs, smaller network, more dropout etc."
},
{
"code": null,
"e": 10788,
"s": 10571,
"text": "I have used Sigmoid activation for last layer which may suffer from limitation of not being able to predict a price greater than ‘max’ price in dataset. You could try ‘Linear’ activation for last layer to solve this."
},
{
"code": null,
"e": 10846,
"s": 10788,
"text": "Fixed a typo in “converting data to time-series” section."
},
{
"code": null,
"e": 10904,
"s": 10846,
"text": "Thanks to the readers for bringing these to my attention."
},
{
"code": null,
"e": 10921,
"s": 10904,
"text": "UPDATE 21/1/2020"
}
] |
turtle.up() method in Python - GeeksforGeeks | 16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.up() method is used to pull the pen up from the screen. It gives no drawing on moving to another position or direction.
turtle.up() or turtle.pu() or turtle.penup()
Here, this method can be called with three names as written above i.e; it has Aliases: penup | pu | up. There is no argument required for this method.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # forward the turtle (drawing)turtle.forward(50)
Output:
Example 2 :
Python3
# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # turn right 90 degreesturtle.right(90) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # turn right 90 degreesturtle.right(90) # forward the turtle (drawing)turtle.forward(50)
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24509,
"s": 24292,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 24641,
"s": 24509,
"text": "The turtle.up() method is used to pull the pen up from the screen. It gives no drawing on moving to another position or direction. "
},
{
"code": null,
"e": 24687,
"s": 24641,
"text": "turtle.up() or turtle.pu() or turtle.penup()\n"
},
{
"code": null,
"e": 24838,
"s": 24687,
"text": "Here, this method can be called with three names as written above i.e; it has Aliases: penup | pu | up. There is no argument required for this method."
},
{
"code": null,
"e": 24907,
"s": 24838,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 24919,
"s": 24907,
"text": "Example 1 :"
},
{
"code": null,
"e": 24927,
"s": 24919,
"text": "Python3"
},
{
"code": "# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # forward the turtle (drawing)turtle.forward(50)",
"e": 25172,
"s": 24927,
"text": null
},
{
"code": null,
"e": 25180,
"s": 25172,
"text": "Output:"
},
{
"code": null,
"e": 25192,
"s": 25180,
"text": "Example 2 :"
},
{
"code": null,
"e": 25200,
"s": 25192,
"text": "Python3"
},
{
"code": "# import packageimport turtle # forward the turtle (drawing)turtle.forward(50) # turn right 90 degreesturtle.right(90) # up the turtleturtle.up() # forward the turtle (no drawing)turtle.forward(50) # down the turtleturtle.down() # turn right 90 degreesturtle.right(90) # forward the turtle (drawing)turtle.forward(50)",
"e": 25527,
"s": 25200,
"text": null
},
{
"code": null,
"e": 25535,
"s": 25527,
"text": "Output:"
},
{
"code": null,
"e": 25549,
"s": 25535,
"text": "Python-turtle"
},
{
"code": null,
"e": 25556,
"s": 25549,
"text": "Python"
},
{
"code": null,
"e": 25654,
"s": 25556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25663,
"s": 25654,
"text": "Comments"
},
{
"code": null,
"e": 25676,
"s": 25663,
"text": "Old Comments"
},
{
"code": null,
"e": 25708,
"s": 25676,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25764,
"s": 25708,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25819,
"s": 25764,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25861,
"s": 25819,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25903,
"s": 25861,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25934,
"s": 25903,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25973,
"s": 25934,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26002,
"s": 25973,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26024,
"s": 26002,
"text": "Defaultdict in Python"
}
] |
How to conduct market basket analysis | by Sambit Das | Towards Data Science | Market basket analysis is one of the key techniques that is used by large retailers to uncover hidden associations between items. Market basket analysis uses transaction data i.e. the list of all items bought by a customer in a single purchase to determine what products are ordered or purchased together and identify patterns of co-occurrence. This powerful analysis helps to reveal consumer preferences which will be very challenging to capture through an online survey. Retailers use the results of the market basket analysis to guide product placement in stores, cross-category and co-marketing promotions among others.
My last shopping experience was a fairly unpredictable one. I ended up in an Asian store to pick up a few items. Here is a look at my market basket.
This list will go into one row of the store’s database along with thousands of shopping trips or market baskets from other customers. Association rule mining is one of the most popular methods of extracting useful insights from the transaction data stored in the database. An item set is a collection of items selected from all items for sale in a grocery store. An item set can consist of 2 , 3 items and so on. The association rule determines the relationships between the items in the item set. These relationships are then used to build profiles containing IF-Then rules of the items purchased.
The rules could be written as :
If {A} Then {B}
The IF part of the rule is known as antecedent and the THEN part of the rule is known as consequent. Hence the antecedent is the condition and the consequent is the result. The association rule has three key measures that together determine the strength of the rule : Support , Confidence and Lift.
Lets assume that there are 100 customers. 10 of them brought milk , 8 of them bought butter and 6 bought both of them. If we were to evaluate the association rule “If someone buys milk , they will also buy butter “, then the Support of the association rule can be calculated as :
(Probability of Milk and Butter) or in other words (No of baskets containing both milk and butter) / (No of total baskets)
Support = (Probability of Milk and Butter) = 6/100 = 0.06
A support criterion of 0.06 means six in every hundred market baskets have both milk and butter items.
Confidence = Support of the item set divided by the support of sebset of items in the antecedent. In other words it is the Conditional probability P(Butter | Milk) calculated as :
Confidence of P(B|A) = P(AB) / P(A) => (Probability of Milk and Butter) / (Probability of Milk)ORConfidence = Support / P (Milk)ORConfidence = 0.06 / (10/100) = 0.06/0.1 = 0.6
Finally lift is a measure of relative predictive confidence. It is the confidence with which we can predict that a customer will buy Butter given he has bought milk in the association rule “IF Milk THEN Butter”.
Lift = P(B|A) / P(B)orLift = Confidence / P(Butter) = 0.6 / (8/100) = 0.6/0.08 = 7.5
Lift values greater than 1 reflect stronger associations.
For this analysis I draw upon a grocery dataset analysed by Hahsler , Hornik and Reutterer (2006). There are a total of 9835 transactions containing 169 unique grocery items.
grocery_data = data("Groceries")#Show dimensions of the datasetprint(dim(Groceries))print(dim(Groceries)[1]) # 9835 market baskets for shopping tripsprint(dim(Groceries)[2]) # 169 initial store itemssummary(Groceries)
A closer look at the dataset reveals each row having a subset of items.
# Let's take a look at the first 5 transactionsinspect(Groceries[1:5]) items [1] {citrus fruit,semi-finished bread,margarine,ready soups} [2] {tropical fruit,yogurt,coffee} [3] {whole milk} [4] {pip fruit,yogurt,cream cheese ,meat spreads} [5] {other vegetables,whole milk,condensed milk,long life bakery product}
Let’s take a look at a frequency plot to determine the frequency of items appearing in the market baskets. We set the the support to 0. to ensure each item in the plot appears in every 10 market baskets at a minimum
itemFrequencyPlot(Groceries, support = 0.025, cex.names=0.8, xlim = c(0,0.3),type = "relative", horiz = TRUE, col = "dark red", las = 1,xlab = paste("Proportion of Market Baskets Containing Item","\n(Item Relative Frequency or Support)"))
Let’s take a look at the top 20 frequently appearing items in the shopping baskets.
# Plot the frequency of top 20 itemsitemFrequencyPlot(Groceries,topN = 20)
So whole milk , vegetables , rolls , soda and yogurt are the top 5 most purchased items in the store.
The Apriori algorithm implemented in the arules package in R helps to mine the association rules. A set of 344 rules are obtained by setting the thresholds for support and confidence of 0.025 and 0.05.
rules <- apriori(groceries, parameter = list(support = 0.025 , confidence = 0.05))AprioriParameter specification: confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext 0.05 0.1 1 none FALSE TRUE 5 0.025 1 10 rules TRUEAlgorithmic control: filter tree heap memopt load sort verbose 0.1 TRUE TRUE FALSE TRUE 2 TRUEAbsolute minimum support count: 245set item appearances ...[0 item(s)] done [0.00s].set transactions ...[55 item(s), 9835 transaction(s)] done [0.03s].sorting and recoding items ... [32 item(s)] done [0.00s].creating transaction tree ... done [0.01s].checking subsets of size 1 2 3 4 done [0.00s].writing ... [344 rule(s)] done [0.00s].creating S4 object ... done [0.00s].> rulesset of 344 rules
Let’s investigate the top 10 association rules sorted by the lift value.
inspect(sort(rules,by="lift")[1:10])
A review of all the 344 association rules manually will be extremely tiresome and is not a viable option. Using the R package arulesViz , we will implement visualization techniques to explore the relationships.
It is possible to view a scattered plot with support in the horizontal axis and lift in the vertical axis. Colour coding of the points relates to confidence.
plot(rules,measure = c("support","lift"),shading="confidence")
Unwin , Hofmann and Bernt (2001) introduced a special version of a scatter plot called Two-key plot. Here support and confidence represent the X and Y axis respectively and the colour points are used to indicate the “order” i.e the number of items contained in each rule.
plot(rules,shading="order",control=list(main="Two-Key plot"))
From the above plot , it is clear that the order and the support are inversely proportional to each other.
The below plot provides a clearer view of the identified association rules in the form of a matrix bubbled chart. An item in the antecedent (left hand side) of the association rule is represented in the labels at the top of the matrix while the item in the consequent (right hand side) of an association rule is represented at the right of the matrix. Support is represented by the size of each bubble and lift is reflected in the colour intensity.
plot(rules,method="grouped",control=list(col=rev(brewer.pal(9,"Greens")[4:9])))
Now if i were to identify what are the products that are commonly bought with vegetables , I can filter and report the data from the overall association rules. Below I rank these rules by lift and also identify the top 10 association rules.
vegie.rules <- subset(rules,subset=rhs %pin% "vegetables")inspect(sort(vegie.rules,by="lift")[1:10])
Next I represent the association rules for commonly bought products with vegetables below in a network diagram.
plot(top.vegie.rules,method = "graph",control = list(type="items"),shading = "lift" )
From the network diagram, it is evident that a customer is likely to buy beef, dairy, produce, bread, sausage when buying vegetables.
As a relative frequency or probability estimate, the support value lies between 0 to 1. Lower values of support are ok as long as it is not very low. Confidence also takes the value between 0 to 1 as it is a conditional probability measure. Higher values of confidence is generally preferred. Finally, the lift value needs to be greater than 1.0 to be taken seriously by the management.
The analysis we have done above is descriptive in nature as the shopping data was analysed to study the shopping behaviour. Taking this analysis to the next step is to implement the insights from this study at the ground and on the stores.
Retailers frequently use the findings of association rules to make decisions about store layout , product bundling or cross-selling. Store managers are also running ground experiments such as A/B tests to study how shoppers respond to new store layouts. This is an ongoing and fascinating research to truly test the performance of market basket predictive modelling.
So the next time you walk into your local supermarket store and find the arrangements have been changed, you now know why.
I would like to especially thank Professor Miller for his guidance and inspiration. Having studied in his classes during my Masters in Data science course with Northwestern, his books and his classes have had a profound influence on my data science career. My work draws upon the following literature :
Thomas W. Miller (2014) Modeling Techniques in Predictive Analytics
M. Hahsler, S. Chelluboina (2015) Visualizing Association rules : Introduction to the R-extension arulesViz
Rstat Building a Market Basket Model | [
{
"code": null,
"e": 671,
"s": 47,
"text": "Market basket analysis is one of the key techniques that is used by large retailers to uncover hidden associations between items. Market basket analysis uses transaction data i.e. the list of all items bought by a customer in a single purchase to determine what products are ordered or purchased together and identify patterns of co-occurrence. This powerful analysis helps to reveal consumer preferences which will be very challenging to capture through an online survey. Retailers use the results of the market basket analysis to guide product placement in stores, cross-category and co-marketing promotions among others."
},
{
"code": null,
"e": 820,
"s": 671,
"text": "My last shopping experience was a fairly unpredictable one. I ended up in an Asian store to pick up a few items. Here is a look at my market basket."
},
{
"code": null,
"e": 1419,
"s": 820,
"text": "This list will go into one row of the store’s database along with thousands of shopping trips or market baskets from other customers. Association rule mining is one of the most popular methods of extracting useful insights from the transaction data stored in the database. An item set is a collection of items selected from all items for sale in a grocery store. An item set can consist of 2 , 3 items and so on. The association rule determines the relationships between the items in the item set. These relationships are then used to build profiles containing IF-Then rules of the items purchased."
},
{
"code": null,
"e": 1451,
"s": 1419,
"text": "The rules could be written as :"
},
{
"code": null,
"e": 1467,
"s": 1451,
"text": "If {A} Then {B}"
},
{
"code": null,
"e": 1766,
"s": 1467,
"text": "The IF part of the rule is known as antecedent and the THEN part of the rule is known as consequent. Hence the antecedent is the condition and the consequent is the result. The association rule has three key measures that together determine the strength of the rule : Support , Confidence and Lift."
},
{
"code": null,
"e": 2046,
"s": 1766,
"text": "Lets assume that there are 100 customers. 10 of them brought milk , 8 of them bought butter and 6 bought both of them. If we were to evaluate the association rule “If someone buys milk , they will also buy butter “, then the Support of the association rule can be calculated as :"
},
{
"code": null,
"e": 2169,
"s": 2046,
"text": "(Probability of Milk and Butter) or in other words (No of baskets containing both milk and butter) / (No of total baskets)"
},
{
"code": null,
"e": 2227,
"s": 2169,
"text": "Support = (Probability of Milk and Butter) = 6/100 = 0.06"
},
{
"code": null,
"e": 2330,
"s": 2227,
"text": "A support criterion of 0.06 means six in every hundred market baskets have both milk and butter items."
},
{
"code": null,
"e": 2510,
"s": 2330,
"text": "Confidence = Support of the item set divided by the support of sebset of items in the antecedent. In other words it is the Conditional probability P(Butter | Milk) calculated as :"
},
{
"code": null,
"e": 2686,
"s": 2510,
"text": "Confidence of P(B|A) = P(AB) / P(A) => (Probability of Milk and Butter) / (Probability of Milk)ORConfidence = Support / P (Milk)ORConfidence = 0.06 / (10/100) = 0.06/0.1 = 0.6"
},
{
"code": null,
"e": 2898,
"s": 2686,
"text": "Finally lift is a measure of relative predictive confidence. It is the confidence with which we can predict that a customer will buy Butter given he has bought milk in the association rule “IF Milk THEN Butter”."
},
{
"code": null,
"e": 2983,
"s": 2898,
"text": "Lift = P(B|A) / P(B)orLift = Confidence / P(Butter) = 0.6 / (8/100) = 0.6/0.08 = 7.5"
},
{
"code": null,
"e": 3041,
"s": 2983,
"text": "Lift values greater than 1 reflect stronger associations."
},
{
"code": null,
"e": 3216,
"s": 3041,
"text": "For this analysis I draw upon a grocery dataset analysed by Hahsler , Hornik and Reutterer (2006). There are a total of 9835 transactions containing 169 unique grocery items."
},
{
"code": null,
"e": 3434,
"s": 3216,
"text": "grocery_data = data(\"Groceries\")#Show dimensions of the datasetprint(dim(Groceries))print(dim(Groceries)[1]) # 9835 market baskets for shopping tripsprint(dim(Groceries)[2]) # 169 initial store itemssummary(Groceries)"
},
{
"code": null,
"e": 3506,
"s": 3434,
"text": "A closer look at the dataset reveals each row having a subset of items."
},
{
"code": null,
"e": 4015,
"s": 3506,
"text": "# Let's take a look at the first 5 transactionsinspect(Groceries[1:5]) items [1] {citrus fruit,semi-finished bread,margarine,ready soups} [2] {tropical fruit,yogurt,coffee} [3] {whole milk} [4] {pip fruit,yogurt,cream cheese ,meat spreads} [5] {other vegetables,whole milk,condensed milk,long life bakery product}"
},
{
"code": null,
"e": 4231,
"s": 4015,
"text": "Let’s take a look at a frequency plot to determine the frequency of items appearing in the market baskets. We set the the support to 0. to ensure each item in the plot appears in every 10 market baskets at a minimum"
},
{
"code": null,
"e": 4470,
"s": 4231,
"text": "itemFrequencyPlot(Groceries, support = 0.025, cex.names=0.8, xlim = c(0,0.3),type = \"relative\", horiz = TRUE, col = \"dark red\", las = 1,xlab = paste(\"Proportion of Market Baskets Containing Item\",\"\\n(Item Relative Frequency or Support)\"))"
},
{
"code": null,
"e": 4554,
"s": 4470,
"text": "Let’s take a look at the top 20 frequently appearing items in the shopping baskets."
},
{
"code": null,
"e": 4629,
"s": 4554,
"text": "# Plot the frequency of top 20 itemsitemFrequencyPlot(Groceries,topN = 20)"
},
{
"code": null,
"e": 4731,
"s": 4629,
"text": "So whole milk , vegetables , rolls , soda and yogurt are the top 5 most purchased items in the store."
},
{
"code": null,
"e": 4933,
"s": 4731,
"text": "The Apriori algorithm implemented in the arules package in R helps to mine the association rules. A set of 344 rules are obtained by setting the thresholds for support and confidence of 0.025 and 0.05."
},
{
"code": null,
"e": 5731,
"s": 4933,
"text": "rules <- apriori(groceries, parameter = list(support = 0.025 , confidence = 0.05))AprioriParameter specification: confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext 0.05 0.1 1 none FALSE TRUE 5 0.025 1 10 rules TRUEAlgorithmic control: filter tree heap memopt load sort verbose 0.1 TRUE TRUE FALSE TRUE 2 TRUEAbsolute minimum support count: 245set item appearances ...[0 item(s)] done [0.00s].set transactions ...[55 item(s), 9835 transaction(s)] done [0.03s].sorting and recoding items ... [32 item(s)] done [0.00s].creating transaction tree ... done [0.01s].checking subsets of size 1 2 3 4 done [0.00s].writing ... [344 rule(s)] done [0.00s].creating S4 object ... done [0.00s].> rulesset of 344 rules"
},
{
"code": null,
"e": 5804,
"s": 5731,
"text": "Let’s investigate the top 10 association rules sorted by the lift value."
},
{
"code": null,
"e": 5841,
"s": 5804,
"text": "inspect(sort(rules,by=\"lift\")[1:10])"
},
{
"code": null,
"e": 6052,
"s": 5841,
"text": "A review of all the 344 association rules manually will be extremely tiresome and is not a viable option. Using the R package arulesViz , we will implement visualization techniques to explore the relationships."
},
{
"code": null,
"e": 6210,
"s": 6052,
"text": "It is possible to view a scattered plot with support in the horizontal axis and lift in the vertical axis. Colour coding of the points relates to confidence."
},
{
"code": null,
"e": 6273,
"s": 6210,
"text": "plot(rules,measure = c(\"support\",\"lift\"),shading=\"confidence\")"
},
{
"code": null,
"e": 6545,
"s": 6273,
"text": "Unwin , Hofmann and Bernt (2001) introduced a special version of a scatter plot called Two-key plot. Here support and confidence represent the X and Y axis respectively and the colour points are used to indicate the “order” i.e the number of items contained in each rule."
},
{
"code": null,
"e": 6607,
"s": 6545,
"text": "plot(rules,shading=\"order\",control=list(main=\"Two-Key plot\"))"
},
{
"code": null,
"e": 6714,
"s": 6607,
"text": "From the above plot , it is clear that the order and the support are inversely proportional to each other."
},
{
"code": null,
"e": 7163,
"s": 6714,
"text": "The below plot provides a clearer view of the identified association rules in the form of a matrix bubbled chart. An item in the antecedent (left hand side) of the association rule is represented in the labels at the top of the matrix while the item in the consequent (right hand side) of an association rule is represented at the right of the matrix. Support is represented by the size of each bubble and lift is reflected in the colour intensity."
},
{
"code": null,
"e": 7243,
"s": 7163,
"text": "plot(rules,method=\"grouped\",control=list(col=rev(brewer.pal(9,\"Greens\")[4:9])))"
},
{
"code": null,
"e": 7484,
"s": 7243,
"text": "Now if i were to identify what are the products that are commonly bought with vegetables , I can filter and report the data from the overall association rules. Below I rank these rules by lift and also identify the top 10 association rules."
},
{
"code": null,
"e": 7585,
"s": 7484,
"text": "vegie.rules <- subset(rules,subset=rhs %pin% \"vegetables\")inspect(sort(vegie.rules,by=\"lift\")[1:10])"
},
{
"code": null,
"e": 7697,
"s": 7585,
"text": "Next I represent the association rules for commonly bought products with vegetables below in a network diagram."
},
{
"code": null,
"e": 7783,
"s": 7697,
"text": "plot(top.vegie.rules,method = \"graph\",control = list(type=\"items\"),shading = \"lift\" )"
},
{
"code": null,
"e": 7917,
"s": 7783,
"text": "From the network diagram, it is evident that a customer is likely to buy beef, dairy, produce, bread, sausage when buying vegetables."
},
{
"code": null,
"e": 8304,
"s": 7917,
"text": "As a relative frequency or probability estimate, the support value lies between 0 to 1. Lower values of support are ok as long as it is not very low. Confidence also takes the value between 0 to 1 as it is a conditional probability measure. Higher values of confidence is generally preferred. Finally, the lift value needs to be greater than 1.0 to be taken seriously by the management."
},
{
"code": null,
"e": 8544,
"s": 8304,
"text": "The analysis we have done above is descriptive in nature as the shopping data was analysed to study the shopping behaviour. Taking this analysis to the next step is to implement the insights from this study at the ground and on the stores."
},
{
"code": null,
"e": 8911,
"s": 8544,
"text": "Retailers frequently use the findings of association rules to make decisions about store layout , product bundling or cross-selling. Store managers are also running ground experiments such as A/B tests to study how shoppers respond to new store layouts. This is an ongoing and fascinating research to truly test the performance of market basket predictive modelling."
},
{
"code": null,
"e": 9034,
"s": 8911,
"text": "So the next time you walk into your local supermarket store and find the arrangements have been changed, you now know why."
},
{
"code": null,
"e": 9337,
"s": 9034,
"text": "I would like to especially thank Professor Miller for his guidance and inspiration. Having studied in his classes during my Masters in Data science course with Northwestern, his books and his classes have had a profound influence on my data science career. My work draws upon the following literature :"
},
{
"code": null,
"e": 9405,
"s": 9337,
"text": "Thomas W. Miller (2014) Modeling Techniques in Predictive Analytics"
},
{
"code": null,
"e": 9513,
"s": 9405,
"text": "M. Hahsler, S. Chelluboina (2015) Visualizing Association rules : Introduction to the R-extension arulesViz"
}
] |
How can we extract the Year and Month from a date in MySQL? | It can be done with the following three ways in MySQL
For extracting YEAR and MONTH collectively then we can use the EXTRACT function. We need to provide the YEAR_MONTH as an argument for this function. To understand it, consider the following function using the data from table ‘Collegedetail’ −
mysql> Select EXTRACT(YEAR_MONTH From estb) from collegedetail;
+-------------------------------+
| EXTRACT(YEAR_MONTH From estb) |
+-------------------------------+
| 201005 |
| 199510 |
| 199409 |
| 200107 |
| 201007 |
+-------------------------------+
5 rows in set (0.00 sec)
It can extract the year and the month collectively as well as separately. As the name suggests we can also format its output. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −
mysql> Select DATE_FORMAT(estb, '%Y %m') from collegedetail;
+----------------------------+
| DATE_FORMAT(estb, '%Y %m') |
+----------------------------+
| 2010 05 |
| 1995 10 |
| 1994 09 |
| 2001 07 |
| 2010 07 |
+----------------------------+
5 rows in set (0.00 sec)
mysql> Select DATE_FORMAT(estb, '%Y') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%Y') |
+-------------------------+
| 2010 |
| 1995 |
| 1994 |
| 2001 |
| 2010 |
+-------------------------+
5 rows in set (0.00 sec)
mysql> Select DATE_FORMAT(estb, '%m') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%m') |
+-------------------------+
| 05 |
| 10 |
| 09 |
| 07 |
| 07 |
+-------------------------+
5 rows in set (0.00 sec)
mysql> Select DATE_FORMAT(estb, '%M') from Collegedetail;
+-------------------------+
| DATE_FORMAT(estb, '%M') |
+-------------------------+
| May |
| October |
| September |
| July |
| July |
+-------------------------+
5 rows in set (0.10 sec)
it will extract the Year and month separately by using two different functions. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −
mysql> Select YEAR(estb) AS 'Year', MONTH(estb) As 'MONTH' From collegedetail;
+------+-------+
| Year | MONTH |
+------+-------+
| 2010 | 5 |
| 1995 | 10 |
| 1994 | 9 |
| 2001 | 7 |
| 2010 | 7 |
+------+-------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "It can be done with the following three ways in MySQL"
},
{
"code": null,
"e": 1360,
"s": 1116,
"text": " For extracting YEAR and MONTH collectively then we can use the EXTRACT function. We need to provide the YEAR_MONTH as an argument for this function. To understand it, consider the following function using the data from table ‘Collegedetail’ −"
},
{
"code": null,
"e": 1755,
"s": 1360,
"text": "mysql> Select EXTRACT(YEAR_MONTH From estb) from collegedetail;\n+-------------------------------+\n| EXTRACT(YEAR_MONTH From estb) |\n+-------------------------------+\n| 201005 |\n| 199510 |\n| 199409 |\n| 200107 |\n| 201007 |\n+-------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1980,
"s": 1755,
"text": " It can extract the year and the month collectively as well as separately. As the name suggests we can also format its output. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −"
},
{
"code": null,
"e": 3353,
"s": 1980,
"text": "mysql> Select DATE_FORMAT(estb, '%Y %m') from collegedetail;\n+----------------------------+\n| DATE_FORMAT(estb, '%Y %m') |\n+----------------------------+\n| 2010 05 |\n| 1995 10 |\n| 1994 09 |\n| 2001 07 |\n| 2010 07 |\n+----------------------------+\n5 rows in set (0.00 sec)\n\nmysql> Select DATE_FORMAT(estb, '%Y') from Collegedetail;\n+-------------------------+\n| DATE_FORMAT(estb, '%Y') |\n+-------------------------+\n| 2010 |\n| 1995 |\n| 1994 |\n| 2001 |\n| 2010 |\n+-------------------------+\n5 rows in set (0.00 sec)\n\nmysql> Select DATE_FORMAT(estb, '%m') from Collegedetail;\n+-------------------------+\n| DATE_FORMAT(estb, '%m') |\n+-------------------------+\n| 05 |\n| 10 |\n| 09 |\n| 07 |\n| 07 |\n+-------------------------+\n5 rows in set (0.00 sec)\n\nmysql> Select DATE_FORMAT(estb, '%M') from Collegedetail;\n+-------------------------+\n| DATE_FORMAT(estb, '%M') |\n+-------------------------+\n| May |\n| October |\n| September |\n| July |\n| July |\n+-------------------------+\n5 rows in set (0.10 sec)"
},
{
"code": null,
"e": 3532,
"s": 3353,
"text": " it will extract the Year and month separately by using two different functions. To understand it, consider the following example which uses the data from table ‘Collegedetail’ −"
},
{
"code": null,
"e": 3789,
"s": 3532,
"text": "mysql> Select YEAR(estb) AS 'Year', MONTH(estb) As 'MONTH' From collegedetail;\n+------+-------+\n| Year | MONTH |\n+------+-------+\n| 2010 | 5 |\n| 1995 | 10 |\n| 1994 | 9 |\n| 2001 | 7 |\n| 2010 | 7 |\n+------+-------+\n5 rows in set (0.00 sec)"
}
] |
How to find Square root of complex numbers in Python? | You can find the Square root of complex numbers in Python using the cmath library. The cmath library in python is a library for dealing with complex numbers. You can use it as follows to find the square root −
from cmath import sqrt
a = 0.2 + 0.5j
print(sqrt(a))
This will give the output
(0.6076662244659689+0.4114100635092987j) | [
{
"code": null,
"e": 1272,
"s": 1062,
"text": "You can find the Square root of complex numbers in Python using the cmath library. The cmath library in python is a library for dealing with complex numbers. You can use it as follows to find the square root −"
},
{
"code": null,
"e": 1295,
"s": 1272,
"text": "from cmath import sqrt"
},
{
"code": null,
"e": 1325,
"s": 1295,
"text": "a = 0.2 + 0.5j\nprint(sqrt(a))"
},
{
"code": null,
"e": 1352,
"s": 1325,
"text": "This will give the output "
},
{
"code": null,
"e": 1393,
"s": 1352,
"text": "(0.6076662244659689+0.4114100635092987j)"
}
] |
Split large R Dataframe into list of smaller Dataframes - GeeksforGeeks | 06 Aug, 2021
In this article, we will discuss how to split a large R dataframe into lists of smaller Dataframes. In R Programming language we have a function named split() which is used to split the data frame into parts.
So to do this, we first create an example of a dataframe which is needed to be split.
Creating dataframe:
R
# create the data framedata <- data.frame(id = c("X", "Y", "Z", "X", "X", "X", "Y", "Y", "Z", "X"), x1 = 11 : 20, x2 = 110 : 110) # print the dataframedata
Output:
To split the above Dataframe we use the split() function. The syntax of split() function is:
Syntax: split(x, f, drop = FALSE, ...)
Parameters:
x stands for DataFrame and vector
f stands for grouping of vector or selecting the column according to which we split the Dataframe
drop stands for delete or skip the specified row
Example 1: In this example, we try to run the split function without any argument except the above Dataframe.
When we run the split function without any argument except dataframe we noticed that the split function returns the combination of every element of column 1 with the other columns. In our case, there are 3 distinct elements in column 1 and a total of 10 rows in the data frame. So, the total rows as output are 3 * 10 = 30 rows in our output.
R
# create the data framedata <- data.frame(a1 = c("X", "Y", "Z", "X", "X", "X", "Y", "Y", "Z", "X"), a2 = 11 : 20, a3 = 110 : 110) # split the dataframe using the# split functionsplit_data <- split(data, f = data) # print the splitted data framesplit_data
Output:
Note: The above output screenshot is 1/3 of the actual output, due to conciseness we can not insert the full output screenshot.
Example 2: In this example, we will split the Dataframe by grouping with the help of 1 column.
To do this we will use the “f” argument of the split function and “$” is used to selecting the column according to which we are going to split the Dataframe. In our case, we are going to split the Dataframe according to the a1 column.
R
# create the data framedata <- data.frame(a1 = c("X", "Y", "Z", "X", "X", "X", "Y", "Y", "Z", "X"), a2 = 11 : 20, a3 = 110 : 110) # split the data frame by grouping using "f" argumentsplit_data <- split(data, f = data$a1) # print the split datasplit_data
Output:
Example 3: In this example, we will split the Dataframe by grouping with the help of 2 columns.
To do this we will use the “f” argument of the split function and “$” is used to selecting the columns and make a list of the columns according to which we are going to split the Dataframe. In our case, we are going to split the Dataframe according to the a1 and a2 columns. So, a list of a1 and a2 is created and this list is given as an argument to the “f”.
R
# create the data framedata <- data.frame(a1 = c("X", "Y", "Z", "X", "X", "X", "Y", "Y", "Z", "X"), a2 = c(1, 1, 1, 2, 2, 2, 1, 2, 1, 2), a3 = 110 : 110)# split the data frame by grouping using "f" argumentsplit_data <- split(data, f=list(data$a1, data$a2)) # print the split datasplit_data
Output:
adnanirshad158
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.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
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?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 25060,
"s": 24851,
"text": "In this article, we will discuss how to split a large R dataframe into lists of smaller Dataframes. In R Programming language we have a function named split() which is used to split the data frame into parts."
},
{
"code": null,
"e": 25146,
"s": 25060,
"text": "So to do this, we first create an example of a dataframe which is needed to be split."
},
{
"code": null,
"e": 25166,
"s": 25146,
"text": "Creating dataframe:"
},
{
"code": null,
"e": 25168,
"s": 25166,
"text": "R"
},
{
"code": "# create the data framedata <- data.frame(id = c(\"X\", \"Y\", \"Z\", \"X\", \"X\", \"X\", \"Y\", \"Y\", \"Z\", \"X\"), x1 = 11 : 20, x2 = 110 : 110) # print the dataframedata",
"e": 25386,
"s": 25168,
"text": null
},
{
"code": null,
"e": 25394,
"s": 25386,
"text": "Output:"
},
{
"code": null,
"e": 25487,
"s": 25394,
"text": "To split the above Dataframe we use the split() function. The syntax of split() function is:"
},
{
"code": null,
"e": 25526,
"s": 25487,
"text": "Syntax: split(x, f, drop = FALSE, ...)"
},
{
"code": null,
"e": 25538,
"s": 25526,
"text": "Parameters:"
},
{
"code": null,
"e": 25572,
"s": 25538,
"text": "x stands for DataFrame and vector"
},
{
"code": null,
"e": 25670,
"s": 25572,
"text": "f stands for grouping of vector or selecting the column according to which we split the Dataframe"
},
{
"code": null,
"e": 25719,
"s": 25670,
"text": "drop stands for delete or skip the specified row"
},
{
"code": null,
"e": 25829,
"s": 25719,
"text": "Example 1: In this example, we try to run the split function without any argument except the above Dataframe."
},
{
"code": null,
"e": 26172,
"s": 25829,
"text": "When we run the split function without any argument except dataframe we noticed that the split function returns the combination of every element of column 1 with the other columns. In our case, there are 3 distinct elements in column 1 and a total of 10 rows in the data frame. So, the total rows as output are 3 * 10 = 30 rows in our output."
},
{
"code": null,
"e": 26174,
"s": 26172,
"text": "R"
},
{
"code": "# create the data framedata <- data.frame(a1 = c(\"X\", \"Y\", \"Z\", \"X\", \"X\", \"X\", \"Y\", \"Y\", \"Z\", \"X\"), a2 = 11 : 20, a3 = 110 : 110) # split the dataframe using the# split functionsplit_data <- split(data, f = data) # print the splitted data framesplit_data",
"e": 26494,
"s": 26174,
"text": null
},
{
"code": null,
"e": 26502,
"s": 26494,
"text": "Output:"
},
{
"code": null,
"e": 26630,
"s": 26502,
"text": "Note: The above output screenshot is 1/3 of the actual output, due to conciseness we can not insert the full output screenshot."
},
{
"code": null,
"e": 26725,
"s": 26630,
"text": "Example 2: In this example, we will split the Dataframe by grouping with the help of 1 column."
},
{
"code": null,
"e": 26960,
"s": 26725,
"text": "To do this we will use the “f” argument of the split function and “$” is used to selecting the column according to which we are going to split the Dataframe. In our case, we are going to split the Dataframe according to the a1 column."
},
{
"code": null,
"e": 26962,
"s": 26960,
"text": "R"
},
{
"code": "# create the data framedata <- data.frame(a1 = c(\"X\", \"Y\", \"Z\", \"X\", \"X\", \"X\", \"Y\", \"Y\", \"Z\", \"X\"), a2 = 11 : 20, a3 = 110 : 110) # split the data frame by grouping using \"f\" argumentsplit_data <- split(data, f = data$a1) # print the split datasplit_data",
"e": 27281,
"s": 26962,
"text": null
},
{
"code": null,
"e": 27290,
"s": 27281,
"text": "Output: "
},
{
"code": null,
"e": 27386,
"s": 27290,
"text": "Example 3: In this example, we will split the Dataframe by grouping with the help of 2 columns."
},
{
"code": null,
"e": 27746,
"s": 27386,
"text": "To do this we will use the “f” argument of the split function and “$” is used to selecting the columns and make a list of the columns according to which we are going to split the Dataframe. In our case, we are going to split the Dataframe according to the a1 and a2 columns. So, a list of a1 and a2 is created and this list is given as an argument to the “f”."
},
{
"code": null,
"e": 27748,
"s": 27746,
"text": "R"
},
{
"code": "# create the data framedata <- data.frame(a1 = c(\"X\", \"Y\", \"Z\", \"X\", \"X\", \"X\", \"Y\", \"Y\", \"Z\", \"X\"), a2 = c(1, 1, 1, 2, 2, 2, 1, 2, 1, 2), a3 = 110 : 110)# split the data frame by grouping using \"f\" argumentsplit_data <- split(data, f=list(data$a1, data$a2)) # print the split datasplit_data",
"e": 28148,
"s": 27748,
"text": null
},
{
"code": null,
"e": 28156,
"s": 28148,
"text": "Output:"
},
{
"code": null,
"e": 28171,
"s": 28156,
"text": "adnanirshad158"
},
{
"code": null,
"e": 28178,
"s": 28171,
"text": "Picked"
},
{
"code": null,
"e": 28199,
"s": 28178,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28211,
"s": 28199,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28222,
"s": 28211,
"text": "R Language"
},
{
"code": null,
"e": 28233,
"s": 28222,
"text": "R Programs"
},
{
"code": null,
"e": 28331,
"s": 28233,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28340,
"s": 28331,
"text": "Comments"
},
{
"code": null,
"e": 28353,
"s": 28340,
"text": "Old Comments"
},
{
"code": null,
"e": 28405,
"s": 28353,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28443,
"s": 28405,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28478,
"s": 28443,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28536,
"s": 28478,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28585,
"s": 28536,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28643,
"s": 28585,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28692,
"s": 28643,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28735,
"s": 28692,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28785,
"s": 28735,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Convert a JSON String to Java Object using the json-simple library in Java?
| The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to encode or decode a JSON text.
In the below program, we can convert a JSON String to Java object using the json.simple library.
import org.json.simple.*;
import org.json.simple.parser.*;
public class ConvertJSONStringToObjectTest {
public static void main(String[] args) {
String jsonString = "{\"Name\":\"Raja\",\"EmployeeId\":\"115\",\"Age\":\"30\"}";
JSONParser parser = new JSONParser();
JSONObject obj;
try {
obj = (JSONObject)parser.parse(jsonString);
System.out.println(obj.get("Name"));
System.out.println(obj.get("EmployeeId"));
System.out.println(obj.get("Age"));
} catch(ParseException e) {
e.printStackTrace();
}
}
}
Raja
115
30 | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to encode or decode a JSON text. "
},
{
"code": null,
"e": 1374,
"s": 1277,
"text": "In the below program, we can convert a JSON String to Java object using the json.simple library."
},
{
"code": null,
"e": 1962,
"s": 1374,
"text": "import org.json.simple.*;\nimport org.json.simple.parser.*;\npublic class ConvertJSONStringToObjectTest {\n public static void main(String[] args) {\n String jsonString = \"{\\\"Name\\\":\\\"Raja\\\",\\\"EmployeeId\\\":\\\"115\\\",\\\"Age\\\":\\\"30\\\"}\";\n JSONParser parser = new JSONParser();\n JSONObject obj;\n try {\n obj = (JSONObject)parser.parse(jsonString);\n System.out.println(obj.get(\"Name\"));\n System.out.println(obj.get(\"EmployeeId\"));\n System.out.println(obj.get(\"Age\"));\n } catch(ParseException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 1974,
"s": 1962,
"text": "Raja\n115\n30"
}
] |
Tryit Editor v3.6 - Show React | import React from 'react';
import ReactDOM from 'react-dom/client';
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" /> | [
{
"code": null,
"e": 265,
"s": 0,
"text": "\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\n\nconst myElement = (\n <ul>\n <li>Apples</li>\n <li>Bananas</li>\n <li>Cherries</li>\n </ul>\n);\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(myElement);\n\n"
}
] |
Apriori: Association Rule Mining In-depth Explanation and Python Implementation | by Chonyy | Towards Data Science | The most famous story about association rule mining is the “beer and diaper”. Researchers discovered that customers who buy diapers also tend to buy beer. This classic example shows that there might be many interesting association rules hidden in our daily data.
Association rule mining is a technique to identify underlying relations between different items. There are many methods to perform association rule mining. The Apriori algorithm that we are going to introduce in this article is the most simple and straightforward approach. However, since it’s the fundamental method, there are many different improvements that can be applied to it.
We will not delve deep into these improvements. Instead, I will show the major shortcomings of Apriori in this story. And in the upcoming post, a more efficient FP Growth algorithm will be introduced. We will also compare the pros and cons of FP Growth and Apriori in the next post.
towardsdatascience.com
Fraction of transactions that contain an itemset.
For example, the support of item I is defined as the number of transactions containing I divided by the total number of transactions.
Measures how often items in Y appear in transactions that contain X
Confidence is the likelihood that item Y is also bought if item X is bought. It’s calculated as the number of transactions containing X and Y divided by the number of transactions containing X.
An itemset whose support is greater than or equal to a minSup threshold
Frequent itemsets or also known as frequent pattern simply means all the itemsets that the support satisfies the minimum support threshold.
Feel free to check out the well-commented source code. It could really help to understand the whole algorithm.
github.com
The main idea of Apriori is
All non-empty subsets of a frequent itemset must also be frequent.
It’s a bottom-up approach. We started from every single item in the itemset list. Then, the candidates are generated by self-joining. We extend the length of the itemsets one item at a time. The subset test is performed at each stage and the itemsets that contain infrequent subsets are pruned. We repeat the process until no more successful itemsets can be derived from the data.
This is the official pseudocode of Apriori
Lk: frequent k-itemset, satisfy minimum support
Ck: candidate k-itemset, possible frequent k-itemsets
Please be aware that the pruning step is already included in the apriori-gen function. Personally, I found this pseudocode quite confusing. So, I organized it into my own version. It should be way easier to understand.
L[1] = {frequent 1-itemsets};for (k=2; L[k-1] != 0; k ++) do begin // perform self-joining C[k] = getUnion(L[k-1]) // remove pruned supersets C[k] = pruning(C[k]) // get itemsets that satisfy minSup L[k] = getAboveMinSup(C[k], minSup)endAnswer = Lk (union)
To sum up, the basic components of Apriori can be written as
Use k-1 itemsets to generate k itemsets
Getting C[k] by joining L[k-1] and L[k-1]
Prune C[k] with subset testing
Generate L[k] by extracting the itemsets in C[k] that satisfy minSup
Simulate the algorithm in your head and validate it with the example below. The concept should be really clear now.
This is the main function of this Apriori Python implementation. The most important part of this function is from line 16 ~ line 21. It basically follows my modified pseudocode written above.
Generate the candidate set by joining the frequent itemset from the previous stage.Perform subset testing and prune the candidate set if there’s an infrequent itemset contained.Calculate the final frequent itemset by getting those satisfy minimum support.
Generate the candidate set by joining the frequent itemset from the previous stage.
Perform subset testing and prune the candidate set if there’s an infrequent itemset contained.
Calculate the final frequent itemset by getting those satisfy minimum support.
For self-joining, we simply get all the union through brute-force and only return those are in the specific length.
To perform subset testing, we loop through all possible subsets in the itemset. If the subset is not in the previous frequent itemset, we prune it.
In the final step, we turn the candidate sets into frequent itemsets. Since we are not applying any improvement technique. The only approach we can go for is to brainlessly loop through the item and itemset over and over again to obtain the count. At last, we only retain the itemsets whose support is equal or higher than minimum support.
print(rules) # [[{'beer'}, {'rice'}, 0.666], [{'rice'}, {'beer'}, 1.000]]# (rules[0] --> rules[1]), confidence = rules[2]
For more usage and examples, please check out the GitHub repo or the PyPi package.
There are two major shortcomings of Apriori Algorithms
The size of itemset from candidate generation could be extremely large
Lots of time wasted on counting the support since we have to scan the itemset database over and over again
We will use the data4.csv(generated from IBM generator) in the repo to showcase these shortcomings and see if we can get some interesting observations.
By running Apriori on data4.csv, we can plot the process like the graph above. The shortcomings we mentioned above can be found in the observation of the graphs.
On the right, we can see the itemset size after the three major processes of the algorithm. Two key points can be discovered from the graph
Size of itemset rapidly increase at the beginning, and gradually decrease as the iteration goes on
Pruning process may be useless like stage 1 and 2. However, it could help a lot at some cases like stage 3. Half of the itemset is pruned, which means the counting time could be decreased by half!
From the plot, we can tell that most of the running is spent on counting the support. The time spent on candidate generation and pruning is nothing comparing to scanning the original itemset database over and over again.
Another observation worth attention is that we get a peak in cost at stage 2. Interestingly, This is actually not an accident! Data scientists often meet a bottleneck at stage 2 when using Apriori. Since there are almost no candidates removed at stage 1, the candidates generated at stage 2 are basically all possible combinations of all 1-frequent itemsets. And calculating the support of such a huge itemset leads to extremely high costs.
kaggle.csv
Just like what we mentioned above, we knew that the bottleneck of Apriori is normally at stage 2. However, as it shows on the Kaggle dataset plot, this observation may not always hold. To be accurate, it depends on the dataset itself and the minimum support we want.
data7.csv
As we can see, we need more than one minute to calculate the association rule of data7 with Apriori. Obviously, this running time is hardly acceptable. Remember that I said Apriori is just a fundamental method? The efficiency of it is the reason why it’s not widely used in the data science field. We will take this result and compare it with the result from FP Growth.
towardsdatascience.com
There are many extra techniques that can be applied to Apriori to improve efficiency. Some of them are listed below.
Hashing: reduce database scans
Transaction reduction: remove infrequent transactions from further consideration
Partitioning: possibly frequent must be frequent in one of the partition
Dynamic Itemset Counting: reduce the number of passes over the data
Sampling: pick up random samples | [
{
"code": null,
"e": 435,
"s": 172,
"text": "The most famous story about association rule mining is the “beer and diaper”. Researchers discovered that customers who buy diapers also tend to buy beer. This classic example shows that there might be many interesting association rules hidden in our daily data."
},
{
"code": null,
"e": 818,
"s": 435,
"text": "Association rule mining is a technique to identify underlying relations between different items. There are many methods to perform association rule mining. The Apriori algorithm that we are going to introduce in this article is the most simple and straightforward approach. However, since it’s the fundamental method, there are many different improvements that can be applied to it."
},
{
"code": null,
"e": 1101,
"s": 818,
"text": "We will not delve deep into these improvements. Instead, I will show the major shortcomings of Apriori in this story. And in the upcoming post, a more efficient FP Growth algorithm will be introduced. We will also compare the pros and cons of FP Growth and Apriori in the next post."
},
{
"code": null,
"e": 1124,
"s": 1101,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1174,
"s": 1124,
"text": "Fraction of transactions that contain an itemset."
},
{
"code": null,
"e": 1308,
"s": 1174,
"text": "For example, the support of item I is defined as the number of transactions containing I divided by the total number of transactions."
},
{
"code": null,
"e": 1376,
"s": 1308,
"text": "Measures how often items in Y appear in transactions that contain X"
},
{
"code": null,
"e": 1570,
"s": 1376,
"text": "Confidence is the likelihood that item Y is also bought if item X is bought. It’s calculated as the number of transactions containing X and Y divided by the number of transactions containing X."
},
{
"code": null,
"e": 1642,
"s": 1570,
"text": "An itemset whose support is greater than or equal to a minSup threshold"
},
{
"code": null,
"e": 1782,
"s": 1642,
"text": "Frequent itemsets or also known as frequent pattern simply means all the itemsets that the support satisfies the minimum support threshold."
},
{
"code": null,
"e": 1893,
"s": 1782,
"text": "Feel free to check out the well-commented source code. It could really help to understand the whole algorithm."
},
{
"code": null,
"e": 1904,
"s": 1893,
"text": "github.com"
},
{
"code": null,
"e": 1932,
"s": 1904,
"text": "The main idea of Apriori is"
},
{
"code": null,
"e": 1999,
"s": 1932,
"text": "All non-empty subsets of a frequent itemset must also be frequent."
},
{
"code": null,
"e": 2380,
"s": 1999,
"text": "It’s a bottom-up approach. We started from every single item in the itemset list. Then, the candidates are generated by self-joining. We extend the length of the itemsets one item at a time. The subset test is performed at each stage and the itemsets that contain infrequent subsets are pruned. We repeat the process until no more successful itemsets can be derived from the data."
},
{
"code": null,
"e": 2423,
"s": 2380,
"text": "This is the official pseudocode of Apriori"
},
{
"code": null,
"e": 2471,
"s": 2423,
"text": "Lk: frequent k-itemset, satisfy minimum support"
},
{
"code": null,
"e": 2525,
"s": 2471,
"text": "Ck: candidate k-itemset, possible frequent k-itemsets"
},
{
"code": null,
"e": 2744,
"s": 2525,
"text": "Please be aware that the pruning step is already included in the apriori-gen function. Personally, I found this pseudocode quite confusing. So, I organized it into my own version. It should be way easier to understand."
},
{
"code": null,
"e": 3019,
"s": 2744,
"text": "L[1] = {frequent 1-itemsets};for (k=2; L[k-1] != 0; k ++) do begin // perform self-joining C[k] = getUnion(L[k-1]) // remove pruned supersets C[k] = pruning(C[k]) // get itemsets that satisfy minSup L[k] = getAboveMinSup(C[k], minSup)endAnswer = Lk (union)"
},
{
"code": null,
"e": 3080,
"s": 3019,
"text": "To sum up, the basic components of Apriori can be written as"
},
{
"code": null,
"e": 3120,
"s": 3080,
"text": "Use k-1 itemsets to generate k itemsets"
},
{
"code": null,
"e": 3162,
"s": 3120,
"text": "Getting C[k] by joining L[k-1] and L[k-1]"
},
{
"code": null,
"e": 3193,
"s": 3162,
"text": "Prune C[k] with subset testing"
},
{
"code": null,
"e": 3262,
"s": 3193,
"text": "Generate L[k] by extracting the itemsets in C[k] that satisfy minSup"
},
{
"code": null,
"e": 3378,
"s": 3262,
"text": "Simulate the algorithm in your head and validate it with the example below. The concept should be really clear now."
},
{
"code": null,
"e": 3570,
"s": 3378,
"text": "This is the main function of this Apriori Python implementation. The most important part of this function is from line 16 ~ line 21. It basically follows my modified pseudocode written above."
},
{
"code": null,
"e": 3826,
"s": 3570,
"text": "Generate the candidate set by joining the frequent itemset from the previous stage.Perform subset testing and prune the candidate set if there’s an infrequent itemset contained.Calculate the final frequent itemset by getting those satisfy minimum support."
},
{
"code": null,
"e": 3910,
"s": 3826,
"text": "Generate the candidate set by joining the frequent itemset from the previous stage."
},
{
"code": null,
"e": 4005,
"s": 3910,
"text": "Perform subset testing and prune the candidate set if there’s an infrequent itemset contained."
},
{
"code": null,
"e": 4084,
"s": 4005,
"text": "Calculate the final frequent itemset by getting those satisfy minimum support."
},
{
"code": null,
"e": 4200,
"s": 4084,
"text": "For self-joining, we simply get all the union through brute-force and only return those are in the specific length."
},
{
"code": null,
"e": 4348,
"s": 4200,
"text": "To perform subset testing, we loop through all possible subsets in the itemset. If the subset is not in the previous frequent itemset, we prune it."
},
{
"code": null,
"e": 4688,
"s": 4348,
"text": "In the final step, we turn the candidate sets into frequent itemsets. Since we are not applying any improvement technique. The only approach we can go for is to brainlessly loop through the item and itemset over and over again to obtain the count. At last, we only retain the itemsets whose support is equal or higher than minimum support."
},
{
"code": null,
"e": 4811,
"s": 4688,
"text": "print(rules) # [[{'beer'}, {'rice'}, 0.666], [{'rice'}, {'beer'}, 1.000]]# (rules[0] --> rules[1]), confidence = rules[2]"
},
{
"code": null,
"e": 4894,
"s": 4811,
"text": "For more usage and examples, please check out the GitHub repo or the PyPi package."
},
{
"code": null,
"e": 4949,
"s": 4894,
"text": "There are two major shortcomings of Apriori Algorithms"
},
{
"code": null,
"e": 5020,
"s": 4949,
"text": "The size of itemset from candidate generation could be extremely large"
},
{
"code": null,
"e": 5127,
"s": 5020,
"text": "Lots of time wasted on counting the support since we have to scan the itemset database over and over again"
},
{
"code": null,
"e": 5279,
"s": 5127,
"text": "We will use the data4.csv(generated from IBM generator) in the repo to showcase these shortcomings and see if we can get some interesting observations."
},
{
"code": null,
"e": 5441,
"s": 5279,
"text": "By running Apriori on data4.csv, we can plot the process like the graph above. The shortcomings we mentioned above can be found in the observation of the graphs."
},
{
"code": null,
"e": 5581,
"s": 5441,
"text": "On the right, we can see the itemset size after the three major processes of the algorithm. Two key points can be discovered from the graph"
},
{
"code": null,
"e": 5680,
"s": 5581,
"text": "Size of itemset rapidly increase at the beginning, and gradually decrease as the iteration goes on"
},
{
"code": null,
"e": 5877,
"s": 5680,
"text": "Pruning process may be useless like stage 1 and 2. However, it could help a lot at some cases like stage 3. Half of the itemset is pruned, which means the counting time could be decreased by half!"
},
{
"code": null,
"e": 6098,
"s": 5877,
"text": "From the plot, we can tell that most of the running is spent on counting the support. The time spent on candidate generation and pruning is nothing comparing to scanning the original itemset database over and over again."
},
{
"code": null,
"e": 6539,
"s": 6098,
"text": "Another observation worth attention is that we get a peak in cost at stage 2. Interestingly, This is actually not an accident! Data scientists often meet a bottleneck at stage 2 when using Apriori. Since there are almost no candidates removed at stage 1, the candidates generated at stage 2 are basically all possible combinations of all 1-frequent itemsets. And calculating the support of such a huge itemset leads to extremely high costs."
},
{
"code": null,
"e": 6550,
"s": 6539,
"text": "kaggle.csv"
},
{
"code": null,
"e": 6817,
"s": 6550,
"text": "Just like what we mentioned above, we knew that the bottleneck of Apriori is normally at stage 2. However, as it shows on the Kaggle dataset plot, this observation may not always hold. To be accurate, it depends on the dataset itself and the minimum support we want."
},
{
"code": null,
"e": 6827,
"s": 6817,
"text": "data7.csv"
},
{
"code": null,
"e": 7197,
"s": 6827,
"text": "As we can see, we need more than one minute to calculate the association rule of data7 with Apriori. Obviously, this running time is hardly acceptable. Remember that I said Apriori is just a fundamental method? The efficiency of it is the reason why it’s not widely used in the data science field. We will take this result and compare it with the result from FP Growth."
},
{
"code": null,
"e": 7220,
"s": 7197,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7337,
"s": 7220,
"text": "There are many extra techniques that can be applied to Apriori to improve efficiency. Some of them are listed below."
},
{
"code": null,
"e": 7368,
"s": 7337,
"text": "Hashing: reduce database scans"
},
{
"code": null,
"e": 7449,
"s": 7368,
"text": "Transaction reduction: remove infrequent transactions from further consideration"
},
{
"code": null,
"e": 7522,
"s": 7449,
"text": "Partitioning: possibly frequent must be frequent in one of the partition"
},
{
"code": null,
"e": 7590,
"s": 7522,
"text": "Dynamic Itemset Counting: reduce the number of passes over the data"
}
] |
Column Sort of a Matrix in Python | Suppose we have a matrix, we have to sort each of the columns in ascending order.
So, if the input is like
then the output will be
To solve this, we will follow these steps −
R := row count of matrix, C := column count of matrix
res := matrix of same size as given matrix and fill with 0
for col in range 0 to C, dovalues := take the elements as a vector of matrix[col]for row in range 0 to R, dores[row, col] := delete last element from values
values := take the elements as a vector of matrix[col]
for row in range 0 to R, dores[row, col] := delete last element from values
res[row, col] := delete last element from values
return res
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, matrix):
R = len(matrix)
C = len(matrix[0])
res = [[0] * C for _ in range(R)]
for col in range(C):
values = [r[col] for r in matrix]
values.sort(reverse=True)
for row in range(R):
res[row][col] = values.pop()
return res
ob = Solution()
matrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]]
print(ob.solve(matrix))
[[11, 21, 31],
[6, 6, 4],
[1, 11, 8]]
[[1, 6, 4],[6, 11, 8],[11, 21, 31]] | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Suppose we have a matrix, we have to sort each of the columns in ascending order."
},
{
"code": null,
"e": 1169,
"s": 1144,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1193,
"s": 1169,
"text": "then the output will be"
},
{
"code": null,
"e": 1237,
"s": 1193,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1291,
"s": 1237,
"text": "R := row count of matrix, C := column count of matrix"
},
{
"code": null,
"e": 1350,
"s": 1291,
"text": "res := matrix of same size as given matrix and fill with 0"
},
{
"code": null,
"e": 1507,
"s": 1350,
"text": "for col in range 0 to C, dovalues := take the elements as a vector of matrix[col]for row in range 0 to R, dores[row, col] := delete last element from values"
},
{
"code": null,
"e": 1562,
"s": 1507,
"text": "values := take the elements as a vector of matrix[col]"
},
{
"code": null,
"e": 1638,
"s": 1562,
"text": "for row in range 0 to R, dores[row, col] := delete last element from values"
},
{
"code": null,
"e": 1687,
"s": 1638,
"text": "res[row, col] := delete last element from values"
},
{
"code": null,
"e": 1698,
"s": 1687,
"text": "return res"
},
{
"code": null,
"e": 1768,
"s": 1698,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1779,
"s": 1768,
"text": " Live Demo"
},
{
"code": null,
"e": 2188,
"s": 1779,
"text": "class Solution:\n def solve(self, matrix):\n R = len(matrix)\n C = len(matrix[0])\n res = [[0] * C for _ in range(R)]\n for col in range(C):\n values = [r[col] for r in matrix]\n values.sort(reverse=True)\n for row in range(R):\n res[row][col] = values.pop()\n return res\nob = Solution()\nmatrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]]\nprint(ob.solve(matrix))"
},
{
"code": null,
"e": 2226,
"s": 2188,
"text": "[[11, 21, 31],\n[6, 6, 4],\n[1, 11, 8]]"
},
{
"code": null,
"e": 2262,
"s": 2226,
"text": "[[1, 6, 4],[6, 11, 8],[11, 21, 31]]"
}
] |
Beginners in Java — Getting Started with OOP | by Rishi Sidhu | Towards Data Science | Whenever a programming methodology is based on objects or classes, instead of just functions and procedures it is called Object Oriented Programming (OOP).
All code in Java must be contained within classes
Objects in an object oriented language are organised into classes or in simpler terms a class gives birth to objects. Java is one such programming language.
Everything in a java program is contained within a class. A class can be considered as a factory that produces objects. An object contains data inside of it. It can have one data item or many. e.g. a lunchbox object might contain 3 data items
Fries (of the type solid food)Burger (of the type solid food)Cold Drink (of the type liquid food)
Fries (of the type solid food)
Burger (of the type solid food)
Cold Drink (of the type liquid food)
These 3 different items inside our object are called fields. Every field must have a type. In the above example, we have 3 fields but 2 of them have the same type. At the same time we methods that act on data. For example, methods can be used to see what data is contained inside an object. These are called accessor methods. We can also have methods that modify the data inside the object. These are known as updater methods.
Let’s say that we have a food factory (class). It makes lunch boxes (objects). A lunchbox contains 3 different items of food(fields). Two of them are the same type (solid food) and one is different (liquid food). We have 3 people who interact to use this food. The chef (Method 1) heats the food, the waiter (Method 2) serves the food and the consumer (Method 3) eats the food.
In Java programs, the primary “actors” are objects. Every object is an instance of a class, which serves as the type of the object and as a blueprint, defining the data which the object stores and the methods for accessing and modifying that data. — Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser (Data Structures and Algorithms in Java)
An object is an instance of the class i.e. A class can give rise to many objects. For example
Solid Food Item 1 — FriesSolid Food Item 2 — BurgerLiquid Food Item 1 — Cold Drink
Solid Food Item 1 — Fries
Solid Food Item 2 — Burger
Liquid Food Item 1 — Cold Drink
Solid Food Item 1 — RiceSolid Food Item 2 — FishLiquid Food Item 1 — Water
Solid Food Item 1 — Rice
Solid Food Item 2 — Fish
Liquid Food Item 1 — Water
Let’s try to see how to build a basic Factory Class. Let’s first take a look at the complete code.
The lines public class Factory{} enclose the complete code. The file has to be named as the class name. So the filename is also Factory.java.
public class Factory{ ...}
Now the top 3 lines give you the 3 items (instance variables) you want in your lunchbox. Right now you can see that all 3 have the same type = String. Java gives you the flexibility to create your own types which essentially means creating a class by that name. So if you were to create a SolidFood class, for example, you would have to write public class SolidFood{} and that’s all.
Right now we have 3 instance variables of the type String and names SolidFood1, SolidFood2 and LiquidFood1.
private String SolidFood1; // Solid Food 1st Instance Variable private String SolidFood2; // Solid Food 2nd Instance Variable private String LiquidFood1; // Liquid Food 3rd Instance Variable
The code that creates an object lies inside the constructor. A constructor can be an empty one or can take some input arguments that are used to define the object. In our case sf1, sf2 and lf1 are the arguments that define what items are contained in our lunchbox.
In simple words, a constructor defines what the fields of the object look like.
public Factory(){} // 0-arg constructor (Not used)// 3-arg constructor public Factory(String sf1, String sf2, String lf1){ SolidFood1 = sf1; SolidFood2 = sf2; LiquidFood1 = lf1; }
Methods are used to either fetch object fields or modify them. In our case, we have only written fields that fetch the item names.
public String getSF1(){return SolidFood1;} // Method to get the name of 1st Instance Variable public String getSF2(){return SolidFood2;} // Method to get the name of 2nd Instance Variable public String getLF1(){return LiquidFood1;} // Method to get the name of 3rd Instance Variable
The main method is the only method that needs to be in every program. It is the only thing that java compiler runs. From inside the main, you can create objects, use methods on these objects and print stuff.
Object is created by calling a constructor. Once an object is created you can use various methods at your disposal to understand or modify the object. Here we are just showing how to access field names.
Factory lunchBox = new Factory("s1","s2", "l1"); // Object Created Yay!!!
Just in case you do not have java visit this page.
java.com
Assuming you have java installed in your system you should be able to run the program using the following commands.
> javac Factory.java (This command compiles your code into Machine Readable Code)> java Factory (Running the Program)
The output you see looks like this
There is a lot more involved in OOP. This was just the beginning. Later articles will include more involved concepts of object oriented programming.
Gist LinkJava DownloadData Structures Book
Gist Link
Java Download
Data Structures Book | [
{
"code": null,
"e": 328,
"s": 172,
"text": "Whenever a programming methodology is based on objects or classes, instead of just functions and procedures it is called Object Oriented Programming (OOP)."
},
{
"code": null,
"e": 378,
"s": 328,
"text": "All code in Java must be contained within classes"
},
{
"code": null,
"e": 535,
"s": 378,
"text": "Objects in an object oriented language are organised into classes or in simpler terms a class gives birth to objects. Java is one such programming language."
},
{
"code": null,
"e": 778,
"s": 535,
"text": "Everything in a java program is contained within a class. A class can be considered as a factory that produces objects. An object contains data inside of it. It can have one data item or many. e.g. a lunchbox object might contain 3 data items"
},
{
"code": null,
"e": 876,
"s": 778,
"text": "Fries (of the type solid food)Burger (of the type solid food)Cold Drink (of the type liquid food)"
},
{
"code": null,
"e": 907,
"s": 876,
"text": "Fries (of the type solid food)"
},
{
"code": null,
"e": 939,
"s": 907,
"text": "Burger (of the type solid food)"
},
{
"code": null,
"e": 976,
"s": 939,
"text": "Cold Drink (of the type liquid food)"
},
{
"code": null,
"e": 1403,
"s": 976,
"text": "These 3 different items inside our object are called fields. Every field must have a type. In the above example, we have 3 fields but 2 of them have the same type. At the same time we methods that act on data. For example, methods can be used to see what data is contained inside an object. These are called accessor methods. We can also have methods that modify the data inside the object. These are known as updater methods."
},
{
"code": null,
"e": 1781,
"s": 1403,
"text": "Let’s say that we have a food factory (class). It makes lunch boxes (objects). A lunchbox contains 3 different items of food(fields). Two of them are the same type (solid food) and one is different (liquid food). We have 3 people who interact to use this food. The chef (Method 1) heats the food, the waiter (Method 2) serves the food and the consumer (Method 3) eats the food."
},
{
"code": null,
"e": 2133,
"s": 1781,
"text": "In Java programs, the primary “actors” are objects. Every object is an instance of a class, which serves as the type of the object and as a blueprint, defining the data which the object stores and the methods for accessing and modifying that data. — Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser (Data Structures and Algorithms in Java)"
},
{
"code": null,
"e": 2227,
"s": 2133,
"text": "An object is an instance of the class i.e. A class can give rise to many objects. For example"
},
{
"code": null,
"e": 2310,
"s": 2227,
"text": "Solid Food Item 1 — FriesSolid Food Item 2 — BurgerLiquid Food Item 1 — Cold Drink"
},
{
"code": null,
"e": 2336,
"s": 2310,
"text": "Solid Food Item 1 — Fries"
},
{
"code": null,
"e": 2363,
"s": 2336,
"text": "Solid Food Item 2 — Burger"
},
{
"code": null,
"e": 2395,
"s": 2363,
"text": "Liquid Food Item 1 — Cold Drink"
},
{
"code": null,
"e": 2470,
"s": 2395,
"text": "Solid Food Item 1 — RiceSolid Food Item 2 — FishLiquid Food Item 1 — Water"
},
{
"code": null,
"e": 2495,
"s": 2470,
"text": "Solid Food Item 1 — Rice"
},
{
"code": null,
"e": 2520,
"s": 2495,
"text": "Solid Food Item 2 — Fish"
},
{
"code": null,
"e": 2547,
"s": 2520,
"text": "Liquid Food Item 1 — Water"
},
{
"code": null,
"e": 2646,
"s": 2547,
"text": "Let’s try to see how to build a basic Factory Class. Let’s first take a look at the complete code."
},
{
"code": null,
"e": 2788,
"s": 2646,
"text": "The lines public class Factory{} enclose the complete code. The file has to be named as the class name. So the filename is also Factory.java."
},
{
"code": null,
"e": 2817,
"s": 2788,
"text": "public class Factory{ ...}"
},
{
"code": null,
"e": 3201,
"s": 2817,
"text": "Now the top 3 lines give you the 3 items (instance variables) you want in your lunchbox. Right now you can see that all 3 have the same type = String. Java gives you the flexibility to create your own types which essentially means creating a class by that name. So if you were to create a SolidFood class, for example, you would have to write public class SolidFood{} and that’s all."
},
{
"code": null,
"e": 3309,
"s": 3201,
"text": "Right now we have 3 instance variables of the type String and names SolidFood1, SolidFood2 and LiquidFood1."
},
{
"code": null,
"e": 3510,
"s": 3309,
"text": " private String SolidFood1; // Solid Food 1st Instance Variable private String SolidFood2; // Solid Food 2nd Instance Variable private String LiquidFood1; // Liquid Food 3rd Instance Variable"
},
{
"code": null,
"e": 3775,
"s": 3510,
"text": "The code that creates an object lies inside the constructor. A constructor can be an empty one or can take some input arguments that are used to define the object. In our case sf1, sf2 and lf1 are the arguments that define what items are contained in our lunchbox."
},
{
"code": null,
"e": 3855,
"s": 3775,
"text": "In simple words, a constructor defines what the fields of the object look like."
},
{
"code": null,
"e": 4054,
"s": 3855,
"text": "public Factory(){} // 0-arg constructor (Not used)// 3-arg constructor public Factory(String sf1, String sf2, String lf1){ SolidFood1 = sf1; SolidFood2 = sf2; LiquidFood1 = lf1; }"
},
{
"code": null,
"e": 4185,
"s": 4054,
"text": "Methods are used to either fetch object fields or modify them. In our case, we have only written fields that fetch the item names."
},
{
"code": null,
"e": 4468,
"s": 4185,
"text": "public String getSF1(){return SolidFood1;} // Method to get the name of 1st Instance Variable public String getSF2(){return SolidFood2;} // Method to get the name of 2nd Instance Variable public String getLF1(){return LiquidFood1;} // Method to get the name of 3rd Instance Variable"
},
{
"code": null,
"e": 4676,
"s": 4468,
"text": "The main method is the only method that needs to be in every program. It is the only thing that java compiler runs. From inside the main, you can create objects, use methods on these objects and print stuff."
},
{
"code": null,
"e": 4879,
"s": 4676,
"text": "Object is created by calling a constructor. Once an object is created you can use various methods at your disposal to understand or modify the object. Here we are just showing how to access field names."
},
{
"code": null,
"e": 4953,
"s": 4879,
"text": "Factory lunchBox = new Factory(\"s1\",\"s2\", \"l1\"); // Object Created Yay!!!"
},
{
"code": null,
"e": 5004,
"s": 4953,
"text": "Just in case you do not have java visit this page."
},
{
"code": null,
"e": 5013,
"s": 5004,
"text": "java.com"
},
{
"code": null,
"e": 5129,
"s": 5013,
"text": "Assuming you have java installed in your system you should be able to run the program using the following commands."
},
{
"code": null,
"e": 5247,
"s": 5129,
"text": "> javac Factory.java (This command compiles your code into Machine Readable Code)> java Factory (Running the Program)"
},
{
"code": null,
"e": 5282,
"s": 5247,
"text": "The output you see looks like this"
},
{
"code": null,
"e": 5431,
"s": 5282,
"text": "There is a lot more involved in OOP. This was just the beginning. Later articles will include more involved concepts of object oriented programming."
},
{
"code": null,
"e": 5474,
"s": 5431,
"text": "Gist LinkJava DownloadData Structures Book"
},
{
"code": null,
"e": 5484,
"s": 5474,
"text": "Gist Link"
},
{
"code": null,
"e": 5498,
"s": 5484,
"text": "Java Download"
}
] |
rand() and srand() in C | The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.
Here is the syntax of rand() in C language,
int rand(void);
Here is an example of rand() in C language,
Live Demo
#include <stdio.h>
#include<stdlib.h>
int main() {
printf("%d\n", rand());
printf("%d", rand());
return 0;
}
1804289383
846930886
The function srand() is used to initialize the generated pseudo random number by rand() function. It does not return anything.
Here is the syntax of srand() in C language,
void srand(unsigned int number);
Here is an example of srand() in C language,
Live Demo
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
srand(time(NULL));
printf("%d\n", rand());
srand(12);
printf("%d", rand());
return 0;
}
1432462941
1687063760 | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767."
},
{
"code": null,
"e": 1247,
"s": 1203,
"text": "Here is the syntax of rand() in C language,"
},
{
"code": null,
"e": 1263,
"s": 1247,
"text": "int rand(void);"
},
{
"code": null,
"e": 1307,
"s": 1263,
"text": "Here is an example of rand() in C language,"
},
{
"code": null,
"e": 1318,
"s": 1307,
"text": " Live Demo"
},
{
"code": null,
"e": 1436,
"s": 1318,
"text": "#include <stdio.h>\n#include<stdlib.h>\nint main() {\n printf(\"%d\\n\", rand());\n printf(\"%d\", rand());\n return 0;\n}"
},
{
"code": null,
"e": 1457,
"s": 1436,
"text": "1804289383\n846930886"
},
{
"code": null,
"e": 1584,
"s": 1457,
"text": "The function srand() is used to initialize the generated pseudo random number by rand() function. It does not return anything."
},
{
"code": null,
"e": 1629,
"s": 1584,
"text": "Here is the syntax of srand() in C language,"
},
{
"code": null,
"e": 1662,
"s": 1629,
"text": "void srand(unsigned int number);"
},
{
"code": null,
"e": 1707,
"s": 1662,
"text": "Here is an example of srand() in C language,"
},
{
"code": null,
"e": 1718,
"s": 1707,
"text": " Live Demo"
},
{
"code": null,
"e": 1889,
"s": 1718,
"text": "#include <stdio.h>\n#include<stdlib.h>\n#include<time.h>\nint main() {\n srand(time(NULL));\n printf(\"%d\\n\", rand());\n srand(12);\n printf(\"%d\", rand());\n return 0;\n}"
},
{
"code": null,
"e": 1911,
"s": 1889,
"text": "1432462941\n1687063760"
}
] |
HTML <textarea> disabled Attribute - GeeksforGeeks | 04 Jan, 2019
The disabled attribute for <textarea> element in HTML is used to specify that the text area element is disabled. A disabled text area is un-clickable and unusable. It is a boolean attribute.
Syntax:
<textarea disabled>text content...</textarea>
Example:
<!DOCTYPE html> <html> <head> <title>HTML textarea disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML textarea disabled Attribute</h2> <p>This text area is non editable.</p> <!--A disabled textarea--> <textarea disabled> This textarea field is disabled. </textarea> </body> </html>
Output:
Supported Browsers: The browser supported by <textarea> disabled attribute 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.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
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": 23428,
"s": 23400,
"text": "\n04 Jan, 2019"
},
{
"code": null,
"e": 23619,
"s": 23428,
"text": "The disabled attribute for <textarea> element in HTML is used to specify that the text area element is disabled. A disabled text area is un-clickable and unusable. It is a boolean attribute."
},
{
"code": null,
"e": 23627,
"s": 23619,
"text": "Syntax:"
},
{
"code": null,
"e": 23674,
"s": 23627,
"text": "<textarea disabled>text content...</textarea>\n"
},
{
"code": null,
"e": 23683,
"s": 23674,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML textarea disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML textarea disabled Attribute</h2> <p>This text area is non editable.</p> <!--A disabled textarea--> <textarea disabled> This textarea field is disabled. </textarea> </body> </html> ",
"e": 24128,
"s": 23683,
"text": null
},
{
"code": null,
"e": 24136,
"s": 24128,
"text": "Output:"
},
{
"code": null,
"e": 24229,
"s": 24136,
"text": "Supported Browsers: The browser supported by <textarea> disabled attribute are listed below:"
},
{
"code": null,
"e": 24242,
"s": 24229,
"text": "Apple Safari"
},
{
"code": null,
"e": 24256,
"s": 24242,
"text": "Google Chrome"
},
{
"code": null,
"e": 24264,
"s": 24256,
"text": "Firefox"
},
{
"code": null,
"e": 24270,
"s": 24264,
"text": "Opera"
},
{
"code": null,
"e": 24288,
"s": 24270,
"text": "Internet Explorer"
},
{
"code": null,
"e": 24425,
"s": 24288,
"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": 24441,
"s": 24425,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 24446,
"s": 24441,
"text": "HTML"
},
{
"code": null,
"e": 24463,
"s": 24446,
"text": "Web Technologies"
},
{
"code": null,
"e": 24468,
"s": 24463,
"text": "HTML"
},
{
"code": null,
"e": 24566,
"s": 24468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24575,
"s": 24566,
"text": "Comments"
},
{
"code": null,
"e": 24588,
"s": 24575,
"text": "Old Comments"
},
{
"code": null,
"e": 24650,
"s": 24588,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 24700,
"s": 24650,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 24760,
"s": 24700,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 24808,
"s": 24760,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 24869,
"s": 24808,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 24925,
"s": 24869,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 24958,
"s": 24925,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25020,
"s": 24958,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25063,
"s": 25020,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Bootstrap - Thumbnails | This chapter discusses about Bootstrap thumbnails. A lot of sites need a way to lay out images, videos, text, etc, in a grid, and Bootstrap has an easy way to do this with thumbnails. To create thumbnails using Bootstrap −
Add an <a> tag with the class of .thumbnail around an image.
Add an <a> tag with the class of .thumbnail around an image.
This adds four pixels of padding and a gray border.
This adds four pixels of padding and a gray border.
On hover, an animated glow outlines the image.
On hover, an animated glow outlines the image.
The following example demonstrates a default thumbnail −
<div class = "row">
<div class = "col-sm-6 col-md-3">
<a href = "#" class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</a>
</div>
<div class = "col-sm-6 col-md-3">
<a href = "#" class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</a>
</div>
<div class = "col-sm-6 col-md-3">
<a href = "#" class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</a>
</div>
<div class = "col-sm-6 col-md-3">
<a href = "#" class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</a>
</div>
</div>
Now that we have a basic thumbnail, it's possible to add any kind of HTML content like headings, paragraphs, or buttons into thumbnails. Follow the steps below −
Change the <a> tag that has a class of .thumbnail to a <div>.
Change the <a> tag that has a class of .thumbnail to a <div>.
Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing.
Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing.
If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left.
If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left.
The following example demonstrates this −
<div class = "row">
<div class = "col-sm-6 col-md-3">
<div class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</div>
<div class = "caption">
<h3>Thumbnail label</h3>
<p>Some sample text. Some sample text.</p>
<p>
<a href = "#" class = "btn btn-primary" role = "button">
Button
</a>
<a href = "#" class = "btn btn-default" role = "button">
Button
</a>
</p>
</div>
</div>
<div class = "col-sm-6 col-md-3">
<div class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</div>
<div class = "caption">
<h3>Thumbnail label</h3>
<p>Some sample text. Some sample text.</p>
<p>
<a href = "#" class = "btn btn-primary" role = "button">
Button
</a>
<a href = "#" class = "btn btn-default" role = "button">
Button
</a>
</p>
</div>
</div>
<div class = "col-sm-6 col-md-3">
<div class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</div>
<div class = "caption">
<h3>Thumbnail label</h3>
<p>Some sample text. Some sample text.</p>
<p>
<a href = "#" class = "btn btn-primary" role = "button">
Button
</a>
<a href = "#" class = "btn btn-default" role =" button">
Button
</a>
</p>
</div>
</div>
<div class = "col-sm-6 col-md-3">
<div class = "thumbnail">
<img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
</div>
<div class = "caption">
<h3>Thumbnail label</h3>
<p>Some sample text. Some sample text.</p>
<p>
<a href = "#" class = "btn btn-primary" role = "button">
Button
</a>
<a href = "#" class = "btn btn-default" role = "button">
Button
</a>
</p>
</div>
</div>
</div>
Some sample text. Some sample text.
Button
Button
Some sample text. Some sample text.
Button
Button
Some sample text. Some sample text.
Button
Button
Some sample text. Some sample text.
Button
Button
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3554,
"s": 3331,
"text": "This chapter discusses about Bootstrap thumbnails. A lot of sites need a way to lay out images, videos, text, etc, in a grid, and Bootstrap has an easy way to do this with thumbnails. To create thumbnails using Bootstrap −"
},
{
"code": null,
"e": 3615,
"s": 3554,
"text": "Add an <a> tag with the class of .thumbnail around an image."
},
{
"code": null,
"e": 3676,
"s": 3615,
"text": "Add an <a> tag with the class of .thumbnail around an image."
},
{
"code": null,
"e": 3728,
"s": 3676,
"text": "This adds four pixels of padding and a gray border."
},
{
"code": null,
"e": 3780,
"s": 3728,
"text": "This adds four pixels of padding and a gray border."
},
{
"code": null,
"e": 3827,
"s": 3780,
"text": "On hover, an animated glow outlines the image."
},
{
"code": null,
"e": 3874,
"s": 3827,
"text": "On hover, an animated glow outlines the image."
},
{
"code": null,
"e": 3931,
"s": 3874,
"text": "The following example demonstrates a default thumbnail −"
},
{
"code": null,
"e": 4730,
"s": 3931,
"text": "<div class = \"row\">\n <div class = \"col-sm-6 col-md-3\">\n <a href = \"#\" class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </a>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <a href = \"#\" class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </a>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <a href = \"#\" class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </a>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <a href = \"#\" class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </a>\n </div>\n</div>"
},
{
"code": null,
"e": 4892,
"s": 4730,
"text": "Now that we have a basic thumbnail, it's possible to add any kind of HTML content like headings, paragraphs, or buttons into thumbnails. Follow the steps below −"
},
{
"code": null,
"e": 4954,
"s": 4892,
"text": "Change the <a> tag that has a class of .thumbnail to a <div>."
},
{
"code": null,
"e": 5016,
"s": 4954,
"text": "Change the <a> tag that has a class of .thumbnail to a <div>."
},
{
"code": null,
"e": 5153,
"s": 5016,
"text": "Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing."
},
{
"code": null,
"e": 5290,
"s": 5153,
"text": "Inside of that <div>, you can add anything you need. As this is a <div>, we can use the default span-based naming convention for sizing."
},
{
"code": null,
"e": 5409,
"s": 5290,
"text": "If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left."
},
{
"code": null,
"e": 5528,
"s": 5409,
"text": "If you want to group multiple images, place them in an unordered list, and each list item will be floated to the left."
},
{
"code": null,
"e": 5570,
"s": 5528,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 7953,
"s": 5570,
"text": "<div class = \"row\">\n <div class = \"col-sm-6 col-md-3\">\n <div class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </div>\n \n <div class = \"caption\">\n <h3>Thumbnail label</h3>\n <p>Some sample text. Some sample text.</p>\n \n <p>\n <a href = \"#\" class = \"btn btn-primary\" role = \"button\">\n Button\n </a> \n \n <a href = \"#\" class = \"btn btn-default\" role = \"button\">\n Button\n </a>\n </p>\n </div>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <div class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </div>\n \n <div class = \"caption\">\n <h3>Thumbnail label</h3>\n <p>Some sample text. Some sample text.</p>\n \n <p>\n <a href = \"#\" class = \"btn btn-primary\" role = \"button\">\n Button\n </a> \n \n <a href = \"#\" class = \"btn btn-default\" role = \"button\">\n Button\n </a>\n </p>\n </div>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <div class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </div>\n \n <div class = \"caption\">\n <h3>Thumbnail label</h3>\n <p>Some sample text. Some sample text.</p>\n \n <p>\n <a href = \"#\" class = \"btn btn-primary\" role = \"button\">\n Button\n </a> \n \n <a href = \"#\" class = \"btn btn-default\" role =\" button\">\n Button\n </a>\n </p>\n </div>\n </div>\n \n <div class = \"col-sm-6 col-md-3\">\n <div class = \"thumbnail\">\n <img src = \"/bootstrap/images/kittens.jpg\" alt = \"Generic placeholder thumbnail\">\n </div>\n \n <div class = \"caption\">\n <h3>Thumbnail label</h3>\n <p>Some sample text. Some sample text.</p>\n \n <p>\n <a href = \"#\" class = \"btn btn-primary\" role = \"button\">\n Button\n </a> \n \n <a href = \"#\" class = \"btn btn-default\" role = \"button\">\n Button\n </a>\n </p>\n </div>\n </div>\n</div>"
},
{
"code": null,
"e": 7989,
"s": 7953,
"text": "Some sample text. Some sample text."
},
{
"code": null,
"e": 8087,
"s": 7989,
"text": "\n\n Button\n \n\n Button\n \n"
},
{
"code": null,
"e": 8123,
"s": 8087,
"text": "Some sample text. Some sample text."
},
{
"code": null,
"e": 8221,
"s": 8123,
"text": "\n\n Button\n \n\n Button\n \n"
},
{
"code": null,
"e": 8257,
"s": 8221,
"text": "Some sample text. Some sample text."
},
{
"code": null,
"e": 8355,
"s": 8257,
"text": "\n\n Button\n \n\n Button\n \n"
},
{
"code": null,
"e": 8391,
"s": 8355,
"text": "Some sample text. Some sample text."
},
{
"code": null,
"e": 8489,
"s": 8391,
"text": "\n\n Button\n \n\n Button\n \n"
},
{
"code": null,
"e": 8522,
"s": 8489,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8536,
"s": 8522,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8571,
"s": 8536,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8588,
"s": 8571,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8625,
"s": 8588,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 8653,
"s": 8625,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8686,
"s": 8653,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8698,
"s": 8686,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8733,
"s": 8698,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8750,
"s": 8733,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 8783,
"s": 8750,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8803,
"s": 8783,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 8810,
"s": 8803,
"text": " Print"
},
{
"code": null,
"e": 8821,
"s": 8810,
"text": " Add Notes"
}
] |
Rearrange array in alternating positive & negative items with O(1) extra space | Set 1 | 23 Jun, 2022
Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.
Examples :
Input: arr[] = {1, 2, 3, -4, -1, 4}
Output: arr[] = {-4, 1, -1, 2, 3, 4}
Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}
This question has been asked at many places (See this and this)
Naive Approach :
The above problem can be easily solved if O(n) extra space is allowed. It becomes interesting due to the limitations that O(1) extra space and order of appearances. The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index (0 based index), or it is positive and at even index (0 based index) . Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two).
Following is the implementation of above idea.
C++
Java
Python
C#
PHP
Javascript
/* C++ program to rearrange positive and negative integers in alternate fashion while keeping the order of positive and negative numbers. */#include <assert.h>#include <iostream>using namespace std; // Utility function to right rotate all elements between// [outofplace, cur]void rightrotate(int arr[], int n, int outofplace, int cur){ char tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp;} void rearrange(int arr[], int n){ int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into the // out-of-place entry if out-of-place entry is // positive and current entry is negative OR if // out-of-place entry is negative and current // entry is negative then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 steps // ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && (!(index & 0x01))) || ((arr[index] < 0) && (index & 0x01))) { outofplace = index; } } }} // A utility function to print an array 'arr[]' of size 'n'void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver codeint main(){ int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; printArray(arr, n); rearrange(arr, n); cout << "Rearranged array is \n"; printArray(arr, n); return 0;}
class RearrangeArray{ // Utility function to right rotate all elements // between [outofplace, cur] void rightrotate(int arr[], int n, int outofplace, int cur) { int tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } void rearrange(int arr[], int n) { int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr[]' of size 'n' void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(""); } // Driver Code public static void main(String[] args) { RearrangeArray rearrange = new RearrangeArray(); /* int arr[n] = {-5, 3, 4, 5, -6, -2, 8, 9, -1, -4}; int arr[] = {-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4}; int arr[] = {5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4}; int arr[] = {-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4};*/ int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.length; System.out.println("Given array is "); rearrange.printArray(arr, n); rearrange.rearrange(arr, n); System.out.println("RearrangeD array is "); rearrange.printArray(arr, n); }} // This code has been contributed by Mayank Jaiswal
# Python3 program to rearrange# positive and negative integers# in alternate fashion and# maintaining the order of positive# and negative numbers # rotates the array to right by once# from index 'outOfPlace to cur' def rightRotate(arr, n, outOfPlace, cur): temp = arr[cur] for i in range(cur, outOfPlace, -1): arr[i] = arr[i - 1] arr[outOfPlace] = temp return arr def rearrange(arr, n): outOfPlace = -1 for index in range(n): if(outOfPlace >= 0): # if element at outOfPlace place in # negative and if element at index # is positive we can rotate the # array to right or if element # at outOfPlace place in positive and # if element at index is negative we # can rotate the array to right if((arr[index] >= 0 and arr[outOfPlace] < 0) or (arr[index] < 0 and arr[outOfPlace] >= 0)): arr = rightRotate(arr, n, outOfPlace, index) if(index-outOfPlace > 2): outOfPlace += 2 else: outOfPlace = - 1 if(outOfPlace == -1): # conditions for A[index] to # be in out of place if((arr[index] >= 0 and index % 2 == 0) or (arr[index] < 0 and index % 2 == 1)): outOfPlace = index return arr # Driver Codearr = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8] print("Given Array is:")print(arr) print("\nRearranged array is:")print(rearrange(arr, len(arr))) # This code is contributed# by Charan Sai
// Rearrange array in alternating positive// & negative items with O(1) extra spaceusing System; class GFG { // Utility function to right rotate // all elements between [outofplace, cur] static void rightrotate(int[] arr, int n, int outofplace, int cur) { int tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } static void rearrange(int[] arr, int n) { int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved // into the out-of-place entry if out-of- // place entry is positive and current // entry is negative OR if out-of-place // entry is negative and current entry // is negative then right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry // is now 2 steps ahead if (index - outofplace > 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print an // array 'arr[]' of size 'n' static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(""); } // Driver code public static void Main() { int[] arr = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.Length; Console.WriteLine("Given array is "); printArray(arr, n); rearrange(arr, n); Console.WriteLine("RearrangeD array is "); printArray(arr, n); }} // This code is contributed by Sam007
<?php// PHP program to rearrange positive and// negative integers in alternate fashion// while keeping the order of positive// and negative numbers. // Utility function to right rotate all// elements between [outofplace, cur]function rightrotate(&$arr, $n, $outofplace, $cur){ $tmp = $arr[$cur]; for ($i = $cur; $i > $outofplace; $i--) $arr[$i] = $arr[$i - 1]; $arr[$outofplace] = $tmp;} function rearrange(&$arr, $n){ $outofplace = -1; for ($index = 0; $index < $n; $index ++) { if ($outofplace >= 0) { // find the item which must be moved // into the out-of-place entry if // out-of-place entry is positive and // current entry is negative OR if // out-of-place entry is negative // and current entry is negative then // right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if ((($arr[$index] >= 0) && ($arr[$outofplace] < 0)) || (($arr[$index] < 0) && ($arr[$outofplace] >= 0))) { rightrotate($arr, $n, $outofplace, $index); // the new out-of-place entry is // now 2 steps ahead if ($index - $outofplace > 2) $outofplace = $outofplace + 2; else $outofplace = -1; } } // if no entry has been flagged out-of-place if ($outofplace == -1) { // check if current entry is out-of-place if ((($arr[$index] >= 0) && (!($index & 0x01))) || (($arr[$index] < 0) && ($index & 0x01))) { $outofplace = $index; } } }} // A utility function to print an// array 'arr[]' of size 'n'function printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i]." "; echo "\n";} // Driver Code // arr = array(-5, 3, 4, 5, -6, -2, 8, 9, -1, -4);// arr = array(-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4);// arr = array(5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4);// arr = array(-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4);$arr = array(-5, -2, 5, 2, 4, 7, 1, 8, 0, -8);$n = sizeof($arr); echo "Given array is \n";printArray($arr, $n); rearrange($arr, $n); echo "Rearranged array is \n";printArray($arr, $n); // This code is contributed by ChitraNayal?>
<script> // Utility function to right rotate all elements // between [outofplace, cur] function rightrotate(arr , n , outofplace , cur) { var tmp = arr[cur]; for (i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } function rearrange(arr , n) { var outofplace = -1; for (var index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr' of size 'n' function printArray(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + " "); document.write(""); } // Driver Code /* * var arr[n] = [-5, 3, 4, 5, -6, -2, 8, 9, -1, -4]; var arr = [-5, -3, -4, * -5, -6, 2 , 8, 9, 1 , 4]; var arr = [5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4]; * var arr = [-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4]; */ var arr = [ -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 ]; var n = arr.length; document.write("Given array is "); printArray(arr, n); rearrange(arr, n); document.write("<br/>RearrangeD array is "); printArray(arr, n); // This code is contributed by gauravrajput1</script>
Given array is
-5 -2 5 2 4 7 1 8 0 -8
Rearranged array is
-5 5 -2 2 -8 4 7 1 8 0
Time Complexity: O(N^2), as we are using a loop to traverse N times and calling function rightrotate each time which will cost O (N).Space Complexity: O(1), as we are not using any extra space.
Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
Sam007
Charan Sai Gummadava
ukasp
AmanGautam1
vvkbisht
jyoti369
sweetyty
tharun07
sagartomar9927
GauravRajput1
splevel62
dark_hunter
rohitkumarsinghcna
hardikkoriintern
array-rearrange
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Arrays in C/C++
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Subset Sum Problem | DP-25 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 456,
"s": 54,
"text": "Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array."
},
{
"code": null,
"e": 468,
"s": 456,
"text": "Examples : "
},
{
"code": null,
"e": 643,
"s": 468,
"text": "Input: arr[] = {1, 2, 3, -4, -1, 4}\nOutput: arr[] = {-4, 1, -1, 2, 3, 4}\n\nInput: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}\noutput: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}"
},
{
"code": null,
"e": 707,
"s": 643,
"text": "This question has been asked at many places (See this and this)"
},
{
"code": null,
"e": 725,
"s": 707,
"text": "Naive Approach : "
},
{
"code": null,
"e": 1334,
"s": 725,
"text": "The above problem can be easily solved if O(n) extra space is allowed. It becomes interesting due to the limitations that O(1) extra space and order of appearances. The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index (0 based index), or it is positive and at even index (0 based index) . Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two)."
},
{
"code": null,
"e": 1383,
"s": 1334,
"text": "Following is the implementation of above idea. "
},
{
"code": null,
"e": 1387,
"s": 1383,
"text": "C++"
},
{
"code": null,
"e": 1392,
"s": 1387,
"text": "Java"
},
{
"code": null,
"e": 1399,
"s": 1392,
"text": "Python"
},
{
"code": null,
"e": 1402,
"s": 1399,
"text": "C#"
},
{
"code": null,
"e": 1406,
"s": 1402,
"text": "PHP"
},
{
"code": null,
"e": 1417,
"s": 1406,
"text": "Javascript"
},
{
"code": "/* C++ program to rearrange positive and negative integers in alternate fashion while keeping the order of positive and negative numbers. */#include <assert.h>#include <iostream>using namespace std; // Utility function to right rotate all elements between// [outofplace, cur]void rightrotate(int arr[], int n, int outofplace, int cur){ char tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp;} void rearrange(int arr[], int n){ int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into the // out-of-place entry if out-of-place entry is // positive and current entry is negative OR if // out-of-place entry is negative and current // entry is negative then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 steps // ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && (!(index & 0x01))) || ((arr[index] < 0) && (index & 0x01))) { outofplace = index; } } }} // A utility function to print an array 'arr[]' of size 'n'void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver codeint main(){ int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is \\n\"; printArray(arr, n); rearrange(arr, n); cout << \"Rearranged array is \\n\"; printArray(arr, n); return 0;}",
"e": 3810,
"s": 1417,
"text": null
},
{
"code": "class RearrangeArray{ // Utility function to right rotate all elements // between [outofplace, cur] void rightrotate(int arr[], int n, int outofplace, int cur) { int tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } void rearrange(int arr[], int n) { int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr[]' of size 'n' void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(\"\"); } // Driver Code public static void main(String[] args) { RearrangeArray rearrange = new RearrangeArray(); /* int arr[n] = {-5, 3, 4, 5, -6, -2, 8, 9, -1, -4}; int arr[] = {-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4}; int arr[] = {5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4}; int arr[] = {-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4};*/ int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.length; System.out.println(\"Given array is \"); rearrange.printArray(arr, n); rearrange.rearrange(arr, n); System.out.println(\"RearrangeD array is \"); rearrange.printArray(arr, n); }} // This code has been contributed by Mayank Jaiswal",
"e": 6882,
"s": 3810,
"text": null
},
{
"code": "# Python3 program to rearrange# positive and negative integers# in alternate fashion and# maintaining the order of positive# and negative numbers # rotates the array to right by once# from index 'outOfPlace to cur' def rightRotate(arr, n, outOfPlace, cur): temp = arr[cur] for i in range(cur, outOfPlace, -1): arr[i] = arr[i - 1] arr[outOfPlace] = temp return arr def rearrange(arr, n): outOfPlace = -1 for index in range(n): if(outOfPlace >= 0): # if element at outOfPlace place in # negative and if element at index # is positive we can rotate the # array to right or if element # at outOfPlace place in positive and # if element at index is negative we # can rotate the array to right if((arr[index] >= 0 and arr[outOfPlace] < 0) or (arr[index] < 0 and arr[outOfPlace] >= 0)): arr = rightRotate(arr, n, outOfPlace, index) if(index-outOfPlace > 2): outOfPlace += 2 else: outOfPlace = - 1 if(outOfPlace == -1): # conditions for A[index] to # be in out of place if((arr[index] >= 0 and index % 2 == 0) or (arr[index] < 0 and index % 2 == 1)): outOfPlace = index return arr # Driver Codearr = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8] print(\"Given Array is:\")print(arr) print(\"\\nRearranged array is:\")print(rearrange(arr, len(arr))) # This code is contributed# by Charan Sai",
"e": 8449,
"s": 6882,
"text": null
},
{
"code": "// Rearrange array in alternating positive// & negative items with O(1) extra spaceusing System; class GFG { // Utility function to right rotate // all elements between [outofplace, cur] static void rightrotate(int[] arr, int n, int outofplace, int cur) { int tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } static void rearrange(int[] arr, int n) { int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved // into the out-of-place entry if out-of- // place entry is positive and current // entry is negative OR if out-of-place // entry is negative and current entry // is negative then right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry // is now 2 steps ahead if (index - outofplace > 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print an // array 'arr[]' of size 'n' static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(\"\"); } // Driver code public static void Main() { int[] arr = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.Length; Console.WriteLine(\"Given array is \"); printArray(arr, n); rearrange(arr, n); Console.WriteLine(\"RearrangeD array is \"); printArray(arr, n); }} // This code is contributed by Sam007",
"e": 11119,
"s": 8449,
"text": null
},
{
"code": "<?php// PHP program to rearrange positive and// negative integers in alternate fashion// while keeping the order of positive// and negative numbers. // Utility function to right rotate all// elements between [outofplace, cur]function rightrotate(&$arr, $n, $outofplace, $cur){ $tmp = $arr[$cur]; for ($i = $cur; $i > $outofplace; $i--) $arr[$i] = $arr[$i - 1]; $arr[$outofplace] = $tmp;} function rearrange(&$arr, $n){ $outofplace = -1; for ($index = 0; $index < $n; $index ++) { if ($outofplace >= 0) { // find the item which must be moved // into the out-of-place entry if // out-of-place entry is positive and // current entry is negative OR if // out-of-place entry is negative // and current entry is negative then // right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if ((($arr[$index] >= 0) && ($arr[$outofplace] < 0)) || (($arr[$index] < 0) && ($arr[$outofplace] >= 0))) { rightrotate($arr, $n, $outofplace, $index); // the new out-of-place entry is // now 2 steps ahead if ($index - $outofplace > 2) $outofplace = $outofplace + 2; else $outofplace = -1; } } // if no entry has been flagged out-of-place if ($outofplace == -1) { // check if current entry is out-of-place if ((($arr[$index] >= 0) && (!($index & 0x01))) || (($arr[$index] < 0) && ($index & 0x01))) { $outofplace = $index; } } }} // A utility function to print an// array 'arr[]' of size 'n'function printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i].\" \"; echo \"\\n\";} // Driver Code // arr = array(-5, 3, 4, 5, -6, -2, 8, 9, -1, -4);// arr = array(-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4);// arr = array(5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4);// arr = array(-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4);$arr = array(-5, -2, 5, 2, 4, 7, 1, 8, 0, -8);$n = sizeof($arr); echo \"Given array is \\n\";printArray($arr, $n); rearrange($arr, $n); echo \"Rearranged array is \\n\";printArray($arr, $n); // This code is contributed by ChitraNayal?>",
"e": 13632,
"s": 11119,
"text": null
},
{
"code": "<script> // Utility function to right rotate all elements // between [outofplace, cur] function rightrotate(arr , n , outofplace , cur) { var tmp = arr[cur]; for (i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } function rearrange(arr , n) { var outofplace = -1; for (var index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr' of size 'n' function printArray(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(\"\"); } // Driver Code /* * var arr[n] = [-5, 3, 4, 5, -6, -2, 8, 9, -1, -4]; var arr = [-5, -3, -4, * -5, -6, 2 , 8, 9, 1 , 4]; var arr = [5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4]; * var arr = [-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4]; */ var arr = [ -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 ]; var n = arr.length; document.write(\"Given array is \"); printArray(arr, n); rearrange(arr, n); document.write(\"<br/>RearrangeD array is \"); printArray(arr, n); // This code is contributed by gauravrajput1</script>",
"e": 16202,
"s": 13632,
"text": null
},
{
"code": null,
"e": 16287,
"s": 16202,
"text": "Given array is \n-5 -2 5 2 4 7 1 8 0 -8 \nRearranged array is \n-5 5 -2 2 -8 4 7 1 8 0 "
},
{
"code": null,
"e": 16481,
"s": 16287,
"text": "Time Complexity: O(N^2), as we are using a loop to traverse N times and calling function rightrotate each time which will cost O (N).Space Complexity: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 16568,
"s": 16481,
"text": "Rearrange array in alternating positive & negative items with O(1) extra space | Set 2"
},
{
"code": null,
"e": 16575,
"s": 16568,
"text": "Sam007"
},
{
"code": null,
"e": 16596,
"s": 16575,
"text": "Charan Sai Gummadava"
},
{
"code": null,
"e": 16602,
"s": 16596,
"text": "ukasp"
},
{
"code": null,
"e": 16614,
"s": 16602,
"text": "AmanGautam1"
},
{
"code": null,
"e": 16623,
"s": 16614,
"text": "vvkbisht"
},
{
"code": null,
"e": 16632,
"s": 16623,
"text": "jyoti369"
},
{
"code": null,
"e": 16641,
"s": 16632,
"text": "sweetyty"
},
{
"code": null,
"e": 16650,
"s": 16641,
"text": "tharun07"
},
{
"code": null,
"e": 16665,
"s": 16650,
"text": "sagartomar9927"
},
{
"code": null,
"e": 16679,
"s": 16665,
"text": "GauravRajput1"
},
{
"code": null,
"e": 16689,
"s": 16679,
"text": "splevel62"
},
{
"code": null,
"e": 16701,
"s": 16689,
"text": "dark_hunter"
},
{
"code": null,
"e": 16720,
"s": 16701,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 16737,
"s": 16720,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 16753,
"s": 16737,
"text": "array-rearrange"
},
{
"code": null,
"e": 16760,
"s": 16753,
"text": "Arrays"
},
{
"code": null,
"e": 16767,
"s": 16760,
"text": "Arrays"
},
{
"code": null,
"e": 16865,
"s": 16767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16880,
"s": 16865,
"text": "Arrays in Java"
},
{
"code": null,
"e": 16926,
"s": 16880,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 16994,
"s": 16926,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 17038,
"s": 16994,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 17070,
"s": 17038,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 17086,
"s": 17070,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 17118,
"s": 17086,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 17166,
"s": 17118,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 17180,
"s": 17166,
"text": "Linear Search"
}
] |
Lossless Join and Dependency Preserving Decomposition | 28 May, 2017
Decomposition of a relation is done when a relation in relational model is not in appropriate normal form. Relation R is decomposed into two or more relations if decomposition is lossless join as well as dependency preserving.
Lossless Join Decomposition
If we decompose a relation R into relations R1 and R2,
Decomposition is lossy if R1 ⋈ R2 ⊃ R
Decomposition is lossless if R1 ⋈ R2 = R
To check for lossless join decomposition using FD set, following conditions must hold:
Union of Attributes of R1 and R2 must be equal to attribute of R. Each attribute of R must be either in R1 or in R2. Att(R1) U Att(R2) = Att(R)Intersection of Attributes of R1 and R2 must not be NULL. Att(R1) ∩ Att(R2) ≠ ΦCommon attribute must be a key for at least one relation (R1 or R2) Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)
Union of Attributes of R1 and R2 must be equal to attribute of R. Each attribute of R must be either in R1 or in R2. Att(R1) U Att(R2) = Att(R)
Att(R1) U Att(R2) = Att(R)
Intersection of Attributes of R1 and R2 must not be NULL. Att(R1) ∩ Att(R2) ≠ Φ
Att(R1) ∩ Att(R2) ≠ Φ
Common attribute must be a key for at least one relation (R1 or R2) Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)
Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)
For Example, A relation R (A, B, C, D) with FD set{A->BC} is decomposed into R1(ABC) and R2(AD) which is a lossless join decomposition as:
First condition holds true as Att(R1) U Att(R2) = (ABC) U (AD) = (ABCD) = Att(R).Second condition holds true as Att(R1) ∩ Att(R2) = (ABC) ∩ (AD) ≠ ΦThird condition holds true as Att(R1) ∩ Att(R2) = A is a key of R1(ABC) because A->BC is given.
First condition holds true as Att(R1) U Att(R2) = (ABC) U (AD) = (ABCD) = Att(R).
Second condition holds true as Att(R1) ∩ Att(R2) = (ABC) ∩ (AD) ≠ Φ
Third condition holds true as Att(R1) ∩ Att(R2) = A is a key of R1(ABC) because A->BC is given.
Dependency Preserving Decomposition
If we decompose a relation R into relations R1 and R2, All dependencies of R either must be a part of R1 or R2 or must be derivable from combination of FD’s of R1 and R2.For Example, A relation R (A, B, C, D) with FD set{A->BC} is decomposed into R1(ABC) and R2(AD) which is dependency preserving because FD A->BC is a part of R1(ABC).
GATE Question: Consider a schema R(A,B,C,D) and functional dependencies A->B and C->D. Then the decomposition of R into R1(AB) and R2(CD) is [GATE-CS-2001]A. dependency preserving and lossless joinB. lossless join but not dependency preservingC. dependency preserving but not lossless joinD. not dependency preserving and not lossless join
Answer: For lossless join decomposition, these three conditions must hold true:
Att(R1) U Att(R2) = ABCD = Att(R)Att(R1) ∩ Att(R2) = Φ, which violates the condition of lossless join decomposition. Hence the decomposition is not lossless.
Att(R1) U Att(R2) = ABCD = Att(R)
Att(R1) ∩ Att(R2) = Φ, which violates the condition of lossless join decomposition. Hence the decomposition is not lossless.
For dependency preserving decomposition,A->B can be ensured in R1(AB) and C->D can be ensured in R2(CD). Hence it is dependency preserving decomposition.So, the correct option is C.This article is contributed by Sonal Tuteja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DBMS-Normalization
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 279,
"s": 52,
"text": "Decomposition of a relation is done when a relation in relational model is not in appropriate normal form. Relation R is decomposed into two or more relations if decomposition is lossless join as well as dependency preserving."
},
{
"code": null,
"e": 307,
"s": 279,
"text": "Lossless Join Decomposition"
},
{
"code": null,
"e": 362,
"s": 307,
"text": "If we decompose a relation R into relations R1 and R2,"
},
{
"code": null,
"e": 400,
"s": 362,
"text": "Decomposition is lossy if R1 ⋈ R2 ⊃ R"
},
{
"code": null,
"e": 441,
"s": 400,
"text": "Decomposition is lossless if R1 ⋈ R2 = R"
},
{
"code": null,
"e": 528,
"s": 441,
"text": "To check for lossless join decomposition using FD set, following conditions must hold:"
},
{
"code": null,
"e": 880,
"s": 528,
"text": "Union of Attributes of R1 and R2 must be equal to attribute of R. Each attribute of R must be either in R1 or in R2. Att(R1) U Att(R2) = Att(R)Intersection of Attributes of R1 and R2 must not be NULL. Att(R1) ∩ Att(R2) ≠ ΦCommon attribute must be a key for at least one relation (R1 or R2) Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)"
},
{
"code": null,
"e": 1024,
"s": 880,
"text": "Union of Attributes of R1 and R2 must be equal to attribute of R. Each attribute of R must be either in R1 or in R2. Att(R1) U Att(R2) = Att(R)"
},
{
"code": null,
"e": 1052,
"s": 1024,
"text": " Att(R1) U Att(R2) = Att(R)"
},
{
"code": null,
"e": 1133,
"s": 1052,
"text": "Intersection of Attributes of R1 and R2 must not be NULL. Att(R1) ∩ Att(R2) ≠ Φ"
},
{
"code": null,
"e": 1157,
"s": 1133,
"text": " Att(R1) ∩ Att(R2) ≠ Φ"
},
{
"code": null,
"e": 1286,
"s": 1157,
"text": "Common attribute must be a key for at least one relation (R1 or R2) Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)"
},
{
"code": null,
"e": 1348,
"s": 1286,
"text": " Att(R1) ∩ Att(R2) -> Att(R1) or Att(R1) ∩ Att(R2) -> Att(R2)"
},
{
"code": null,
"e": 1487,
"s": 1348,
"text": "For Example, A relation R (A, B, C, D) with FD set{A->BC} is decomposed into R1(ABC) and R2(AD) which is a lossless join decomposition as:"
},
{
"code": null,
"e": 1732,
"s": 1487,
"text": "First condition holds true as Att(R1) U Att(R2) = (ABC) U (AD) = (ABCD) = Att(R).Second condition holds true as Att(R1) ∩ Att(R2) = (ABC) ∩ (AD) ≠ ΦThird condition holds true as Att(R1) ∩ Att(R2) = A is a key of R1(ABC) because A->BC is given."
},
{
"code": null,
"e": 1814,
"s": 1732,
"text": "First condition holds true as Att(R1) U Att(R2) = (ABC) U (AD) = (ABCD) = Att(R)."
},
{
"code": null,
"e": 1883,
"s": 1814,
"text": "Second condition holds true as Att(R1) ∩ Att(R2) = (ABC) ∩ (AD) ≠ Φ"
},
{
"code": null,
"e": 1979,
"s": 1883,
"text": "Third condition holds true as Att(R1) ∩ Att(R2) = A is a key of R1(ABC) because A->BC is given."
},
{
"code": null,
"e": 2015,
"s": 1979,
"text": "Dependency Preserving Decomposition"
},
{
"code": null,
"e": 2351,
"s": 2015,
"text": "If we decompose a relation R into relations R1 and R2, All dependencies of R either must be a part of R1 or R2 or must be derivable from combination of FD’s of R1 and R2.For Example, A relation R (A, B, C, D) with FD set{A->BC} is decomposed into R1(ABC) and R2(AD) which is dependency preserving because FD A->BC is a part of R1(ABC)."
},
{
"code": null,
"e": 2691,
"s": 2351,
"text": "GATE Question: Consider a schema R(A,B,C,D) and functional dependencies A->B and C->D. Then the decomposition of R into R1(AB) and R2(CD) is [GATE-CS-2001]A. dependency preserving and lossless joinB. lossless join but not dependency preservingC. dependency preserving but not lossless joinD. not dependency preserving and not lossless join"
},
{
"code": null,
"e": 2771,
"s": 2691,
"text": "Answer: For lossless join decomposition, these three conditions must hold true:"
},
{
"code": null,
"e": 2929,
"s": 2771,
"text": "Att(R1) U Att(R2) = ABCD = Att(R)Att(R1) ∩ Att(R2) = Φ, which violates the condition of lossless join decomposition. Hence the decomposition is not lossless."
},
{
"code": null,
"e": 2963,
"s": 2929,
"text": "Att(R1) U Att(R2) = ABCD = Att(R)"
},
{
"code": null,
"e": 3088,
"s": 2963,
"text": "Att(R1) ∩ Att(R2) = Φ, which violates the condition of lossless join decomposition. Hence the decomposition is not lossless."
},
{
"code": null,
"e": 3569,
"s": 3088,
"text": "For dependency preserving decomposition,A->B can be ensured in R1(AB) and C->D can be ensured in R2(CD). Hence it is dependency preserving decomposition.So, the correct option is C.This article is contributed by Sonal Tuteja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3694,
"s": 3569,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3713,
"s": 3694,
"text": "DBMS-Normalization"
},
{
"code": null,
"e": 3718,
"s": 3713,
"text": "DBMS"
},
{
"code": null,
"e": 3723,
"s": 3718,
"text": "DBMS"
},
{
"code": null,
"e": 3821,
"s": 3723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3868,
"s": 3821,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 3886,
"s": 3868,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 3927,
"s": 3886,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 3938,
"s": 3927,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3991,
"s": 3938,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 4022,
"s": 3991,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 4046,
"s": 4022,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 4058,
"s": 4046,
"text": "SQL | Views"
},
{
"code": null,
"e": 4092,
"s": 4058,
"text": "Data Preprocessing in Data Mining"
}
] |
‘AND’ vs ‘&&’ as operator in PHP | 10 Oct, 2018
‘AND’ Operator
The AND operator is called logical operator. It returns true if both the operands are true.Example:
<?php // Variable declaration and// initialization$a = 100;$b = 50; // Check two condition using// AND operatorif ($a == 100 and $b == 10) echo "True";else echo "False";?>
False
Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and $b == 10 also evaluates to true. Therefore, ‘$a == 100 and $b == 10’ evaluates to true because AND logic states that if both the operands are true, then result also be true. But when the input $b = 20, the condition $b == 10 is false, so the AND operation result will be false.
‘&&’ Operator
The && operator is called logical operator. It returns true if both operands are true.Example:
<?php // Declare a variable and initialize it$a = 100;$b = 10; // Check the conditionif ($a == 100 && pow($b, 2) == $a) echo "True";else echo "False";?>
True
Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and pow($b, 2) == $a also evaluates to true because $b = 10 raised to the power of 2 is 100 which is equal to $a. Therefore, ‘$a == 100 && pow($b, 2) == $a’ evaluates to true as AND logic states that only when both the operands are true, the AND operation result is true. But when the input $b = 20, the condition pow($b, 2) == $a is false, so the AND operation result is false.
Comparison between ‘AND’ and ;&&’ operator: There are some difference between both operator are listed below:
Based on Precedence: Precedence basically decides which operations are performed first in an expression. The precedence of ‘&&’ operator is high and the precedence of ‘AND’ operator is low.
Based on operation:Example:<?php // Expression to use && operator$bool = TRUE && FALSE; // Display the result of && operationecho ($bool ? 'TRUE' : 'FALSE'), "\n"; // Expression to use AND operator$bool = TRUE and FALSE; // Display the result of AND operationecho ($bool ? 'TRUE' : 'FALSE'); ?>Output:FALSE
TRUE
Explanation:The result of both operator is different whenever operands are same. The first expression evaluates to FALSE while the second expression evaluates TRUE even though both are using the same operation.The first expression, $bool = TRUE && FALSE; evaluates to FALSE because first && operation is performed, then the result to assigned to the variable $bool because precedence of && operator is higher than the precedence of =.The second expression, $bool = TRUE and FALSE; evaluates to TRUE because the operator “and” has lower precedence than the operator “=” so the value TRUE which is on the right of = is assigned to $bool and then the “and” operation is performed internally but is not assigned, therefore $bool now holds TRUE.So to explain, the fundamental difference in the AND operator and the && operator is their precedence difference but both perform the same operation.
<?php // Expression to use && operator$bool = TRUE && FALSE; // Display the result of && operationecho ($bool ? 'TRUE' : 'FALSE'), "\n"; // Expression to use AND operator$bool = TRUE and FALSE; // Display the result of AND operationecho ($bool ? 'TRUE' : 'FALSE'); ?>
FALSE
TRUE
Explanation:The result of both operator is different whenever operands are same. The first expression evaluates to FALSE while the second expression evaluates TRUE even though both are using the same operation.
The first expression, $bool = TRUE && FALSE; evaluates to FALSE because first && operation is performed, then the result to assigned to the variable $bool because precedence of && operator is higher than the precedence of =.
The second expression, $bool = TRUE and FALSE; evaluates to TRUE because the operator “and” has lower precedence than the operator “=” so the value TRUE which is on the right of = is assigned to $bool and then the “and” operation is performed internally but is not assigned, therefore $bool now holds TRUE.
So to explain, the fundamental difference in the AND operator and the && operator is their precedence difference but both perform the same operation.
PHP-basics
Picked
Technical Scripter 2018
Difference Between
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 43,
"s": 28,
"text": "‘AND’ Operator"
},
{
"code": null,
"e": 143,
"s": 43,
"text": "The AND operator is called logical operator. It returns true if both the operands are true.Example:"
},
{
"code": "<?php // Variable declaration and// initialization$a = 100;$b = 50; // Check two condition using// AND operatorif ($a == 100 and $b == 10) echo \"True\";else echo \"False\";?>",
"e": 323,
"s": 143,
"text": null
},
{
"code": null,
"e": 330,
"s": 323,
"text": "False\n"
},
{
"code": null,
"e": 721,
"s": 330,
"text": "Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and $b == 10 also evaluates to true. Therefore, ‘$a == 100 and $b == 10’ evaluates to true because AND logic states that if both the operands are true, then result also be true. But when the input $b = 20, the condition $b == 10 is false, so the AND operation result will be false."
},
{
"code": null,
"e": 735,
"s": 721,
"text": "‘&&’ Operator"
},
{
"code": null,
"e": 830,
"s": 735,
"text": "The && operator is called logical operator. It returns true if both operands are true.Example:"
},
{
"code": "<?php // Declare a variable and initialize it$a = 100;$b = 10; // Check the conditionif ($a == 100 && pow($b, 2) == $a) echo \"True\";else echo \"False\";?>",
"e": 991,
"s": 830,
"text": null
},
{
"code": null,
"e": 997,
"s": 991,
"text": "True\n"
},
{
"code": null,
"e": 1485,
"s": 997,
"text": "Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and pow($b, 2) == $a also evaluates to true because $b = 10 raised to the power of 2 is 100 which is equal to $a. Therefore, ‘$a == 100 && pow($b, 2) == $a’ evaluates to true as AND logic states that only when both the operands are true, the AND operation result is true. But when the input $b = 20, the condition pow($b, 2) == $a is false, so the AND operation result is false."
},
{
"code": null,
"e": 1595,
"s": 1485,
"text": "Comparison between ‘AND’ and ;&&’ operator: There are some difference between both operator are listed below:"
},
{
"code": null,
"e": 1785,
"s": 1595,
"text": "Based on Precedence: Precedence basically decides which operations are performed first in an expression. The precedence of ‘&&’ operator is high and the precedence of ‘AND’ operator is low."
},
{
"code": null,
"e": 2991,
"s": 1785,
"text": "Based on operation:Example:<?php // Expression to use && operator$bool = TRUE && FALSE; // Display the result of && operationecho ($bool ? 'TRUE' : 'FALSE'), \"\\n\"; // Expression to use AND operator$bool = TRUE and FALSE; // Display the result of AND operationecho ($bool ? 'TRUE' : 'FALSE'); ?>Output:FALSE\nTRUE\nExplanation:The result of both operator is different whenever operands are same. The first expression evaluates to FALSE while the second expression evaluates TRUE even though both are using the same operation.The first expression, $bool = TRUE && FALSE; evaluates to FALSE because first && operation is performed, then the result to assigned to the variable $bool because precedence of && operator is higher than the precedence of =.The second expression, $bool = TRUE and FALSE; evaluates to TRUE because the operator “and” has lower precedence than the operator “=” so the value TRUE which is on the right of = is assigned to $bool and then the “and” operation is performed internally but is not assigned, therefore $bool now holds TRUE.So to explain, the fundamental difference in the AND operator and the && operator is their precedence difference but both perform the same operation."
},
{
"code": "<?php // Expression to use && operator$bool = TRUE && FALSE; // Display the result of && operationecho ($bool ? 'TRUE' : 'FALSE'), \"\\n\"; // Expression to use AND operator$bool = TRUE and FALSE; // Display the result of AND operationecho ($bool ? 'TRUE' : 'FALSE'); ?>",
"e": 3263,
"s": 2991,
"text": null
},
{
"code": null,
"e": 3275,
"s": 3263,
"text": "FALSE\nTRUE\n"
},
{
"code": null,
"e": 3486,
"s": 3275,
"text": "Explanation:The result of both operator is different whenever operands are same. The first expression evaluates to FALSE while the second expression evaluates TRUE even though both are using the same operation."
},
{
"code": null,
"e": 3711,
"s": 3486,
"text": "The first expression, $bool = TRUE && FALSE; evaluates to FALSE because first && operation is performed, then the result to assigned to the variable $bool because precedence of && operator is higher than the precedence of =."
},
{
"code": null,
"e": 4018,
"s": 3711,
"text": "The second expression, $bool = TRUE and FALSE; evaluates to TRUE because the operator “and” has lower precedence than the operator “=” so the value TRUE which is on the right of = is assigned to $bool and then the “and” operation is performed internally but is not assigned, therefore $bool now holds TRUE."
},
{
"code": null,
"e": 4168,
"s": 4018,
"text": "So to explain, the fundamental difference in the AND operator and the && operator is their precedence difference but both perform the same operation."
},
{
"code": null,
"e": 4179,
"s": 4168,
"text": "PHP-basics"
},
{
"code": null,
"e": 4186,
"s": 4179,
"text": "Picked"
},
{
"code": null,
"e": 4210,
"s": 4186,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4229,
"s": 4210,
"text": "Difference Between"
},
{
"code": null,
"e": 4233,
"s": 4229,
"text": "PHP"
},
{
"code": null,
"e": 4252,
"s": 4233,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4256,
"s": 4252,
"text": "PHP"
}
] |
In-place conversion of Sorted DLL to Balanced BST | 25 Feb, 2022
Given a Doubly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Doubly Linked List. The tree must be constructed in-place (No new node should be allocated for tree conversion)
Examples:
Input: Doubly Linked List 1 2 3
Output: A Balanced BST
2
/ \
1 3
Input: Doubly Linked List 1 2 3 4 5 6 7
Output: A Balanced BST
4
/ \
2 6
/ \ / \
1 3 5 7
Input: Doubly Linked List 1 2 3 4
Output: A Balanced BST
3
/ \
2 4
/
1
Input: Doubly Linked List 1 2 3 4 5 6
Output: A Balanced BST
4
/ \
2 6
/ \ /
1 3 5
The Doubly Linked List conversion is very much similar to this Singly Linked List problem and the method 1 is exactly same as the method 1 of previous post. Method 2 is also almost same. The only difference in method 2 is, instead of allocating new nodes for BST, we reuse same DLL nodes. We use prev pointer as left and next pointer as right.
Method 1 (Simple) Following is a simple algorithm where we first find the middle node of list and make it root of the tree to be constructed.
1) Get the Middle of the linked list and make it root.
2) Recursively do same for left half and right half.
a) Get the middle of left half and make it left child of the root
created in step 1.
b) Get the middle of right half and make it right child of the
root created in step 1.
Time complexity: O(nLogn) where n is the number of nodes in Linked List.
Method 2 (Tricky) The method 1 constructs the tree from root to leaves. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as they appear in Doubly Linked List, so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we assign middle node to root and link the left subtree with root. Finally, we recursively construct the right subtree and link it with root. While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.
Following is the implementation of method 2. The main code which creates Balanced BST is highlighted.
C++
C
Java
C#
Javascript
#include <bits/stdc++.h>using namespace std; /* A Doubly Linked List node thatwill also be used as a tree node */class Node{ public: int data; // For tree, next pointer can be // used as right subtree pointer Node* next; // For tree, prev pointer can be // used as left subtree pointer Node* prev;}; // A utility function to count nodes in a Linked Listint countNodes(Node *head); Node* sortedListToBSTRecur(Node **head_ref, int n); /* This function counts the number ofnodes in Linked List and then callssortedListToBSTRecur() to construct BST */Node* sortedListToBST(Node *head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(&head, n);} /* The main function that constructsbalanced BST and returns root of it.head_ref --> Pointer to pointer tohead node of Doubly linked listn --> No. of nodes in the Doubly Linked List */Node* sortedListToBSTRecur(Node **head_ref, int n){ /* Base Case */ if (n <= 0) return NULL; /* Recursively construct the left subtree */ Node *left = sortedListToBSTRecur(head_ref, n/2); /* head_ref now refers to middle node, make middle node as root of BST*/ Node *root = *head_ref; // Set pointer to left subtree root->prev = left; /* Change head pointer of Linked List for parent recursive calls */ *head_ref = (*head_ref)->next; /* Recursively construct the right subtree and link it with root The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root->next = sortedListToBSTRecur(head_ref, n-n/2-1); return root;} /* UTILITY FUNCTIONS *//* A utility function that returnscount of nodes in a given Linked List */int countNodes(Node *head){ int count = 0; Node *temp = head; while(temp) { temp = temp->next; count++; } return count;} /* Function to insert a node atthe beginning of the Doubly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node *node){ while (node!=NULL) { cout<<node->data<<" "; node = node->next; }} /* A utility function to printpreorder traversal of BST */void preOrder(Node* node){ if (node == NULL) return; cout<<node->data<<" "; preOrder(node->prev); preOrder(node->next);} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout<<"Given Linked List\n"; printList(head); /* Convert List to BST */ Node *root = sortedListToBST(head); cout<<"\nPreOrder Traversal of constructed BST \n "; preOrder(root); return 0;} // This code is contributed by rathbhupendra
#include<stdio.h>#include<stdlib.h> /* A Doubly Linked List node that will also be used as a tree node */struct Node{ int data; // For tree, next pointer can be used as right subtree pointer struct Node* next; // For tree, prev pointer can be used as left subtree pointer struct Node* prev;}; // A utility function to count nodes in a Linked Listint countNodes(struct Node *head); struct Node* sortedListToBSTRecur(struct Node **head_ref, int n); /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */struct Node* sortedListToBST(struct Node *head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(&head, n);} /* The main function that constructs balanced BST and returns root of it. head_ref --> Pointer to pointer to head node of Doubly linked list n --> No. of nodes in the Doubly Linked List */struct Node* sortedListToBSTRecur(struct Node **head_ref, int n){ /* Base Case */ if (n <= 0) return NULL; /* Recursively construct the left subtree */ struct Node *left = sortedListToBSTRecur(head_ref, n/2); /* head_ref now refers to middle node, make middle node as root of BST*/ struct Node *root = *head_ref; // Set pointer to left subtree root->prev = left; /* Change head pointer of Linked List for parent recursive calls */ *head_ref = (*head_ref)->next; /* Recursively construct the right subtree and link it with root The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root->next = sortedListToBSTRecur(head_ref, n-n/2-1); return root;} /* UTILITY FUNCTIONS *//* A utility function that returns count of nodes in a given Linked List */int countNodes(struct Node *head){ int count = 0; struct Node *temp = head; while(temp) { temp = temp->next; count++; } return count;} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node!=NULL) { printf("%d ", node->data); node = node->next; }} /* A utility function to print preorder traversal of BST */void preOrder(struct Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->prev); preOrder(node->next);} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("Given Linked List\n"); printList(head); /* Convert List to BST */ struct Node *root = sortedListToBST(head); printf("\n PreOrder Traversal of constructed BST \n "); preOrder(root); return 0;}
class Node{ int data; Node next, prev; Node(int d) { data = d; next = prev = null; }} class LinkedList{ Node head; /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */ Node sortedListToBST() { /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n); } /* The main function that constructs balanced BST and returns root of it. n --> No. of nodes in the Doubly Linked List */ Node sortedListToBSTRecur(int n) { /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ Node left = sortedListToBSTRecur(n / 2); /* head_ref now refers to middle node, make middle node as root of BST*/ Node root = head; // Set pointer to left subtree root.prev = left; /* Change head pointer of Linked List for parent recursive calls */ head = head.next; /* Recursively construct the right subtree and link it with root. The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - n / 2 - 1); return root; } /* UTILITY FUNCTIONS */ /* A utility function that returns count of nodes in a given Linked List */ int countNodes(Node head) { int count = 0; Node temp = head; while (temp != null) { temp = temp.next; count++; } return count; } /* Function to insert a node at the beginning of the Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given linked list */ void printList() { Node node = head; while (node != null) { System.out.print(node.data + " "); node = node.next; } } /* A utility function to print preorder traversal of BST */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + " "); preOrder(node.prev); preOrder(node.next); } /* Driver program to test above functions */ public static void main(String[] args) { LinkedList llist = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println("Given Linked List "); llist.printList(); /* Convert List to BST */ Node root = llist.sortedListToBST(); System.out.println(""); System.out.println("Pre-Order Traversal of constructed BST "); llist.preOrder(root); }}// This code has been contributed by Mayank Jaiswal(mayank_24)
using System;public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; }} public class List { Node head; /* * This function counts the number of nodes in Linked List and then calls * sortedListToBSTRecur() to construct BST */ Node sortedListToBST() { /* Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n); } /* * The main function that constructs balanced BST and returns root of it. n --> * No. of nodes in the Doubly Linked List */ Node sortedListToBSTRecur(int n) { /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ Node left = sortedListToBSTRecur(n / 2); /* * head_ref now refers to middle node, make middle node as root of BST */ Node root = head; // Set pointer to left subtree root.prev = left; /* * Change head pointer of Linked List for parent recursive calls */ head = head.next; /* * Recursively construct the right subtree and link it with root. The number of * nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - n / 2 - 1); return root; } /* UTILITY FUNCTIONS */ /* * A utility function that returns count of nodes in a given Linked List */ int countNodes(Node head) { int count = 0; Node temp = head; while (temp != null) { temp = temp.next; count++; } return count; } /* * Function to insert a node at the beginning of the Doubly Linked List */ void Push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given linked list */ void printList() { Node node = head; while (node != null) { Console.Write(node.data + " "); node = node.next; } } /* A utility function to print preorder traversal of BST */ void preOrder(Node node) { if (node == null) return; Console.Write(node.data + " "); preOrder(node.prev); preOrder(node.next); } /* Driver program to test above functions */ public static void Main(String[] args) { List llist = new List(); /* * Let us create a sorted linked list to test the functions Created linked list * will be 7->6->5->4->3->2->1 */ llist.Push(7); llist.Push(6); llist.Push(5); llist.Push(4); llist.Push(3); llist.Push(2); llist.Push(1); Console.WriteLine("Given Linked List "); llist.printList(); /* Convert List to BST */ Node root = llist.sortedListToBST(); Console.WriteLine(""); Console.WriteLine("Pre-Order Traversal of constructed BST "); llist.preOrder(root); }} // This code is contributed by Rajput-Ji
<script> class Node{ constructor(d) { this.data=d; this.next=this.prev=null; }} let head; /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */function sortedListToBST(){ /*Count the number of nodes in Linked List */ let n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n);} /* The main function that constructs balanced BST and returns root of it. n --> No. of nodes in the Doubly Linked List */function sortedListToBSTRecur(n){ /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ let left = sortedListToBSTRecur(Math.floor(n / 2)); /* head_ref now refers to middle node, make middle node as root of BST*/ let root = head; // Set pointer to left subtree root.prev = left; /* Change head pointer of Linked List for parent recursive calls */ head = head.next; /* Recursively construct the right subtree and link it with root. The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - Math.floor(n / 2) - 1); return root;} /* UTILITY FUNCTIONS */ /* A utility function that returns count of nodes in a given Linked List */function countNodes(head){ let count = 0; let temp = head; while (temp != null) { temp = temp.next; count++; } return count;} /* Function to insert a node at the beginning of the Doubly Linked List */function push(new_data){ /* allocate node */ let new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node;} /* Function to print nodes in a given linked list */function printList(){ let node = head; while (node != null) { document.write(node.data + " "); node = node.next; }} /* A utility function to print preorder traversal of BST */function preOrder(node){ if (node == null) return; document.write(node.data + " "); preOrder(node.prev); preOrder(node.next);} /* Driver program to test above functions *//* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */push(7);push(6);push(5);push(4);push(3);push(2);push(1); document.write("Given Linked List <br>");printList(); /* Convert List to BST */let root = sortedListToBST();document.write("<br>");document.write("Pre-Order Traversal of constructed BST <br>");preOrder(root); // This code is contributed by avanitrachhadiya2155</script>
Output:
Given Linked List
1 2 3 4 5 6 7
Pre-Order Traversal of constructed BST
4 2 1 3 6 5 7
Time Complexity: O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
Akanksha_Rai
gauravbaghel2k
simranarora5sos
avanitrachhadiya2155
volumezero9786
simmytarika5
Rajput-Ji
doubly linked list
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 323,
"s": 52,
"text": "Given a Doubly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Doubly Linked List. The tree must be constructed in-place (No new node should be allocated for tree conversion) "
},
{
"code": null,
"e": 334,
"s": 323,
"text": "Examples: "
},
{
"code": null,
"e": 784,
"s": 334,
"text": "Input: Doubly Linked List 1 2 3\nOutput: A Balanced BST \n 2 \n / \\ \n 1 3 \n\n\nInput: Doubly Linked List 1 2 3 4 5 6 7\nOutput: A Balanced BST\n 4\n / \\\n 2 6\n / \\ / \\\n 1 3 5 7 \n\nInput: Doubly Linked List 1 2 3 4\nOutput: A Balanced BST\n 3 \n / \\ \n 2 4 \n / \n1\n\nInput: Doubly Linked List 1 2 3 4 5 6\nOutput: A Balanced BST\n 4 \n / \\ \n 2 6 \n / \\ / \n1 3 5 "
},
{
"code": null,
"e": 1128,
"s": 784,
"text": "The Doubly Linked List conversion is very much similar to this Singly Linked List problem and the method 1 is exactly same as the method 1 of previous post. Method 2 is also almost same. The only difference in method 2 is, instead of allocating new nodes for BST, we reuse same DLL nodes. We use prev pointer as left and next pointer as right."
},
{
"code": null,
"e": 1272,
"s": 1128,
"text": "Method 1 (Simple) Following is a simple algorithm where we first find the middle node of list and make it root of the tree to be constructed. "
},
{
"code": null,
"e": 1586,
"s": 1272,
"text": "1) Get the Middle of the linked list and make it root.\n2) Recursively do same for left half and right half.\n a) Get the middle of left half and make it left child of the root\n created in step 1.\n b) Get the middle of right half and make it right child of the\n root created in step 1."
},
{
"code": null,
"e": 1659,
"s": 1586,
"text": "Time complexity: O(nLogn) where n is the number of nodes in Linked List."
},
{
"code": null,
"e": 2423,
"s": 1659,
"text": "Method 2 (Tricky) The method 1 constructs the tree from root to leaves. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as they appear in Doubly Linked List, so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we assign middle node to root and link the left subtree with root. Finally, we recursively construct the right subtree and link it with root. While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call. "
},
{
"code": null,
"e": 2527,
"s": 2423,
"text": "Following is the implementation of method 2. The main code which creates Balanced BST is highlighted. "
},
{
"code": null,
"e": 2531,
"s": 2527,
"text": "C++"
},
{
"code": null,
"e": 2533,
"s": 2531,
"text": "C"
},
{
"code": null,
"e": 2538,
"s": 2533,
"text": "Java"
},
{
"code": null,
"e": 2541,
"s": 2538,
"text": "C#"
},
{
"code": null,
"e": 2552,
"s": 2541,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* A Doubly Linked List node thatwill also be used as a tree node */class Node{ public: int data; // For tree, next pointer can be // used as right subtree pointer Node* next; // For tree, prev pointer can be // used as left subtree pointer Node* prev;}; // A utility function to count nodes in a Linked Listint countNodes(Node *head); Node* sortedListToBSTRecur(Node **head_ref, int n); /* This function counts the number ofnodes in Linked List and then callssortedListToBSTRecur() to construct BST */Node* sortedListToBST(Node *head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(&head, n);} /* The main function that constructsbalanced BST and returns root of it.head_ref --> Pointer to pointer tohead node of Doubly linked listn --> No. of nodes in the Doubly Linked List */Node* sortedListToBSTRecur(Node **head_ref, int n){ /* Base Case */ if (n <= 0) return NULL; /* Recursively construct the left subtree */ Node *left = sortedListToBSTRecur(head_ref, n/2); /* head_ref now refers to middle node, make middle node as root of BST*/ Node *root = *head_ref; // Set pointer to left subtree root->prev = left; /* Change head pointer of Linked List for parent recursive calls */ *head_ref = (*head_ref)->next; /* Recursively construct the right subtree and link it with root The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root->next = sortedListToBSTRecur(head_ref, n-n/2-1); return root;} /* UTILITY FUNCTIONS *//* A utility function that returnscount of nodes in a given Linked List */int countNodes(Node *head){ int count = 0; Node *temp = head; while(temp) { temp = temp->next; count++; } return count;} /* Function to insert a node atthe beginning of the Doubly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node *node){ while (node!=NULL) { cout<<node->data<<\" \"; node = node->next; }} /* A utility function to printpreorder traversal of BST */void preOrder(Node* node){ if (node == NULL) return; cout<<node->data<<\" \"; preOrder(node->prev); preOrder(node->next);} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout<<\"Given Linked List\\n\"; printList(head); /* Convert List to BST */ Node *root = sortedListToBST(head); cout<<\"\\nPreOrder Traversal of constructed BST \\n \"; preOrder(root); return 0;} // This code is contributed by rathbhupendra",
"e": 6016,
"s": 2552,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h> /* A Doubly Linked List node that will also be used as a tree node */struct Node{ int data; // For tree, next pointer can be used as right subtree pointer struct Node* next; // For tree, prev pointer can be used as left subtree pointer struct Node* prev;}; // A utility function to count nodes in a Linked Listint countNodes(struct Node *head); struct Node* sortedListToBSTRecur(struct Node **head_ref, int n); /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */struct Node* sortedListToBST(struct Node *head){ /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(&head, n);} /* The main function that constructs balanced BST and returns root of it. head_ref --> Pointer to pointer to head node of Doubly linked list n --> No. of nodes in the Doubly Linked List */struct Node* sortedListToBSTRecur(struct Node **head_ref, int n){ /* Base Case */ if (n <= 0) return NULL; /* Recursively construct the left subtree */ struct Node *left = sortedListToBSTRecur(head_ref, n/2); /* head_ref now refers to middle node, make middle node as root of BST*/ struct Node *root = *head_ref; // Set pointer to left subtree root->prev = left; /* Change head pointer of Linked List for parent recursive calls */ *head_ref = (*head_ref)->next; /* Recursively construct the right subtree and link it with root The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root->next = sortedListToBSTRecur(head_ref, n-n/2-1); return root;} /* UTILITY FUNCTIONS *//* A utility function that returns count of nodes in a given Linked List */int countNodes(struct Node *head){ int count = 0; struct Node *temp = head; while(temp) { temp = temp->next; count++; } return count;} /* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node!=NULL) { printf(\"%d \", node->data); node = node->next; }} /* A utility function to print preorder traversal of BST */void preOrder(struct Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->prev); preOrder(node->next);} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf(\"Given Linked List\\n\"); printList(head); /* Convert List to BST */ struct Node *root = sortedListToBST(head); printf(\"\\n PreOrder Traversal of constructed BST \\n \"); preOrder(root); return 0;}",
"e": 9650,
"s": 6016,
"text": null
},
{
"code": "class Node{ int data; Node next, prev; Node(int d) { data = d; next = prev = null; }} class LinkedList{ Node head; /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */ Node sortedListToBST() { /*Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n); } /* The main function that constructs balanced BST and returns root of it. n --> No. of nodes in the Doubly Linked List */ Node sortedListToBSTRecur(int n) { /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ Node left = sortedListToBSTRecur(n / 2); /* head_ref now refers to middle node, make middle node as root of BST*/ Node root = head; // Set pointer to left subtree root.prev = left; /* Change head pointer of Linked List for parent recursive calls */ head = head.next; /* Recursively construct the right subtree and link it with root. The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - n / 2 - 1); return root; } /* UTILITY FUNCTIONS */ /* A utility function that returns count of nodes in a given Linked List */ int countNodes(Node head) { int count = 0; Node temp = head; while (temp != null) { temp = temp.next; count++; } return count; } /* Function to insert a node at the beginning of the Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given linked list */ void printList() { Node node = head; while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } /* A utility function to print preorder traversal of BST */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + \" \"); preOrder(node.prev); preOrder(node.next); } /* Driver program to test above functions */ public static void main(String[] args) { LinkedList llist = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println(\"Given Linked List \"); llist.printList(); /* Convert List to BST */ Node root = llist.sortedListToBST(); System.out.println(\"\"); System.out.println(\"Pre-Order Traversal of constructed BST \"); llist.preOrder(root); }}// This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 13157,
"s": 9650,
"text": null
},
{
"code": "using System;public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; }} public class List { Node head; /* * This function counts the number of nodes in Linked List and then calls * sortedListToBSTRecur() to construct BST */ Node sortedListToBST() { /* Count the number of nodes in Linked List */ int n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n); } /* * The main function that constructs balanced BST and returns root of it. n --> * No. of nodes in the Doubly Linked List */ Node sortedListToBSTRecur(int n) { /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ Node left = sortedListToBSTRecur(n / 2); /* * head_ref now refers to middle node, make middle node as root of BST */ Node root = head; // Set pointer to left subtree root.prev = left; /* * Change head pointer of Linked List for parent recursive calls */ head = head.next; /* * Recursively construct the right subtree and link it with root. The number of * nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - n / 2 - 1); return root; } /* UTILITY FUNCTIONS */ /* * A utility function that returns count of nodes in a given Linked List */ int countNodes(Node head) { int count = 0; Node temp = head; while (temp != null) { temp = temp.next; count++; } return count; } /* * Function to insert a node at the beginning of the Doubly Linked List */ void Push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given linked list */ void printList() { Node node = head; while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } /* A utility function to print preorder traversal of BST */ void preOrder(Node node) { if (node == null) return; Console.Write(node.data + \" \"); preOrder(node.prev); preOrder(node.next); } /* Driver program to test above functions */ public static void Main(String[] args) { List llist = new List(); /* * Let us create a sorted linked list to test the functions Created linked list * will be 7->6->5->4->3->2->1 */ llist.Push(7); llist.Push(6); llist.Push(5); llist.Push(4); llist.Push(3); llist.Push(2); llist.Push(1); Console.WriteLine(\"Given Linked List \"); llist.printList(); /* Convert List to BST */ Node root = llist.sortedListToBST(); Console.WriteLine(\"\"); Console.WriteLine(\"Pre-Order Traversal of constructed BST \"); llist.preOrder(root); }} // This code is contributed by Rajput-Ji",
"e": 16376,
"s": 13157,
"text": null
},
{
"code": "<script> class Node{ constructor(d) { this.data=d; this.next=this.prev=null; }} let head; /* This function counts the number of nodes in Linked List and then calls sortedListToBSTRecur() to construct BST */function sortedListToBST(){ /*Count the number of nodes in Linked List */ let n = countNodes(head); /* Construct BST */ return sortedListToBSTRecur(n);} /* The main function that constructs balanced BST and returns root of it. n --> No. of nodes in the Doubly Linked List */function sortedListToBSTRecur(n){ /* Base Case */ if (n <= 0) return null; /* Recursively construct the left subtree */ let left = sortedListToBSTRecur(Math.floor(n / 2)); /* head_ref now refers to middle node, make middle node as root of BST*/ let root = head; // Set pointer to left subtree root.prev = left; /* Change head pointer of Linked List for parent recursive calls */ head = head.next; /* Recursively construct the right subtree and link it with root. The number of nodes in right subtree is total nodes - nodes in left subtree - 1 (for root) */ root.next = sortedListToBSTRecur(n - Math.floor(n / 2) - 1); return root;} /* UTILITY FUNCTIONS */ /* A utility function that returns count of nodes in a given Linked List */function countNodes(head){ let count = 0; let temp = head; while (temp != null) { temp = temp.next; count++; } return count;} /* Function to insert a node at the beginning of the Doubly Linked List */function push(new_data){ /* allocate node */ let new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) head.prev = new_node; /* move the head to point to the new node */ head = new_node;} /* Function to print nodes in a given linked list */function printList(){ let node = head; while (node != null) { document.write(node.data + \" \"); node = node.next; }} /* A utility function to print preorder traversal of BST */function preOrder(node){ if (node == null) return; document.write(node.data + \" \"); preOrder(node.prev); preOrder(node.next);} /* Driver program to test above functions *//* Let us create a sorted linked list to test the functions Created linked list will be 7->6->5->4->3->2->1 */push(7);push(6);push(5);push(4);push(3);push(2);push(1); document.write(\"Given Linked List <br>\");printList(); /* Convert List to BST */let root = sortedListToBST();document.write(\"<br>\");document.write(\"Pre-Order Traversal of constructed BST <br>\");preOrder(root); // This code is contributed by avanitrachhadiya2155</script>",
"e": 19481,
"s": 16376,
"text": null
},
{
"code": null,
"e": 19490,
"s": 19481,
"text": "Output: "
},
{
"code": null,
"e": 19579,
"s": 19490,
"text": "Given Linked List \n1 2 3 4 5 6 7 \nPre-Order Traversal of constructed BST \n4 2 1 3 6 5 7 "
},
{
"code": null,
"e": 19601,
"s": 19579,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 19727,
"s": 19601,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 19741,
"s": 19727,
"text": "rathbhupendra"
},
{
"code": null,
"e": 19754,
"s": 19741,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 19769,
"s": 19754,
"text": "gauravbaghel2k"
},
{
"code": null,
"e": 19785,
"s": 19769,
"text": "simranarora5sos"
},
{
"code": null,
"e": 19806,
"s": 19785,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 19821,
"s": 19806,
"text": "volumezero9786"
},
{
"code": null,
"e": 19834,
"s": 19821,
"text": "simmytarika5"
},
{
"code": null,
"e": 19844,
"s": 19834,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 19863,
"s": 19844,
"text": "doubly linked list"
},
{
"code": null,
"e": 19875,
"s": 19863,
"text": "Linked List"
},
{
"code": null,
"e": 19887,
"s": 19875,
"text": "Linked List"
}
] |
How to plot a graph in Python? | Graphs in Python can be plotted by using the Matplotlib library. Matplotlib library is mainly used for graph plotting.
You need to install matplotlib before using it to plot graphs. Matplotlib is used to draw a simple line, bargraphs, histograms and piecharts. Inbuilt functions are available to draw all types of graphs in the matplotlib library.
We will plot a simple line in a graph using matplotlib. The following steps are involved in plotting a line.
Import matplotlib
Import matplotlib
Specify the x-coordinates and y-coordinates of the line
Specify the x-coordinates and y-coordinates of the line
Plot the specified points using specific function using .plot() function
Plot the specified points using specific function using .plot() function
Name the x-axis and y-axis using .xlabel() and .ylabel() functions
Name the x-axis and y-axis using .xlabel() and .ylabel() functions
Give a title to the graph(optional) using .title() function
Give a title to the graph(optional) using .title() function
Show the graph using .show() function
Show the graph using .show() function
These are the simple steps involved in plotting a line using matplotlib.
import matplotlib.pyplot as plt
x=[1,3,5,7]
y=[2,4,6,1]
plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple line graph")
plt.show()
The above code plots the points (1,2),(3,4),(5,6),(7,1) and joins these points with a line which is shown as the graph.
A bar graph is the way of representing data by rectangles of different heights at specific positions on the x-axis.
The following steps are involved in drawing a bar graph −
Import matplotlib
Import matplotlib
Specify the x-coordinates where the left bottom corner of the rectangle lies.
Specify the x-coordinates where the left bottom corner of the rectangle lies.
Specify the heights of the bars or rectangles.
Specify the heights of the bars or rectangles.
Specify the labels for the bars
Specify the labels for the bars
Plot the bar graph using .bar() function
Plot the bar graph using .bar() function
Give labels to the x-axis and y-axis
Give labels to the x-axis and y-axis
Give a title to the graph
Give a title to the graph
Show the graph using .show() function.
Show the graph using .show() function.
import matplotlib.pyplot as plt
left_coordinates=[1,2,3,4,5]
heights=[10,20,30,15,40]
bar_labels=['One','Two','Three','Four','Five']
plt.bar(left_coordinates,heights,tick_label=bar_labels,width=0.6,color=['re
d','black'])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple bar graph")
plt.show()
The width parameter in the plt.bar() specifies the width of each bar. The color lists specify the colors of the bars. | [
{
"code": null,
"e": 1306,
"s": 1187,
"text": "Graphs in Python can be plotted by using the Matplotlib library. Matplotlib library is mainly used for graph plotting."
},
{
"code": null,
"e": 1535,
"s": 1306,
"text": "You need to install matplotlib before using it to plot graphs. Matplotlib is used to draw a simple line, bargraphs, histograms and piecharts. Inbuilt functions are available to draw all types of graphs in the matplotlib library."
},
{
"code": null,
"e": 1644,
"s": 1535,
"text": "We will plot a simple line in a graph using matplotlib. The following steps are involved in plotting a line."
},
{
"code": null,
"e": 1662,
"s": 1644,
"text": "Import matplotlib"
},
{
"code": null,
"e": 1680,
"s": 1662,
"text": "Import matplotlib"
},
{
"code": null,
"e": 1736,
"s": 1680,
"text": "Specify the x-coordinates and y-coordinates of the line"
},
{
"code": null,
"e": 1792,
"s": 1736,
"text": "Specify the x-coordinates and y-coordinates of the line"
},
{
"code": null,
"e": 1865,
"s": 1792,
"text": "Plot the specified points using specific function using .plot() function"
},
{
"code": null,
"e": 1938,
"s": 1865,
"text": "Plot the specified points using specific function using .plot() function"
},
{
"code": null,
"e": 2005,
"s": 1938,
"text": "Name the x-axis and y-axis using .xlabel() and .ylabel() functions"
},
{
"code": null,
"e": 2072,
"s": 2005,
"text": "Name the x-axis and y-axis using .xlabel() and .ylabel() functions"
},
{
"code": null,
"e": 2132,
"s": 2072,
"text": "Give a title to the graph(optional) using .title() function"
},
{
"code": null,
"e": 2192,
"s": 2132,
"text": "Give a title to the graph(optional) using .title() function"
},
{
"code": null,
"e": 2230,
"s": 2192,
"text": "Show the graph using .show() function"
},
{
"code": null,
"e": 2268,
"s": 2230,
"text": "Show the graph using .show() function"
},
{
"code": null,
"e": 2341,
"s": 2268,
"text": "These are the simple steps involved in plotting a line using matplotlib."
},
{
"code": null,
"e": 2498,
"s": 2341,
"text": "import matplotlib.pyplot as plt\n\nx=[1,3,5,7]\ny=[2,4,6,1]\nplt.plot(x,y)\nplt.xlabel('X-axis')\nplt.ylabel('Y-axis')\nplt.title(\"A simple line graph\")\nplt.show()"
},
{
"code": null,
"e": 2618,
"s": 2498,
"text": "The above code plots the points (1,2),(3,4),(5,6),(7,1) and joins these points with a line which is shown as the graph."
},
{
"code": null,
"e": 2734,
"s": 2618,
"text": "A bar graph is the way of representing data by rectangles of different heights at specific positions on the x-axis."
},
{
"code": null,
"e": 2792,
"s": 2734,
"text": "The following steps are involved in drawing a bar graph −"
},
{
"code": null,
"e": 2810,
"s": 2792,
"text": "Import matplotlib"
},
{
"code": null,
"e": 2828,
"s": 2810,
"text": "Import matplotlib"
},
{
"code": null,
"e": 2906,
"s": 2828,
"text": "Specify the x-coordinates where the left bottom corner of the rectangle lies."
},
{
"code": null,
"e": 2984,
"s": 2906,
"text": "Specify the x-coordinates where the left bottom corner of the rectangle lies."
},
{
"code": null,
"e": 3031,
"s": 2984,
"text": "Specify the heights of the bars or rectangles."
},
{
"code": null,
"e": 3078,
"s": 3031,
"text": "Specify the heights of the bars or rectangles."
},
{
"code": null,
"e": 3110,
"s": 3078,
"text": "Specify the labels for the bars"
},
{
"code": null,
"e": 3142,
"s": 3110,
"text": "Specify the labels for the bars"
},
{
"code": null,
"e": 3183,
"s": 3142,
"text": "Plot the bar graph using .bar() function"
},
{
"code": null,
"e": 3224,
"s": 3183,
"text": "Plot the bar graph using .bar() function"
},
{
"code": null,
"e": 3261,
"s": 3224,
"text": "Give labels to the x-axis and y-axis"
},
{
"code": null,
"e": 3298,
"s": 3261,
"text": "Give labels to the x-axis and y-axis"
},
{
"code": null,
"e": 3324,
"s": 3298,
"text": "Give a title to the graph"
},
{
"code": null,
"e": 3350,
"s": 3324,
"text": "Give a title to the graph"
},
{
"code": null,
"e": 3389,
"s": 3350,
"text": "Show the graph using .show() function."
},
{
"code": null,
"e": 3428,
"s": 3389,
"text": "Show the graph using .show() function."
},
{
"code": null,
"e": 3736,
"s": 3428,
"text": "import matplotlib.pyplot as plt\n\nleft_coordinates=[1,2,3,4,5]\nheights=[10,20,30,15,40]\nbar_labels=['One','Two','Three','Four','Five']\nplt.bar(left_coordinates,heights,tick_label=bar_labels,width=0.6,color=['re\nd','black'])\nplt.xlabel('X-axis')\nplt.ylabel('Y-axis')\nplt.title(\"A simple bar graph\")\nplt.show()"
},
{
"code": null,
"e": 3854,
"s": 3736,
"text": "The width parameter in the plt.bar() specifies the width of each bar. The color lists specify the colors of the bars."
}
] |
How to Set a Column Value to Null in SQL? | 21 Aug, 2021
In this article, we will look into how you can set the column value to Null in SQL.
Firstly, let’s create a table using CREATE TABLE command:
-- create a table
CREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2));
-- insert some values
INSERT INTO students VALUES (1, 'Nikita', 'F');
INSERT INTO students VALUES (2, 'Akshit', 'M');
INSERT INTO students VALUES (3, 'Ritesh', 'F');
INSERT INTO students VALUES (4, 'Himani', 'F');
-- fetch some values
SELECT * FROM students ;
The table would look like this:
To UPDATE Column value, use the below command:
UPDATE TABLE [TABLE_NAME]
To set column value to NULL use syntax:
update [TABLE_NAME] set [COLUMN_NAME] = NULL where [CRITERIA]
Example: For the above table
update students set Gender = NULL where Gender='F';
SELECT * FROM students ;
Output:
Column value can also be set to NULL without specifying the ‘where’ condition.
Example:
update students set Gender = NULL;
SELECT * FROM students ;
Output:
If you have set a constraint that a particular column value can not be NULL, and later try to set it as NULL, then it will generate an error.
Example:
-- create a table
CREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2) NOT NULL);
-- insert some values
INSERT INTO students VALUES (1, 'Nikita', 'F');
INSERT INTO students VALUES (2, 'Akshit', 'M');
INSERT INTO students VALUES (3, 'Ritesh', 'F');
INSERT INTO students VALUES (4, 'Himani', 'F');
-- fetch some values
SELECT * FROM students ;
Output:
ERROR: Gender may not be NULL.
Picked
SQL-Query
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?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Window functions in SQL
SQL | GROUP BY
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
SQL | Sub queries in From Clause | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "In this article, we will look into how you can set the column value to Null in SQL."
},
{
"code": null,
"e": 170,
"s": 112,
"text": "Firstly, let’s create a table using CREATE TABLE command:"
},
{
"code": null,
"e": 523,
"s": 170,
"text": "-- create a table\nCREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2));\n-- insert some values\nINSERT INTO students VALUES (1, 'Nikita', 'F');\nINSERT INTO students VALUES (2, 'Akshit', 'M');\nINSERT INTO students VALUES (3, 'Ritesh', 'F');\nINSERT INTO students VALUES (4, 'Himani', 'F');\n-- fetch some values\nSELECT * FROM students ;"
},
{
"code": null,
"e": 555,
"s": 523,
"text": "The table would look like this:"
},
{
"code": null,
"e": 602,
"s": 555,
"text": "To UPDATE Column value, use the below command:"
},
{
"code": null,
"e": 629,
"s": 602,
"text": " UPDATE TABLE [TABLE_NAME]"
},
{
"code": null,
"e": 669,
"s": 629,
"text": "To set column value to NULL use syntax:"
},
{
"code": null,
"e": 733,
"s": 669,
"text": " update [TABLE_NAME] set [COLUMN_NAME] = NULL where [CRITERIA] "
},
{
"code": null,
"e": 762,
"s": 733,
"text": "Example: For the above table"
},
{
"code": null,
"e": 839,
"s": 762,
"text": "update students set Gender = NULL where Gender='F';\nSELECT * FROM students ;"
},
{
"code": null,
"e": 847,
"s": 839,
"text": "Output:"
},
{
"code": null,
"e": 926,
"s": 847,
"text": "Column value can also be set to NULL without specifying the ‘where’ condition."
},
{
"code": null,
"e": 935,
"s": 926,
"text": "Example:"
},
{
"code": null,
"e": 995,
"s": 935,
"text": "update students set Gender = NULL;\nSELECT * FROM students ;"
},
{
"code": null,
"e": 1003,
"s": 995,
"text": "Output:"
},
{
"code": null,
"e": 1145,
"s": 1003,
"text": "If you have set a constraint that a particular column value can not be NULL, and later try to set it as NULL, then it will generate an error."
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Example:"
},
{
"code": null,
"e": 1516,
"s": 1154,
"text": "-- create a table\nCREATE TABLE students (Sr_No integer,Name varchar(20), Gender varchar(2) NOT NULL);\n-- insert some values\nINSERT INTO students VALUES (1, 'Nikita', 'F');\nINSERT INTO students VALUES (2, 'Akshit', 'M');\nINSERT INTO students VALUES (3, 'Ritesh', 'F');\nINSERT INTO students VALUES (4, 'Himani', 'F');\n-- fetch some values\nSELECT * FROM students ;"
},
{
"code": null,
"e": 1524,
"s": 1516,
"text": "Output:"
},
{
"code": null,
"e": 1555,
"s": 1524,
"text": "ERROR: Gender may not be NULL."
},
{
"code": null,
"e": 1562,
"s": 1555,
"text": "Picked"
},
{
"code": null,
"e": 1572,
"s": 1562,
"text": "SQL-Query"
},
{
"code": null,
"e": 1583,
"s": 1572,
"text": "SQL-Server"
},
{
"code": null,
"e": 1587,
"s": 1583,
"text": "SQL"
},
{
"code": null,
"e": 1591,
"s": 1587,
"text": "SQL"
},
{
"code": null,
"e": 1689,
"s": 1591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1755,
"s": 1689,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1779,
"s": 1755,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1824,
"s": 1779,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 1856,
"s": 1824,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 1895,
"s": 1856,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 1919,
"s": 1895,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1934,
"s": 1919,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 1973,
"s": 1934,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 1999,
"s": 1973,
"text": "SQL Correlated Subqueries"
}
] |
Python | Pandas Series.ravel() | 11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.ravel() function returns the flattened underlying data as an ndarray.
Syntax: Series.ravel(order=’C’)
Parameter : order
Returns : ndarray
Example #1: Use Series.ravel() function to return the elements of the given Series object as an ndarray.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray.
# return an ndarrayresult = sr.ravel() # Print the resultprint(result)
Output :
As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object.
Example #2: Use Series.ravel() function to return the elements of the given Series object as an ndarray.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray.
# return an ndarrayresult = sr.ravel() # Print the resultprint(result)
Output :
As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 369,
"s": 285,
"text": "Pandas Series.ravel() function returns the flattened underlying data as an ndarray."
},
{
"code": null,
"e": 401,
"s": 369,
"text": "Syntax: Series.ravel(order=’C’)"
},
{
"code": null,
"e": 419,
"s": 401,
"text": "Parameter : order"
},
{
"code": null,
"e": 437,
"s": 419,
"text": "Returns : ndarray"
},
{
"code": null,
"e": 542,
"s": 437,
"text": "Example #1: Use Series.ravel() function to return the elements of the given Series object as an ndarray."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 798,
"s": 542,
"text": null
},
{
"code": null,
"e": 807,
"s": 798,
"text": "Output :"
},
{
"code": null,
"e": 919,
"s": 807,
"text": "Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray."
},
{
"code": "# return an ndarrayresult = sr.ravel() # Print the resultprint(result)",
"e": 991,
"s": 919,
"text": null
},
{
"code": null,
"e": 1000,
"s": 991,
"text": "Output :"
},
{
"code": null,
"e": 1133,
"s": 1000,
"text": "As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object."
},
{
"code": null,
"e": 1238,
"s": 1133,
"text": "Example #2: Use Series.ravel() function to return the elements of the given Series object as an ndarray."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1515,
"s": 1238,
"text": null
},
{
"code": null,
"e": 1524,
"s": 1515,
"text": "Output :"
},
{
"code": null,
"e": 1636,
"s": 1524,
"text": "Now we will use Series.ravel() function to return the underlying data of the given Series object as an ndarray."
},
{
"code": "# return an ndarrayresult = sr.ravel() # Print the resultprint(result)",
"e": 1708,
"s": 1636,
"text": null
},
{
"code": null,
"e": 1717,
"s": 1708,
"text": "Output :"
},
{
"code": null,
"e": 1850,
"s": 1717,
"text": "As we can see in the output, the Series.ravel() function has returned the an ndarray containing the data of the given series object."
},
{
"code": null,
"e": 1871,
"s": 1850,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1900,
"s": 1871,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1914,
"s": 1900,
"text": "Python-pandas"
},
{
"code": null,
"e": 1921,
"s": 1914,
"text": "Python"
}
] |
How to change the background and foreground colors of tab in Java? | To change the background and foreground colors of tab, use the following methods −
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
Above, we have used the Color class to set the colors for the background and foregroud colors −
The following is an example to change the background and foreground colors of tab −
package my;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class SwingDemo {
public static void main(String args[]) {
JFrame frame = new JFrame("Devices");
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel1, panel2, panel3, panel4, panel5;
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel5 = new JPanel();
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
tabbedPane.addTab("Laptop", panel1);
tabbedPane.addTab("Desktop ", panel2);
tabbedPane.addTab("Notebook", panel3);
tabbedPane.addTab("Tablet ", panel4);
tabbedPane.addTab("Mobile", panel5);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550,350);
frame.setVisible(true);
}
} | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "To change the background and foreground colors of tab, use the following methods −"
},
{
"code": null,
"e": 1266,
"s": 1145,
"text": "JTabbedPane tabbedPane = new JTabbedPane();\ntabbedPane.setBackground(Color.blue);\ntabbedPane.setForeground(Color.white);"
},
{
"code": null,
"e": 1362,
"s": 1266,
"text": "Above, we have used the Color class to set the colors for the background and foregroud colors −"
},
{
"code": null,
"e": 1446,
"s": 1362,
"text": "The following is an example to change the background and foreground colors of tab −"
},
{
"code": null,
"e": 2357,
"s": 1446,
"text": "package my;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.KeyEvent;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Devices\");\n JTabbedPane tabbedPane = new JTabbedPane();\n JPanel panel1, panel2, panel3, panel4, panel5;\n panel1 = new JPanel();\n panel2 = new JPanel();\n panel3 = new JPanel();\n panel4 = new JPanel();\n panel5 = new JPanel();\n tabbedPane.setBackground(Color.blue);\n tabbedPane.setForeground(Color.white);\n tabbedPane.addTab(\"Laptop\", panel1);\n tabbedPane.addTab(\"Desktop \", panel2);\n tabbedPane.addTab(\"Notebook\", panel3);\n tabbedPane.addTab(\"Tablet \", panel4);\n tabbedPane.addTab(\"Mobile\", panel5);\n frame.add(tabbedPane);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(550,350);\n frame.setVisible(true);\n }\n}"
}
] |
React Native - MapView | In this chapter we will show you how to use maps in React Native.
Let's create src/components/home/MapViewExample.js
We are adding several props to MapView.
showsUserLocation and followUserLocation are booleans. You will need users permission before it can be used.
We also want to enable zoom by setting zoomEnabled = {true}
src/components/home/MapViewExample.js
import React, { Component } from 'react'
import {
MapView,
StyleSheet
} from 'react-native'
export default MapViewExample = (props) => {
return (
<MapView
style = {styles.map}
showsUserLocation = {false}
followUserLocation = {false}
zoomEnabled = {true}
/>
)
}
const styles = StyleSheet.create ({
map: {
height: 400,
marginTop: 80
}
})
And finally we need to pass this to HomeContainer component.
src/components/home/HomeContainer.js
import React, { Component } from 'react'
import { MapView } from 'react-native'
import MapViewExample from './MapViewExample'
export default class HomeContainer extends Component {
constructor() {
super();
}
render() {
return (
<MapViewExample/>
);
}
}
When we run the app, we can see the map.
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2410,
"s": 2344,
"text": "In this chapter we will show you how to use maps in React Native."
},
{
"code": null,
"e": 2461,
"s": 2410,
"text": "Let's create src/components/home/MapViewExample.js"
},
{
"code": null,
"e": 2501,
"s": 2461,
"text": "We are adding several props to MapView."
},
{
"code": null,
"e": 2610,
"s": 2501,
"text": "showsUserLocation and followUserLocation are booleans. You will need users permission before it can be used."
},
{
"code": null,
"e": 2670,
"s": 2610,
"text": "We also want to enable zoom by setting zoomEnabled = {true}"
},
{
"code": null,
"e": 2708,
"s": 2670,
"text": "src/components/home/MapViewExample.js"
},
{
"code": null,
"e": 3124,
"s": 2708,
"text": "import React, { Component } from 'react'\nimport {\n MapView,\n StyleSheet\n} from 'react-native'\n\nexport default MapViewExample = (props) => {\n return (\n <MapView\n style = {styles.map}\n showsUserLocation = {false}\n followUserLocation = {false}\n zoomEnabled = {true}\n />\n )\n}\n\nconst styles = StyleSheet.create ({\n map: {\n height: 400,\n marginTop: 80\n }\n})"
},
{
"code": null,
"e": 3185,
"s": 3124,
"text": "And finally we need to pass this to HomeContainer component."
},
{
"code": null,
"e": 3222,
"s": 3185,
"text": "src/components/home/HomeContainer.js"
},
{
"code": null,
"e": 3516,
"s": 3222,
"text": "import React, { Component } from 'react'\nimport { MapView } from 'react-native'\nimport MapViewExample from './MapViewExample'\n\nexport default class HomeContainer extends Component {\n\n constructor() {\n super();\n }\n render() {\n return (\n <MapViewExample/>\n );\n }\n}"
},
{
"code": null,
"e": 3557,
"s": 3516,
"text": "When we run the app, we can see the map."
},
{
"code": null,
"e": 3592,
"s": 3557,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3606,
"s": 3592,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3641,
"s": 3606,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3656,
"s": 3641,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 3691,
"s": 3656,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3719,
"s": 3691,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3755,
"s": 3719,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3783,
"s": 3755,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3818,
"s": 3783,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3830,
"s": 3818,
"text": " Senol Atac"
},
{
"code": null,
"e": 3865,
"s": 3830,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3877,
"s": 3865,
"text": " Senol Atac"
},
{
"code": null,
"e": 3884,
"s": 3877,
"text": " Print"
},
{
"code": null,
"e": 3895,
"s": 3884,
"text": " Add Notes"
}
] |
Arcesium Interview Experience for On-Campus Internship 2021 - GeeksforGeeks | 07 Oct, 2021
Arcesium visited our campus (MNIT Jaipur) in the latter part of August 2020 offering a 2-month Summer Internship for 2021. Initially, there was shortlisting based on CGPA, 12th-grade percentage, and 10th-grade CGPA. 87 students were shortlisted for further rounds.
Round 1 (Hackerrank Platform): The first round comprised of 15 MCQ questions of quantitative aptitude, 15 MCQ questions of Technical aptitude, and 2 coding questions.(Test duration – 80 minutes – 20 + 15 + 45).
Quantitative aptitude and Technical aptitude problems were challenging especially due to the time limit for each section. It covered a variety of topics including probability, number theory as well as concepts of Object Orientated Programming and time complexity analysis. There was a negative marking of 25 percent.
Coding Questions:
Given an infinite binary string 100000... For each subsequent day, the updated value at each index >= 1 is given by xor of the value of (i-1)th index and ith index on the previous day. We are provided with number n. We are required to find out, the decimal value of the binary string (up to (n+1) characters) on an nth day.A company has a certain number of corona tablets given in the input, and we are given an array representing a packet we could use. The packets are of different sizes. We are required to find out the maximum number of packets that can be used to package the tablets.Example:Input:
size = 5
array = [3, 2, 5]
Output: 2
Explanation: As we could use a packet of size 3 and a
packet of size 2 to package 5 tablets.
Given an infinite binary string 100000... For each subsequent day, the updated value at each index >= 1 is given by xor of the value of (i-1)th index and ith index on the previous day. We are provided with number n. We are required to find out, the decimal value of the binary string (up to (n+1) characters) on an nth day.
A company has a certain number of corona tablets given in the input, and we are given an array representing a packet we could use. The packets are of different sizes. We are required to find out the maximum number of packets that can be used to package the tablets.Example:Input:
size = 5
array = [3, 2, 5]
Output: 2
Explanation: As we could use a packet of size 3 and a
packet of size 2 to package 5 tablets.
Example:
Input:
size = 5
array = [3, 2, 5]
Output: 2
Explanation: As we could use a packet of size 3 and a
packet of size 2 to package 5 tablets.
15 students were shortlisted out of 87 students for further rounds.
Round 2 (Technical Interview): All the technical Interviews were held on Hackerrank code pair platform. There were 2 interviewers for this round.
The interviewers asked me to introduce myself.They asked me about my projects. I told them about the functionality and inspiration for the projects in short.Coding question: Given a string, we are required to output all the sub-sequences of the string such that each sub-sequence is sorted.Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string.Input: string = cab
Output: "" a b c ab ac bc abcCoding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > linkExample: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more.Input: array = [ 1, 2, -1 ]
Output: 3
The interviewers asked me to introduce myself.
They asked me about my projects. I told them about the functionality and inspiration for the projects in short.
Coding question: Given a string, we are required to output all the sub-sequences of the string such that each sub-sequence is sorted.Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string.Input: string = cab
Output: "" a b c ab ac bc abc
Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string.
Input: string = cab
Output: "" a b c ab ac bc abc
Coding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > linkExample: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more.Input: array = [ 1, 2, -1 ]
Output: 3
Coding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > link
Example: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more.
Input: array = [ 1, 2, -1 ]
Output: 3
They asked me if I had any questions for them. I asked about the atmosphere inside the company.
Round 3 (Technical Interview):
The interviewer asked me to introduce myself.He asked me about OOPS concepts in C++ as I was familiar with it. The discussion was detailed.He asked me to explain method overloading and method overriding through an example in c++.Concept of inheritance and the role of access specifiers during the creation of child class. I wrote a small example to explain it.He asked me about the virtual keyword in C++ and all its use cases. I was also asked to write a class to show its usage.He questioned if there is a virtual constructor in C++. I answered NO. Then, he asked me about the reason for it. Similarly, for virtual destructor.What is a Singleton class? Design a singleton class and explain the concepts regarding it. I told him about a singleton class and coded it in C++. He asked me about the copy constructor in a singleton class and how would it affect the singleton class.After the discussion on OOPS concepts, he gave me a puzzle to solve. I was not able to reach the optimum solution initially but did in the second try.
The interviewer asked me to introduce myself.
He asked me about OOPS concepts in C++ as I was familiar with it. The discussion was detailed.
He asked me to explain method overloading and method overriding through an example in c++.
Concept of inheritance and the role of access specifiers during the creation of child class. I wrote a small example to explain it.
He asked me about the virtual keyword in C++ and all its use cases. I was also asked to write a class to show its usage.
He questioned if there is a virtual constructor in C++. I answered NO. Then, he asked me about the reason for it. Similarly, for virtual destructor.
What is a Singleton class? Design a singleton class and explain the concepts regarding it. I told him about a singleton class and coded it in C++. He asked me about the copy constructor in a singleton class and how would it affect the singleton class.
After the discussion on OOPS concepts, he gave me a puzzle to solve. I was not able to reach the optimum solution initially but did in the second try.
Finally, he asked whether I had questions for him. I asked about the domains in which the company works.
Round 4 (Technical Interview):
The interviewer asked me to introduce myself.Then we had a discussion on projects. In one of the projects, he asked me the schema of the database used for that project. Also, to explain a particular functionality in the project.Coding Question: Given the numerator and denominator, we are required to output the division in the following format.Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99
Output: 0.(81)
Explanation: As the division leads to 0.818181...Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2
Output: 1.5
The interviewer asked me to introduce myself.
Then we had a discussion on projects. In one of the projects, he asked me the schema of the database used for that project. Also, to explain a particular functionality in the project.
Coding Question: Given the numerator and denominator, we are required to output the division in the following format.Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99
Output: 0.(81)
Explanation: As the division leads to 0.818181...Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2
Output: 1.5
Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99
Output: 0.(81)
Explanation: As the division leads to 0.818181...
Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)
Example:
Input: numerator = 81, denominator = 99
Output: 0.(81)
Explanation: As the division leads to 0.818181...
Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2
Output: 1.5
Case 2: If the division is non-recurring, then output the division.
Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.
Input: numerator = 3, denominator = 2
Output: 1.5
He asked me if I had questions for him.
Round 5 (HR): The HR round was held on bluejeans platform.
Introduce myself.She asked me about the projects, the inspiration, the execution phase, and the completion phase.She asked about the competitions I had participated in. Whether they were individual or team collaboration. She asked me to share the entire journey of the competitions. From the inspiration to the experience I had during the competition.How did I spend my time apart from academics and what got me interested in robotics (as I had done projects on it) and software development?What things I like about Arcesium.
Introduce myself.
She asked me about the projects, the inspiration, the execution phase, and the completion phase.
She asked about the competitions I had participated in. Whether they were individual or team collaboration. She asked me to share the entire journey of the competitions. From the inspiration to the experience I had during the competition.
How did I spend my time apart from academics and what got me interested in robotics (as I had done projects on it) and software development?
What things I like about Arcesium.
Finally, if I had any questions for her. I asked about the work-life balance and prerequisite knowledge required.
Final Selection: Two students were selected for the internship. I was one of them
Arcesium
Marketing
On-Campus
Interview Experiences
Arcesium
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Amazon Interview Experience
Difference between ANN, CNN and RNN
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience for SDE-1
Zoho Interview | Set 1 (On-Campus)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 | [
{
"code": null,
"e": 25278,
"s": 25250,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 25543,
"s": 25278,
"text": "Arcesium visited our campus (MNIT Jaipur) in the latter part of August 2020 offering a 2-month Summer Internship for 2021. Initially, there was shortlisting based on CGPA, 12th-grade percentage, and 10th-grade CGPA. 87 students were shortlisted for further rounds."
},
{
"code": null,
"e": 25755,
"s": 25543,
"text": "Round 1 (Hackerrank Platform): The first round comprised of 15 MCQ questions of quantitative aptitude, 15 MCQ questions of Technical aptitude, and 2 coding questions.(Test duration – 80 minutes – 20 + 15 + 45). "
},
{
"code": null,
"e": 26072,
"s": 25755,
"text": "Quantitative aptitude and Technical aptitude problems were challenging especially due to the time limit for each section. It covered a variety of topics including probability, number theory as well as concepts of Object Orientated Programming and time complexity analysis. There was a negative marking of 25 percent."
},
{
"code": null,
"e": 26090,
"s": 26072,
"text": "Coding Questions:"
},
{
"code": null,
"e": 26823,
"s": 26090,
"text": "Given an infinite binary string 100000... For each subsequent day, the updated value at each index >= 1 is given by xor of the value of (i-1)th index and ith index on the previous day. We are provided with number n. We are required to find out, the decimal value of the binary string (up to (n+1) characters) on an nth day.A company has a certain number of corona tablets given in the input, and we are given an array representing a packet we could use. The packets are of different sizes. We are required to find out the maximum number of packets that can be used to package the tablets.Example:Input:\nsize = 5\narray = [3, 2, 5]\nOutput: 2\nExplanation: As we could use a packet of size 3 and a\npacket of size 2 to package 5 tablets."
},
{
"code": null,
"e": 27147,
"s": 26823,
"text": "Given an infinite binary string 100000... For each subsequent day, the updated value at each index >= 1 is given by xor of the value of (i-1)th index and ith index on the previous day. We are provided with number n. We are required to find out, the decimal value of the binary string (up to (n+1) characters) on an nth day."
},
{
"code": null,
"e": 27557,
"s": 27147,
"text": "A company has a certain number of corona tablets given in the input, and we are given an array representing a packet we could use. The packets are of different sizes. We are required to find out the maximum number of packets that can be used to package the tablets.Example:Input:\nsize = 5\narray = [3, 2, 5]\nOutput: 2\nExplanation: As we could use a packet of size 3 and a\npacket of size 2 to package 5 tablets."
},
{
"code": null,
"e": 27566,
"s": 27557,
"text": "Example:"
},
{
"code": null,
"e": 27703,
"s": 27566,
"text": "Input:\nsize = 5\narray = [3, 2, 5]\nOutput: 2\nExplanation: As we could use a packet of size 3 and a\npacket of size 2 to package 5 tablets."
},
{
"code": null,
"e": 27771,
"s": 27703,
"text": "15 students were shortlisted out of 87 students for further rounds."
},
{
"code": null,
"e": 27917,
"s": 27771,
"text": "Round 2 (Technical Interview): All the technical Interviews were held on Hackerrank code pair platform. There were 2 interviewers for this round."
},
{
"code": null,
"e": 28748,
"s": 27917,
"text": "The interviewers asked me to introduce myself.They asked me about my projects. I told them about the functionality and inspiration for the projects in short.Coding question: Given a string, we are required to output all the sub-sequences of the string such that each sub-sequence is sorted.Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string.Input: string = cab\nOutput: \"\" a b c ab ac bc abcCoding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > linkExample: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more.Input: array = [ 1, 2, -1 ]\nOutput: 3"
},
{
"code": null,
"e": 28795,
"s": 28748,
"text": "The interviewers asked me to introduce myself."
},
{
"code": null,
"e": 28907,
"s": 28795,
"text": "They asked me about my projects. I told them about the functionality and inspiration for the projects in short."
},
{
"code": null,
"e": 29221,
"s": 28907,
"text": "Coding question: Given a string, we are required to output all the sub-sequences of the string such that each sub-sequence is sorted.Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string.Input: string = cab\nOutput: \"\" a b c ab ac bc abc"
},
{
"code": null,
"e": 29353,
"s": 29221,
"text": "Example: I explained my intuition for the solution and coded the problem. They checked my code for edge cases such as empty string."
},
{
"code": null,
"e": 29403,
"s": 29353,
"text": "Input: string = cab\nOutput: \"\" a b c ab ac bc abc"
},
{
"code": null,
"e": 29764,
"s": 29403,
"text": "Coding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > linkExample: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more.Input: array = [ 1, 2, -1 ]\nOutput: 3"
},
{
"code": null,
"e": 29954,
"s": 29764,
"text": "Coding question: Given an array, we are required to output the maximum sub-array sum of the array.Problem: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1” > link"
},
{
"code": null,
"e": 30088,
"s": 29954,
"text": "Example: I explained my intuition and coded the problem. They checked my code for cases like all 0’s, all negative numbers, and more."
},
{
"code": null,
"e": 30127,
"s": 30088,
"text": "Input: array = [ 1, 2, -1 ]\nOutput: 3"
},
{
"code": null,
"e": 30223,
"s": 30127,
"text": "They asked me if I had any questions for them. I asked about the atmosphere inside the company."
},
{
"code": null,
"e": 30254,
"s": 30223,
"text": "Round 3 (Technical Interview):"
},
{
"code": null,
"e": 31284,
"s": 30254,
"text": "The interviewer asked me to introduce myself.He asked me about OOPS concepts in C++ as I was familiar with it. The discussion was detailed.He asked me to explain method overloading and method overriding through an example in c++.Concept of inheritance and the role of access specifiers during the creation of child class. I wrote a small example to explain it.He asked me about the virtual keyword in C++ and all its use cases. I was also asked to write a class to show its usage.He questioned if there is a virtual constructor in C++. I answered NO. Then, he asked me about the reason for it. Similarly, for virtual destructor.What is a Singleton class? Design a singleton class and explain the concepts regarding it. I told him about a singleton class and coded it in C++. He asked me about the copy constructor in a singleton class and how would it affect the singleton class.After the discussion on OOPS concepts, he gave me a puzzle to solve. I was not able to reach the optimum solution initially but did in the second try."
},
{
"code": null,
"e": 31330,
"s": 31284,
"text": "The interviewer asked me to introduce myself."
},
{
"code": null,
"e": 31425,
"s": 31330,
"text": "He asked me about OOPS concepts in C++ as I was familiar with it. The discussion was detailed."
},
{
"code": null,
"e": 31516,
"s": 31425,
"text": "He asked me to explain method overloading and method overriding through an example in c++."
},
{
"code": null,
"e": 31648,
"s": 31516,
"text": "Concept of inheritance and the role of access specifiers during the creation of child class. I wrote a small example to explain it."
},
{
"code": null,
"e": 31769,
"s": 31648,
"text": "He asked me about the virtual keyword in C++ and all its use cases. I was also asked to write a class to show its usage."
},
{
"code": null,
"e": 31918,
"s": 31769,
"text": "He questioned if there is a virtual constructor in C++. I answered NO. Then, he asked me about the reason for it. Similarly, for virtual destructor."
},
{
"code": null,
"e": 32170,
"s": 31918,
"text": "What is a Singleton class? Design a singleton class and explain the concepts regarding it. I told him about a singleton class and coded it in C++. He asked me about the copy constructor in a singleton class and how would it affect the singleton class."
},
{
"code": null,
"e": 32321,
"s": 32170,
"text": "After the discussion on OOPS concepts, he gave me a puzzle to solve. I was not able to reach the optimum solution initially but did in the second try."
},
{
"code": null,
"e": 32426,
"s": 32321,
"text": "Finally, he asked whether I had questions for him. I asked about the domains in which the company works."
},
{
"code": null,
"e": 32457,
"s": 32426,
"text": "Round 4 (Technical Interview):"
},
{
"code": null,
"e": 33388,
"s": 32457,
"text": "The interviewer asked me to introduce myself.Then we had a discussion on projects. In one of the projects, he asked me the schema of the database used for that project. Also, to explain a particular functionality in the project.Coding Question: Given the numerator and denominator, we are required to output the division in the following format.Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99\nOutput: 0.(81)\nExplanation: As the division leads to 0.818181...Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2\nOutput: 1.5"
},
{
"code": null,
"e": 33434,
"s": 33388,
"text": "The interviewer asked me to introduce myself."
},
{
"code": null,
"e": 33618,
"s": 33434,
"text": "Then we had a discussion on projects. In one of the projects, he asked me the schema of the database used for that project. Also, to explain a particular functionality in the project."
},
{
"code": null,
"e": 34321,
"s": 33618,
"text": "Coding Question: Given the numerator and denominator, we are required to output the division in the following format.Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99\nOutput: 0.(81)\nExplanation: As the division leads to 0.818181...Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2\nOutput: 1.5"
},
{
"code": null,
"e": 34553,
"s": 34321,
"text": "Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)Example:Input: numerator = 81, denominator = 99\nOutput: 0.(81)\nExplanation: As the division leads to 0.818181..."
},
{
"code": null,
"e": 34673,
"s": 34553,
"text": "Case 1: If the division leads to a recurring decimal then output in the form – numerator/ denominator. (recurring part)"
},
{
"code": null,
"e": 34682,
"s": 34673,
"text": "Example:"
},
{
"code": null,
"e": 34787,
"s": 34682,
"text": "Input: numerator = 81, denominator = 99\nOutput: 0.(81)\nExplanation: As the division leads to 0.818181..."
},
{
"code": null,
"e": 35142,
"s": 34787,
"text": "Case 2: If the division is non-recurring, then output the division.Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output.Input: numerator = 3, denominator = 2\nOutput: 1.5"
},
{
"code": null,
"e": 35210,
"s": 35142,
"text": "Case 2: If the division is non-recurring, then output the division."
},
{
"code": null,
"e": 35449,
"s": 35210,
"text": "Example: I was able to give the logic and tried to code it, but was getting a few errors in the output. The interviewers pointed out some problems that could lead to the error and after reviewing the code again, I got the required output."
},
{
"code": null,
"e": 35499,
"s": 35449,
"text": "Input: numerator = 3, denominator = 2\nOutput: 1.5"
},
{
"code": null,
"e": 35539,
"s": 35499,
"text": "He asked me if I had questions for him."
},
{
"code": null,
"e": 35598,
"s": 35539,
"text": "Round 5 (HR): The HR round was held on bluejeans platform."
},
{
"code": null,
"e": 36124,
"s": 35598,
"text": "Introduce myself.She asked me about the projects, the inspiration, the execution phase, and the completion phase.She asked about the competitions I had participated in. Whether they were individual or team collaboration. She asked me to share the entire journey of the competitions. From the inspiration to the experience I had during the competition.How did I spend my time apart from academics and what got me interested in robotics (as I had done projects on it) and software development?What things I like about Arcesium."
},
{
"code": null,
"e": 36142,
"s": 36124,
"text": "Introduce myself."
},
{
"code": null,
"e": 36239,
"s": 36142,
"text": "She asked me about the projects, the inspiration, the execution phase, and the completion phase."
},
{
"code": null,
"e": 36478,
"s": 36239,
"text": "She asked about the competitions I had participated in. Whether they were individual or team collaboration. She asked me to share the entire journey of the competitions. From the inspiration to the experience I had during the competition."
},
{
"code": null,
"e": 36619,
"s": 36478,
"text": "How did I spend my time apart from academics and what got me interested in robotics (as I had done projects on it) and software development?"
},
{
"code": null,
"e": 36654,
"s": 36619,
"text": "What things I like about Arcesium."
},
{
"code": null,
"e": 36768,
"s": 36654,
"text": "Finally, if I had any questions for her. I asked about the work-life balance and prerequisite knowledge required."
},
{
"code": null,
"e": 36851,
"s": 36768,
"text": "Final Selection: Two students were selected for the internship. I was one of them "
},
{
"code": null,
"e": 36860,
"s": 36851,
"text": "Arcesium"
},
{
"code": null,
"e": 36870,
"s": 36860,
"text": "Marketing"
},
{
"code": null,
"e": 36880,
"s": 36870,
"text": "On-Campus"
},
{
"code": null,
"e": 36902,
"s": 36880,
"text": "Interview Experiences"
},
{
"code": null,
"e": 36911,
"s": 36902,
"text": "Arcesium"
},
{
"code": null,
"e": 37009,
"s": 36911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37059,
"s": 37009,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 37118,
"s": 37059,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 37156,
"s": 37118,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 37184,
"s": 37156,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 37220,
"s": 37184,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 37266,
"s": 37220,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 37316,
"s": 37266,
"text": "Amazon Interview Experience for SDE-1(Off-Campus)"
},
{
"code": null,
"e": 37354,
"s": 37316,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 37389,
"s": 37354,
"text": "Zoho Interview | Set 1 (On-Campus)"
}
] |
Find N distinct integers with zero sum - GeeksforGeeks | 25 Nov, 2021
Given an integer N, our task is to print N distinct numbers such that their sum is 0.Examples:
Input: N = 3 Output: 1, -1, 0 Explanation: On adding the numbers that is 1 + (-1) + 0 the sum is 0.Input: N = 4 Output: 1, -1, 2, -2 Explanation: On adding the numbers that is 1 + (-1) + 2 + (-2) the sum is 0.
Approach: To solve the problem mentioned above the main idea is to print Symmetric Pairs like (+x, -x) so that the sum will always be 0. The edge case to the problem is to observe that if integer N is odd, then print one 0 along with the numbers so that sum is not affected.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Print N distinct// numbers such that their sum is 0 #include <bits/stdc++.h>using namespace std; // Function to print distinct n// numbers such that their sum is 0void findNumbers(int N){ for (int i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers cout << i << ", " << -i << ", "; } // print a extra 0 if N is odd if (N % 2 == 1) cout << 0;} // Driver codeint main(){ int N = 10; findNumbers(N);}
// Java implementation to Print N distinct// numbers such that their sum is 0 class GFG{ // Function to print distinct n// numbers such that their sum is 0static void findNumbers(int N){ for (int i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers System.out.print(i + ", " + -i + ", "); } // Print a extra 0 if N is odd if (N % 2 == 1) System.out.print(0);} // Driver codepublic static void main(String[] args){ int N = 10; findNumbers(N);}} // This code is contributed by 29AjayKumar
# Python3 implementation to print N distinct# numbers such that their sum is 0 # Function to print distinct n# numbers such that their sum is 0def findNumbers(N): for i in range(1, N // 2 + 1): # Print 2 symmetric numbers print(i, end = ', ') print(-i, end = ', ') # Print a extra 0 if N is odd if N % 2 == 1: print(0, end = '') # Driver codeif __name__=='__main__': N = 10 findNumbers(N) # This code is contributed by rutvik_56
// C# implementation to print N distinct// numbers such that their sum is 0using System; class GFG { // Function to print distinct n// numbers such that their sum is 0static void findNumbers(int N){ for(int i = 1; i <= (N / 2); i++) { // Print 2 symmetric numbers Console.Write(i + ", " + -i + ", "); } // Print a extra 0 if N is odd if (N % 2 == 1) Console.Write(0);} // Driver codestatic void Main(){ int N = 10; findNumbers(N);}} // This code is contributed by divyeshrabadiya07
<script> // Javascript implementation to Print N distinct// numbers such that their sum is 0 // Function to print distinct n// numbers such that their sum is 0function findNumbers(N){ for (var i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers document.write( i + ", " + -i + ", "); } // print a extra 0 if N is odd if (N % 2 == 1) document.write( 0);} // Driver codevar N = 10;findNumbers(N); </script>
1, -1, 2, -2, 3, -3, 4, -4, 5, -5,
Time Complexity: O(N)
29AjayKumar
rutvik_56
divyeshrabadiya07
itsok
ardotrtrian
Numbers
Mathematical
School Programming
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24717,
"s": 24689,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 24813,
"s": 24717,
"text": "Given an integer N, our task is to print N distinct numbers such that their sum is 0.Examples: "
},
{
"code": null,
"e": 25025,
"s": 24813,
"text": "Input: N = 3 Output: 1, -1, 0 Explanation: On adding the numbers that is 1 + (-1) + 0 the sum is 0.Input: N = 4 Output: 1, -1, 2, -2 Explanation: On adding the numbers that is 1 + (-1) + 2 + (-2) the sum is 0. "
},
{
"code": null,
"e": 25354,
"s": 25027,
"text": "Approach: To solve the problem mentioned above the main idea is to print Symmetric Pairs like (+x, -x) so that the sum will always be 0. The edge case to the problem is to observe that if integer N is odd, then print one 0 along with the numbers so that sum is not affected.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25358,
"s": 25354,
"text": "C++"
},
{
"code": null,
"e": 25363,
"s": 25358,
"text": "Java"
},
{
"code": null,
"e": 25371,
"s": 25363,
"text": "Python3"
},
{
"code": null,
"e": 25374,
"s": 25371,
"text": "C#"
},
{
"code": null,
"e": 25385,
"s": 25374,
"text": "Javascript"
},
{
"code": "// C++ implementation to Print N distinct// numbers such that their sum is 0 #include <bits/stdc++.h>using namespace std; // Function to print distinct n// numbers such that their sum is 0void findNumbers(int N){ for (int i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers cout << i << \", \" << -i << \", \"; } // print a extra 0 if N is odd if (N % 2 == 1) cout << 0;} // Driver codeint main(){ int N = 10; findNumbers(N);}",
"e": 25853,
"s": 25385,
"text": null
},
{
"code": "// Java implementation to Print N distinct// numbers such that their sum is 0 class GFG{ // Function to print distinct n// numbers such that their sum is 0static void findNumbers(int N){ for (int i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers System.out.print(i + \", \" + -i + \", \"); } // Print a extra 0 if N is odd if (N % 2 == 1) System.out.print(0);} // Driver codepublic static void main(String[] args){ int N = 10; findNumbers(N);}} // This code is contributed by 29AjayKumar",
"e": 26385,
"s": 25853,
"text": null
},
{
"code": "# Python3 implementation to print N distinct# numbers such that their sum is 0 # Function to print distinct n# numbers such that their sum is 0def findNumbers(N): for i in range(1, N // 2 + 1): # Print 2 symmetric numbers print(i, end = ', ') print(-i, end = ', ') # Print a extra 0 if N is odd if N % 2 == 1: print(0, end = '') # Driver codeif __name__=='__main__': N = 10 findNumbers(N) # This code is contributed by rutvik_56",
"e": 26889,
"s": 26385,
"text": null
},
{
"code": "// C# implementation to print N distinct// numbers such that their sum is 0using System; class GFG { // Function to print distinct n// numbers such that their sum is 0static void findNumbers(int N){ for(int i = 1; i <= (N / 2); i++) { // Print 2 symmetric numbers Console.Write(i + \", \" + -i + \", \"); } // Print a extra 0 if N is odd if (N % 2 == 1) Console.Write(0);} // Driver codestatic void Main(){ int N = 10; findNumbers(N);}} // This code is contributed by divyeshrabadiya07 ",
"e": 27425,
"s": 26889,
"text": null
},
{
"code": "<script> // Javascript implementation to Print N distinct// numbers such that their sum is 0 // Function to print distinct n// numbers such that their sum is 0function findNumbers(N){ for (var i = 1; i <= N / 2; i++) { // Print 2 symmetric numbers document.write( i + \", \" + -i + \", \"); } // print a extra 0 if N is odd if (N % 2 == 1) document.write( 0);} // Driver codevar N = 10;findNumbers(N); </script>",
"e": 27868,
"s": 27425,
"text": null
},
{
"code": null,
"e": 27903,
"s": 27868,
"text": "1, -1, 2, -2, 3, -3, 4, -4, 5, -5,"
},
{
"code": null,
"e": 27928,
"s": 27905,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 27940,
"s": 27928,
"text": "29AjayKumar"
},
{
"code": null,
"e": 27950,
"s": 27940,
"text": "rutvik_56"
},
{
"code": null,
"e": 27968,
"s": 27950,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 27974,
"s": 27968,
"text": "itsok"
},
{
"code": null,
"e": 27986,
"s": 27974,
"text": "ardotrtrian"
},
{
"code": null,
"e": 27994,
"s": 27986,
"text": "Numbers"
},
{
"code": null,
"e": 28007,
"s": 27994,
"text": "Mathematical"
},
{
"code": null,
"e": 28026,
"s": 28007,
"text": "School Programming"
},
{
"code": null,
"e": 28039,
"s": 28026,
"text": "Mathematical"
},
{
"code": null,
"e": 28047,
"s": 28039,
"text": "Numbers"
},
{
"code": null,
"e": 28145,
"s": 28047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28177,
"s": 28145,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 28221,
"s": 28177,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 28246,
"s": 28221,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 28279,
"s": 28246,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 28310,
"s": 28279,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 28328,
"s": 28310,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28344,
"s": 28328,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28363,
"s": 28344,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28388,
"s": 28363,
"text": "Reverse a string in Java"
}
] |
Print all unique paths from given source to destination in a Matrix moving only down or right - GeeksforGeeks | 04 Jan, 2022
Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down.
Examples:
Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6
Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4
Approach: Use recursion to move first right then down from each cell in the path of the matrix mat[][], starting from source, and store each value in a vector. If the destination is reached, print the vector as one of the possible paths. Follow the steps below to solve the problem:
If the current cell is out of the boundary, then return.
Push the current cell’s value into the vector path[].
If the current cell is the destination, then print the current path.
Call the same function for the values {i+1, j} and {i, j+1}.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; vector<vector<int> > mat;vector<int> s;vector<int> d;int m = 2, n = 3; // Function to print all the pathsvoid printVector(vector<int> path){ int cnt = path.size(); for (int i = 0; i < cnt; i += 2) cout << mat[path[i]][path[i + 1]] << " "; cout << endl;} // Function to find all the paths recursivelyvoid countPaths(int i, int j, vector<int> path){ // Base Case if (i > d[0] || j > d[1]) return; path.push_back(i); path.push_back(j); // Destination is reached if (i == d[0] && j == d[1]) { printVector(path); return; } // Calling the function countPaths(i, j + 1, path); countPaths(i + 1, j, path);} // DriverCodeint main(){ mat = { { 1, 2, 3 }, { 4, 5, 6 } }; s = { 0, 0 }; d = { 1, 2 }; vector<int> path; countPaths(s[0], s[1], path); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ static Vector<Integer> s = new Vector<>(); static Vector<Integer> d = new Vector<>(); static int m = 2, n = 3; // Function to print all the paths static void printVector(Vector<Integer> path, int[][] mat) { int cnt = path.size(); for (int i = 0; i < cnt; i += 2) System.out.print(mat[path.get(i)][path.get(i + 1)]+ " "); System.out.println(); } // Function to find all the paths recursively static void countPaths(int i, int j, Vector<Integer> path, int[][]mat) { // Base Case if (i > d.get(0) || j > d.get(1)) return; path.add(i); path.add(j); // Destination is reached if (i == d.get(0) && j == d.get(1)) { printVector(path,mat); path.remove(path.size()-1); path.remove(path.size()-1); return; } // Calling the function countPaths(i, j + 1, path,mat); countPaths(i + 1, j, path,mat); path.remove(path.size()-1); path.remove(path.size()-1); } // DriverCode public static void main(String[] args) { int[][] mat = {{ 1, 2, 3 }, { 4, 5, 6 } }; s.add(0); s.add(0); d.add(1); d.add(2); Vector<Integer> path = new Vector<>(); countPaths(s.get(0), s.get(1), path, mat); }} // This code is contributed by Rajput-Ji.
# Python code for the above approachmat = Nones = Noned = Nonem = 2n = 3 # Function to print all the pathsdef printVector(path): cnt = len(path) for i in range(0, cnt, 2): print(mat[path[i]][path[i + 1]], end=" ") print("") # Function to find all the paths recursivelydef countPaths(i, j, path): # Base Case if (i > d[0] or j > d[1]): return path.append(i) path.append(j) # Destination is reached if (i == d[0] and j == d[1]): printVector(path) path.pop() path.pop() return # Calling the function countPaths(i, j + 1, path) countPaths(i + 1, j, path) path.pop() path.pop() # DriverCodemat = [[1, 2, 3], [4, 5, 6]]s = [0, 0]d = [1, 2]path = [] countPaths(s[0], s[1], path) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static List<int> s = new List<int>(); static List<int> d = new List<int>(); static int m = 2, n = 3; // Function to print all the paths static void printList(List<int> path, int[,] mat) { int cnt = path.Count; for (int i = 0; i < cnt; i += 2) Console.Write(mat[path[i],path[i + 1]] + " "); Console.WriteLine(); } // Function to find all the paths recursively static void countPaths(int i, int j, List<int> path, int[,] mat) { // Base Case if (i > d[0] || j > d[1]) return; path.Add(i); path.Add(j); // Destination is reached if (i == d[0] && j == d[1]) { printList(path, mat); path.RemoveAt(path.Count - 1); path.RemoveAt(path.Count - 1); return; } // Calling the function countPaths(i, j + 1, path, mat); countPaths(i + 1, j, path, mat); path.RemoveAt(path.Count - 1); path.RemoveAt(path.Count - 1); } // DriverCode public static void Main(String[] args) { int[,] mat = { { 1, 2, 3 }, { 4, 5, 6 } }; s.Add(0); s.Add(0); d.Add(1); d.Add(2); List<int> path = new List<int>(); countPaths(s[0], s[1], path, mat); }} // This code is contributed by Rajput-Ji
<script> // JavaScript code for the above approach let mat; let s; let d; let m = 2, n = 3; // Function to print all the paths function printVector(path) { let cnt = path.length; for (let i = 0; i < cnt; i += 2) document.write(mat[path[i]][path[i + 1]] + " ") document.write("<br>") } // Function to find all the paths recursively function countPaths(i, j, path) { // Base Case if (i > d[0] || j > d[1]) return; path.push(i); path.push(j); // Destination is reached if (i == d[0] && j == d[1]) { printVector(path); path.pop(); path.pop(); return; } // Calling the function countPaths(i, j + 1, path); countPaths(i + 1, j, path); path.pop(); path.pop(); } // DriverCode mat = [[1, 2, 3], [4, 5, 6]]; s = [0, 0]; d = [1, 2]; let path = []; countPaths(s[0], s[1], path); // This code is contributed by Potta Lokesh </script>
1 2 3 6
1 2 5 6
1 4 5 6
Time Complexity: O(2n+m)Auxiliary Space: O(1)
lokeshpotta20
_saurabh_jaiswal
Rajput-Ji
Backtracking
Matrix
Recursion
Recursion
Matrix
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Backtracking and Branch-N-Bound technique
Designing algorithm to solve Ball Sort Puzzle
Rat in a Maze | Backtracking using Stack
Match a pattern and String without using regular expressions
N-Queen Problem | Local Search using Hill climbing with random neighbour
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Find the number of islands | Set 1 (Using DFS) | [
{
"code": null,
"e": 24567,
"s": 24539,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24740,
"s": 24567,
"text": "Given a 2-D array mat[][], a source ‘s’ and a destination ‘d’, print all unique paths from given ‘s’ to ‘d’. From each cell, you can either move only to the right or down."
},
{
"code": null,
"e": 24750,
"s": 24740,
"text": "Examples:"
},
{
"code": null,
"e": 24846,
"s": 24750,
"text": "Input: mat[][] = {{1, 2, 3}, {4, 5, 6}}, s[] = {0, 0}, d[]={1, 2}Output: 1 4 5 61 2 5 61 2 3 6"
},
{
"code": null,
"e": 24919,
"s": 24846,
"text": "Input: mat[][] = {{1, 2}, {3, 4}}, s[] = {0, 1}, d[] = {1, 1}Output: 2 4"
},
{
"code": null,
"e": 25202,
"s": 24919,
"text": "Approach: Use recursion to move first right then down from each cell in the path of the matrix mat[][], starting from source, and store each value in a vector. If the destination is reached, print the vector as one of the possible paths. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25259,
"s": 25202,
"text": "If the current cell is out of the boundary, then return."
},
{
"code": null,
"e": 25313,
"s": 25259,
"text": "Push the current cell’s value into the vector path[]."
},
{
"code": null,
"e": 25382,
"s": 25313,
"text": "If the current cell is the destination, then print the current path."
},
{
"code": null,
"e": 25443,
"s": 25382,
"text": "Call the same function for the values {i+1, j} and {i, j+1}."
},
{
"code": null,
"e": 25494,
"s": 25443,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 25498,
"s": 25494,
"text": "C++"
},
{
"code": null,
"e": 25503,
"s": 25498,
"text": "Java"
},
{
"code": null,
"e": 25511,
"s": 25503,
"text": "Python3"
},
{
"code": null,
"e": 25514,
"s": 25511,
"text": "C#"
},
{
"code": null,
"e": 25525,
"s": 25514,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; vector<vector<int> > mat;vector<int> s;vector<int> d;int m = 2, n = 3; // Function to print all the pathsvoid printVector(vector<int> path){ int cnt = path.size(); for (int i = 0; i < cnt; i += 2) cout << mat[path[i]][path[i + 1]] << \" \"; cout << endl;} // Function to find all the paths recursivelyvoid countPaths(int i, int j, vector<int> path){ // Base Case if (i > d[0] || j > d[1]) return; path.push_back(i); path.push_back(j); // Destination is reached if (i == d[0] && j == d[1]) { printVector(path); return; } // Calling the function countPaths(i, j + 1, path); countPaths(i + 1, j, path);} // DriverCodeint main(){ mat = { { 1, 2, 3 }, { 4, 5, 6 } }; s = { 0, 0 }; d = { 1, 2 }; vector<int> path; countPaths(s[0], s[1], path); return 0;}",
"e": 26467,
"s": 25525,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ static Vector<Integer> s = new Vector<>(); static Vector<Integer> d = new Vector<>(); static int m = 2, n = 3; // Function to print all the paths static void printVector(Vector<Integer> path, int[][] mat) { int cnt = path.size(); for (int i = 0; i < cnt; i += 2) System.out.print(mat[path.get(i)][path.get(i + 1)]+ \" \"); System.out.println(); } // Function to find all the paths recursively static void countPaths(int i, int j, Vector<Integer> path, int[][]mat) { // Base Case if (i > d.get(0) || j > d.get(1)) return; path.add(i); path.add(j); // Destination is reached if (i == d.get(0) && j == d.get(1)) { printVector(path,mat); path.remove(path.size()-1); path.remove(path.size()-1); return; } // Calling the function countPaths(i, j + 1, path,mat); countPaths(i + 1, j, path,mat); path.remove(path.size()-1); path.remove(path.size()-1); } // DriverCode public static void main(String[] args) { int[][] mat = {{ 1, 2, 3 }, { 4, 5, 6 } }; s.add(0); s.add(0); d.add(1); d.add(2); Vector<Integer> path = new Vector<>(); countPaths(s.get(0), s.get(1), path, mat); }} // This code is contributed by Rajput-Ji.",
"e": 27781,
"s": 26467,
"text": null
},
{
"code": "# Python code for the above approachmat = Nones = Noned = Nonem = 2n = 3 # Function to print all the pathsdef printVector(path): cnt = len(path) for i in range(0, cnt, 2): print(mat[path[i]][path[i + 1]], end=\" \") print(\"\") # Function to find all the paths recursivelydef countPaths(i, j, path): # Base Case if (i > d[0] or j > d[1]): return path.append(i) path.append(j) # Destination is reached if (i == d[0] and j == d[1]): printVector(path) path.pop() path.pop() return # Calling the function countPaths(i, j + 1, path) countPaths(i + 1, j, path) path.pop() path.pop() # DriverCodemat = [[1, 2, 3], [4, 5, 6]]s = [0, 0]d = [1, 2]path = [] countPaths(s[0], s[1], path) # This code is contributed by Saurabh Jaiswal",
"e": 28595,
"s": 27781,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static List<int> s = new List<int>(); static List<int> d = new List<int>(); static int m = 2, n = 3; // Function to print all the paths static void printList(List<int> path, int[,] mat) { int cnt = path.Count; for (int i = 0; i < cnt; i += 2) Console.Write(mat[path[i],path[i + 1]] + \" \"); Console.WriteLine(); } // Function to find all the paths recursively static void countPaths(int i, int j, List<int> path, int[,] mat) { // Base Case if (i > d[0] || j > d[1]) return; path.Add(i); path.Add(j); // Destination is reached if (i == d[0] && j == d[1]) { printList(path, mat); path.RemoveAt(path.Count - 1); path.RemoveAt(path.Count - 1); return; } // Calling the function countPaths(i, j + 1, path, mat); countPaths(i + 1, j, path, mat); path.RemoveAt(path.Count - 1); path.RemoveAt(path.Count - 1); } // DriverCode public static void Main(String[] args) { int[,] mat = { { 1, 2, 3 }, { 4, 5, 6 } }; s.Add(0); s.Add(0); d.Add(1); d.Add(2); List<int> path = new List<int>(); countPaths(s[0], s[1], path, mat); }} // This code is contributed by Rajput-Ji",
"e": 29894,
"s": 28595,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach let mat; let s; let d; let m = 2, n = 3; // Function to print all the paths function printVector(path) { let cnt = path.length; for (let i = 0; i < cnt; i += 2) document.write(mat[path[i]][path[i + 1]] + \" \") document.write(\"<br>\") } // Function to find all the paths recursively function countPaths(i, j, path) { // Base Case if (i > d[0] || j > d[1]) return; path.push(i); path.push(j); // Destination is reached if (i == d[0] && j == d[1]) { printVector(path); path.pop(); path.pop(); return; } // Calling the function countPaths(i, j + 1, path); countPaths(i + 1, j, path); path.pop(); path.pop(); } // DriverCode mat = [[1, 2, 3], [4, 5, 6]]; s = [0, 0]; d = [1, 2]; let path = []; countPaths(s[0], s[1], path); // This code is contributed by Potta Lokesh </script>",
"e": 31078,
"s": 29894,
"text": null
},
{
"code": null,
"e": 31107,
"s": 31081,
"text": "1 2 3 6 \n1 2 5 6 \n1 4 5 6"
},
{
"code": null,
"e": 31155,
"s": 31109,
"text": "Time Complexity: O(2n+m)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31169,
"s": 31155,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31186,
"s": 31169,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31196,
"s": 31186,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31209,
"s": 31196,
"text": "Backtracking"
},
{
"code": null,
"e": 31216,
"s": 31209,
"text": "Matrix"
},
{
"code": null,
"e": 31226,
"s": 31216,
"text": "Recursion"
},
{
"code": null,
"e": 31236,
"s": 31226,
"text": "Recursion"
},
{
"code": null,
"e": 31243,
"s": 31236,
"text": "Matrix"
},
{
"code": null,
"e": 31256,
"s": 31243,
"text": "Backtracking"
},
{
"code": null,
"e": 31354,
"s": 31256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31363,
"s": 31354,
"text": "Comments"
},
{
"code": null,
"e": 31376,
"s": 31363,
"text": "Old Comments"
},
{
"code": null,
"e": 31437,
"s": 31376,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 31483,
"s": 31437,
"text": "Designing algorithm to solve Ball Sort Puzzle"
},
{
"code": null,
"e": 31524,
"s": 31483,
"text": "Rat in a Maze | Backtracking using Stack"
},
{
"code": null,
"e": 31585,
"s": 31524,
"text": "Match a pattern and String without using regular expressions"
},
{
"code": null,
"e": 31658,
"s": 31585,
"text": "N-Queen Problem | Local Search using Hill climbing with random neighbour"
},
{
"code": null,
"e": 31693,
"s": 31658,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 31737,
"s": 31693,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 31773,
"s": 31737,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 31835,
"s": 31773,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
}
] |
Java Program to Convert Char to Int - GeeksforGeeks | 09 Feb, 2022
Given a character in Java, your task is to write a Java program to convert this given character into an integer. In Java, we can convert the Char to Int using different approaches.
If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character.getNumericValue(char) method. Alternatively, we can use String.valueOf(char) method.
Examples:
Input: ch = '3'
Output: 3
Input: ch = '9'
Output: 9
Integer: The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless there is no problem with memory.
Example:
int a = 10
Character: The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).The char data type is used to store characters.
Example:
char ch = 'c'
There are numerous approaches to do the conversion of Char datatype to Integer (int) datatype. A few of them are listed below.
Using ASCII Values
Using String.valueOf() Method
Using Character.getNumericValue() Method
This method uses TypeCasting to get the ASCII value of the given character. The respective integer is calculated from this ASCII value by subtracting it from the ASCII value of 0. In other words, this method converts the char to int by finding the difference between the ASCII value of this char and the ASCII value of 0.
Example:
Java
// Java program to convert// char to int using ASCII value class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println("char value: " + ch); // Converting ch to it's int value int a = ch - '0'; System.out.println("int value: " + a); }}
char value: 3
int value: 3
The method valueOf() of class String can convert various types of values to a String value. It can convert int, char, long, boolean, float, double, object, and char array to String, which can be converted to an int value by using the Integer.parseInt() method. The below program illustrates the use of the valueOf() method.
Example:
Java
// Java program to convert// char to int using String.valueOf() class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println("char value: " + ch); // Converting the character to it's int value int a = Integer.parseInt(String.valueOf(ch)); System.out.println("int value: " + a); }}
char value: 3
int value: 3
The getNumericValue() method of class Character is used to get the integer value of any specific character. For example, the character ‘9’ will return an int having a value of 9. The below program illustrates the use of the getNumericValue() method.
Example:
Java
// Java program to convert char to int// using Character.getNumericValue() class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println("char value: " + ch); // Converting the Character to it's int value int a = Character.getNumericValue(ch); System.out.println("int value: " + a); }}
char value: 3
int value: 3
nishkarshgandhi
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 24129,
"s": 23948,
"text": "Given a character in Java, your task is to write a Java program to convert this given character into an integer. In Java, we can convert the Char to Int using different approaches."
},
{
"code": null,
"e": 24399,
"s": 24129,
"text": "If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character.getNumericValue(char) method. Alternatively, we can use String.valueOf(char) method."
},
{
"code": null,
"e": 24409,
"s": 24399,
"text": "Examples:"
},
{
"code": null,
"e": 24462,
"s": 24409,
"text": "Input: ch = '3'\nOutput: 3\n\nInput: ch = '9'\nOutput: 9"
},
{
"code": null,
"e": 24854,
"s": 24462,
"text": "Integer: The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless there is no problem with memory."
},
{
"code": null,
"e": 24863,
"s": 24854,
"text": "Example:"
},
{
"code": null,
"e": 24874,
"s": 24863,
"text": "int a = 10"
},
{
"code": null,
"e": 25069,
"s": 24874,
"text": "Character: The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\\u0000’ (or 0) to ‘\\uffff’ (or 65,535 inclusive).The char data type is used to store characters."
},
{
"code": null,
"e": 25078,
"s": 25069,
"text": "Example:"
},
{
"code": null,
"e": 25092,
"s": 25078,
"text": "char ch = 'c'"
},
{
"code": null,
"e": 25219,
"s": 25092,
"text": "There are numerous approaches to do the conversion of Char datatype to Integer (int) datatype. A few of them are listed below."
},
{
"code": null,
"e": 25238,
"s": 25219,
"text": "Using ASCII Values"
},
{
"code": null,
"e": 25268,
"s": 25238,
"text": "Using String.valueOf() Method"
},
{
"code": null,
"e": 25309,
"s": 25268,
"text": "Using Character.getNumericValue() Method"
},
{
"code": null,
"e": 25631,
"s": 25309,
"text": "This method uses TypeCasting to get the ASCII value of the given character. The respective integer is calculated from this ASCII value by subtracting it from the ASCII value of 0. In other words, this method converts the char to int by finding the difference between the ASCII value of this char and the ASCII value of 0."
},
{
"code": null,
"e": 25640,
"s": 25631,
"text": "Example:"
},
{
"code": null,
"e": 25645,
"s": 25640,
"text": "Java"
},
{
"code": "// Java program to convert// char to int using ASCII value class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println(\"char value: \" + ch); // Converting ch to it's int value int a = ch - '0'; System.out.println(\"int value: \" + a); }}",
"e": 25996,
"s": 25645,
"text": null
},
{
"code": null,
"e": 26023,
"s": 25996,
"text": "char value: 3\nint value: 3"
},
{
"code": null,
"e": 26348,
"s": 26023,
"text": "The method valueOf() of class String can convert various types of values to a String value. It can convert int, char, long, boolean, float, double, object, and char array to String, which can be converted to an int value by using the Integer.parseInt() method. The below program illustrates the use of the valueOf() method."
},
{
"code": null,
"e": 26358,
"s": 26348,
"text": "Example: "
},
{
"code": null,
"e": 26363,
"s": 26358,
"text": "Java"
},
{
"code": "// Java program to convert// char to int using String.valueOf() class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println(\"char value: \" + ch); // Converting the character to it's int value int a = Integer.parseInt(String.valueOf(ch)); System.out.println(\"int value: \" + a); }}",
"e": 26756,
"s": 26363,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26756,
"text": "char value: 3\nint value: 3"
},
{
"code": null,
"e": 27033,
"s": 26783,
"text": "The getNumericValue() method of class Character is used to get the integer value of any specific character. For example, the character ‘9’ will return an int having a value of 9. The below program illustrates the use of the getNumericValue() method."
},
{
"code": null,
"e": 27043,
"s": 27033,
"text": "Example: "
},
{
"code": null,
"e": 27048,
"s": 27043,
"text": "Java"
},
{
"code": "// Java program to convert char to int// using Character.getNumericValue() class GFG { public static void main(String[] args) { // Initializing a character(ch) char ch = '3'; System.out.println(\"char value: \" + ch); // Converting the Character to it's int value int a = Character.getNumericValue(ch); System.out.println(\"int value: \" + a); }}",
"e": 27447,
"s": 27048,
"text": null
},
{
"code": null,
"e": 27474,
"s": 27447,
"text": "char value: 3\nint value: 3"
},
{
"code": null,
"e": 27490,
"s": 27474,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 27495,
"s": 27490,
"text": "Java"
},
{
"code": null,
"e": 27509,
"s": 27495,
"text": "Java Programs"
},
{
"code": null,
"e": 27514,
"s": 27509,
"text": "Java"
},
{
"code": null,
"e": 27612,
"s": 27514,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27627,
"s": 27612,
"text": "Stream In Java"
},
{
"code": null,
"e": 27673,
"s": 27627,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27694,
"s": 27673,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27713,
"s": 27694,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27743,
"s": 27713,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27787,
"s": 27743,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27813,
"s": 27787,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27847,
"s": 27813,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27894,
"s": 27847,
"text": "Implementing a Linked List in Java using Class"
}
] |
C++ Program to Check Whether Topological Sorting can be Performed in a Graph | In a Directed Acyclic Graph, we can sort vertices in linear order using topological sort.
Topological sort is only work on Directed Acyclic Graph. In a Directed Acyclic Graph (DAG), there can be more than one topological sort.
In the following C++ program, we shall perform topological sort to check existence of a cycle in a graph.
Begin
Define function Topo_Sort()
Declare x to the integer datatype, vstd[] of the Boolean array and Stack as a stack.
Pass them as parameter.
Initialize vstd[x] = true to mark the current node as vstd.
Declare an iterator i.
for (i = a[x].begin(); i != a[x].end(); ++i)
if (!vstd[*i]) then
Call Topo_Sort(*i, vstd, Stack) function.
Call push() function to insert values into stack.
End.
#include<iostream>
#include <list>
#include <stack>
using namespace std;
class grph { // Class to represent a graph
int ver;
list<int> *a; // Pointer to an array containing adjacency listsList
void Topo_Sort(int x, bool vstd[], stack<int> &Stack); // A function used by TopologicalSort
public:
grph(int ver); // Constructor of grpf
void Insert_Edge(int x, int y); // to insert an edge to graph
void Topol_Sort(); // prints a Topological Sort of the complete graph
};
grph::grph(int ver) {
this->ver = ver;
a = new list<int>[ver];
}
void grph::Insert_Edge(int x, int y) {
a[x].push_back(y); // Add y to x’s list.
}
// A recursive function used by Topol_Sort
void grph::Topo_Sort(int x, bool vstd[], stack<int> &Stack) {
vstd[x] = true; // Mark the current node as vstd.
list<int>::iterator i;
for (i = a[x].begin(); i != a[x].end(); ++i)
if (!vstd[*i])
Topo_Sort(*i, vstd, Stack);
// Push current vertex to stack which stores result
Stack.push(x);
}
void grph::Topol_Sort() {
stack<int> Stack;
// Mark all the vertices as not vstd
bool *vstd = new bool[ver];
for (int i = 0; i < ver; i++)
vstd[i] = false;
for (int i = 0; i < ver; i++)
if (vstd[i] == false)
Topo_Sort(i, vstd, Stack);
while (Stack.empty() == false) {
cout << Stack.top() << " ";
Stack.pop();
}
}
int main() {
grph g(6); // Create a graph given in the above diagram
g.Insert_Edge(5, 2);
g.Insert_Edge(5, 0);
g.Insert_Edge(4, 0);
g.Insert_Edge(4, 1);
g.Insert_Edge(2, 3);
g.Insert_Edge(3, 1);
cout << "Topological Sort of the graph is: \n";
g.Topol_Sort();
return 0;
}
Topological Sort of the graph is:
5 4 2 3 1 0 | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "In a Directed Acyclic Graph, we can sort vertices in linear order using topological sort."
},
{
"code": null,
"e": 1289,
"s": 1152,
"text": "Topological sort is only work on Directed Acyclic Graph. In a Directed Acyclic Graph (DAG), there can be more than one topological sort."
},
{
"code": null,
"e": 1395,
"s": 1289,
"text": "In the following C++ program, we shall perform topological sort to check existence of a cycle in a graph."
},
{
"code": null,
"e": 1837,
"s": 1395,
"text": "Begin\n Define function Topo_Sort()\n Declare x to the integer datatype, vstd[] of the Boolean array and Stack as a stack.\n Pass them as parameter.\n Initialize vstd[x] = true to mark the current node as vstd.\n Declare an iterator i.\n for (i = a[x].begin(); i != a[x].end(); ++i)\n if (!vstd[*i]) then\n Call Topo_Sort(*i, vstd, Stack) function.\n Call push() function to insert values into stack.\nEnd."
},
{
"code": null,
"e": 3517,
"s": 1837,
"text": "#include<iostream>\n#include <list>\n#include <stack>\nusing namespace std;\nclass grph { // Class to represent a graph\n int ver;\n list<int> *a; // Pointer to an array containing adjacency listsList\n void Topo_Sort(int x, bool vstd[], stack<int> &Stack); // A function used by TopologicalSort\n public:\n grph(int ver); // Constructor of grpf\n void Insert_Edge(int x, int y); // to insert an edge to graph\n void Topol_Sort(); // prints a Topological Sort of the complete graph\n};\ngrph::grph(int ver) {\n this->ver = ver;\n a = new list<int>[ver];\n}\nvoid grph::Insert_Edge(int x, int y) {\n a[x].push_back(y); // Add y to x’s list.\n}\n// A recursive function used by Topol_Sort\nvoid grph::Topo_Sort(int x, bool vstd[], stack<int> &Stack) {\n vstd[x] = true; // Mark the current node as vstd.\n list<int>::iterator i;\n for (i = a[x].begin(); i != a[x].end(); ++i)\n if (!vstd[*i])\n Topo_Sort(*i, vstd, Stack);\n // Push current vertex to stack which stores result\n Stack.push(x);\n}\nvoid grph::Topol_Sort() {\n stack<int> Stack;\n // Mark all the vertices as not vstd\n bool *vstd = new bool[ver];\n for (int i = 0; i < ver; i++)\n vstd[i] = false;\n for (int i = 0; i < ver; i++)\n if (vstd[i] == false)\n Topo_Sort(i, vstd, Stack);\n while (Stack.empty() == false) {\n cout << Stack.top() << \" \";\n Stack.pop();\n }\n}\nint main() {\n grph g(6); // Create a graph given in the above diagram\n g.Insert_Edge(5, 2);\n g.Insert_Edge(5, 0);\n g.Insert_Edge(4, 0);\n g.Insert_Edge(4, 1);\n g.Insert_Edge(2, 3);\n g.Insert_Edge(3, 1);\n cout << \"Topological Sort of the graph is: \\n\";\n g.Topol_Sort();\n return 0;\n}"
},
{
"code": null,
"e": 3563,
"s": 3517,
"text": "Topological Sort of the graph is:\n5 4 2 3 1 0"
}
] |
HTML5 Canvas - Scaling | HTML5 canvas provides scale(x, y) method which is used to increase or decrease the units in our canvas grid. This can be used to draw scaled down or enlarged shapes and bitmaps.
This method takes two parameters where x is the scale factor in the horizontal direction and y is the scale factor in the vertical direction. Both parameters must be positive numbers.
Values smaller than 1.0 reduce the unit size and values larger than 1.0 increase the unit size. Setting the scaling factor to precisely 1.0 doesn't affect the unit size.
Following is a simple example which uses spirograph function to draw nine shapes with different scaling factors.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
ctx.strokeStyle = "#fc0";
ctx.lineWidth = 1.5;
ctx.fillRect(0,0,300,300);
// Uniform scaling
ctx.save()
ctx.translate(50,50);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(133.333,0);
ctx.scale(0.75,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
// Non uniform scaling (y direction)
ctx.strokeStyle = "#0cf";
ctx.save()
ctx.translate(50,150);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.translate(100,0);
ctx.scale(1,0.75);
drawSpirograph(ctx,22,6,5);
ctx.restore();
// Non uniform scaling (x direction)
ctx.strokeStyle = "#cf0";
ctx.save()
ctx.translate(50,250);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.translate(133.333,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.translate(177.777,0);
ctx.scale(0.75,1);
drawSpirograph(ctx,22,6,5);
ctx.restore();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
function drawSpirograph(ctx,R,r,O) {
var x1 = R-O;
var y1 = 0;
var i = 1;
ctx.beginPath();
ctx.moveTo(x1,y1);
do {
if (i>20000) break;
var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
ctx.lineTo(x2,y2);
x1 = x2;
y1 = y2;
i++;
}
while (x2 != R-O && y2 != 0 );
ctx.stroke();
}
</script>
</head>
<body onload = "drawShape();">
<canvas id = "mycanvas" width = "400" height = "400"></canvas>
</body>
</html>
The above example would produce following result −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2786,
"s": 2608,
"text": "HTML5 canvas provides scale(x, y) method which is used to increase or decrease the units in our canvas grid. This can be used to draw scaled down or enlarged shapes and bitmaps."
},
{
"code": null,
"e": 2970,
"s": 2786,
"text": "This method takes two parameters where x is the scale factor in the horizontal direction and y is the scale factor in the vertical direction. Both parameters must be positive numbers."
},
{
"code": null,
"e": 3140,
"s": 2970,
"text": "Values smaller than 1.0 reduce the unit size and values larger than 1.0 increase the unit size. Setting the scaling factor to precisely 1.0 doesn't affect the unit size."
},
{
"code": null,
"e": 3253,
"s": 3140,
"text": "Following is a simple example which uses spirograph function to draw nine shapes with different scaling factors."
},
{
"code": null,
"e": 6338,
"s": 3253,
"text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n ctx.strokeStyle = \"#fc0\";\n ctx.lineWidth = 1.5;\n ctx.fillRect(0,0,300,300);\n \n // Uniform scaling\n ctx.save()\n ctx.translate(50,50);\n drawSpirograph(ctx,22,6,5);\n ctx.translate(100,0);\n ctx.scale(0.75,0.75);\n drawSpirograph(ctx,22,6,5);\n \n ctx.translate(133.333,0);\n ctx.scale(0.75,0.75);\n drawSpirograph(ctx,22,6,5);\n ctx.restore();\n \n // Non uniform scaling (y direction)\n ctx.strokeStyle = \"#0cf\";\n ctx.save()\n ctx.translate(50,150);\n ctx.scale(1,0.75);\n drawSpirograph(ctx,22,6,5);\n \n ctx.translate(100,0);\n ctx.scale(1,0.75);\n drawSpirograph(ctx,22,6,5);\n \n ctx.translate(100,0);\n ctx.scale(1,0.75);\n drawSpirograph(ctx,22,6,5);\n ctx.restore();\n \n // Non uniform scaling (x direction)\n ctx.strokeStyle = \"#cf0\";\n ctx.save()\n ctx.translate(50,250);\n ctx.scale(0.75,1);\n drawSpirograph(ctx,22,6,5);\n \n ctx.translate(133.333,0);\n ctx.scale(0.75,1);\n drawSpirograph(ctx,22,6,5);\n \n ctx.translate(177.777,0);\n ctx.scale(0.75,1);\n drawSpirograph(ctx,22,6,5);\n ctx.restore();\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n \n function drawSpirograph(ctx,R,r,O) {\n var x1 = R-O;\n var y1 = 0;\n var i = 1;\n \n ctx.beginPath();\n ctx.moveTo(x1,y1);\n \n do {\n if (i>20000) break;\n var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))\n var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))\n ctx.lineTo(x2,y2);\n \n x1 = x2;\n y1 = y2;\n i++;\n }\n \n while (x2 != R-O && y2 != 0 );\n ctx.stroke();\n }\n </script>\n </head>\n \n <body onload = \"drawShape();\">\n <canvas id = \"mycanvas\" width = \"400\" height = \"400\"></canvas>\n </body>\n \n</html>"
},
{
"code": null,
"e": 6390,
"s": 6338,
"text": "The above example would produce following result −"
},
{
"code": null,
"e": 6423,
"s": 6390,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6437,
"s": 6423,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6472,
"s": 6437,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6486,
"s": 6472,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6521,
"s": 6486,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6538,
"s": 6521,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6573,
"s": 6538,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6604,
"s": 6573,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6637,
"s": 6604,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6668,
"s": 6637,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6703,
"s": 6668,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6734,
"s": 6703,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6741,
"s": 6734,
"text": " Print"
},
{
"code": null,
"e": 6752,
"s": 6741,
"text": " Add Notes"
}
] |
C++ | Constructors | Question 16 - GeeksforGeeks | 28 Jun, 2021
Predict the output of following program?
#include <iostream>using namespace std;class Test{private: int x;public: Test(int i) { x = i; cout << "Called" << endl; }}; int main(){ Test t(20); t = 30; // conversion constructor is called here. return 0;}
(A) Compiler Error(B)
Called
Called
(C)
Called
Answer: (B)Explanation: If a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed.
A conversion constructor can be called anywhere when the type of single argument is assigned to the object. The output of the given program is
Called
Called
Quiz of this Question
C++-Constructors
Constructors
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Inheritance | Question 7
C++ | Virtual Functions | Question 12
C++ | new and delete | Question 1 | [
{
"code": null,
"e": 24442,
"s": 24414,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24483,
"s": 24442,
"text": "Predict the output of following program?"
},
{
"code": "#include <iostream>using namespace std;class Test{private: int x;public: Test(int i) { x = i; cout << \"Called\" << endl; }}; int main(){ Test t(20); t = 30; // conversion constructor is called here. return 0;}",
"e": 24728,
"s": 24483,
"text": null
},
{
"code": null,
"e": 24750,
"s": 24728,
"text": "(A) Compiler Error(B)"
},
{
"code": null,
"e": 24764,
"s": 24750,
"text": "Called\nCalled"
},
{
"code": null,
"e": 24768,
"s": 24764,
"text": "(C)"
},
{
"code": null,
"e": 24775,
"s": 24768,
"text": "Called"
},
{
"code": null,
"e": 25012,
"s": 24775,
"text": "Answer: (B)Explanation: If a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed."
},
{
"code": null,
"e": 25155,
"s": 25012,
"text": "A conversion constructor can be called anywhere when the type of single argument is assigned to the object. The output of the given program is"
},
{
"code": null,
"e": 25169,
"s": 25155,
"text": "Called\nCalled"
},
{
"code": null,
"e": 25191,
"s": 25169,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25208,
"s": 25191,
"text": "C++-Constructors"
},
{
"code": null,
"e": 25221,
"s": 25208,
"text": "Constructors"
},
{
"code": null,
"e": 25232,
"s": 25221,
"text": "C Language"
},
{
"code": null,
"e": 25241,
"s": 25232,
"text": "C++ Quiz"
},
{
"code": null,
"e": 25339,
"s": 25241,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25348,
"s": 25339,
"text": "Comments"
},
{
"code": null,
"e": 25361,
"s": 25348,
"text": "Old Comments"
},
{
"code": null,
"e": 25396,
"s": 25361,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25424,
"s": 25396,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25464,
"s": 25424,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25496,
"s": 25464,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25542,
"s": 25496,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25580,
"s": 25542,
"text": "C++ | Exception Handling | Question 3"
},
{
"code": null,
"e": 25614,
"s": 25580,
"text": "C++ | new and delete | Question 4"
},
{
"code": null,
"e": 25645,
"s": 25614,
"text": "C++ | Inheritance | Question 7"
},
{
"code": null,
"e": 25683,
"s": 25645,
"text": "C++ | Virtual Functions | Question 12"
}
] |
Power BI: Filter vs Row Context. ... a concept made simple. | by Peter Hui | Towards Data Science | I am what you term a “super commuter”. I used to wake up at 5 am. Leave the door at 5:30 am, catch the train and arrive at work by 8:00 am. It sounds like a nightmare. I love my job and I love it enough to do that. Then the pandemic came and it’s not something I have to do as often anymore. I am thankful of that, but what does this have to do with Power BI filter and row context?
You see, filter and row context can be seen in common situations if you know what you are looking for. I ride the train. The train is divided into different coaches and within each coach there are two different types of seats. There are the window seats and aisle seats.
I am a very visual person. I will draw out what I mean here.
Here is my attempt to draw a train in Excel. Here you can see that in this train there are 3 coaches and a controller room.
Now, what does filter and row context mean here?
Let’s pretend you are a fare inspector. You need to find a family on the train and find out how much they had spent on the fares. You know they ride in the first coach and they are all sitting at window seats.
In this scenario, you will need to go to the first coach and go to the window seats and tally up their ticket prices. This, in its simplest form, demonstrates filter context and row context.
Here the filter context would be the first coach and window seats. The row context would be the individual seats. The tally of how much they have spent would be the aggregation.
If you translate this into Power BI, this would be a measure of something like this.
A =SUMX ( FILTER ( Train, Coach == "First" && Seats == "Windows" && Family == "Smith" ), [Ticket_Price])
Here you would tell Power BI to go to the first coach, go down the window seats, find the family group — this is the filter context. The next question is equally, if not more important.
What do you want to do with this? Power BI goes to the location but doesn’t know what to do. It needs to know what to do when it gets there! This is row context. Here with SUMX, you are telling Power BI to sum up, row by row, or in our metaphor, seat by seat, the ticket price.
Now for another example, what if I want to know, in the second coach, the total price of the window seats and aisle seats by occupancy?
You, being the fare inspector, would once again go to the second coach, walk to the window seats and aisle seats. Now what do we do? Now we need row context. What are we doing by row? We need to add up the cost of the window seats and aisle seats. This is the SUMX in Power BI. You will add up the price by window seat and add the price of the aisle seat, and move on to the next row and do the same.
Basically, that is the filter and row context. In Power BI, you are no longer looking at trains but rather looking at tables. You will need to filter tables by certain criteria and then the aggregation.
Here, when users filter, likely in a visual, they will slice by the coach numbers and style, whether it is occupied etc. This will be the filter context. Finally, to calculate the Price*Promotion would be the row context to which it applies.
Okay, now what about all these? ALLEXCEPT, ALLSELECTED and ALL? What do these terms mean?
Let’s go back to our trains. You are the fare inspector but now you have an assistant. This assistant will help you by recording your totals by group. That is the ALLEXCEPT function in Power BI.
Visually, you can see this on the train again.
As a table in Power BI, it will look something like this.
Think of these filter functions as your helpers to change the way you can tally up your data. ALLEXCEPT will help you group according to your criteria, ALL will remove any filters you have specified and ALLSELECTED will use user selections to create filters.
I won’t go through all of this, but the concept is the same, they act as assistants to your task. In Microsoft terms, they change the “context” of your filters.
I hope this helps to clarify what filter context and row context mean in Power BI. Now of course, this is just one train. This only helps to illustrate a simple concept, you may see many trains and joined on the same track etc. The concept is the same.
I will attempt to explain this in my next article :)
I hope this helps in your data journey! | [
{
"code": null,
"e": 554,
"s": 171,
"text": "I am what you term a “super commuter”. I used to wake up at 5 am. Leave the door at 5:30 am, catch the train and arrive at work by 8:00 am. It sounds like a nightmare. I love my job and I love it enough to do that. Then the pandemic came and it’s not something I have to do as often anymore. I am thankful of that, but what does this have to do with Power BI filter and row context?"
},
{
"code": null,
"e": 825,
"s": 554,
"text": "You see, filter and row context can be seen in common situations if you know what you are looking for. I ride the train. The train is divided into different coaches and within each coach there are two different types of seats. There are the window seats and aisle seats."
},
{
"code": null,
"e": 886,
"s": 825,
"text": "I am a very visual person. I will draw out what I mean here."
},
{
"code": null,
"e": 1010,
"s": 886,
"text": "Here is my attempt to draw a train in Excel. Here you can see that in this train there are 3 coaches and a controller room."
},
{
"code": null,
"e": 1059,
"s": 1010,
"text": "Now, what does filter and row context mean here?"
},
{
"code": null,
"e": 1269,
"s": 1059,
"text": "Let’s pretend you are a fare inspector. You need to find a family on the train and find out how much they had spent on the fares. You know they ride in the first coach and they are all sitting at window seats."
},
{
"code": null,
"e": 1460,
"s": 1269,
"text": "In this scenario, you will need to go to the first coach and go to the window seats and tally up their ticket prices. This, in its simplest form, demonstrates filter context and row context."
},
{
"code": null,
"e": 1638,
"s": 1460,
"text": "Here the filter context would be the first coach and window seats. The row context would be the individual seats. The tally of how much they have spent would be the aggregation."
},
{
"code": null,
"e": 1723,
"s": 1638,
"text": "If you translate this into Power BI, this would be a measure of something like this."
},
{
"code": null,
"e": 1834,
"s": 1723,
"text": "A =SUMX ( FILTER ( Train, Coach == \"First\" && Seats == \"Windows\" && Family == \"Smith\" ), [Ticket_Price])"
},
{
"code": null,
"e": 2020,
"s": 1834,
"text": "Here you would tell Power BI to go to the first coach, go down the window seats, find the family group — this is the filter context. The next question is equally, if not more important."
},
{
"code": null,
"e": 2298,
"s": 2020,
"text": "What do you want to do with this? Power BI goes to the location but doesn’t know what to do. It needs to know what to do when it gets there! This is row context. Here with SUMX, you are telling Power BI to sum up, row by row, or in our metaphor, seat by seat, the ticket price."
},
{
"code": null,
"e": 2434,
"s": 2298,
"text": "Now for another example, what if I want to know, in the second coach, the total price of the window seats and aisle seats by occupancy?"
},
{
"code": null,
"e": 2835,
"s": 2434,
"text": "You, being the fare inspector, would once again go to the second coach, walk to the window seats and aisle seats. Now what do we do? Now we need row context. What are we doing by row? We need to add up the cost of the window seats and aisle seats. This is the SUMX in Power BI. You will add up the price by window seat and add the price of the aisle seat, and move on to the next row and do the same."
},
{
"code": null,
"e": 3038,
"s": 2835,
"text": "Basically, that is the filter and row context. In Power BI, you are no longer looking at trains but rather looking at tables. You will need to filter tables by certain criteria and then the aggregation."
},
{
"code": null,
"e": 3280,
"s": 3038,
"text": "Here, when users filter, likely in a visual, they will slice by the coach numbers and style, whether it is occupied etc. This will be the filter context. Finally, to calculate the Price*Promotion would be the row context to which it applies."
},
{
"code": null,
"e": 3370,
"s": 3280,
"text": "Okay, now what about all these? ALLEXCEPT, ALLSELECTED and ALL? What do these terms mean?"
},
{
"code": null,
"e": 3565,
"s": 3370,
"text": "Let’s go back to our trains. You are the fare inspector but now you have an assistant. This assistant will help you by recording your totals by group. That is the ALLEXCEPT function in Power BI."
},
{
"code": null,
"e": 3612,
"s": 3565,
"text": "Visually, you can see this on the train again."
},
{
"code": null,
"e": 3670,
"s": 3612,
"text": "As a table in Power BI, it will look something like this."
},
{
"code": null,
"e": 3929,
"s": 3670,
"text": "Think of these filter functions as your helpers to change the way you can tally up your data. ALLEXCEPT will help you group according to your criteria, ALL will remove any filters you have specified and ALLSELECTED will use user selections to create filters."
},
{
"code": null,
"e": 4090,
"s": 3929,
"text": "I won’t go through all of this, but the concept is the same, they act as assistants to your task. In Microsoft terms, they change the “context” of your filters."
},
{
"code": null,
"e": 4343,
"s": 4090,
"text": "I hope this helps to clarify what filter context and row context mean in Power BI. Now of course, this is just one train. This only helps to illustrate a simple concept, you may see many trains and joined on the same track etc. The concept is the same."
},
{
"code": null,
"e": 4396,
"s": 4343,
"text": "I will attempt to explain this in my next article :)"
}
] |
100 Helpful Python Tips You Can Learn Before Finishing Your Morning Coffee | by Fatos Morina | Towards Data Science | Python is quite popular nowadays, mainly due to its simplicity, and easiness to learn.
You can use it for a wide range of tasks like data science and machine learning, web development, scripting, automation, etc.
Since this is a pretty long article and you want to reach its end before you finish your coffee, why don’t we just start?
Okay, here we go...
Despite all the Python code that you have seen so far, chances are that you may have missed the following “for-else” which I also got to see for the first time a couple of weeks ago.
This is a “for-else” method of looping through a list, where despite having an iteration through a list, you also have an “else” condition, which is quite unusual.
This is not something that I have seen in other programming languages like Java, Ruby, or JavaScript.
Let’s see an example of how it looks in practice.
Let’s say that we are trying to check whether there are no odd numbers in a list.
Let’s iterate through it:
numbers = [2, 4, 6, 8, 1]for number in numbers: if number % 2 == 1: print(number) breakelse: print("No odd numbers")
In case we find an odd number, then that number will be printed since break will be executed and the else branch will be skipped.
Otherwise, if break is never executed, the execution flow will continue with the else branch.
In this example, we are going to print 1.
my_list = [1, 2, 3, 4, 5]one, two, three, four, five = my_list
import heapqscores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]print(heapq.nlargest(3, scores)) # [91, 87, 82]print(heapq.nsmallest(5, scores)) # [15, 33, 33, 49, 51]
We can extract all elements of a list using “*”:
my_list = [1, 2, 3, 4]print(my_list) # [1, 2, 3, 4]print(*my_list) # 1 2 3 4
This can be helpful in situations where we want to pass all elements of a list as method arguments:
def sum_of_elements(*arg): total = 0 for i in arg: total += i return totalresult = sum_of_elements(*[1, 2, 3, 4])print(result) # 10
_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]print(elements_in_the_middle) # [2, 3, 4, 5, 6, 7]
one, two, three, four = 1, 2, 3, 4
You can loop through the elements in a list in a single line in a very comprehensive way.
Let’s see that in action in the following example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]even_numbers = [number for number in numbers if number % 2 == 0]print(even_numbers) # [2, 4, 6, 8]
We can do the same with dictionaries, sets, and generators.
Let’s see another example, but now for dictionaries.
dictionary = {'first_element': 1, 'second_element': 2, 'third_element': 3, 'fourth_element': 4}odd_value_elements = {key: num for (key, num) in dictionary.items() if num % 2 == 1}print(odd_value_elements) # {'first_element': 1, 'third_element': 3}
This example was inspired by this article.
From the docs:
An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr(), grouping, type-safety, and a few other features.
Here is an example:
from enum import Enumclass Status(Enum): NO_STATUS = -1 NOT_STARTED = 0 IN_PROGRESS = 1 COMPLETED = 2print(Status.IN_PROGRESS.name) # IN_PROGRESSprint(Status.COMPLETED.value) # 2
string = "Abc"print(string * 5) # AbcAbcAbcAbcAbc
If you have a value and you want to compare it whether it is between two other values, there is a simple expression that you use in Math:
1 < x < 10
That is the algebraic expression that we learn in elementary school. However, you can also use that same expression in Python as well.
Yes, you heard that right. You have probably done comparisons of such form up until now:
1 < x and x < 10
For that, you simply need to use the following in Python:
1 < x < 10
This doesn’t work in Ruby, the programming language that was developed with the intention of making programmers happy. This turns out to be working in JavaScript as well.
I was really impressed seeing such a simple expression not being talked about more widely. At least, I haven’t seen it being mentioned that much.
This is available as of Python 3.9:
first_dictionary = {'name': 'Fatos', 'location': 'Munich'}second_dictionary = {'name': 'Fatos', 'surname': 'Morina', 'location': 'Bavaria, Munich'}result = first_dictionary | second_dictionaryprint(result) # {'name': 'Fatos', 'location': 'Bavaria, Munich', 'surname': 'Morina'}
books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')print(books.index('Mastery')) # 3
Let’s say that you get the input in a function that is a string, but it is supposed to be a list:
input = "[1,2,3]"
You don’t need it in that format. You need it to be a list:
input = [1,2,3]
Or maybe you the following response from an API call:
input = [[1, 2, 3], [4, 5, 6]]
Rather than bothering with complicated regular expressions, all you have to do is import the module ast and then call its method literal_eval:
import astdef string_to_list(string): return ast.literal_eval(string)
That’s all you need to do.
Now you will get the result as a list, or list of lists, namely like the following:
import astdef string_to_list(string): return ast.literal_eval(string)string = "[[1, 2, 3],[4, 5, 6]]"my_list = string_to_list(string)print(my_list) # [[1, 2, 3], [4, 5, 6]]
Let’s assume that you want to find the difference between 2 numbers. The difference is not commutative:
a - b != b -a
However, we may forget the ordering of the parameters which can cause “trivial” mistakes:
def subtract(a, b): return a - bprint((subtract(1, 3))) # -2print((subtract(3, 1))) # 2
To avoid such potential mistakes, we can simply use named parameters and the ordering of parameters doesn’t matter anymore:
def subtract(a, b): return a - bprint((subtract(a=1, b=3))) # -2print((subtract(b=3, a=1))) # -2
print(1, 2, 3, "a", "z", "this is here", "here is something else")
print("Hello", end="")print("World") # HelloWorldprint("Hello", end=" ")print("World") # Hello Worldprint('words', 'with', 'commas', 'in', 'between', sep=', ')# words, with, commas, in, between
You can do advanced printing quite easily:
print("29", "01", "2022", sep="/") # 29/01/2022print("name", "domain.com", sep="@") # [email protected]
four_letters = “abcd” # this works4_letters = “abcd” # this doesn’t work
+variable = “abcd” # this doesn’t work
number = 0110 # this doesn't work
This means, anywhere you want, as many times as you want in the name of a variable:
a______b = "abcd" # this works_a_b_c_d = "abcd" # this also works
I am not encouraging you to use it, but in case you see a weird naming of a variable like that, know that it is actually a valid name of a variable.
This way it can be easier to read them.
print(1_000_000_000) # 1000000000print(1_234_567) # 1234567
my_list = ['a', 'b', 'c', 'd']my_list.reverse()print(my_list) # ['d', 'c', 'b', 'a']
my_string = "This is just a sentence"print(my_string[0:5]) # This# Take three steps forwardprint(my_string[0:10:3]) # Tsse
my_string = "This is just a sentence"print(my_string[10:0:-1]) # suj si sih# Take two steps forwardprint(my_string[10:0:-2]) # sjs i
Indices indicating the start and end of slicing can be optional.
my_string = "This is just a sentence"print(my_string[4:]) # is just a sentenceprint(my_string[:3]) # Thi
print(3/2) # 1.5print(3//2) # 1
“is” checks whether 2 variables are pointing to the same object in memory.
“==” compares the equality of values that these 2 objects hold.
first_list = [1, 2, 3]second_list = [1, 2, 3]# Is their actual value the same?print(first_list == second_list) # True# Are they pointing to the same object in memoryprint(first_list is second_list) # False, since they have same values, but in different objects in memorythird_list = first_listprint(third_list is first_list) # True, since both point to the same object in memory
dictionary_one = {"a": 1, "b": 2}dictionary_two = {"c": 3, "d": 4}merged = {**dictionary_one, **dictionary_two}print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
first = "abc"second = "def"print(first < second) # Truesecond = "ab"print(first < second) # False
my_string = "abcdef"print(my_string.startswith("b")) # False
print(id(1)) # 4325776624print(id(2)) # 4325776656print(id("string")) # 4327978288
When we assign a variable to an immutable type such as integers, floats, strings, booleans, and tuples, then this variable points to an object in memory.
In case we assign to that variable another value, the original object is still in memory, but the variable pointing to it is lost:
number = 1print(id(number)) # 4325215472print(id(1)) # 4325215472number = 3print(id(number)) # 4325215536print(id(1)) # 4325215472
This was already mentioned in the previous point but wanted to emphasize it since this is quite important.
name = "Fatos"print(id(name)) # 4422282544name = "fatos"print(id(name)) # 4422346608
my_tuple = (1, 2, 3, 4)print(id(my_tuple)) # 4499290128my_tuple = ('a', 'b')print(id(my_tuple)) # 4498867584
This means that we can change the object without losing binding to it:
cities = ["Munich", "Zurich", "London"]print(id(cities)) # 4482699712cities.append("Berlin")print(id(cities)) # 4482699712
Here is another example with sets:
my_set = {1, 2, 3, 4}print(id(my_set)) # 4352726176my_set.add(5)print(id(my_set)) # 4352726176
This way, you can no longer modify it:
my_set = frozenset(['a', 'b', 'c', 'd'])my_set.add("a")
If you do that, an error will be thrown:
AttributeError: 'frozenset' object has no attribute 'add'
However, “elif” cannot stand on its own without an “if” step before it:
def check_number(number): if number > 0: return "Positive" elif number == 0: return "Zero" return "Negative"print(check_number(1)) # Positive
def check_if_anagram(first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() return sorted(first_word) == sorted(second_word)print(check_if_anagram("testinG", "Testing")) # Trueprint(check_if_anagram("Here", "Rehe")) # Trueprint(check_if_anagram("Know", "Now")) # False
print(ord("A")) # 65print(ord("B")) # 66print(ord("C")) # 66print(ord("a")) # 97
dictionary = {"a": 1, "b": 2, "c": 3}keys = dictionary.keys()print(list(keys)) # ['a', 'b', 'c']
dictionary = {"a": 1, "b": 2, "c": 3}values = dictionary.values()print(list(values)) # [1, 2, 3]
dictionary = {"a": 1, "b": 2, "c": 3}reversed_dictionary = {j: i for i, j in dictionary.items()}print(reversed) # {1: 'a', 2: 'b', 3: 'c'}
print(int(False)) # 0print(float(True)) # 1.0
“False” is 0, whereas “True” is 1.
x = 10y = 12result = (x - False)/(y * True)print(result) # 0.8333333333333334
print(bool(.0)) # Falseprint(bool(3)) # Trueprint(bool("-")) # Trueprint(bool("string")) # Trueprint(bool(" ")) # True
print(complex(10, 2)) # (10+2j)
You can also convert a number into a hexadecimal number:
print(hex(11)) # 0xb
If you use append(), you are going to insert new values from the right.
We can also use insert() to specify the index and the element where we want to insert this new element. In our case, we want to insert it in the first position, so we use 0 as the index:
my_list = [3, 4, 5]my_list.append(6)my_list.insert(0, 2)print(my_list) # [2, 3, 4, 5, 6]
You cannot have lambdas in more than one line.
Let’s try the following:
comparison = lambda x: if x > 3: print("x > 3") else: print("x is not greater than 3")
The following error is going to be thrown:
result = lambda x: if x > 3: ^SyntaxError: invalid syntax
Let’s try the following:
comparison = lambda x: "x > 3" if x > 3
We are going to get the following error:
comparison = lambda x: "x > 3" if x > 3 ^SyntaxError: invalid syntax
Noe that this is a feature of the conditional expression and not of the lambda itself.
my_list = [1, 2, 3, 4]odd = filter(lambda x: x % 2 == 1, my_list)print(list(odd)) # [1, 3]print(my_list) # [1, 2, 3, 4]
my_list = [1, 2, 3, 4]squared = map(lambda x: x ** 2, my_list)print(list(squared)) # [1, 4, 9, 16]print(my_list) # [1, 2, 3, 4]
for number in range(1, 10, 3): print(number, end=" ")# 1 4 7
So you don’t need to include it at all.
def range_with_zero(number): for i in range(0, number): print(i, end=' ')def range_with_no_zero(number): for i in range(number): print(i, end=' ')range_with_zero(3) # 0 1 2range_with_no_zero(3) # 0 1 2
If the length is greater than 0, then it is by default True, so you don’t really need to compare it with 0:
def get_element_with_comparison(my_list): if len(my_list) > 0: return my_list[0]def get_first_element(my_list): if len(my_list): return my_list[0]elements = [1, 2, 3, 4]first_result = get_element_with_comparison(elements)second_result = get_element_with_comparison(elements)print(first_result == second_result) # True
However, only the last one is called, since it overrides previous ones.
def get_address(): return "First address"def get_address(): return "Second address"def get_address(): return "Third address"print(get_address()) # Third address
class Engineer: def __init__(self, name): self.name = name self.__starting_salary = 62000dain = Engineer('Dain')print(dain._Engineer__starting_salary) # 62000
import sysprint(sys.getsizeof("bitcoin")) # 56
def get_sum(*arguments): result = 0 for i in arguments: result += i return resultprint(get_sum(1, 2, 3)) # 6print(get_sum(1, 2, 3, 4, 5)) # 15print(get_sum(1, 2, 3, 4, 5, 6, 7)) # 28
Calling the parent’s class initializer using super():
class Parent: def __init__(self, city, address): self.city = city self.address = addressclass Child(Parent): def __init__(self, city, address, university): super().__init__(city, address) self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')print(child.university) # ETH Zürich
Calling the parent’s class using the parent class’s name:
class Parent: def __init__(self, city, address): self.city = city self.address = addressclass Child(Parent): def __init__(self, city, address, university): Parent.__init__(self, city, address) self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')print(child.university) # ETH Zürich
Note that calls to parent initializers using __init__() and super() can only be used inside the child class’s initializer.
Whenever you use the + operator between two int data types, then you are going to find their sum.
However, when you use it between two string data types, you are going to merge them:
print(10 + 1) # Adding two integers using '+'print('first' + 'second') # Merging two strings '+'
This represents the operator overloading.
You can also use it with your own classes as well:
class Expenses: def __init__(self, rent, groceries): self.rent = rent self.groceries = groceries def __add__(self, other): return Expenses(self.rent + other.rent, self.groceries + other.groceries)april_expenses = Expenses(1000, 200)may_expenses = Expenses(1000, 300)total_expenses = april_expenses + may_expensesprint(total_expenses.rent) # 2000print(total_expenses.groceries) # 500
Here is another example of an operation overloadding that you can define yourself:
class Game: def __init__(self, score): self.score = score def __lt__(self, other): return self.score < other.scorefirst = Game(1)second = Game(2)print(first < second) # True
Similarly, like the two previous cases, we can override the __eq__() function based on our own needs:
class Journey: def __init__(self, location, destination, duration): self.location = location self.destination = destination self.duration = duration def __eq__(self, other): return ((self.location == other.location) and (self.destination == other.destination) and (self.duration == other.duration))first = Journey('Location A', 'Destination A', '30min')second = Journey('Location B', 'Destination B', '30min')print(first == second)
You can also analogously define:
__sub__() for -
__mul__() for *
__truediv__() for /
__ne__() for !=
__ge__() for >=
__gt__() for >
class Rectangle: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return repr('Rectangle with area=' + str(self.a * self.b))print(Rectangle(3, 4)) # 'Rectangle with area=12'
string = "This is just a sentence."result = string.swapcase()print(result) # tHIS IS JUST A SENTENCE.
string = " "result = string.isspace()print(result) # True
name = "Password"print(name.isalnum()) # True, because all characters are alphabetsname = "Secure Password "print(name.isalnum()) # False, because it contains whitespacesname = "S3cur3P4ssw0rd"print(name.isalnum()) # Truename = "133"print(name.isalnum()) # True, because all characters are numbers
string = "Name"print(string.isalpha()) # Truestring = "Firstname Lastname"print(string.isalpha()) # False, because it contains whitespacestring = “P4ssw0rd”print(string.isalpha()) # False, because it contains numbers
string = "This is a sentence with "# Remove trailing spaces from the rightprint(string.rstrip()) # "This is a sentence with"string = "this here is a sentence.....,,,,aaaaasd"print(string.rstrip(“.,dsa”)) # "this here is a sentence"
You can similarly remove characters from the left based on the argument:
string = "ffffffffFirst"print(string.lstrip(“f”)) # First
string = "seven"print(string.isdigit()) # Falsestring = "1337"print(string.isdigit()) # Truestring = "5a"print(string.isdigit()) # False, because it contains the character 'a'string = "2**5"print(string.isdigit()) # False
# 42673 in Arabic numeralsstring = "四二六七三"print(string.isdigit()) # Falseprint(string.isnumeric()) # True
string = "This is a sentence"print(string.istitle()) # Falsestring = "10 Python Tips"print(string.istitle()) # Truestring = "How to Print A String in Python"# False, because of the first characters being lowercase in "to" and "in"print(string.istitle())string = "PYTHON"print(string.istitle()) # False. It's titlelized version is "Python"
numbers = (1, 2, 3, 4)print(numbers[-1]) # 4print(numbers[-4]) # 1
mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])print(mixed_tuple[1]) # ['first', 'second', 'third']print(mixed_tuple[0]) # ('aaaaaaaaaa', 3, 4)
names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"]print(names.count("Besim")) # 2
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]slicing = slice(-4, None)# Getting the last 3 elements from the listprint(my_list[slicing]) # [4, 5, 6]# Getting only the third element starting from the rightprint(my_list[-3]) # 4
You can also use slice() for other usual slicing tasks, like:
string = "Data Science"# start = 1, stop = None (don't stop anywhere), step = 1# contains 1, 3 and 5 indicesslice_object = slice(5, None)print(string[slice_object]) # Science
my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.count('a')) # 3
my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.index('f')) # 2
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[::3]) # (1, 4, 7, 10)
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[3:]) # (4, 5, 6, 7, 8, 9, 10)
my_list = [1, 2, 3, 4]my_list.clear()print(my_list) # []my_set = {1, 2, 3}my_set.clear()print(my_set) # set()my_dict = {"a": 1, "b": 2}my_dict.clear()print(my_dict) # {}
One way is to use the method union() which returns a new set as a result of the joining:
first_set = {4, 5, 6}second_set = {1, 2, 3}print(first_set.union(second_set)) # {1, 2, 3, 4, 5, 6}
Another one is method update, which inserts the element of the second set into the first one:
first_set = {4, 5, 6}second_set = {1, 2, 3}first_set.update(second_set)print(first_set) # {1, 2, 3, 4, 5, 6}
def is_positive(number): print("Positive" if number > 0 else "Negative") # Positiveis_positive(-3)
math_points = 51biology_points = 78physics_points = 56history_points = 72my_conditions = [math_points > 50, biology_points > 50, physics_points > 50, history_points > 50]if all(my_conditions): print("Congratulations! You have passed all of the exams.")else: print("I am sorry, but it seems that you have to repeat at least one exam.")# Congratulations! You have passed all of the exams.
math_points = 51biology_points = 78physics_points = 56history_points = 72my_conditions = [math_points > 50, biology_points > 50, physics_points > 50, history_points > 50]if any(my_conditions): print("Congratulations! You have passed all of the exams.")else: print("I am sorry, but it seems that you have to repeat at least one exam.")# Congratulations! You have passed all of the exams.
print(bool("Non empty")) # Trueprint(bool("")) # False
print(bool([])) # Falseprint(bool(set([]))) # Falseprint(bool({})) # Falseprint(bool({"a": 1})) # True
print(bool(False)) # Falseprint(bool(None)) # Falseprint(bool(0)) # False
string = "string"def do_nothing(): string = "inside a method"do_nothing()print(string) # string
You need to use the access modifier global as well:
string = "string"def do_nothing(): global string string = "inside a method"do_nothing()print(string) # inside a method
from collections import Counterresult = Counter("Banana")print(result) # Counter({'a': 3, 'n': 2, 'B': 1})result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])print(result) # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})
from collections import Counterdef check_if_anagram(first_string, second_string): first_string = first_string.lower() second_string = second_string.lower() return Counter(first_string) == Counter(second_string)print(check_if_anagram('testinG', 'Testing')) # Trueprint(check_if_anagram('Here', 'Rehe')) # Trueprint(check_if_anagram('Know', 'Now')) # False
You can also check whether 2 strings are anagrams using sorted():
def check_if_anagram(first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() return sorted(first_word) == sorted(second_word)print(check_if_anagram("testinG", "Testing")) # Trueprint(check_if_anagram("Here", "Rehe")) # Trueprint(check_if_anagram("Know", "Now")) # False
from itertools import countmy_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']current_counter = count()string = "This is just a sentence."for i in string: if i in my_vowels: print(f"Current vowel: {i}") print(f"Number of vowels found so far: {next(current_counter)}")
This is the result in the console:
Current vowel: iNumber of vowels found so far: 0Current vowel: iNumber of vowels found so far: 1Current vowel: uNumber of vowels found so far: 2Current vowel: aNumber of vowels found so far: 3Current vowel: eNumber of vowels found so far: 4Current vowel: eNumber of vowels found so far: 5Current vowel: eNumber of vowels found so far: 6
Counter from the collections module by default doesn’t order elements based on their frequencies.
from collections import Counterresult = Counter([1, 2, 3, 2, 2, 2, 2])print(result) # Counter({2: 5, 1: 1, 3: 1})print(result.most_common()) # [(2, 5), (1, 1), (3, 1)]
my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']print(max(set(my_list), key=my_list.count)) # a
Here is the explanation from the docs:
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Maybe, an even more comprehensive description can be found here:
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won’t create copies of the child objects themselves.A deep copy makes the copying process recursive. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. Copying an object this way walks the whole object tree to create a fully independent clone of the original object and all of its children.
Here is an example for the copy():
first_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = first_list.copy()first_list[0][2] = 831print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]print(second_list) # [[1, 2, 831], ['a', 'b', 'c']]
Here is an example for the deepcopy() case:
import copyfirst_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = copy.deepcopy(first_list)first_list[0][2] = 831print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]print(second_list) # [[1, 2, 3], ['a', 'b', 'c']]
If you use a usual dictionary and try to access a non-existent key, then you are going to get an error:
my_dictonary = {"name": "Name", "surname": "Surname"}print(my_dictonary["age"])
Here it’s the error thrown:
KeyError: 'age'
We can avoid such errors using defaultdict():
from collections import defaultdictmy_dictonary = defaultdict(str)my_dictonary['name'] = "Name"my_dictonary['surname'] = "Surname"print(my_dictonary["age"])
class OddNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 2 return xodd_numbers_object = OddNumbers()iterator = iter(odd_numbers_object)print(next(iterator)) # 1print(next(iterator)) # 3print(next(iterator)) # 5
my_set = set([1, 2, 1, 2, 3, 4, 5])print(list(my_set)) # [1, 2, 3, 4, 5]
import torchprint(torch) # <module 'torch' from '/Users/...'
odd_numbers = [1, 3, 5, 7, 9]even_numbers = []for i in range(9): if i not in odd_numbers: even_numbers.append(i)print(even_numbers) # [0, 2, 4, 6, 8]
sort() sorts the original list.
sorted() returns a new sorted list.
groceries = ['milk', 'bread', 'tea']new_groceries = sorted(groceries)# new_groceries = ['bread', 'milk', 'tea']print(new_groceries)# groceries = ['milk', 'bread', 'tea']print(groceries)groceries.sort()# groceries = ['bread', 'milk', 'tea']print(groceries)
UUID stands for Universally Unique Identifier.
import uuid# Generate a UUID from a host ID, sequence number, and the current timeprint(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af# Generate a random UUIDprint(uuid.uuid4()) # 93bc700b-253e-4081-a358-24b60591076a
If you come from a Java background, you know that String in Java is a non-primitive data type, because it refers to an object.
In Python, a string is a primitive data type.
I hope you learned at least something from this article. | [
{
"code": null,
"e": 259,
"s": 172,
"text": "Python is quite popular nowadays, mainly due to its simplicity, and easiness to learn."
},
{
"code": null,
"e": 385,
"s": 259,
"text": "You can use it for a wide range of tasks like data science and machine learning, web development, scripting, automation, etc."
},
{
"code": null,
"e": 507,
"s": 385,
"text": "Since this is a pretty long article and you want to reach its end before you finish your coffee, why don’t we just start?"
},
{
"code": null,
"e": 527,
"s": 507,
"text": "Okay, here we go..."
},
{
"code": null,
"e": 710,
"s": 527,
"text": "Despite all the Python code that you have seen so far, chances are that you may have missed the following “for-else” which I also got to see for the first time a couple of weeks ago."
},
{
"code": null,
"e": 874,
"s": 710,
"text": "This is a “for-else” method of looping through a list, where despite having an iteration through a list, you also have an “else” condition, which is quite unusual."
},
{
"code": null,
"e": 976,
"s": 874,
"text": "This is not something that I have seen in other programming languages like Java, Ruby, or JavaScript."
},
{
"code": null,
"e": 1026,
"s": 976,
"text": "Let’s see an example of how it looks in practice."
},
{
"code": null,
"e": 1108,
"s": 1026,
"text": "Let’s say that we are trying to check whether there are no odd numbers in a list."
},
{
"code": null,
"e": 1134,
"s": 1108,
"text": "Let’s iterate through it:"
},
{
"code": null,
"e": 1271,
"s": 1134,
"text": "numbers = [2, 4, 6, 8, 1]for number in numbers: if number % 2 == 1: print(number) breakelse: print(\"No odd numbers\")"
},
{
"code": null,
"e": 1401,
"s": 1271,
"text": "In case we find an odd number, then that number will be printed since break will be executed and the else branch will be skipped."
},
{
"code": null,
"e": 1495,
"s": 1401,
"text": "Otherwise, if break is never executed, the execution flow will continue with the else branch."
},
{
"code": null,
"e": 1537,
"s": 1495,
"text": "In this example, we are going to print 1."
},
{
"code": null,
"e": 1600,
"s": 1537,
"text": "my_list = [1, 2, 3, 4, 5]one, two, three, four, five = my_list"
},
{
"code": null,
"e": 1767,
"s": 1600,
"text": "import heapqscores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]print(heapq.nlargest(3, scores)) # [91, 87, 82]print(heapq.nsmallest(5, scores)) # [15, 33, 33, 49, 51]"
},
{
"code": null,
"e": 1816,
"s": 1767,
"text": "We can extract all elements of a list using “*”:"
},
{
"code": null,
"e": 1895,
"s": 1816,
"text": "my_list = [1, 2, 3, 4]print(my_list) # [1, 2, 3, 4]print(*my_list) # 1 2 3 4"
},
{
"code": null,
"e": 1995,
"s": 1895,
"text": "This can be helpful in situations where we want to pass all elements of a list as method arguments:"
},
{
"code": null,
"e": 2144,
"s": 1995,
"text": "def sum_of_elements(*arg): total = 0 for i in arg: total += i return totalresult = sum_of_elements(*[1, 2, 3, 4])print(result) # 10"
},
{
"code": null,
"e": 2252,
"s": 2144,
"text": "_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]print(elements_in_the_middle) # [2, 3, 4, 5, 6, 7]"
},
{
"code": null,
"e": 2287,
"s": 2252,
"text": "one, two, three, four = 1, 2, 3, 4"
},
{
"code": null,
"e": 2377,
"s": 2287,
"text": "You can loop through the elements in a list in a single line in a very comprehensive way."
},
{
"code": null,
"e": 2428,
"s": 2377,
"text": "Let’s see that in action in the following example:"
},
{
"code": null,
"e": 2562,
"s": 2428,
"text": "numbers = [1, 2, 3, 4, 5, 6, 7, 8]even_numbers = [number for number in numbers if number % 2 == 0]print(even_numbers) # [2, 4, 6, 8]"
},
{
"code": null,
"e": 2622,
"s": 2562,
"text": "We can do the same with dictionaries, sets, and generators."
},
{
"code": null,
"e": 2675,
"s": 2622,
"text": "Let’s see another example, but now for dictionaries."
},
{
"code": null,
"e": 2958,
"s": 2675,
"text": "dictionary = {'first_element': 1, 'second_element': 2, 'third_element': 3, 'fourth_element': 4}odd_value_elements = {key: num for (key, num) in dictionary.items() if num % 2 == 1}print(odd_value_elements) # {'first_element': 1, 'third_element': 3}"
},
{
"code": null,
"e": 3001,
"s": 2958,
"text": "This example was inspired by this article."
},
{
"code": null,
"e": 3016,
"s": 3001,
"text": "From the docs:"
},
{
"code": null,
"e": 3199,
"s": 3016,
"text": "An Enum is a set of symbolic names bound to unique values. They are similar to global variables, but they offer a more useful repr(), grouping, type-safety, and a few other features."
},
{
"code": null,
"e": 3219,
"s": 3199,
"text": "Here is an example:"
},
{
"code": null,
"e": 3412,
"s": 3219,
"text": "from enum import Enumclass Status(Enum): NO_STATUS = -1 NOT_STARTED = 0 IN_PROGRESS = 1 COMPLETED = 2print(Status.IN_PROGRESS.name) # IN_PROGRESSprint(Status.COMPLETED.value) # 2"
},
{
"code": null,
"e": 3463,
"s": 3412,
"text": "string = \"Abc\"print(string * 5) # AbcAbcAbcAbcAbc"
},
{
"code": null,
"e": 3601,
"s": 3463,
"text": "If you have a value and you want to compare it whether it is between two other values, there is a simple expression that you use in Math:"
},
{
"code": null,
"e": 3612,
"s": 3601,
"text": "1 < x < 10"
},
{
"code": null,
"e": 3747,
"s": 3612,
"text": "That is the algebraic expression that we learn in elementary school. However, you can also use that same expression in Python as well."
},
{
"code": null,
"e": 3836,
"s": 3747,
"text": "Yes, you heard that right. You have probably done comparisons of such form up until now:"
},
{
"code": null,
"e": 3853,
"s": 3836,
"text": "1 < x and x < 10"
},
{
"code": null,
"e": 3911,
"s": 3853,
"text": "For that, you simply need to use the following in Python:"
},
{
"code": null,
"e": 3922,
"s": 3911,
"text": "1 < x < 10"
},
{
"code": null,
"e": 4093,
"s": 3922,
"text": "This doesn’t work in Ruby, the programming language that was developed with the intention of making programmers happy. This turns out to be working in JavaScript as well."
},
{
"code": null,
"e": 4239,
"s": 4093,
"text": "I was really impressed seeing such a simple expression not being talked about more widely. At least, I haven’t seen it being mentioned that much."
},
{
"code": null,
"e": 4275,
"s": 4239,
"text": "This is available as of Python 3.9:"
},
{
"code": null,
"e": 4574,
"s": 4275,
"text": "first_dictionary = {'name': 'Fatos', 'location': 'Munich'}second_dictionary = {'name': 'Fatos', 'surname': 'Morina', 'location': 'Bavaria, Munich'}result = first_dictionary | second_dictionaryprint(result) # {'name': 'Fatos', 'location': 'Bavaria, Munich', 'surname': 'Morina'}"
},
{
"code": null,
"e": 4678,
"s": 4574,
"text": "books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')print(books.index('Mastery')) # 3"
},
{
"code": null,
"e": 4776,
"s": 4678,
"text": "Let’s say that you get the input in a function that is a string, but it is supposed to be a list:"
},
{
"code": null,
"e": 4794,
"s": 4776,
"text": "input = \"[1,2,3]\""
},
{
"code": null,
"e": 4854,
"s": 4794,
"text": "You don’t need it in that format. You need it to be a list:"
},
{
"code": null,
"e": 4870,
"s": 4854,
"text": "input = [1,2,3]"
},
{
"code": null,
"e": 4924,
"s": 4870,
"text": "Or maybe you the following response from an API call:"
},
{
"code": null,
"e": 4955,
"s": 4924,
"text": "input = [[1, 2, 3], [4, 5, 6]]"
},
{
"code": null,
"e": 5098,
"s": 4955,
"text": "Rather than bothering with complicated regular expressions, all you have to do is import the module ast and then call its method literal_eval:"
},
{
"code": null,
"e": 5171,
"s": 5098,
"text": "import astdef string_to_list(string): return ast.literal_eval(string)"
},
{
"code": null,
"e": 5198,
"s": 5171,
"text": "That’s all you need to do."
},
{
"code": null,
"e": 5282,
"s": 5198,
"text": "Now you will get the result as a list, or list of lists, namely like the following:"
},
{
"code": null,
"e": 5459,
"s": 5282,
"text": "import astdef string_to_list(string): return ast.literal_eval(string)string = \"[[1, 2, 3],[4, 5, 6]]\"my_list = string_to_list(string)print(my_list) # [[1, 2, 3], [4, 5, 6]]"
},
{
"code": null,
"e": 5563,
"s": 5459,
"text": "Let’s assume that you want to find the difference between 2 numbers. The difference is not commutative:"
},
{
"code": null,
"e": 5577,
"s": 5563,
"text": "a - b != b -a"
},
{
"code": null,
"e": 5667,
"s": 5577,
"text": "However, we may forget the ordering of the parameters which can cause “trivial” mistakes:"
},
{
"code": null,
"e": 5760,
"s": 5667,
"text": "def subtract(a, b): return a - bprint((subtract(1, 3))) # -2print((subtract(3, 1))) # 2"
},
{
"code": null,
"e": 5884,
"s": 5760,
"text": "To avoid such potential mistakes, we can simply use named parameters and the ordering of parameters doesn’t matter anymore:"
},
{
"code": null,
"e": 5986,
"s": 5884,
"text": "def subtract(a, b): return a - bprint((subtract(a=1, b=3))) # -2print((subtract(b=3, a=1))) # -2"
},
{
"code": null,
"e": 6053,
"s": 5986,
"text": "print(1, 2, 3, \"a\", \"z\", \"this is here\", \"here is something else\")"
},
{
"code": null,
"e": 6251,
"s": 6053,
"text": "print(\"Hello\", end=\"\")print(\"World\") # HelloWorldprint(\"Hello\", end=\" \")print(\"World\") # Hello Worldprint('words', 'with', 'commas', 'in', 'between', sep=', ')# words, with, commas, in, between"
},
{
"code": null,
"e": 6294,
"s": 6251,
"text": "You can do advanced printing quite easily:"
},
{
"code": null,
"e": 6398,
"s": 6294,
"text": "print(\"29\", \"01\", \"2022\", sep=\"/\") # 29/01/2022print(\"name\", \"domain.com\", sep=\"@\") # [email protected]"
},
{
"code": null,
"e": 6471,
"s": 6398,
"text": "four_letters = “abcd” # this works4_letters = “abcd” # this doesn’t work"
},
{
"code": null,
"e": 6511,
"s": 6471,
"text": "+variable = “abcd” # this doesn’t work"
},
{
"code": null,
"e": 6545,
"s": 6511,
"text": "number = 0110 # this doesn't work"
},
{
"code": null,
"e": 6629,
"s": 6545,
"text": "This means, anywhere you want, as many times as you want in the name of a variable:"
},
{
"code": null,
"e": 6697,
"s": 6629,
"text": "a______b = \"abcd\" # this works_a_b_c_d = \"abcd\" # this also works"
},
{
"code": null,
"e": 6846,
"s": 6697,
"text": "I am not encouraging you to use it, but in case you see a weird naming of a variable like that, know that it is actually a valid name of a variable."
},
{
"code": null,
"e": 6886,
"s": 6846,
"text": "This way it can be easier to read them."
},
{
"code": null,
"e": 6948,
"s": 6886,
"text": "print(1_000_000_000) # 1000000000print(1_234_567) # 1234567"
},
{
"code": null,
"e": 7034,
"s": 6948,
"text": "my_list = ['a', 'b', 'c', 'd']my_list.reverse()print(my_list) # ['d', 'c', 'b', 'a']"
},
{
"code": null,
"e": 7159,
"s": 7034,
"text": "my_string = \"This is just a sentence\"print(my_string[0:5]) # This# Take three steps forwardprint(my_string[0:10:3]) # Tsse"
},
{
"code": null,
"e": 7294,
"s": 7159,
"text": "my_string = \"This is just a sentence\"print(my_string[10:0:-1]) # suj si sih# Take two steps forwardprint(my_string[10:0:-2]) # sjs i"
},
{
"code": null,
"e": 7359,
"s": 7294,
"text": "Indices indicating the start and end of slicing can be optional."
},
{
"code": null,
"e": 7466,
"s": 7359,
"text": "my_string = \"This is just a sentence\"print(my_string[4:]) # is just a sentenceprint(my_string[:3]) # Thi"
},
{
"code": null,
"e": 7500,
"s": 7466,
"text": "print(3/2) # 1.5print(3//2) # 1"
},
{
"code": null,
"e": 7575,
"s": 7500,
"text": "“is” checks whether 2 variables are pointing to the same object in memory."
},
{
"code": null,
"e": 7639,
"s": 7575,
"text": "“==” compares the equality of values that these 2 objects hold."
},
{
"code": null,
"e": 8021,
"s": 7639,
"text": "first_list = [1, 2, 3]second_list = [1, 2, 3]# Is their actual value the same?print(first_list == second_list) # True# Are they pointing to the same object in memoryprint(first_list is second_list) # False, since they have same values, but in different objects in memorythird_list = first_listprint(third_list is first_list) # True, since both point to the same object in memory"
},
{
"code": null,
"e": 8182,
"s": 8021,
"text": "dictionary_one = {\"a\": 1, \"b\": 2}dictionary_two = {\"c\": 3, \"d\": 4}merged = {**dictionary_one, **dictionary_two}print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}"
},
{
"code": null,
"e": 8282,
"s": 8182,
"text": "first = \"abc\"second = \"def\"print(first < second) # Truesecond = \"ab\"print(first < second) # False"
},
{
"code": null,
"e": 8344,
"s": 8282,
"text": "my_string = \"abcdef\"print(my_string.startswith(\"b\")) # False"
},
{
"code": null,
"e": 8430,
"s": 8344,
"text": "print(id(1)) # 4325776624print(id(2)) # 4325776656print(id(\"string\")) # 4327978288"
},
{
"code": null,
"e": 8584,
"s": 8430,
"text": "When we assign a variable to an immutable type such as integers, floats, strings, booleans, and tuples, then this variable points to an object in memory."
},
{
"code": null,
"e": 8715,
"s": 8584,
"text": "In case we assign to that variable another value, the original object is still in memory, but the variable pointing to it is lost:"
},
{
"code": null,
"e": 8850,
"s": 8715,
"text": "number = 1print(id(number)) # 4325215472print(id(1)) # 4325215472number = 3print(id(number)) # 4325215536print(id(1)) # 4325215472"
},
{
"code": null,
"e": 8957,
"s": 8850,
"text": "This was already mentioned in the previous point but wanted to emphasize it since this is quite important."
},
{
"code": null,
"e": 9044,
"s": 8957,
"text": "name = \"Fatos\"print(id(name)) # 4422282544name = \"fatos\"print(id(name)) # 4422346608"
},
{
"code": null,
"e": 9155,
"s": 9044,
"text": "my_tuple = (1, 2, 3, 4)print(id(my_tuple)) # 4499290128my_tuple = ('a', 'b')print(id(my_tuple)) # 4498867584"
},
{
"code": null,
"e": 9226,
"s": 9155,
"text": "This means that we can change the object without losing binding to it:"
},
{
"code": null,
"e": 9351,
"s": 9226,
"text": "cities = [\"Munich\", \"Zurich\", \"London\"]print(id(cities)) # 4482699712cities.append(\"Berlin\")print(id(cities)) # 4482699712"
},
{
"code": null,
"e": 9386,
"s": 9351,
"text": "Here is another example with sets:"
},
{
"code": null,
"e": 9483,
"s": 9386,
"text": "my_set = {1, 2, 3, 4}print(id(my_set)) # 4352726176my_set.add(5)print(id(my_set)) # 4352726176"
},
{
"code": null,
"e": 9522,
"s": 9483,
"text": "This way, you can no longer modify it:"
},
{
"code": null,
"e": 9578,
"s": 9522,
"text": "my_set = frozenset(['a', 'b', 'c', 'd'])my_set.add(\"a\")"
},
{
"code": null,
"e": 9619,
"s": 9578,
"text": "If you do that, an error will be thrown:"
},
{
"code": null,
"e": 9677,
"s": 9619,
"text": "AttributeError: 'frozenset' object has no attribute 'add'"
},
{
"code": null,
"e": 9749,
"s": 9677,
"text": "However, “elif” cannot stand on its own without an “if” step before it:"
},
{
"code": null,
"e": 9915,
"s": 9749,
"text": "def check_number(number): if number > 0: return \"Positive\" elif number == 0: return \"Zero\" return \"Negative\"print(check_number(1)) # Positive"
},
{
"code": null,
"e": 10233,
"s": 9915,
"text": "def check_if_anagram(first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() return sorted(first_word) == sorted(second_word)print(check_if_anagram(\"testinG\", \"Testing\")) # Trueprint(check_if_anagram(\"Here\", \"Rehe\")) # Trueprint(check_if_anagram(\"Know\", \"Now\")) # False"
},
{
"code": null,
"e": 10318,
"s": 10233,
"text": "print(ord(\"A\")) # 65print(ord(\"B\")) # 66print(ord(\"C\")) # 66print(ord(\"a\")) # 97"
},
{
"code": null,
"e": 10416,
"s": 10318,
"text": "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}keys = dictionary.keys()print(list(keys)) # ['a', 'b', 'c']"
},
{
"code": null,
"e": 10514,
"s": 10416,
"text": "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}values = dictionary.values()print(list(values)) # [1, 2, 3]"
},
{
"code": null,
"e": 10654,
"s": 10514,
"text": "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}reversed_dictionary = {j: i for i, j in dictionary.items()}print(reversed) # {1: 'a', 2: 'b', 3: 'c'}"
},
{
"code": null,
"e": 10702,
"s": 10654,
"text": "print(int(False)) # 0print(float(True)) # 1.0"
},
{
"code": null,
"e": 10737,
"s": 10702,
"text": "“False” is 0, whereas “True” is 1."
},
{
"code": null,
"e": 10816,
"s": 10737,
"text": "x = 10y = 12result = (x - False)/(y * True)print(result) # 0.8333333333333334"
},
{
"code": null,
"e": 10940,
"s": 10816,
"text": "print(bool(.0)) # Falseprint(bool(3)) # Trueprint(bool(\"-\")) # Trueprint(bool(\"string\")) # Trueprint(bool(\" \")) # True"
},
{
"code": null,
"e": 10973,
"s": 10940,
"text": "print(complex(10, 2)) # (10+2j)"
},
{
"code": null,
"e": 11030,
"s": 10973,
"text": "You can also convert a number into a hexadecimal number:"
},
{
"code": null,
"e": 11052,
"s": 11030,
"text": "print(hex(11)) # 0xb"
},
{
"code": null,
"e": 11124,
"s": 11052,
"text": "If you use append(), you are going to insert new values from the right."
},
{
"code": null,
"e": 11311,
"s": 11124,
"text": "We can also use insert() to specify the index and the element where we want to insert this new element. In our case, we want to insert it in the first position, so we use 0 as the index:"
},
{
"code": null,
"e": 11401,
"s": 11311,
"text": "my_list = [3, 4, 5]my_list.append(6)my_list.insert(0, 2)print(my_list) # [2, 3, 4, 5, 6]"
},
{
"code": null,
"e": 11448,
"s": 11401,
"text": "You cannot have lambdas in more than one line."
},
{
"code": null,
"e": 11473,
"s": 11448,
"text": "Let’s try the following:"
},
{
"code": null,
"e": 11613,
"s": 11473,
"text": "comparison = lambda x: if x > 3: print(\"x > 3\") else: print(\"x is not greater than 3\")"
},
{
"code": null,
"e": 11656,
"s": 11613,
"text": "The following error is going to be thrown:"
},
{
"code": null,
"e": 11714,
"s": 11656,
"text": "result = lambda x: if x > 3: ^SyntaxError: invalid syntax"
},
{
"code": null,
"e": 11739,
"s": 11714,
"text": "Let’s try the following:"
},
{
"code": null,
"e": 11779,
"s": 11739,
"text": "comparison = lambda x: \"x > 3\" if x > 3"
},
{
"code": null,
"e": 11820,
"s": 11779,
"text": "We are going to get the following error:"
},
{
"code": null,
"e": 11930,
"s": 11820,
"text": "comparison = lambda x: \"x > 3\" if x > 3 ^SyntaxError: invalid syntax"
},
{
"code": null,
"e": 12017,
"s": 11930,
"text": "Noe that this is a feature of the conditional expression and not of the lambda itself."
},
{
"code": null,
"e": 12140,
"s": 12017,
"text": "my_list = [1, 2, 3, 4]odd = filter(lambda x: x % 2 == 1, my_list)print(list(odd)) # [1, 3]print(my_list) # [1, 2, 3, 4]"
},
{
"code": null,
"e": 12271,
"s": 12140,
"text": "my_list = [1, 2, 3, 4]squared = map(lambda x: x ** 2, my_list)print(list(squared)) # [1, 4, 9, 16]print(my_list) # [1, 2, 3, 4]"
},
{
"code": null,
"e": 12335,
"s": 12271,
"text": "for number in range(1, 10, 3): print(number, end=\" \")# 1 4 7"
},
{
"code": null,
"e": 12375,
"s": 12335,
"text": "So you don’t need to include it at all."
},
{
"code": null,
"e": 12599,
"s": 12375,
"text": "def range_with_zero(number): for i in range(0, number): print(i, end=' ')def range_with_no_zero(number): for i in range(number): print(i, end=' ')range_with_zero(3) # 0 1 2range_with_no_zero(3) # 0 1 2"
},
{
"code": null,
"e": 12707,
"s": 12599,
"text": "If the length is greater than 0, then it is by default True, so you don’t really need to compare it with 0:"
},
{
"code": null,
"e": 13046,
"s": 12707,
"text": "def get_element_with_comparison(my_list): if len(my_list) > 0: return my_list[0]def get_first_element(my_list): if len(my_list): return my_list[0]elements = [1, 2, 3, 4]first_result = get_element_with_comparison(elements)second_result = get_element_with_comparison(elements)print(first_result == second_result) # True"
},
{
"code": null,
"e": 13118,
"s": 13046,
"text": "However, only the last one is called, since it overrides previous ones."
},
{
"code": null,
"e": 13289,
"s": 13118,
"text": "def get_address(): return \"First address\"def get_address(): return \"Second address\"def get_address(): return \"Third address\"print(get_address()) # Third address"
},
{
"code": null,
"e": 13466,
"s": 13289,
"text": "class Engineer: def __init__(self, name): self.name = name self.__starting_salary = 62000dain = Engineer('Dain')print(dain._Engineer__starting_salary) # 62000"
},
{
"code": null,
"e": 13514,
"s": 13466,
"text": "import sysprint(sys.getsizeof(\"bitcoin\")) # 56"
},
{
"code": null,
"e": 13716,
"s": 13514,
"text": "def get_sum(*arguments): result = 0 for i in arguments: result += i return resultprint(get_sum(1, 2, 3)) # 6print(get_sum(1, 2, 3, 4, 5)) # 15print(get_sum(1, 2, 3, 4, 5, 6, 7)) # 28"
},
{
"code": null,
"e": 13770,
"s": 13716,
"text": "Calling the parent’s class initializer using super():"
},
{
"code": null,
"e": 14118,
"s": 13770,
"text": "class Parent: def __init__(self, city, address): self.city = city self.address = addressclass Child(Parent): def __init__(self, city, address, university): super().__init__(city, address) self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')print(child.university) # ETH Zürich"
},
{
"code": null,
"e": 14176,
"s": 14118,
"text": "Calling the parent’s class using the parent class’s name:"
},
{
"code": null,
"e": 14529,
"s": 14176,
"text": "class Parent: def __init__(self, city, address): self.city = city self.address = addressclass Child(Parent): def __init__(self, city, address, university): Parent.__init__(self, city, address) self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')print(child.university) # ETH Zürich"
},
{
"code": null,
"e": 14652,
"s": 14529,
"text": "Note that calls to parent initializers using __init__() and super() can only be used inside the child class’s initializer."
},
{
"code": null,
"e": 14750,
"s": 14652,
"text": "Whenever you use the + operator between two int data types, then you are going to find their sum."
},
{
"code": null,
"e": 14835,
"s": 14750,
"text": "However, when you use it between two string data types, you are going to merge them:"
},
{
"code": null,
"e": 14934,
"s": 14835,
"text": "print(10 + 1) # Adding two integers using '+'print('first' + 'second') # Merging two strings '+'"
},
{
"code": null,
"e": 14976,
"s": 14934,
"text": "This represents the operator overloading."
},
{
"code": null,
"e": 15027,
"s": 14976,
"text": "You can also use it with your own classes as well:"
},
{
"code": null,
"e": 15462,
"s": 15027,
"text": "class Expenses: def __init__(self, rent, groceries): self.rent = rent self.groceries = groceries def __add__(self, other): return Expenses(self.rent + other.rent, self.groceries + other.groceries)april_expenses = Expenses(1000, 200)may_expenses = Expenses(1000, 300)total_expenses = april_expenses + may_expensesprint(total_expenses.rent) # 2000print(total_expenses.groceries) # 500"
},
{
"code": null,
"e": 15545,
"s": 15462,
"text": "Here is another example of an operation overloadding that you can define yourself:"
},
{
"code": null,
"e": 15740,
"s": 15545,
"text": "class Game: def __init__(self, score): self.score = score def __lt__(self, other): return self.score < other.scorefirst = Game(1)second = Game(2)print(first < second) # True"
},
{
"code": null,
"e": 15842,
"s": 15740,
"text": "Similarly, like the two previous cases, we can override the __eq__() function based on our own needs:"
},
{
"code": null,
"e": 16338,
"s": 15842,
"text": "class Journey: def __init__(self, location, destination, duration): self.location = location self.destination = destination self.duration = duration def __eq__(self, other): return ((self.location == other.location) and (self.destination == other.destination) and (self.duration == other.duration))first = Journey('Location A', 'Destination A', '30min')second = Journey('Location B', 'Destination B', '30min')print(first == second)"
},
{
"code": null,
"e": 16371,
"s": 16338,
"text": "You can also analogously define:"
},
{
"code": null,
"e": 16387,
"s": 16371,
"text": "__sub__() for -"
},
{
"code": null,
"e": 16403,
"s": 16387,
"text": "__mul__() for *"
},
{
"code": null,
"e": 16423,
"s": 16403,
"text": "__truediv__() for /"
},
{
"code": null,
"e": 16439,
"s": 16423,
"text": "__ne__() for !="
},
{
"code": null,
"e": 16455,
"s": 16439,
"text": "__ge__() for >="
},
{
"code": null,
"e": 16470,
"s": 16455,
"text": "__gt__() for >"
},
{
"code": null,
"e": 16691,
"s": 16470,
"text": "class Rectangle: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return repr('Rectangle with area=' + str(self.a * self.b))print(Rectangle(3, 4)) # 'Rectangle with area=12'"
},
{
"code": null,
"e": 16794,
"s": 16691,
"text": "string = \"This is just a sentence.\"result = string.swapcase()print(result) # tHIS IS JUST A SENTENCE."
},
{
"code": null,
"e": 16854,
"s": 16794,
"text": "string = \" \"result = string.isspace()print(result) # True"
},
{
"code": null,
"e": 17156,
"s": 16854,
"text": "name = \"Password\"print(name.isalnum()) # True, because all characters are alphabetsname = \"Secure Password \"print(name.isalnum()) # False, because it contains whitespacesname = \"S3cur3P4ssw0rd\"print(name.isalnum()) # Truename = \"133\"print(name.isalnum()) # True, because all characters are numbers"
},
{
"code": null,
"e": 17376,
"s": 17156,
"text": "string = \"Name\"print(string.isalpha()) # Truestring = \"Firstname Lastname\"print(string.isalpha()) # False, because it contains whitespacestring = “P4ssw0rd”print(string.isalpha()) # False, because it contains numbers"
},
{
"code": null,
"e": 17616,
"s": 17376,
"text": "string = \"This is a sentence with \"# Remove trailing spaces from the rightprint(string.rstrip()) # \"This is a sentence with\"string = \"this here is a sentence.....,,,,aaaaasd\"print(string.rstrip(“.,dsa”)) # \"this here is a sentence\""
},
{
"code": null,
"e": 17689,
"s": 17616,
"text": "You can similarly remove characters from the left based on the argument:"
},
{
"code": null,
"e": 17748,
"s": 17689,
"text": "string = \"ffffffffFirst\"print(string.lstrip(“f”)) # First"
},
{
"code": null,
"e": 17974,
"s": 17748,
"text": "string = \"seven\"print(string.isdigit()) # Falsestring = \"1337\"print(string.isdigit()) # Truestring = \"5a\"print(string.isdigit()) # False, because it contains the character 'a'string = \"2**5\"print(string.isdigit()) # False"
},
{
"code": null,
"e": 18082,
"s": 17974,
"text": "# 42673 in Arabic numeralsstring = \"四二六七三\"print(string.isdigit()) # Falseprint(string.isnumeric()) # True"
},
{
"code": null,
"e": 18424,
"s": 18082,
"text": "string = \"This is a sentence\"print(string.istitle()) # Falsestring = \"10 Python Tips\"print(string.istitle()) # Truestring = \"How to Print A String in Python\"# False, because of the first characters being lowercase in \"to\" and \"in\"print(string.istitle())string = \"PYTHON\"print(string.istitle()) # False. It's titlelized version is \"Python\""
},
{
"code": null,
"e": 18493,
"s": 18424,
"text": "numbers = (1, 2, 3, 4)print(numbers[-1]) # 4print(numbers[-4]) # 1"
},
{
"code": null,
"e": 18652,
"s": 18493,
"text": "mixed_tuple = ((\"a\"*10, 3, 4), ['first', 'second', 'third'])print(mixed_tuple[1]) # ['first', 'second', 'third']print(mixed_tuple[0]) # ('aaaaaaaaaa', 3, 4)"
},
{
"code": null,
"e": 18742,
"s": 18652,
"text": "names = [\"Besim\", \"Albert\", \"Besim\", \"Fisnik\", \"Meriton\"]print(names.count(\"Besim\")) # 2"
},
{
"code": null,
"e": 18967,
"s": 18742,
"text": "my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]slicing = slice(-4, None)# Getting the last 3 elements from the listprint(my_list[slicing]) # [4, 5, 6]# Getting only the third element starting from the rightprint(my_list[-3]) # 4"
},
{
"code": null,
"e": 19029,
"s": 18967,
"text": "You can also use slice() for other usual slicing tasks, like:"
},
{
"code": null,
"e": 19206,
"s": 19029,
"text": "string = \"Data Science\"# start = 1, stop = None (don't stop anywhere), step = 1# contains 1, 3 and 5 indicesslice_object = slice(5, None)print(string[slice_object]) # Science"
},
{
"code": null,
"e": 19275,
"s": 19206,
"text": "my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.count('a')) # 3"
},
{
"code": null,
"e": 19345,
"s": 19275,
"text": "my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.index('f')) # 2"
},
{
"code": null,
"e": 19425,
"s": 19345,
"text": "my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[::3]) # (1, 4, 7, 10)"
},
{
"code": null,
"e": 19513,
"s": 19425,
"text": "my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[3:]) # (4, 5, 6, 7, 8, 9, 10)"
},
{
"code": null,
"e": 19686,
"s": 19513,
"text": "my_list = [1, 2, 3, 4]my_list.clear()print(my_list) # []my_set = {1, 2, 3}my_set.clear()print(my_set) # set()my_dict = {\"a\": 1, \"b\": 2}my_dict.clear()print(my_dict) # {}"
},
{
"code": null,
"e": 19775,
"s": 19686,
"text": "One way is to use the method union() which returns a new set as a result of the joining:"
},
{
"code": null,
"e": 19875,
"s": 19775,
"text": "first_set = {4, 5, 6}second_set = {1, 2, 3}print(first_set.union(second_set)) # {1, 2, 3, 4, 5, 6}"
},
{
"code": null,
"e": 19969,
"s": 19875,
"text": "Another one is method update, which inserts the element of the second set into the first one:"
},
{
"code": null,
"e": 20079,
"s": 19969,
"text": "first_set = {4, 5, 6}second_set = {1, 2, 3}first_set.update(second_set)print(first_set) # {1, 2, 3, 4, 5, 6}"
},
{
"code": null,
"e": 20182,
"s": 20079,
"text": "def is_positive(number): print(\"Positive\" if number > 0 else \"Negative\") # Positiveis_positive(-3)"
},
{
"code": null,
"e": 20591,
"s": 20182,
"text": "math_points = 51biology_points = 78physics_points = 56history_points = 72my_conditions = [math_points > 50, biology_points > 50, physics_points > 50, history_points > 50]if all(my_conditions): print(\"Congratulations! You have passed all of the exams.\")else: print(\"I am sorry, but it seems that you have to repeat at least one exam.\")# Congratulations! You have passed all of the exams."
},
{
"code": null,
"e": 21000,
"s": 20591,
"text": "math_points = 51biology_points = 78physics_points = 56history_points = 72my_conditions = [math_points > 50, biology_points > 50, physics_points > 50, history_points > 50]if any(my_conditions): print(\"Congratulations! You have passed all of the exams.\")else: print(\"I am sorry, but it seems that you have to repeat at least one exam.\")# Congratulations! You have passed all of the exams."
},
{
"code": null,
"e": 21057,
"s": 21000,
"text": "print(bool(\"Non empty\")) # Trueprint(bool(\"\")) # False"
},
{
"code": null,
"e": 21164,
"s": 21057,
"text": "print(bool([])) # Falseprint(bool(set([]))) # Falseprint(bool({})) # Falseprint(bool({\"a\": 1})) # True"
},
{
"code": null,
"e": 21241,
"s": 21164,
"text": "print(bool(False)) # Falseprint(bool(None)) # Falseprint(bool(0)) # False"
},
{
"code": null,
"e": 21339,
"s": 21241,
"text": "string = \"string\"def do_nothing(): string = \"inside a method\"do_nothing()print(string) # string"
},
{
"code": null,
"e": 21391,
"s": 21339,
"text": "You need to use the access modifier global as well:"
},
{
"code": null,
"e": 21517,
"s": 21391,
"text": "string = \"string\"def do_nothing(): global string string = \"inside a method\"do_nothing()print(string) # inside a method"
},
{
"code": null,
"e": 21735,
"s": 21517,
"text": "from collections import Counterresult = Counter(\"Banana\")print(result) # Counter({'a': 3, 'n': 2, 'B': 1})result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])print(result) # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})"
},
{
"code": null,
"e": 22102,
"s": 21735,
"text": "from collections import Counterdef check_if_anagram(first_string, second_string): first_string = first_string.lower() second_string = second_string.lower() return Counter(first_string) == Counter(second_string)print(check_if_anagram('testinG', 'Testing')) # Trueprint(check_if_anagram('Here', 'Rehe')) # Trueprint(check_if_anagram('Know', 'Now')) # False"
},
{
"code": null,
"e": 22168,
"s": 22102,
"text": "You can also check whether 2 strings are anagrams using sorted():"
},
{
"code": null,
"e": 22486,
"s": 22168,
"text": "def check_if_anagram(first_word, second_word): first_word = first_word.lower() second_word = second_word.lower() return sorted(first_word) == sorted(second_word)print(check_if_anagram(\"testinG\", \"Testing\")) # Trueprint(check_if_anagram(\"Here\", \"Rehe\")) # Trueprint(check_if_anagram(\"Know\", \"Now\")) # False"
},
{
"code": null,
"e": 22782,
"s": 22486,
"text": "from itertools import countmy_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']current_counter = count()string = \"This is just a sentence.\"for i in string: if i in my_vowels: print(f\"Current vowel: {i}\") print(f\"Number of vowels found so far: {next(current_counter)}\")"
},
{
"code": null,
"e": 22817,
"s": 22782,
"text": "This is the result in the console:"
},
{
"code": null,
"e": 23154,
"s": 22817,
"text": "Current vowel: iNumber of vowels found so far: 0Current vowel: iNumber of vowels found so far: 1Current vowel: uNumber of vowels found so far: 2Current vowel: aNumber of vowels found so far: 3Current vowel: eNumber of vowels found so far: 4Current vowel: eNumber of vowels found so far: 5Current vowel: eNumber of vowels found so far: 6"
},
{
"code": null,
"e": 23252,
"s": 23154,
"text": "Counter from the collections module by default doesn’t order elements based on their frequencies."
},
{
"code": null,
"e": 23422,
"s": 23252,
"text": "from collections import Counterresult = Counter([1, 2, 3, 2, 2, 2, 2])print(result) # Counter({2: 5, 1: 1, 3: 1})print(result.most_common()) # [(2, 5), (1, 1), (3, 1)]"
},
{
"code": null,
"e": 23520,
"s": 23422,
"text": "my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']print(max(set(my_list), key=my_list.count)) # a"
},
{
"code": null,
"e": 23559,
"s": 23520,
"text": "Here is the explanation from the docs:"
},
{
"code": null,
"e": 23834,
"s": 23559,
"text": "A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original."
},
{
"code": null,
"e": 23899,
"s": 23834,
"text": "Maybe, an even more comprehensive description can be found here:"
},
{
"code": null,
"e": 24525,
"s": 23899,
"text": "A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won’t create copies of the child objects themselves.A deep copy makes the copying process recursive. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. Copying an object this way walks the whole object tree to create a fully independent clone of the original object and all of its children."
},
{
"code": null,
"e": 24560,
"s": 24525,
"text": "Here is an example for the copy():"
},
{
"code": null,
"e": 24758,
"s": 24560,
"text": "first_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = first_list.copy()first_list[0][2] = 831print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]print(second_list) # [[1, 2, 831], ['a', 'b', 'c']]"
},
{
"code": null,
"e": 24802,
"s": 24758,
"text": "Here is an example for the deepcopy() case:"
},
{
"code": null,
"e": 25017,
"s": 24802,
"text": "import copyfirst_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = copy.deepcopy(first_list)first_list[0][2] = 831print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]print(second_list) # [[1, 2, 3], ['a', 'b', 'c']]"
},
{
"code": null,
"e": 25121,
"s": 25017,
"text": "If you use a usual dictionary and try to access a non-existent key, then you are going to get an error:"
},
{
"code": null,
"e": 25203,
"s": 25121,
"text": "my_dictonary = {\"name\": \"Name\", \"surname\": \"Surname\"}print(my_dictonary[\"age\"]) "
},
{
"code": null,
"e": 25231,
"s": 25203,
"text": "Here it’s the error thrown:"
},
{
"code": null,
"e": 25247,
"s": 25231,
"text": "KeyError: 'age'"
},
{
"code": null,
"e": 25293,
"s": 25247,
"text": "We can avoid such errors using defaultdict():"
},
{
"code": null,
"e": 25452,
"s": 25293,
"text": "from collections import defaultdictmy_dictonary = defaultdict(str)my_dictonary['name'] = \"Name\"my_dictonary['surname'] = \"Surname\"print(my_dictonary[\"age\"]) "
},
{
"code": null,
"e": 25752,
"s": 25452,
"text": "class OddNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 2 return xodd_numbers_object = OddNumbers()iterator = iter(odd_numbers_object)print(next(iterator)) # 1print(next(iterator)) # 3print(next(iterator)) # 5"
},
{
"code": null,
"e": 25826,
"s": 25752,
"text": "my_set = set([1, 2, 1, 2, 3, 4, 5])print(list(my_set)) # [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 25888,
"s": 25826,
"text": "import torchprint(torch) # <module 'torch' from '/Users/...'"
},
{
"code": null,
"e": 26049,
"s": 25888,
"text": "odd_numbers = [1, 3, 5, 7, 9]even_numbers = []for i in range(9): if i not in odd_numbers: even_numbers.append(i)print(even_numbers) # [0, 2, 4, 6, 8]"
},
{
"code": null,
"e": 26081,
"s": 26049,
"text": "sort() sorts the original list."
},
{
"code": null,
"e": 26117,
"s": 26081,
"text": "sorted() returns a new sorted list."
},
{
"code": null,
"e": 26373,
"s": 26117,
"text": "groceries = ['milk', 'bread', 'tea']new_groceries = sorted(groceries)# new_groceries = ['bread', 'milk', 'tea']print(new_groceries)# groceries = ['milk', 'bread', 'tea']print(groceries)groceries.sort()# groceries = ['bread', 'milk', 'tea']print(groceries)"
},
{
"code": null,
"e": 26420,
"s": 26373,
"text": "UUID stands for Universally Unique Identifier."
},
{
"code": null,
"e": 26645,
"s": 26420,
"text": "import uuid# Generate a UUID from a host ID, sequence number, and the current timeprint(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af# Generate a random UUIDprint(uuid.uuid4()) # 93bc700b-253e-4081-a358-24b60591076a"
},
{
"code": null,
"e": 26772,
"s": 26645,
"text": "If you come from a Java background, you know that String in Java is a non-primitive data type, because it refers to an object."
},
{
"code": null,
"e": 26818,
"s": 26772,
"text": "In Python, a string is a primitive data type."
}
] |
Lagged MLP for predictive maintenance of turbofan engines | by Koen Peters | Towards Data Science | <disclaimer I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.>
Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. In our last analysis we trained a Random Forest and set up hyperparameter tuning for FD003.
Today we’ll develop a model for dataset FD002. A dataset where the engines can operate on six unique operating condition, which was much more challenging to deal with than I had expected. For that purpose, I have chosen to write about this dataset after FD003. As, in my opinion, changing the order gives a more gradual increase in complexity. More complex datasets often require more complex solutions, this will be the first article in the series where we’ll train and tune a Neural Network (NN). This is also the longest article yet because there’s just so much to discuss, so let’s get started!
First, we’ll import the required libraries.
Next, we’ll load the data and inspect the first few rows.
Looks good, let’s compute the Remaining Useful Life (RUL).
Time to start exploring our data. I will skip the descriptive statistics for now, there isn’t much interesting to be found. We will, however, verify the presence of the six unique operating conditions.
As you can see, the six unique operating conditions are present. One operating condition occurs more frequently, but otherwise it’s pretty balanced.
Previously I’ve plotted all sensor signals of multiple engines. Unfortunately, the current signals are rather incomprehensible. To get a clearer understanding of what’s going on I chose to plot just one sensor of one unit.
The signal is jumping all over the place and there is no trend to be seen like in the previous datasets. This dataset does include different operating conditions for the engines, let’s look at those next.
Setting 1 and 2 look quite similar so I left the graph of setting 2 out. Setting 3 behaves a bit different (see image below).
That explains a lot, I had expected different engines to run on different operating conditions, but apparently operating conditions change between cycles. Which makes analysing and predicting RUL much more complex. There is no use in plotting more signals for now, let’s continue with the baseline model.
The baseline model will be a simple linear regression without any feature engineering or selection. The only thing we’ll do is update our belief or RUL for the training set as explained in a previous post [4]. Essentially what we’re doing is instead of letting the computed RUL decline linearly we set the upper limit of computed RUL to 125. Clipping the RUL is a proven method that generates much better results compared to the naïve linear declining RUL [5].
# returns:# train set RMSE:21.94192340996904, R2:0.7226666213449306# test set RMSE:32.64244063056574, R2:0.6315800619887212
Our baseline model has a training RMSE of 21.94 and a test RMSE of 32.64, which will be the score to beat. Let’s continue preparing the first implementation of our NN.
Neural networks are quite prone to overfitting. To get a better idea of model performance and overfitting before running it on the test set, it’s absolutely necessary to use a validation set.
Like last time we’ll split the data in such a way that all records of a single engine are either assigned to the training or validation set to prevent ‘data leakage’. For this purpose, we’ll use sklearns’ GroupShuffleSplit where our groups for splitting consist of the unit numbers.
The validation set should have a similar distribution in order to compare model performance between the train and validation set. Let’s check the target variable distribution to get a grasp of the similarity of the datasets.
Although the frequency is lower, the distribution of validation RUL looks similar to the training RUL.
As with the Support Vector Regression implementation, NNs tend to use relative distances between data points, but are not very good in comprehending the magnitude of absolute differences. Therefore, adding scaling is a necessity.
Note, the train-validation split is exactly the same as the previous one. I’ve taken more precautions to ensure results are reproducible and comparable, which you can read about here.
The MLP is considered the ‘vanilla’ NN, suitable for learning non-linear patterns and consisting of at least an input, hidden and output layer [6]. Creating and training this type of NN in keras is relatively simple.
First, we define the input dimension, which is the number of features the NN expects. Then we create a model object by initiating the Sequential layer and adding a few Dense layers, specifying the number of nodes in each layer. The input dimension should be passed to the first Dense layer. The last layer in the model should be a Dense layer with a single node, since we’re expecting the model to return a single value (predicted RUL) for a single row of data.
Afterwards, we compile the model. At this stage the random weights are initialized. We also define the optimizer, which is responsible for updating the weights and the loss function, which is the parameter to optimize.
Next, we train the model. One additional argument is passed to the fit function, which is the number of Epochs. The number of Epochs represents how often the data is presented to the model for learning, in this case we’ll present the dataset 20 times.
When inspecting the training results, it’s important to look at the reductions in training and validation loss. When both losses are going down everything is going well, and the model is learning the patterns in the dataset. When the training loss is going down, but the validation loss is going up (steadily) the model is overfitting, which we’ll want to avoid. There is an easier way to interpret the loss though and that is by plotting it.
Note the validation loss sometimes peaks upwards but then decreases again. Indicating overfitting at that specific epoch, but in general the model is not overfit. We might even be able to train for a few more epochs. For now, let’s check how the model performs.
# returns:# train set RMSE:22.393854937161706, R2:0.7111246569724521# test set RMSE:34.00842713320483, R2:0.600100397460153
We now have a model whose performance comes near the baseline model. Time to start feature engineering.
When I read the engines in this dataset would run on different operating conditions, I immediately thought of one hot encoding. Unfortunately, it didn’t work so well, but I will take you through my thought process.
One hot encoding is often used to encode a categorical variable into binary columns. In this case, each unique operating condition would be a ‘category’, see the image below.
Each row would only have one unique operating condition active, i.e. only one column will have a 1 in it, while the others will have 0. Appending this information to your data while removing the original settings makes it easier for the NN to figure out which unique combination of settings are being used and how they relate to the target variable.
Training a model with these new features did yield an improvement (train RMSE = 20.80, test RMSE = 32.01), but there are two problems with this implementation:
The improvement due to one hot encoding is not nearly as large as I would have hopedThis implementation leaves little room for additional feature engineering. For example, we can’t use any signal filters when the sensor signals deviate so much between operating conditions. In addition, adding lagged variables is impractical, as lags need to be included to account for changing operating conditions as well.
The improvement due to one hot encoding is not nearly as large as I would have hoped
This implementation leaves little room for additional feature engineering. For example, we can’t use any signal filters when the sensor signals deviate so much between operating conditions. In addition, adding lagged variables is impractical, as lags need to be included to account for changing operating conditions as well.
I’ve kept the code in the notebook for reference, you can find the link at the bottom of this article. Next, we’ll try a different method for dealing with the operating conditions.
Previously we’ve tried min-max scaling the complete dataset at once. In condition-based standardization you group all records of a single operating condition together and scale them using a standard scaler. Applying this type of scaling will bring the mean of the grouped operating conditions to zero. Because you’re applying this technique for each operating condition separately, all signals will receive a mean of zero, bringing them somewhat to the same line and making them comparable [7]. This type of standardization works very well if the signals have similar behavior but are centered around a different mean. Please do note, this technique can only be used if the operating condition itself has no effect on the imminence of breakdown!
First, we’ll add the unique operating condition to the dataframe, similar to the first step of one hot encoding.
To verify the signals have different means but similar behavior we’ll plot the points of all engines for a single sensor, for each operating condition.
The plot confirms the signals indeed seem to have different mean values but otherwise similar behavior. So finally, we’ll add the condition-based standardization and plot the sensor signals as we would have normally done during EDA.
Sensor 1, 5, 16 and 19 look similar and don’t seem very useful at this point.
Sensor 2, 3, 4, 11, 15, and 17 show a similar upward trend and should be included for further model development.
Sensor 6, 10 and 16 look similar and don’t seem to hold any useful information after using this standardization technique.
Sensor 7, 12, 20 and 21 show a similar downward trend and should be included for further model development.
Sensor 8 and 13, almost look a bit like the standardization didn’t fully work towards the end, as the signal is still jumping up and down quite a bit. I think their trend is similar to those of sensor 9 and 14 (see below) just a bit noisier. We’ll keep them in for now.
Sensor 9 and 14 look similar to sensor 8 and 13, but less noisy. I would also consider these for further model development.
Last and also least (pun intended) is sensor 18, which remarkably seems to hold no information whatsoever after condition-based standardization. We should leave it out.
To summarize, the sensors which seem useable after condition-based standardization are:
We can now fit a new model and check the results.
The validation loss has reduced over 100 points which is a good sign, let’s evaluate to see the full effect of condition-based standardization.
# returns:# train set RMSE:19.35447487320054, R2:0.7842178390649497# test set RMSE:29.36496528407863, R2:0.7018485932169383
With a test RMSE of 29.364 we’ve already achieved an improvement of 10.04% over our baseline model. Let’s see if we can improve it even further.
Like in the timeseries article, we can add lagged variables to provide the model with information of previous timecycles. Combining information of multiple cyles allows the model to detect trends and gives a more complete view of the data. See below example to grasp the essence of lagged variables.
Row 2 contains the data of the two rows before it. Rows where NA’s are introduced are dropped as the model cannot cope with these. Hence adding many lags greatly impacts the size of your dataset. Let’s train a model with lagged variables to see if performance improves.
Looks like validation loss has reduced by another 50 points. Let’s evaluate to see the full effect.
# returns:# train set RMSE:17.572959256116462, R2:0.8236048587786006# test set RMSE:29.075227321534157, R2:0.7077031620947969
We’ve gained a slight improvement. However, the model seems to start overfitting after a few epochs, we’ll try to combat this later.
Originally, I tried making the data stationary. As explained in my post on timeseries, stationary data implies the statistical properties of a signal do not change over time. Due to this stationarity, statistical models will be able to predict future values in a robust manner.
You can use an adfuller test, to test if your data is stationary. If it isn’t, you can difference your data once to de-trend it and test again. By differencing your data, you will introduce NA’s, as the first row cannot be differenced with any previous row. Rows with NA’s have to be dropped, ultimately affecting how many lags we can add, which is the first point against making your data stationary in this scenario. Since some of the engines in the test set have a very limited number of rows and we’re already introducing NA’s by adding lagged variables.
Now, let’s check the stationarity of our data after condition-based standardization.
Although a slight trend is visible, this signal can be considered stationary right off the bat, which holds true for most, but not all, signals in the dataset.
For smoothing I chose to implement an exponential weighted moving average. This smoothing function is quite simple yet very powerful. Essentially it takes the current value and the previous filtered value into account when calculating the filtered value (see simplified formula below) [7].
~Xt = a*Xt + (1 - a)*~Xt-1
Where ~Xt is the filtered value of Xt and α the strength of the filter. The value for alpha lies between 0–1. When alpha is 0.8, the filtered datapoint will be comprised of 80% of the value at Xt and 20% of the (already filtered) value at Xt-1. Hence, lower values for alpha will have a stronger smoothing effect.
Luckily, Pandas already has this type of filter implemented in its exponential weighted function [8]. Now let’s check the stationarity of our data after condition-based standardization and smoothing.
So, after smoothing, the signal is no longer considered stationary. Depending on the value of alpha (remember, lower values indicate stronger smoothing) the data would be considered less and less stationary as the general trend would become more apparent when the noise in the signal is smoothed out.
Reaching stationarity would thus require more and more differencing, resulting in a larger reduction of rows in your dataset. In an attempt to reach stationarity, alpha values below 0.69 would cause all rows of some engines in the test set to be dropped completely, something we want to avoid. However, the effect of filtering with values of alpha >= 0.69 isn’t that strong and therefore doesn’t improve model performance that much. In the end I chose to abandon stationarity, as stronger smoothing gave better model performance.
Let’s add smoothing to our data preparations and retrain our model to see where we are.
# returns:# train set RMSE:15.916032412669667, R2:0.85530069539296# test set RMSE:27.852681524828476, R2:0.731767185824673
Great, our test RMSE has reduced quite a bit more to 27.853. There is one more thing I’d like to test. Using the same model, we’ll crank up the epochs to see how the validation loss will behave. If it remains relatively constant for a higher number of epochs it means we can use more epochs in hyperparameter tuning.
# returns:# train set RMSE:19.784558538181454, R2:0.7764114588121707# test set RMSE:32.17059484378398, R2:0.6421540867400053
Test RMSE has increased significantly, but it should be okay to tune between 10–30 epochs, given we’ll also add drop-out to combat overfitting. We now have all the preprocessing components to start hyperparameter tuning.
There are a lot of hyperparameters we can potentially tune, which I’ll explain below. To reduce complexity, I choose not to tune all of them.
Alpha: the strength of our exponential smoothing average filter
Lags: the previous timesteps to add to the row. I choose not to tune this parameter.
Epochs: the number of times the data is fed to the NN. More epochs allows for better learning, but also introduces the possibility of overfitting.
Number of layers in our NN, I choose not to tune this parameter
Nodes per layer: the number of nodes in each layer
Dropout: The fraction of node outputs in a layer which will be set to zero, dropout helps against overfitting [9]
Optimizer & learning rate, I choose not to tune this parameter
Activation function, activation functions can be considered as a form of post processing of layer outputs. For example, after computing the outputs the famous relu activation will set any negative output to zero.
Batch size: The number of samples fed to the network before updating the weights [10]
We can’t use the hyperparameter tuning setup of our Random Forest from last time. Since the parameters defined above need to be tuned in different places, e.g. data, NN architecture and fitting, we’ll have to write some custom code.
Let’s start by defining the hyperparameters, functions to prep our data and create the model.
The data preparation and create model functions should look familiar as we’ve used this same logic earlier in this post.
Now, the code block for hyperparameter tuning is quite large. Check out the code first and read my explanation below.
Like last time, the type of hyperparameter tuning implemented here can be considered random search. 60 iterations should be enough to get you within 95% of the best solution [11], more iterations will get you closer to the best solution. I’ve set the number of iterations to 100. For each iteration we’ll randomly sample hyper parameter values from our lists of defined parameters. Based on these parameters, the dataset is pre-processed, and the model created. We’ll use the group shuffle split introduced earlier for cross validation, however for hyperparameter tuning we’ll use 3 splits.
After training we save the used parameters, the mean and standard deviation of the validation loss. The standard deviation of the validation loss gives an indication of how robust your model performs across the validation splits of your dataset. Let’s have a look at the output.
As you can see the overall parameters can highly influence model performance, with the best model having a mean validation loss of 171.19 and the worst model having a mean validation loss of 3640.33, which is 21 times worse!
We train our final model based on the best parameters.
# returns:# train set RMSE:12.82085148416833, R2:0.9061075756420954# test set RMSE:25.352943890689797, R2:0.7777536332595578
With an RMSE of 25.353 we’ve improved 22.33% over our baseline model, neat! This could be pushed a little further when also tuning the lags, number of layers, optimizer and learning rate.
For the complete notebook you can check out my github page here. I would like to thank Maikel Grobbe for his inputs and reviewing my article. Next time we’ll delve into the last dataset and an LSTM. Have any questions or remarks? Let me know in the comments below!
References:[1] https://keras.io/getting_started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development[2] https://stackoverflow.com/questions/32419510/how-to-get-reproducible-results-in-keras/59076062#59076062[3] https://www.onlinemathlearning.com/probability-without-replacement.html[4] The importance of problem framing for supervised predictive maintenance solutions[5] F. O. Heimes, “Recurrent neural networks for remaining useful life estimation,” 2008 International Conference on Prognostics and Health Management, Denver, CO, 2008, pp. 1–6, doi: 10.1109/PHM.2008.4711422.[6] https://en.wikipedia.org/wiki/Multilayer_perceptron[7] Duarte Pasa, G., Paixão de Medeiros, I., & Yoneyama, T. (2019). Operating Condition-Invariant Neural Network-based Prognostics Methods applied on Turbofan Aircraft Engines. Annual Conference of the PHM Society, 11(1). https://doi.org/10.36001/phmconf.2019.v11i1.786[8] https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html[9] https://www.tensorflow.org/tutorials/keras/overfit_and_underfit#add_dropout[10] https://www.tensorflow.org/api_docs/python/tf/keras/Sequential[11] Zheng, Alice. Evaluating Machine Learning Models. O’Reilly Media, Inc. 2015 | [
{
"code": null,
"e": 414,
"s": 172,
"text": "<disclaimer I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.>"
},
{
"code": null,
"e": 588,
"s": 414,
"text": "Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. In our last analysis we trained a Random Forest and set up hyperparameter tuning for FD003."
},
{
"code": null,
"e": 1187,
"s": 588,
"text": "Today we’ll develop a model for dataset FD002. A dataset where the engines can operate on six unique operating condition, which was much more challenging to deal with than I had expected. For that purpose, I have chosen to write about this dataset after FD003. As, in my opinion, changing the order gives a more gradual increase in complexity. More complex datasets often require more complex solutions, this will be the first article in the series where we’ll train and tune a Neural Network (NN). This is also the longest article yet because there’s just so much to discuss, so let’s get started!"
},
{
"code": null,
"e": 1231,
"s": 1187,
"text": "First, we’ll import the required libraries."
},
{
"code": null,
"e": 1289,
"s": 1231,
"text": "Next, we’ll load the data and inspect the first few rows."
},
{
"code": null,
"e": 1348,
"s": 1289,
"text": "Looks good, let’s compute the Remaining Useful Life (RUL)."
},
{
"code": null,
"e": 1550,
"s": 1348,
"text": "Time to start exploring our data. I will skip the descriptive statistics for now, there isn’t much interesting to be found. We will, however, verify the presence of the six unique operating conditions."
},
{
"code": null,
"e": 1699,
"s": 1550,
"text": "As you can see, the six unique operating conditions are present. One operating condition occurs more frequently, but otherwise it’s pretty balanced."
},
{
"code": null,
"e": 1922,
"s": 1699,
"text": "Previously I’ve plotted all sensor signals of multiple engines. Unfortunately, the current signals are rather incomprehensible. To get a clearer understanding of what’s going on I chose to plot just one sensor of one unit."
},
{
"code": null,
"e": 2127,
"s": 1922,
"text": "The signal is jumping all over the place and there is no trend to be seen like in the previous datasets. This dataset does include different operating conditions for the engines, let’s look at those next."
},
{
"code": null,
"e": 2253,
"s": 2127,
"text": "Setting 1 and 2 look quite similar so I left the graph of setting 2 out. Setting 3 behaves a bit different (see image below)."
},
{
"code": null,
"e": 2558,
"s": 2253,
"text": "That explains a lot, I had expected different engines to run on different operating conditions, but apparently operating conditions change between cycles. Which makes analysing and predicting RUL much more complex. There is no use in plotting more signals for now, let’s continue with the baseline model."
},
{
"code": null,
"e": 3020,
"s": 2558,
"text": "The baseline model will be a simple linear regression without any feature engineering or selection. The only thing we’ll do is update our belief or RUL for the training set as explained in a previous post [4]. Essentially what we’re doing is instead of letting the computed RUL decline linearly we set the upper limit of computed RUL to 125. Clipping the RUL is a proven method that generates much better results compared to the naïve linear declining RUL [5]."
},
{
"code": null,
"e": 3144,
"s": 3020,
"text": "# returns:# train set RMSE:21.94192340996904, R2:0.7226666213449306# test set RMSE:32.64244063056574, R2:0.6315800619887212"
},
{
"code": null,
"e": 3312,
"s": 3144,
"text": "Our baseline model has a training RMSE of 21.94 and a test RMSE of 32.64, which will be the score to beat. Let’s continue preparing the first implementation of our NN."
},
{
"code": null,
"e": 3504,
"s": 3312,
"text": "Neural networks are quite prone to overfitting. To get a better idea of model performance and overfitting before running it on the test set, it’s absolutely necessary to use a validation set."
},
{
"code": null,
"e": 3787,
"s": 3504,
"text": "Like last time we’ll split the data in such a way that all records of a single engine are either assigned to the training or validation set to prevent ‘data leakage’. For this purpose, we’ll use sklearns’ GroupShuffleSplit where our groups for splitting consist of the unit numbers."
},
{
"code": null,
"e": 4012,
"s": 3787,
"text": "The validation set should have a similar distribution in order to compare model performance between the train and validation set. Let’s check the target variable distribution to get a grasp of the similarity of the datasets."
},
{
"code": null,
"e": 4115,
"s": 4012,
"text": "Although the frequency is lower, the distribution of validation RUL looks similar to the training RUL."
},
{
"code": null,
"e": 4345,
"s": 4115,
"text": "As with the Support Vector Regression implementation, NNs tend to use relative distances between data points, but are not very good in comprehending the magnitude of absolute differences. Therefore, adding scaling is a necessity."
},
{
"code": null,
"e": 4529,
"s": 4345,
"text": "Note, the train-validation split is exactly the same as the previous one. I’ve taken more precautions to ensure results are reproducible and comparable, which you can read about here."
},
{
"code": null,
"e": 4746,
"s": 4529,
"text": "The MLP is considered the ‘vanilla’ NN, suitable for learning non-linear patterns and consisting of at least an input, hidden and output layer [6]. Creating and training this type of NN in keras is relatively simple."
},
{
"code": null,
"e": 5208,
"s": 4746,
"text": "First, we define the input dimension, which is the number of features the NN expects. Then we create a model object by initiating the Sequential layer and adding a few Dense layers, specifying the number of nodes in each layer. The input dimension should be passed to the first Dense layer. The last layer in the model should be a Dense layer with a single node, since we’re expecting the model to return a single value (predicted RUL) for a single row of data."
},
{
"code": null,
"e": 5427,
"s": 5208,
"text": "Afterwards, we compile the model. At this stage the random weights are initialized. We also define the optimizer, which is responsible for updating the weights and the loss function, which is the parameter to optimize."
},
{
"code": null,
"e": 5679,
"s": 5427,
"text": "Next, we train the model. One additional argument is passed to the fit function, which is the number of Epochs. The number of Epochs represents how often the data is presented to the model for learning, in this case we’ll present the dataset 20 times."
},
{
"code": null,
"e": 6122,
"s": 5679,
"text": "When inspecting the training results, it’s important to look at the reductions in training and validation loss. When both losses are going down everything is going well, and the model is learning the patterns in the dataset. When the training loss is going down, but the validation loss is going up (steadily) the model is overfitting, which we’ll want to avoid. There is an easier way to interpret the loss though and that is by plotting it."
},
{
"code": null,
"e": 6384,
"s": 6122,
"text": "Note the validation loss sometimes peaks upwards but then decreases again. Indicating overfitting at that specific epoch, but in general the model is not overfit. We might even be able to train for a few more epochs. For now, let’s check how the model performs."
},
{
"code": null,
"e": 6508,
"s": 6384,
"text": "# returns:# train set RMSE:22.393854937161706, R2:0.7111246569724521# test set RMSE:34.00842713320483, R2:0.600100397460153"
},
{
"code": null,
"e": 6612,
"s": 6508,
"text": "We now have a model whose performance comes near the baseline model. Time to start feature engineering."
},
{
"code": null,
"e": 6827,
"s": 6612,
"text": "When I read the engines in this dataset would run on different operating conditions, I immediately thought of one hot encoding. Unfortunately, it didn’t work so well, but I will take you through my thought process."
},
{
"code": null,
"e": 7002,
"s": 6827,
"text": "One hot encoding is often used to encode a categorical variable into binary columns. In this case, each unique operating condition would be a ‘category’, see the image below."
},
{
"code": null,
"e": 7352,
"s": 7002,
"text": "Each row would only have one unique operating condition active, i.e. only one column will have a 1 in it, while the others will have 0. Appending this information to your data while removing the original settings makes it easier for the NN to figure out which unique combination of settings are being used and how they relate to the target variable."
},
{
"code": null,
"e": 7512,
"s": 7352,
"text": "Training a model with these new features did yield an improvement (train RMSE = 20.80, test RMSE = 32.01), but there are two problems with this implementation:"
},
{
"code": null,
"e": 7921,
"s": 7512,
"text": "The improvement due to one hot encoding is not nearly as large as I would have hopedThis implementation leaves little room for additional feature engineering. For example, we can’t use any signal filters when the sensor signals deviate so much between operating conditions. In addition, adding lagged variables is impractical, as lags need to be included to account for changing operating conditions as well."
},
{
"code": null,
"e": 8006,
"s": 7921,
"text": "The improvement due to one hot encoding is not nearly as large as I would have hoped"
},
{
"code": null,
"e": 8331,
"s": 8006,
"text": "This implementation leaves little room for additional feature engineering. For example, we can’t use any signal filters when the sensor signals deviate so much between operating conditions. In addition, adding lagged variables is impractical, as lags need to be included to account for changing operating conditions as well."
},
{
"code": null,
"e": 8512,
"s": 8331,
"text": "I’ve kept the code in the notebook for reference, you can find the link at the bottom of this article. Next, we’ll try a different method for dealing with the operating conditions."
},
{
"code": null,
"e": 9258,
"s": 8512,
"text": "Previously we’ve tried min-max scaling the complete dataset at once. In condition-based standardization you group all records of a single operating condition together and scale them using a standard scaler. Applying this type of scaling will bring the mean of the grouped operating conditions to zero. Because you’re applying this technique for each operating condition separately, all signals will receive a mean of zero, bringing them somewhat to the same line and making them comparable [7]. This type of standardization works very well if the signals have similar behavior but are centered around a different mean. Please do note, this technique can only be used if the operating condition itself has no effect on the imminence of breakdown!"
},
{
"code": null,
"e": 9371,
"s": 9258,
"text": "First, we’ll add the unique operating condition to the dataframe, similar to the first step of one hot encoding."
},
{
"code": null,
"e": 9523,
"s": 9371,
"text": "To verify the signals have different means but similar behavior we’ll plot the points of all engines for a single sensor, for each operating condition."
},
{
"code": null,
"e": 9756,
"s": 9523,
"text": "The plot confirms the signals indeed seem to have different mean values but otherwise similar behavior. So finally, we’ll add the condition-based standardization and plot the sensor signals as we would have normally done during EDA."
},
{
"code": null,
"e": 9834,
"s": 9756,
"text": "Sensor 1, 5, 16 and 19 look similar and don’t seem very useful at this point."
},
{
"code": null,
"e": 9947,
"s": 9834,
"text": "Sensor 2, 3, 4, 11, 15, and 17 show a similar upward trend and should be included for further model development."
},
{
"code": null,
"e": 10070,
"s": 9947,
"text": "Sensor 6, 10 and 16 look similar and don’t seem to hold any useful information after using this standardization technique."
},
{
"code": null,
"e": 10178,
"s": 10070,
"text": "Sensor 7, 12, 20 and 21 show a similar downward trend and should be included for further model development."
},
{
"code": null,
"e": 10448,
"s": 10178,
"text": "Sensor 8 and 13, almost look a bit like the standardization didn’t fully work towards the end, as the signal is still jumping up and down quite a bit. I think their trend is similar to those of sensor 9 and 14 (see below) just a bit noisier. We’ll keep them in for now."
},
{
"code": null,
"e": 10572,
"s": 10448,
"text": "Sensor 9 and 14 look similar to sensor 8 and 13, but less noisy. I would also consider these for further model development."
},
{
"code": null,
"e": 10741,
"s": 10572,
"text": "Last and also least (pun intended) is sensor 18, which remarkably seems to hold no information whatsoever after condition-based standardization. We should leave it out."
},
{
"code": null,
"e": 10829,
"s": 10741,
"text": "To summarize, the sensors which seem useable after condition-based standardization are:"
},
{
"code": null,
"e": 10879,
"s": 10829,
"text": "We can now fit a new model and check the results."
},
{
"code": null,
"e": 11023,
"s": 10879,
"text": "The validation loss has reduced over 100 points which is a good sign, let’s evaluate to see the full effect of condition-based standardization."
},
{
"code": null,
"e": 11147,
"s": 11023,
"text": "# returns:# train set RMSE:19.35447487320054, R2:0.7842178390649497# test set RMSE:29.36496528407863, R2:0.7018485932169383"
},
{
"code": null,
"e": 11292,
"s": 11147,
"text": "With a test RMSE of 29.364 we’ve already achieved an improvement of 10.04% over our baseline model. Let’s see if we can improve it even further."
},
{
"code": null,
"e": 11592,
"s": 11292,
"text": "Like in the timeseries article, we can add lagged variables to provide the model with information of previous timecycles. Combining information of multiple cyles allows the model to detect trends and gives a more complete view of the data. See below example to grasp the essence of lagged variables."
},
{
"code": null,
"e": 11862,
"s": 11592,
"text": "Row 2 contains the data of the two rows before it. Rows where NA’s are introduced are dropped as the model cannot cope with these. Hence adding many lags greatly impacts the size of your dataset. Let’s train a model with lagged variables to see if performance improves."
},
{
"code": null,
"e": 11962,
"s": 11862,
"text": "Looks like validation loss has reduced by another 50 points. Let’s evaluate to see the full effect."
},
{
"code": null,
"e": 12088,
"s": 11962,
"text": "# returns:# train set RMSE:17.572959256116462, R2:0.8236048587786006# test set RMSE:29.075227321534157, R2:0.7077031620947969"
},
{
"code": null,
"e": 12221,
"s": 12088,
"text": "We’ve gained a slight improvement. However, the model seems to start overfitting after a few epochs, we’ll try to combat this later."
},
{
"code": null,
"e": 12499,
"s": 12221,
"text": "Originally, I tried making the data stationary. As explained in my post on timeseries, stationary data implies the statistical properties of a signal do not change over time. Due to this stationarity, statistical models will be able to predict future values in a robust manner."
},
{
"code": null,
"e": 13058,
"s": 12499,
"text": "You can use an adfuller test, to test if your data is stationary. If it isn’t, you can difference your data once to de-trend it and test again. By differencing your data, you will introduce NA’s, as the first row cannot be differenced with any previous row. Rows with NA’s have to be dropped, ultimately affecting how many lags we can add, which is the first point against making your data stationary in this scenario. Since some of the engines in the test set have a very limited number of rows and we’re already introducing NA’s by adding lagged variables."
},
{
"code": null,
"e": 13143,
"s": 13058,
"text": "Now, let’s check the stationarity of our data after condition-based standardization."
},
{
"code": null,
"e": 13303,
"s": 13143,
"text": "Although a slight trend is visible, this signal can be considered stationary right off the bat, which holds true for most, but not all, signals in the dataset."
},
{
"code": null,
"e": 13593,
"s": 13303,
"text": "For smoothing I chose to implement an exponential weighted moving average. This smoothing function is quite simple yet very powerful. Essentially it takes the current value and the previous filtered value into account when calculating the filtered value (see simplified formula below) [7]."
},
{
"code": null,
"e": 13620,
"s": 13593,
"text": "~Xt = a*Xt + (1 - a)*~Xt-1"
},
{
"code": null,
"e": 13934,
"s": 13620,
"text": "Where ~Xt is the filtered value of Xt and α the strength of the filter. The value for alpha lies between 0–1. When alpha is 0.8, the filtered datapoint will be comprised of 80% of the value at Xt and 20% of the (already filtered) value at Xt-1. Hence, lower values for alpha will have a stronger smoothing effect."
},
{
"code": null,
"e": 14134,
"s": 13934,
"text": "Luckily, Pandas already has this type of filter implemented in its exponential weighted function [8]. Now let’s check the stationarity of our data after condition-based standardization and smoothing."
},
{
"code": null,
"e": 14435,
"s": 14134,
"text": "So, after smoothing, the signal is no longer considered stationary. Depending on the value of alpha (remember, lower values indicate stronger smoothing) the data would be considered less and less stationary as the general trend would become more apparent when the noise in the signal is smoothed out."
},
{
"code": null,
"e": 14965,
"s": 14435,
"text": "Reaching stationarity would thus require more and more differencing, resulting in a larger reduction of rows in your dataset. In an attempt to reach stationarity, alpha values below 0.69 would cause all rows of some engines in the test set to be dropped completely, something we want to avoid. However, the effect of filtering with values of alpha >= 0.69 isn’t that strong and therefore doesn’t improve model performance that much. In the end I chose to abandon stationarity, as stronger smoothing gave better model performance."
},
{
"code": null,
"e": 15053,
"s": 14965,
"text": "Let’s add smoothing to our data preparations and retrain our model to see where we are."
},
{
"code": null,
"e": 15176,
"s": 15053,
"text": "# returns:# train set RMSE:15.916032412669667, R2:0.85530069539296# test set RMSE:27.852681524828476, R2:0.731767185824673"
},
{
"code": null,
"e": 15493,
"s": 15176,
"text": "Great, our test RMSE has reduced quite a bit more to 27.853. There is one more thing I’d like to test. Using the same model, we’ll crank up the epochs to see how the validation loss will behave. If it remains relatively constant for a higher number of epochs it means we can use more epochs in hyperparameter tuning."
},
{
"code": null,
"e": 15618,
"s": 15493,
"text": "# returns:# train set RMSE:19.784558538181454, R2:0.7764114588121707# test set RMSE:32.17059484378398, R2:0.6421540867400053"
},
{
"code": null,
"e": 15839,
"s": 15618,
"text": "Test RMSE has increased significantly, but it should be okay to tune between 10–30 epochs, given we’ll also add drop-out to combat overfitting. We now have all the preprocessing components to start hyperparameter tuning."
},
{
"code": null,
"e": 15981,
"s": 15839,
"text": "There are a lot of hyperparameters we can potentially tune, which I’ll explain below. To reduce complexity, I choose not to tune all of them."
},
{
"code": null,
"e": 16045,
"s": 15981,
"text": "Alpha: the strength of our exponential smoothing average filter"
},
{
"code": null,
"e": 16130,
"s": 16045,
"text": "Lags: the previous timesteps to add to the row. I choose not to tune this parameter."
},
{
"code": null,
"e": 16277,
"s": 16130,
"text": "Epochs: the number of times the data is fed to the NN. More epochs allows for better learning, but also introduces the possibility of overfitting."
},
{
"code": null,
"e": 16341,
"s": 16277,
"text": "Number of layers in our NN, I choose not to tune this parameter"
},
{
"code": null,
"e": 16392,
"s": 16341,
"text": "Nodes per layer: the number of nodes in each layer"
},
{
"code": null,
"e": 16506,
"s": 16392,
"text": "Dropout: The fraction of node outputs in a layer which will be set to zero, dropout helps against overfitting [9]"
},
{
"code": null,
"e": 16569,
"s": 16506,
"text": "Optimizer & learning rate, I choose not to tune this parameter"
},
{
"code": null,
"e": 16782,
"s": 16569,
"text": "Activation function, activation functions can be considered as a form of post processing of layer outputs. For example, after computing the outputs the famous relu activation will set any negative output to zero."
},
{
"code": null,
"e": 16868,
"s": 16782,
"text": "Batch size: The number of samples fed to the network before updating the weights [10]"
},
{
"code": null,
"e": 17101,
"s": 16868,
"text": "We can’t use the hyperparameter tuning setup of our Random Forest from last time. Since the parameters defined above need to be tuned in different places, e.g. data, NN architecture and fitting, we’ll have to write some custom code."
},
{
"code": null,
"e": 17195,
"s": 17101,
"text": "Let’s start by defining the hyperparameters, functions to prep our data and create the model."
},
{
"code": null,
"e": 17316,
"s": 17195,
"text": "The data preparation and create model functions should look familiar as we’ve used this same logic earlier in this post."
},
{
"code": null,
"e": 17434,
"s": 17316,
"text": "Now, the code block for hyperparameter tuning is quite large. Check out the code first and read my explanation below."
},
{
"code": null,
"e": 18025,
"s": 17434,
"text": "Like last time, the type of hyperparameter tuning implemented here can be considered random search. 60 iterations should be enough to get you within 95% of the best solution [11], more iterations will get you closer to the best solution. I’ve set the number of iterations to 100. For each iteration we’ll randomly sample hyper parameter values from our lists of defined parameters. Based on these parameters, the dataset is pre-processed, and the model created. We’ll use the group shuffle split introduced earlier for cross validation, however for hyperparameter tuning we’ll use 3 splits."
},
{
"code": null,
"e": 18304,
"s": 18025,
"text": "After training we save the used parameters, the mean and standard deviation of the validation loss. The standard deviation of the validation loss gives an indication of how robust your model performs across the validation splits of your dataset. Let’s have a look at the output."
},
{
"code": null,
"e": 18529,
"s": 18304,
"text": "As you can see the overall parameters can highly influence model performance, with the best model having a mean validation loss of 171.19 and the worst model having a mean validation loss of 3640.33, which is 21 times worse!"
},
{
"code": null,
"e": 18584,
"s": 18529,
"text": "We train our final model based on the best parameters."
},
{
"code": null,
"e": 18709,
"s": 18584,
"text": "# returns:# train set RMSE:12.82085148416833, R2:0.9061075756420954# test set RMSE:25.352943890689797, R2:0.7777536332595578"
},
{
"code": null,
"e": 18897,
"s": 18709,
"text": "With an RMSE of 25.353 we’ve improved 22.33% over our baseline model, neat! This could be pushed a little further when also tuning the lags, number of layers, optimizer and learning rate."
},
{
"code": null,
"e": 19162,
"s": 18897,
"text": "For the complete notebook you can check out my github page here. I would like to thank Maikel Grobbe for his inputs and reviewing my article. Next time we’ll delve into the last dataset and an LSTM. Have any questions or remarks? Let me know in the comments below!"
}
] |
Storing Training Data on the Cloud | by Connor Shorten | Towards Data Science | When you are building deep learning models, you will likely benefit from having more data to train with. You may run out of space on your local machine and therefore need to find ways to store datasets on the cloud and then access them while training your models.
I recently came across on an obstacle in an Image Classification project where I did not have enough storage on my laptop to increase the size of my training dataset. When doing multi-output, (more than 2 classes), image recognition problems, storing 10–100,000s of images for each class, (especially at medium+ resolution), can result in a lot of GBs!
In this article, I will present a couple of tips that helped me use cloud storage in order to formulate batches during model training.
How much is 1 GB of storage?
The image above is 54 KB compressed, (png), at a size of 266x168x3, (resolution x RGB color channels).
Therefore, you could store 18,518 of these images with 1 GB.
The beauty of cloud storage is that we can store many GBs online for free and even TBs, (1,000 GBs), for fairly low costs... Whereas storing several GBs on our local machines can be quite problematic/outright impossible.
How can I access data hosted on the cloud while training my model?
The main idea I wanted to communicate with this article is how a naming convention for my dataset helped me retrieve batches of images from the URL. This is important because when training models, we want to select some random batch of images to feed into the model at each iteration. The dataset is too big to load the entire dataset into memory and select random instances from there. Therefore, I used a naming convention that would let me partition the batches with indices and then fetch the images from the bucket URL accordingly.
You will be given a URL to your bucket and you can use a random number generator to append desired indices to the URL request. This will help you parse the bucket to formulate these batches for training a model.
For example, if you name each item in the dataset: SHOE_1, SHOE_2,... SHOE_9998, SHOE_9999. You will be able to formulate a URL fetch string with something like:
#PSEUDOCODEi = randomnumber()fetch_item = url + ‘SHOE_’ + inew_item = httprequest(fetch_item)batch.append(new_item)
By using a consistent naming convention for your dataset, you can easily parse and fetch random batches for training, without loading the dataset into memory.
Please check out this stack overflow post on exactly how to access s3 files such as images with python:
stackoverflow.com
Conclusion
In Conclusion, I hope this article inspired thought about how you plan on storing your datasets once they grow too large to be hosted on your local machine. I think this is great to do as soon as possible, especially if you are using the google colab environment to train your models. This way you can easily access your data from google colab. Please share any thoughts or strategies that you have used to host custom machine learning training datasets on the cloud. Thanks for reading!
Connor Shorten is a Computer Science student at Florida Atlantic University. Research interests in software economics, deep learning, and software engineering. | [
{
"code": null,
"e": 436,
"s": 172,
"text": "When you are building deep learning models, you will likely benefit from having more data to train with. You may run out of space on your local machine and therefore need to find ways to store datasets on the cloud and then access them while training your models."
},
{
"code": null,
"e": 789,
"s": 436,
"text": "I recently came across on an obstacle in an Image Classification project where I did not have enough storage on my laptop to increase the size of my training dataset. When doing multi-output, (more than 2 classes), image recognition problems, storing 10–100,000s of images for each class, (especially at medium+ resolution), can result in a lot of GBs!"
},
{
"code": null,
"e": 924,
"s": 789,
"text": "In this article, I will present a couple of tips that helped me use cloud storage in order to formulate batches during model training."
},
{
"code": null,
"e": 953,
"s": 924,
"text": "How much is 1 GB of storage?"
},
{
"code": null,
"e": 1056,
"s": 953,
"text": "The image above is 54 KB compressed, (png), at a size of 266x168x3, (resolution x RGB color channels)."
},
{
"code": null,
"e": 1117,
"s": 1056,
"text": "Therefore, you could store 18,518 of these images with 1 GB."
},
{
"code": null,
"e": 1338,
"s": 1117,
"text": "The beauty of cloud storage is that we can store many GBs online for free and even TBs, (1,000 GBs), for fairly low costs... Whereas storing several GBs on our local machines can be quite problematic/outright impossible."
},
{
"code": null,
"e": 1405,
"s": 1338,
"text": "How can I access data hosted on the cloud while training my model?"
},
{
"code": null,
"e": 1942,
"s": 1405,
"text": "The main idea I wanted to communicate with this article is how a naming convention for my dataset helped me retrieve batches of images from the URL. This is important because when training models, we want to select some random batch of images to feed into the model at each iteration. The dataset is too big to load the entire dataset into memory and select random instances from there. Therefore, I used a naming convention that would let me partition the batches with indices and then fetch the images from the bucket URL accordingly."
},
{
"code": null,
"e": 2154,
"s": 1942,
"text": "You will be given a URL to your bucket and you can use a random number generator to append desired indices to the URL request. This will help you parse the bucket to formulate these batches for training a model."
},
{
"code": null,
"e": 2316,
"s": 2154,
"text": "For example, if you name each item in the dataset: SHOE_1, SHOE_2,... SHOE_9998, SHOE_9999. You will be able to formulate a URL fetch string with something like:"
},
{
"code": null,
"e": 2432,
"s": 2316,
"text": "#PSEUDOCODEi = randomnumber()fetch_item = url + ‘SHOE_’ + inew_item = httprequest(fetch_item)batch.append(new_item)"
},
{
"code": null,
"e": 2591,
"s": 2432,
"text": "By using a consistent naming convention for your dataset, you can easily parse and fetch random batches for training, without loading the dataset into memory."
},
{
"code": null,
"e": 2695,
"s": 2591,
"text": "Please check out this stack overflow post on exactly how to access s3 files such as images with python:"
},
{
"code": null,
"e": 2713,
"s": 2695,
"text": "stackoverflow.com"
},
{
"code": null,
"e": 2724,
"s": 2713,
"text": "Conclusion"
},
{
"code": null,
"e": 3212,
"s": 2724,
"text": "In Conclusion, I hope this article inspired thought about how you plan on storing your datasets once they grow too large to be hosted on your local machine. I think this is great to do as soon as possible, especially if you are using the google colab environment to train your models. This way you can easily access your data from google colab. Please share any thoughts or strategies that you have used to host custom machine learning training datasets on the cloud. Thanks for reading!"
}
] |
What is traits in PHP? | In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn't permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
<?php
trait Reader{
public function add($var1,$var2){
return $var1+$var2;
}
}
trait writer {
public function multiplication($var1,$var2){
return $var1*$var2;
}
}
class File {
use Reader;
use writer;
public function calculate($var1,$var2){
echo "Ressult of addition:".$this->add($var1,$var2) ."\n";
echo "Ressult of multiplication:".$this->multiplication($var1,$var2);
}
}
$o = new File();
$o->calculate(5,3);
?>
Result of addition two numbers:8
Result of multiplication of two numbers:15
In the above example, we have implemented a function from two traits in a single class. Due to trait, we are able to access multiple functions in a single class.
We are using the "USE" keyword to access traits inside a class. | [
{
"code": null,
"e": 1602,
"s": 1062,
"text": "In 5.4 PHP version trait is introduced to PHP object-oriented programming. A trait is like class however it is only for grouping methods in a fine-grained and reliable way. It isn't permitted to instantiate a trait on its own. Traits are introduced to PHP 5.4 to overcome the problems of single inheritance. As we know in single inheritance class can only inherit from one other single class. In the case of trait, it enables a developer to reuse sets of methods freely in several independent classes living in different class hierarchies."
},
{
"code": null,
"e": 2122,
"s": 1602,
"text": "<?php\n trait Reader{\n public function add($var1,$var2){\n return $var1+$var2;\n }\n }\n trait writer {\n public function multiplication($var1,$var2){\n return $var1*$var2;\n }\n }\n class File {\n use Reader;\n use writer;\n public function calculate($var1,$var2){\n echo \"Ressult of addition:\".$this->add($var1,$var2) .\"\\n\";\n echo \"Ressult of multiplication:\".$this->multiplication($var1,$var2);\n }\n }\n $o = new File();\n $o->calculate(5,3);\n?>"
},
{
"code": null,
"e": 2198,
"s": 2122,
"text": "Result of addition two numbers:8\nResult of multiplication of two numbers:15"
},
{
"code": null,
"e": 2360,
"s": 2198,
"text": "In the above example, we have implemented a function from two traits in a single class. Due to trait, we are able to access multiple functions in a single class."
},
{
"code": null,
"e": 2424,
"s": 2360,
"text": "We are using the \"USE\" keyword to access traits inside a class."
}
] |
How to disable GridView scrolling in Android? | This example demonstrates how do I disable gridView scrolling 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="8dp"
tools:context=".MainActivity">
<GridView
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
GridView gridView;
Integer[] imageIDs = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven, R.drawable.eight, R.drawable.nine, R.drawable.ten};
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridLayout);
gridView.setAdapter(new ImageAdapterGridView(this));
gridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(MainActivity.this, "Scrolling is Disabled", Toast.LENGTH_SHORT).show();
return event.getAction() == MotionEvent.ACTION_MOVE;
}
});
}
public class ImageAdapterGridView extends BaseAdapter {
private Context context;
ImageAdapterGridView(Context c) {
context = c;
}
public int getCount() {
return imageIDs.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new
GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(20, 20, 20, 20);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<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 the 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": 1136,
"s": 1062,
"text": "This example demonstrates how do I disable gridView scrolling in android."
},
{
"code": null,
"e": 1265,
"s": 1136,
"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": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1774,
"s": 1330,
"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=\"8dp\"\n tools:context=\".MainActivity\">\n<GridView\n android:id=\"@+id/gridLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1831,
"s": 1774,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4141,
"s": 1831,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.annotation.SuppressLint;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.GridView;\nimport android.widget.ImageView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n GridView gridView;\n Integer[] imageIDs = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven, R.drawable.eight, R.drawable.nine, R.drawable.ten};\n @SuppressLint(\"ClickableViewAccessibility\")\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n gridView = findViewById(R.id.gridLayout);\n gridView.setAdapter(new ImageAdapterGridView(this));\n gridView.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n Toast.makeText(MainActivity.this, \"Scrolling is Disabled\", Toast.LENGTH_SHORT).show();\n return event.getAction() == MotionEvent.ACTION_MOVE;\n }\n });\n }\n public class ImageAdapterGridView extends BaseAdapter {\n private Context context;\n ImageAdapterGridView(Context c) {\n context = c;\n }\n public int getCount() {\n return imageIDs.length;\n }\n public Object getItem(int position) {\n return null;\n }\n public long getItemId(int position) {\n return 0;\n }\n public View getView(int position, View convertView, ViewGroup parent) {\n ImageView imageView;\n if (convertView == null) {\n imageView = new ImageView(context);\n imageView.setLayoutParams(new\n GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.MATCH_PARENT));\n imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);\n imageView.setPadding(20, 20, 20, 20);\n } else {\n imageView = (ImageView) convertView;\n }\n imageView.setImageResource(imageIDs[position]);\n return imageView;\n }\n }\n}\n"
},
{
"code": null,
"e": 4196,
"s": 4141,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4869,
"s": 4196,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\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": 5223,
"s": 4869,
"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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
PHP | DOMDocument loadXML() Function | 30 Aug, 2019
The DOMDocument::loadXML() function is an inbuilt function in PHP which is used to load the XML file from a string.
Syntax:
mixed DOMDocument::loadXML( string $source, int $options = 0 )
Parameters: This function accepts two parameters as mentioned above and described below:
$source: This parameter holds the string containing the XML document.
$options: This parameter holds the Bitwise OR of the libxml option constants.
Return Value: This function returns TRUE on success or FALSE on failure. This function returns a DOMDocument if it is called statically or FALSE on failure.
Below programs illustrate the DOMDocument::loadXML() function in PHP:
Program 1:
<?php // Create a new DOMDocument$doc = new DOMDocument(); // Load the XML file$doc->loadXML("<user> <username>Geeks123</username> <name>GeeksforGeeks</name> <address> <phone>+91-XXXXXXXXXX</phone> <email>[email protected]</email> </address> </user>"); // Create XML file and display itecho $doc->saveHTML(); ?>
<user>
<username>Geeks123</username>
<name>GeeksforGeeks</name>
<address>
<phone>+91-XXXXXXXXXX</phone>
<email>[email protected]</email>
</address>
</user>
Program 2:
<?php // Create new DOMDocument$doc = new DOMDocument(); // Create a comment document$comm1 = $doc->createComment('Starting of XML document'); // Append element to the document$doc->appendChild($comm1); // Create XML file and display itecho $doc->saveHTML(); // Load the XML file$doc->loadXML("<user> <username>Geeks123</username> <name>GeeksforGeeks</name> <address> <phone>+91-XXXXXXXXXX</phone> <email>[email protected]</email> </address> </user>"); // Create comment element$comm2 = $doc->createComment('Ending of XML document'); // Append element to the document$doc->appendChild($comm2); // Create XML element and display itecho $doc->saveHTML(); ?>
<!--Starting of XML document-->
<user>
<username>Geeks123</username>
<name>GeeksforGeeks</name>
<address>
<phone>+91-XXXXXXXXXX</phone>
<email>[email protected]</email>
</address>
</user><!--Ending of XML document-->
Reference: https://www.php.net/manual/en/domdocument.loadxml.php
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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": "\n30 Aug, 2019"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "The DOMDocument::loadXML() function is an inbuilt function in PHP which is used to load the XML file from a string."
},
{
"code": null,
"e": 152,
"s": 144,
"text": "Syntax:"
},
{
"code": null,
"e": 215,
"s": 152,
"text": "mixed DOMDocument::loadXML( string $source, int $options = 0 )"
},
{
"code": null,
"e": 304,
"s": 215,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 374,
"s": 304,
"text": "$source: This parameter holds the string containing the XML document."
},
{
"code": null,
"e": 452,
"s": 374,
"text": "$options: This parameter holds the Bitwise OR of the libxml option constants."
},
{
"code": null,
"e": 609,
"s": 452,
"text": "Return Value: This function returns TRUE on success or FALSE on failure. This function returns a DOMDocument if it is called statically or FALSE on failure."
},
{
"code": null,
"e": 679,
"s": 609,
"text": "Below programs illustrate the DOMDocument::loadXML() function in PHP:"
},
{
"code": null,
"e": 690,
"s": 679,
"text": "Program 1:"
},
{
"code": "<?php // Create a new DOMDocument$doc = new DOMDocument(); // Load the XML file$doc->loadXML(\"<user> <username>Geeks123</username> <name>GeeksforGeeks</name> <address> <phone>+91-XXXXXXXXXX</phone> <email>[email protected]</email> </address> </user>\"); // Create XML file and display itecho $doc->saveHTML(); ?>",
"e": 1045,
"s": 690,
"text": null
},
{
"code": null,
"e": 1245,
"s": 1045,
"text": "<user> \n <username>Geeks123</username> \n <name>GeeksforGeeks</name> \n <address> \n <phone>+91-XXXXXXXXXX</phone>\n <email>[email protected]</email>\n </address> \n</user>\n"
},
{
"code": null,
"e": 1256,
"s": 1245,
"text": "Program 2:"
},
{
"code": "<?php // Create new DOMDocument$doc = new DOMDocument(); // Create a comment document$comm1 = $doc->createComment('Starting of XML document'); // Append element to the document$doc->appendChild($comm1); // Create XML file and display itecho $doc->saveHTML(); // Load the XML file$doc->loadXML(\"<user> <username>Geeks123</username> <name>GeeksforGeeks</name> <address> <phone>+91-XXXXXXXXXX</phone> <email>[email protected]</email> </address> </user>\"); // Create comment element$comm2 = $doc->createComment('Ending of XML document'); // Append element to the document$doc->appendChild($comm2); // Create XML element and display itecho $doc->saveHTML(); ?>",
"e": 1966,
"s": 1256,
"text": null
},
{
"code": null,
"e": 2227,
"s": 1966,
"text": "<!--Starting of XML document-->\n<user> \n <username>Geeks123</username> \n <name>GeeksforGeeks</name> \n <address> \n <phone>+91-XXXXXXXXXX</phone>\n <email>[email protected]</email>\n </address> \n</user><!--Ending of XML document-->\n"
},
{
"code": null,
"e": 2292,
"s": 2227,
"text": "Reference: https://www.php.net/manual/en/domdocument.loadxml.php"
},
{
"code": null,
"e": 2300,
"s": 2292,
"text": "PHP-DOM"
},
{
"code": null,
"e": 2313,
"s": 2300,
"text": "PHP-function"
},
{
"code": null,
"e": 2317,
"s": 2313,
"text": "PHP"
},
{
"code": null,
"e": 2334,
"s": 2317,
"text": "Web Technologies"
},
{
"code": null,
"e": 2338,
"s": 2334,
"text": "PHP"
},
{
"code": null,
"e": 2436,
"s": 2338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2486,
"s": 2436,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2526,
"s": 2486,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2587,
"s": 2526,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2637,
"s": 2587,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2682,
"s": 2637,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2715,
"s": 2682,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2777,
"s": 2715,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2838,
"s": 2777,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2888,
"s": 2838,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
SQL using Python | Set 3 (Handling large data) | 24 Nov, 2020
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2
In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions.A simple way is to execute the query and use fetchall(). This has been already discussed in SET 1.
executescript()This is a convenience method for executing multiple SQL statements at once. It executes the SQL script it gets as a parameter.Syntax:sqlite3.connect.executescript(script)import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executed# SQL piece of code Executedcursor.executescript(""" CREATE TABLE people( firstname, lastname, age ); CREATE TABLE book( title, author, published ); INSERT INTO book(title, author, published) VALUES ( 'Dan Clarke''s GFG Detective Agency', 'Sean Simpsons', 1987 ); """) sql = """SELECT COUNT(*) FROM book;""" cursor.execute(sql) # The output in fetched and returned# as a List by fetchall()result = cursor.fetchall()print(result) sql = """SELECT * FROM book;""" cursor.execute(sql) result = cursor.fetchall()print(result) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()Output:[(1,)]
[("Dan Clarke's GFG Detective Agency", 'Sean Simpsons', 1987)]
Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database.
Syntax:sqlite3.connect.executescript(script)
import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executed# SQL piece of code Executedcursor.executescript(""" CREATE TABLE people( firstname, lastname, age ); CREATE TABLE book( title, author, published ); INSERT INTO book(title, author, published) VALUES ( 'Dan Clarke''s GFG Detective Agency', 'Sean Simpsons', 1987 ); """) sql = """SELECT COUNT(*) FROM book;""" cursor.execute(sql) # The output in fetched and returned# as a List by fetchall()result = cursor.fetchall()print(result) sql = """SELECT * FROM book;""" cursor.execute(sql) result = cursor.fetchall()print(result) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()
Output:
[(1,)]
[("Dan Clarke's GFG Detective Agency", 'Sean Simpsons', 1987)]
Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database.
executemany()It is often the case when, large amount of data has to be inserted into database from Data Files(for simpler case take Lists, arrays). It would be simple to iterate the code many a times than write every time, each line into database. But the use of loop would not be suitable in this case, the below example shows why. Syntax and use of executemany() is explained below and how it can be used like a loop.import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(""" CREATE TABLE book( title, author, published);""") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(""" INSERT INTO book(title, author, published) VALUES (?, ?, ?)""", List) sql = """ SELECT * FROM book;"""cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()Output:Traceback (most recent call last):
File "C:/Users/GFG/Desktop/SQLITE3.py", line 16, in
List[2][3] =[['A', 'B', 2008], ['C', 'D', 2008], ['E', 'F', 2010]]
NameError: name 'List' is not defined
The use of executemany(), can make the piece of code functional.import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(""" CREATE TABLE book( title, author, published);""") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(""" INSERT INTO book(title, author, published) VALUES (?, ?, ?)""", List) sql = """SELECT * FROM book;"""cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken)# with DataBaseconnection.close()Output:('A', 'B', 2008)
('C', 'D', 2008)
('E', 'F', 2010)
import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(""" CREATE TABLE book( title, author, published);""") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(""" INSERT INTO book(title, author, published) VALUES (?, ?, ?)""", List) sql = """ SELECT * FROM book;"""cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()
Output:
Traceback (most recent call last):
File "C:/Users/GFG/Desktop/SQLITE3.py", line 16, in
List[2][3] =[['A', 'B', 2008], ['C', 'D', 2008], ['E', 'F', 2010]]
NameError: name 'List' is not defined
The use of executemany(), can make the piece of code functional.
import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect("library.db")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(""" CREATE TABLE book( title, author, published);""") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(""" INSERT INTO book(title, author, published) VALUES (?, ?, ?)""", List) sql = """SELECT * FROM book;"""cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken)# with DataBaseconnection.close()
Output:
('A', 'B', 2008)
('C', 'D', 2008)
('E', 'F', 2010)
Fetch Large Dataimport sqlite3 # Connection created with the# database using sqlite3.connect()connection = sqlite3.connect("company.db")cursor = connection.cursor() # Create Table command executedsql = """ CREATE TABLE employee ( ID INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), dob DATE);"""cursor.execute(sql) # Single Tuple insertedsql = """ INSERT INTO employee VALUES (1007, "Will", "Olsen", "M", "24-SEP-1865");"""cursor.execute(sql) # Multiple Rows insertedList = [(1008, 'Rkb', 'Boss', 'M', "27-NOV-1864"), (1098, 'Sak', 'Rose', 'F', "27-DEC-1864"), (1908, 'Royal', 'Bassen', "F", "17-NOV-1894")] connection. executemany( "INSERT INTO employee VALUES (?, ?, ?, ?, ?)", List) print("Method-1\n") # Multiple Rows fetched from# the Databasefor row in connection.execute('SELECT * FROM employee ORDER BY ID'): print (row) print("\nMethod-2\n") # Method-2 to fetch multiple# rowssql = """ SELECT * FROM employee ORDER BY ID;""" cursor.execute(sql)result = cursor.fetchall() for x in result: print(x) connection.commit()connection.close()Output:Method-1
(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')
(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')
(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')
(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')
Method-2
(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')
(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')
(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')
(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')
Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database.
import sqlite3 # Connection created with the# database using sqlite3.connect()connection = sqlite3.connect("company.db")cursor = connection.cursor() # Create Table command executedsql = """ CREATE TABLE employee ( ID INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), dob DATE);"""cursor.execute(sql) # Single Tuple insertedsql = """ INSERT INTO employee VALUES (1007, "Will", "Olsen", "M", "24-SEP-1865");"""cursor.execute(sql) # Multiple Rows insertedList = [(1008, 'Rkb', 'Boss', 'M', "27-NOV-1864"), (1098, 'Sak', 'Rose', 'F', "27-DEC-1864"), (1908, 'Royal', 'Bassen', "F", "17-NOV-1894")] connection. executemany( "INSERT INTO employee VALUES (?, ?, ?, ?, ?)", List) print("Method-1\n") # Multiple Rows fetched from# the Databasefor row in connection.execute('SELECT * FROM employee ORDER BY ID'): print (row) print("\nMethod-2\n") # Method-2 to fetch multiple# rowssql = """ SELECT * FROM employee ORDER BY ID;""" cursor.execute(sql)result = cursor.fetchall() for x in result: print(x) connection.commit()connection.close()
Output:
Method-1
(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')
(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')
(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')
(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')
Method-2
(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')
(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')
(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')
(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')
Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database.
Python
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
How to find Nth highest salary from a table
CTE in SQL | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 149,
"s": 52,
"text": "It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2"
},
{
"code": null,
"e": 467,
"s": 149,
"text": "In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions.A simple way is to execute the query and use fetchall(). This has been already discussed in SET 1."
},
{
"code": null,
"e": 1741,
"s": 467,
"text": "executescript()This is a convenience method for executing multiple SQL statements at once. It executes the SQL script it gets as a parameter.Syntax:sqlite3.connect.executescript(script)import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executed# SQL piece of code Executedcursor.executescript(\"\"\" CREATE TABLE people( firstname, lastname, age ); CREATE TABLE book( title, author, published ); INSERT INTO book(title, author, published) VALUES ( 'Dan Clarke''s GFG Detective Agency', 'Sean Simpsons', 1987 ); \"\"\") sql = \"\"\"SELECT COUNT(*) FROM book;\"\"\" cursor.execute(sql) # The output in fetched and returned# as a List by fetchall()result = cursor.fetchall()print(result) sql = \"\"\"SELECT * FROM book;\"\"\" cursor.execute(sql) result = cursor.fetchall()print(result) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()Output:[(1,)]\n[(\"Dan Clarke's GFG Detective Agency\", 'Sean Simpsons', 1987)]\nNote: This piece of code may not work on online interpreters, due to permission privileges to create/write database."
},
{
"code": null,
"e": 1786,
"s": 1741,
"text": "Syntax:sqlite3.connect.executescript(script)"
},
{
"code": "import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executed# SQL piece of code Executedcursor.executescript(\"\"\" CREATE TABLE people( firstname, lastname, age ); CREATE TABLE book( title, author, published ); INSERT INTO book(title, author, published) VALUES ( 'Dan Clarke''s GFG Detective Agency', 'Sean Simpsons', 1987 ); \"\"\") sql = \"\"\"SELECT COUNT(*) FROM book;\"\"\" cursor.execute(sql) # The output in fetched and returned# as a List by fetchall()result = cursor.fetchall()print(result) sql = \"\"\"SELECT * FROM book;\"\"\" cursor.execute(sql) result = cursor.fetchall()print(result) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()",
"e": 2682,
"s": 1786,
"text": null
},
{
"code": null,
"e": 2690,
"s": 2682,
"text": "Output:"
},
{
"code": null,
"e": 2761,
"s": 2690,
"text": "[(1,)]\n[(\"Dan Clarke's GFG Detective Agency\", 'Sean Simpsons', 1987)]\n"
},
{
"code": null,
"e": 2878,
"s": 2761,
"text": "Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database."
},
{
"code": null,
"e": 5004,
"s": 2878,
"text": "executemany()It is often the case when, large amount of data has to be inserted into database from Data Files(for simpler case take Lists, arrays). It would be simple to iterate the code many a times than write every time, each line into database. But the use of loop would not be suitable in this case, the below example shows why. Syntax and use of executemany() is explained below and how it can be used like a loop.import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(\"\"\" CREATE TABLE book( title, author, published);\"\"\") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(\"\"\" INSERT INTO book(title, author, published) VALUES (?, ?, ?)\"\"\", List) sql = \"\"\" SELECT * FROM book;\"\"\"cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()Output:Traceback (most recent call last):\n File \"C:/Users/GFG/Desktop/SQLITE3.py\", line 16, in \n List[2][3] =[['A', 'B', 2008], ['C', 'D', 2008], ['E', 'F', 2010]]\nNameError: name 'List' is not defined\nThe use of executemany(), can make the piece of code functional.import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(\"\"\" CREATE TABLE book( title, author, published);\"\"\") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(\"\"\" INSERT INTO book(title, author, published) VALUES (?, ?, ?)\"\"\", List) sql = \"\"\"SELECT * FROM book;\"\"\"cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken)# with DataBaseconnection.close()Output:('A', 'B', 2008)\n('C', 'D', 2008)\n('E', 'F', 2010)\n"
},
{
"code": "import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(\"\"\" CREATE TABLE book( title, author, published);\"\"\") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(\"\"\" INSERT INTO book(title, author, published) VALUES (?, ?, ?)\"\"\", List) sql = \"\"\" SELECT * FROM book;\"\"\"cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken) # with DataBaseconnection.close()",
"e": 5707,
"s": 5004,
"text": null
},
{
"code": null,
"e": 5715,
"s": 5707,
"text": "Output:"
},
{
"code": null,
"e": 5915,
"s": 5715,
"text": "Traceback (most recent call last):\n File \"C:/Users/GFG/Desktop/SQLITE3.py\", line 16, in \n List[2][3] =[['A', 'B', 2008], ['C', 'D', 2008], ['E', 'F', 2010]]\nNameError: name 'List' is not defined\n"
},
{
"code": null,
"e": 5980,
"s": 5915,
"text": "The use of executemany(), can make the piece of code functional."
},
{
"code": "import sqlite3 # Connection with the DataBase# 'library.db'connection = sqlite3.connect(\"library.db\")cursor = connection.cursor() # SQL piece of code Executedcursor.execute(\"\"\" CREATE TABLE book( title, author, published);\"\"\") List = [('A', 'B', 2008), ('C', 'D', 2008), ('E', 'F', 2010)] connection. executemany(\"\"\" INSERT INTO book(title, author, published) VALUES (?, ?, ?)\"\"\", List) sql = \"\"\"SELECT * FROM book;\"\"\"cursor.execute(sql)result = cursor.fetchall()for x in result: print(x) # Changes saved into databaseconnection.commit() # Connection closed(broken)# with DataBaseconnection.close()",
"e": 6657,
"s": 5980,
"text": null
},
{
"code": null,
"e": 6665,
"s": 6657,
"text": "Output:"
},
{
"code": null,
"e": 6717,
"s": 6665,
"text": "('A', 'B', 2008)\n('C', 'D', 2008)\n('E', 'F', 2010)\n"
},
{
"code": null,
"e": 8390,
"s": 6717,
"text": "Fetch Large Dataimport sqlite3 # Connection created with the# database using sqlite3.connect()connection = sqlite3.connect(\"company.db\")cursor = connection.cursor() # Create Table command executedsql = \"\"\" CREATE TABLE employee ( ID INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), dob DATE);\"\"\"cursor.execute(sql) # Single Tuple insertedsql = \"\"\" INSERT INTO employee VALUES (1007, \"Will\", \"Olsen\", \"M\", \"24-SEP-1865\");\"\"\"cursor.execute(sql) # Multiple Rows insertedList = [(1008, 'Rkb', 'Boss', 'M', \"27-NOV-1864\"), (1098, 'Sak', 'Rose', 'F', \"27-DEC-1864\"), (1908, 'Royal', 'Bassen', \"F\", \"17-NOV-1894\")] connection. executemany( \"INSERT INTO employee VALUES (?, ?, ?, ?, ?)\", List) print(\"Method-1\\n\") # Multiple Rows fetched from# the Databasefor row in connection.execute('SELECT * FROM employee ORDER BY ID'): print (row) print(\"\\nMethod-2\\n\") # Method-2 to fetch multiple# rowssql = \"\"\" SELECT * FROM employee ORDER BY ID;\"\"\" cursor.execute(sql)result = cursor.fetchall() for x in result: print(x) connection.commit()connection.close()Output:Method-1\n\n(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')\n(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')\n(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')\n(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')\n\nMethod-2\n\n(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')\n(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')\n(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')\n(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')\nNote: This piece of code may not work on online interpreters, due to permission privileges to create/write database."
},
{
"code": "import sqlite3 # Connection created with the# database using sqlite3.connect()connection = sqlite3.connect(\"company.db\")cursor = connection.cursor() # Create Table command executedsql = \"\"\" CREATE TABLE employee ( ID INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), dob DATE);\"\"\"cursor.execute(sql) # Single Tuple insertedsql = \"\"\" INSERT INTO employee VALUES (1007, \"Will\", \"Olsen\", \"M\", \"24-SEP-1865\");\"\"\"cursor.execute(sql) # Multiple Rows insertedList = [(1008, 'Rkb', 'Boss', 'M', \"27-NOV-1864\"), (1098, 'Sak', 'Rose', 'F', \"27-DEC-1864\"), (1908, 'Royal', 'Bassen', \"F\", \"17-NOV-1894\")] connection. executemany( \"INSERT INTO employee VALUES (?, ?, ?, ?, ?)\", List) print(\"Method-1\\n\") # Multiple Rows fetched from# the Databasefor row in connection.execute('SELECT * FROM employee ORDER BY ID'): print (row) print(\"\\nMethod-2\\n\") # Method-2 to fetch multiple# rowssql = \"\"\" SELECT * FROM employee ORDER BY ID;\"\"\" cursor.execute(sql)result = cursor.fetchall() for x in result: print(x) connection.commit()connection.close()",
"e": 9555,
"s": 8390,
"text": null
},
{
"code": null,
"e": 9563,
"s": 9555,
"text": "Output:"
},
{
"code": null,
"e": 9933,
"s": 9563,
"text": "Method-1\n\n(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')\n(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')\n(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')\n(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')\n\nMethod-2\n\n(1007, 'Will', 'Olsen', 'M', '24-SEP-1865')\n(1008, 'Rkb', 'Boss', 'M', '27-NOV-1864')\n(1098, 'Sak', 'Rose', 'F', '27-DEC-1864')\n(1908, 'Royal', 'Bassen', 'F', '17-NOV-1894')\n"
},
{
"code": null,
"e": 10050,
"s": 9933,
"text": "Note: This piece of code may not work on online interpreters, due to permission privileges to create/write database."
},
{
"code": null,
"e": 10057,
"s": 10050,
"text": "Python"
},
{
"code": null,
"e": 10061,
"s": 10057,
"text": "SQL"
},
{
"code": null,
"e": 10065,
"s": 10061,
"text": "SQL"
},
{
"code": null,
"e": 10163,
"s": 10065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10205,
"s": 10163,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 10227,
"s": 10205,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 10253,
"s": 10227,
"text": "Python String | replace()"
},
{
"code": null,
"e": 10285,
"s": 10253,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 10314,
"s": 10285,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 10356,
"s": 10314,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 10403,
"s": 10356,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 10421,
"s": 10403,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 10465,
"s": 10421,
"text": "How to find Nth highest salary from a table"
}
] |
How to embed audio element in a HTML document ? | 30 Sep, 2020
Since the release of HTML5, audio can be added to webpages using the <audio> tag. Previously audio could be only played on webpages using web plugins like Flash. The <audio> tag is an inline element which is used to embed sound files into a web page. It is a very useful tag if you want to add audio such as songs, interviews, etc on your webpage.
Syntax:
<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>
Example 1:
HTML
<!DOCTYPE html><html> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to embed audio in a HTML document? </h3> <audio controls> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> </body> </html>
Output:
Example 2: In this example, audio will play automatically after loading the web page.
HTML
<!DOCTYPE html><html> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to embed audio in a HTML document? </h3> <audio controls autoplay> <source src="test.mp3" type="audio/mp3"> <source src="test.ogg" type="audio/ogg"> </audio> </body> </html>
Output:
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 401,
"s": 53,
"text": "Since the release of HTML5, audio can be added to webpages using the <audio> tag. Previously audio could be only played on webpages using web plugins like Flash. The <audio> tag is an inline element which is used to embed sound files into a web page. It is a very useful tag if you want to add audio such as songs, interviews, etc on your webpage."
},
{
"code": null,
"e": 409,
"s": 401,
"text": "Syntax:"
},
{
"code": null,
"e": 475,
"s": 409,
"text": "<audio>\n <source src=\"sample.mp3\" type=\"audio/mpeg\">\n</audio>\n"
},
{
"code": null,
"e": 486,
"s": 475,
"text": "Example 1:"
},
{
"code": null,
"e": 491,
"s": 486,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to embed audio in a HTML document? </h3> <audio controls> <source src=\"test.mp3\" type=\"audio/mp3\"> <source src=\"test.ogg\" type=\"audio/ogg\"> </audio> </body> </html>",
"e": 793,
"s": 491,
"text": null
},
{
"code": null,
"e": 801,
"s": 793,
"text": "Output:"
},
{
"code": null,
"e": 887,
"s": 801,
"text": "Example 2: In this example, audio will play automatically after loading the web page."
},
{
"code": null,
"e": 892,
"s": 887,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to embed audio in a HTML document? </h3> <audio controls autoplay> <source src=\"test.mp3\" type=\"audio/mp3\"> <source src=\"test.ogg\" type=\"audio/ogg\"> </audio> </body> </html>",
"e": 1203,
"s": 892,
"text": null
},
{
"code": null,
"e": 1211,
"s": 1203,
"text": "Output:"
},
{
"code": null,
"e": 1221,
"s": 1211,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1226,
"s": 1221,
"text": "HTML"
},
{
"code": null,
"e": 1243,
"s": 1226,
"text": "Web Technologies"
},
{
"code": null,
"e": 1248,
"s": 1243,
"text": "HTML"
},
{
"code": null,
"e": 1346,
"s": 1248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1394,
"s": 1346,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1418,
"s": 1394,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1468,
"s": 1418,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1505,
"s": 1468,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1544,
"s": 1505,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1577,
"s": 1544,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1638,
"s": 1577,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1681,
"s": 1638,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1753,
"s": 1681,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to convert an array into object using stdClass() in PHP? | 02 Sep, 2021
To convert an array into the object, stdClass() is used. The stdClass() is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty.
Example 1: It converts an array into object using stdClass.
PHP
<?php // Function to convert array into// stdClass objectfunction ToObject($Array) { // Create new stdClass object $object = new stdClass(); // Use loop to convert array into // stdClass object foreach ($Array as $key => $value) { if (is_array($value)) { $value = ToObject($value); } $object->$key = $value; } return $object;} // Declare an array and initialize it$Original = array ( '1' => array( 'sNo' => '1', 'Age' => '20', 'name' => 'A' ), '2' => array( 'sNo' => '2', 'Age' => '21', 'name' => 'B' ), '3' => array( 'sNo' => '3', 'Age' => '22', 'name' => 'C' ), '4' => array( 'sNo' => '4', 'Age' => '23', 'name' => 'D' ), '5' => array( 'sNo' => '5', 'Age' => '24', 'name' => 'E' )); // Display the original arrayprint_r($Original); // Function call$convertedObj = ToObject($Original); // Display the stdClass objectprint_r($convertedObj); ?>
Array
(
[1] => Array
(
[sNo] => 1
[Age] => 20
[name] => A
)
[2] => Array
(
[sNo] => 2
[Age] => 21
[name] => B
)
[3] => Array
(
[sNo] => 3
[Age] => 22
[name] => C
)
[4] => Array
(
[sNo] => 4
[Age] => 23
[name] => D
)
[5] => Array
(
[sNo] => 5
[Age] => 24
[name] => E
)
)
stdClass Object
(
[1] => stdClass Object
(
[sNo] => 1
[Age] => 20
[name] => A
)
[2] => stdClass Object
(
[sNo] => 2
[Age] => 21
[name] => B
)
[3] => stdClass Object
(
[sNo] => 3
[Age] => 22
[name] => C
)
[4] => stdClass Object
(
[sNo] => 4
[Age] => 23
[name] => D
)
[5] => stdClass Object
(
[sNo] => 5
[Age] => 24
[name] => E
)
)
Example 2: It converts an array into object using stdClass.
PHP
<?php // Function to convert array into// stdClass objectfunction ToObject($Array) { // Create new stdClass object $object = new stdClass(); // Use loop to convert array into object foreach ($Array as $key => $value) { if (is_array($value)) { $value = ToObject($value); } $object->$key = $value; } return $object;} // Declare an array$Original = array(1, 2, 3, 4, 5, 6); // Display the array elementprint_r($Original); // Function call to convert object$convertedObj = ToObject($Original); // Display the stdClass objectprint_r($convertedObj); ?>
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
stdClass Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
ruhelaa48
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 392,
"s": 54,
"text": "To convert an array into the object, stdClass() is used. The stdClass() is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty."
},
{
"code": null,
"e": 453,
"s": 392,
"text": "Example 1: It converts an array into object using stdClass. "
},
{
"code": null,
"e": 457,
"s": 453,
"text": "PHP"
},
{
"code": "<?php // Function to convert array into// stdClass objectfunction ToObject($Array) { // Create new stdClass object $object = new stdClass(); // Use loop to convert array into // stdClass object foreach ($Array as $key => $value) { if (is_array($value)) { $value = ToObject($value); } $object->$key = $value; } return $object;} // Declare an array and initialize it$Original = array ( '1' => array( 'sNo' => '1', 'Age' => '20', 'name' => 'A' ), '2' => array( 'sNo' => '2', 'Age' => '21', 'name' => 'B' ), '3' => array( 'sNo' => '3', 'Age' => '22', 'name' => 'C' ), '4' => array( 'sNo' => '4', 'Age' => '23', 'name' => 'D' ), '5' => array( 'sNo' => '5', 'Age' => '24', 'name' => 'E' )); // Display the original arrayprint_r($Original); // Function call$convertedObj = ToObject($Original); // Display the stdClass objectprint_r($convertedObj); ?>",
"e": 1499,
"s": 457,
"text": null
},
{
"code": null,
"e": 2669,
"s": 1499,
"text": "Array\n(\n [1] => Array\n (\n [sNo] => 1\n [Age] => 20\n [name] => A\n )\n\n [2] => Array\n (\n [sNo] => 2\n [Age] => 21\n [name] => B\n )\n\n [3] => Array\n (\n [sNo] => 3\n [Age] => 22\n [name] => C\n )\n\n [4] => Array\n (\n [sNo] => 4\n [Age] => 23\n [name] => D\n )\n\n [5] => Array\n (\n [sNo] => 5\n [Age] => 24\n [name] => E\n )\n\n)\nstdClass Object\n(\n [1] => stdClass Object\n (\n [sNo] => 1\n [Age] => 20\n [name] => A\n )\n\n [2] => stdClass Object\n (\n [sNo] => 2\n [Age] => 21\n [name] => B\n )\n\n [3] => stdClass Object\n (\n [sNo] => 3\n [Age] => 22\n [name] => C\n )\n\n [4] => stdClass Object\n (\n [sNo] => 4\n [Age] => 23\n [name] => D\n )\n\n [5] => stdClass Object\n (\n [sNo] => 5\n [Age] => 24\n [name] => E\n )\n\n)"
},
{
"code": null,
"e": 2732,
"s": 2671,
"text": "Example 2: It converts an array into object using stdClass. "
},
{
"code": null,
"e": 2736,
"s": 2732,
"text": "PHP"
},
{
"code": "<?php // Function to convert array into// stdClass objectfunction ToObject($Array) { // Create new stdClass object $object = new stdClass(); // Use loop to convert array into object foreach ($Array as $key => $value) { if (is_array($value)) { $value = ToObject($value); } $object->$key = $value; } return $object;} // Declare an array$Original = array(1, 2, 3, 4, 5, 6); // Display the array elementprint_r($Original); // Function call to convert object$convertedObj = ToObject($Original); // Display the stdClass objectprint_r($convertedObj); ?>",
"e": 3343,
"s": 2736,
"text": null
},
{
"code": null,
"e": 3529,
"s": 3343,
"text": "Array\n(\n [0] => 1\n [1] => 2\n [2] => 3\n [3] => 4\n [4] => 5\n [5] => 6\n)\nstdClass Object\n(\n [0] => 1\n [1] => 2\n [2] => 3\n [3] => 4\n [4] => 5\n [5] => 6\n)"
},
{
"code": null,
"e": 3541,
"s": 3531,
"text": "ruhelaa48"
},
{
"code": null,
"e": 3548,
"s": 3541,
"text": "Picked"
},
{
"code": null,
"e": 3552,
"s": 3548,
"text": "PHP"
},
{
"code": null,
"e": 3565,
"s": 3552,
"text": "PHP Programs"
},
{
"code": null,
"e": 3582,
"s": 3565,
"text": "Web Technologies"
},
{
"code": null,
"e": 3586,
"s": 3582,
"text": "PHP"
},
{
"code": null,
"e": 3684,
"s": 3586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3734,
"s": 3684,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3774,
"s": 3734,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3835,
"s": 3774,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3885,
"s": 3835,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3930,
"s": 3885,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3980,
"s": 3930,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4020,
"s": 3980,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4081,
"s": 4020,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4131,
"s": 4081,
"text": "How to check whether an array is empty using PHP?"
}
] |
DiffUtil in RecyclerView in Android | 03 Sep, 2021
Have you ever created a List in Android? What did you use to make it? ListView or RecyclerView are two types of views. If you are an Android Developer it’s sure you’ve used RecyclerView at some point. In this article, we’ll go through how to update the RecyclerView with DiffUtils. What exactly is RecyclerView? RecyclerView is a more adaptable and efficient version of ListView. It is a container for displaying a larger data set of views that can be recycled and scrolled very quickly. Before we go into Diff Util, let’s have a look at the RecyclerView implementation.
Let’s make an Activity MainActivity and include the following code in the activity main.xml file:
XML
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".GeeksforGeeksActivity"> <androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/gfgRecyclerView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
Let’s make a data model class and a Data Source now,
Kotlin
data class GeeksCourses(val courseNumber: Int, val courseRating: Int, val courseName: String)
and the data source appears to be,
Kotlin
object geeksforGeeks { val courseList: List<Course> get() { val course = ArrayList<Rating>() course.add(Rating(1, 10, "GeeksforGeeks")) course.add(Rating(2, 12, "Android Dev")) course.add(Rating(3, 5, "DSA")) return course }}
Let’s make an adaptor now to set the list in RecyclerView.
Kotlin
class CourseAdapter : RecyclerView.Adapter<CourseAdapter.ViewHolder>() { private val courses = ArrayList<Course>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.course_list, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val Course = courses[position] holder.name_text.text = Course.name } fun setData(courses: List<Course>) { courses.clear() courses.addAll(courses) } override fun getItemCount(): Int { return courses.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val name_text: TextView = itemView.findViewById(R.id.name_text) }}
What if we need to update the list with fresh information?
We’ll refer to it as,
Kotlin
adapter.setData(/** any new data on courses**/)
and make a call from MainActivity,
Kotlin
adapter.notifyDataSetChanged()
GeekTip #1: The recyclerview will be updated with the new set of data as a result of this.
But, since notifyDataSetChanged was performing the work for you, why did you require DiffUtils? Let’s talk about it.
There is no way for the RecyclerView to know what the real changes are if notifyDataSetChanged() is used. As a result, all visible views are rebuilt. This is an extremely costly surgery.
During this procedure, a new instance of the adapter is generated. As a result, the process is highly time-consuming.
To address this, Android introduced DiffUtils as part of its support library.
It’s a utility class that helps us to perform complex tasks easily, Eugene Myers’ algorithm is the foundation of DiffUtils.
DiffUtils is used to track changes made to the RecyclerView Adapter. DiffUtil notifies the RecyclerView of any changes to the data set using the following methods:
notifyItemMovednotifyItemRangeChangednotifyItemRangeInsertednotifyItemRangeRemoved
notifyItemMoved
notifyItemRangeChanged
notifyItemRangeInserted
notifyItemRangeRemoved
These techniques are significantly more efficient than notifyDataSetChanged(). However, in order for DiffUtils to function in the project, we must give information about the old and new lists. DiffUtil is used for this. Request a callback. We’ll make a class.
Kotlin
class CoursesCallback(private val oldList: List<Course>, private val newList: List<Course>) : DiffUtil.Callback() { override fun getCourseNew(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].courseNumber=== newList.get(newItemPosition).rateIndex } override fun areContentsTheSame(oldCourse: Int, newPosition: Int): Boolean { val (_, value, name) = oldList[oldCourse] val (_, value1, name1) = newList[newPosition] return name == name1 && value == value1 } @Nullable override fun geeksPayload(oldCourse: Int, newPosition: Int): Any? { return super.geeksPayload(oldCourse, newPosition) }}
Here,
getOldCourse(): This function returns the length of the old list.
getNewCourse(): Returns the new list’s size.
areItemsTheSame(oldPosition:Int, newPosition:Int): Called by the DiffUtil to determine whether two objects in the old and new lists represent the same Item.
areContentsTheSame(oldPosition:Int, newPosition:Int): Determines if two objects have the same data. Depending on your UI, you may modify its behavior. DiffUtil calls this function only if areItemsTheSame returns true. In our example, we’re contrasting the name and price of a certain item.
obtaingeeksPayload(oldPosition:Int, newPosition:Int): If areItemTheSame returns true and areContentsTheSame returns false, the condition is satisfied. Diff This method is called by Util to obtain a payload about the modification.
To utilize this, we change the setData function in Adapter.
Kotlin
fun setCourses(newCourse: List<Courses>) { val diffCallback = CoursesDiffCallback(ratings, newCourse) val diffCourses = DiffUtil.calculateDiff(diffCallback) courses.clear() courses.addAll(newCourse) diffResult.dispatchUpdatesTo(this)}
The performance chart below shows that using DiffUtil is superior in the case of RecyclerView. These findings are based on the Nexus 6P with M-
100 items and 10 modifications: average: 0.39 milliseconds, median: 0.35 milliseconds3.82 ms for 100 items and 100 modifications, 3.75 ms for the median.2.09 ms for 100 items and 100 changes without movements, with a median of 2.06 ms.1000 items and 50 modifications: average: 4.67 milliseconds, median: 4.59 milliseconds1000 things and 50 changes with no moves: 3.59 ms on average, 3.50 ms on average1000 items and 200 modifications: 27.07 milliseconds, median: 26.92 milliseconds1000 items and 200 changes without moves: 13.54 milliseconds, median: 13.36 milliseconds
100 items and 10 modifications: average: 0.39 milliseconds, median: 0.35 milliseconds
3.82 ms for 100 items and 100 modifications, 3.75 ms for the median.
2.09 ms for 100 items and 100 changes without movements, with a median of 2.06 ms.
1000 items and 50 modifications: average: 4.67 milliseconds, median: 4.59 milliseconds
1000 things and 50 changes with no moves: 3.59 ms on average, 3.50 ms on average
1000 items and 200 modifications: 27.07 milliseconds, median: 26.92 milliseconds
1000 items and 200 changes without moves: 13.54 milliseconds, median: 13.36 milliseconds
Because of the specified limitation, the maximum size of the list is 226. This is how DiffUtils may be used to update the list in RecyclerView.
Blogathon-2021
Picked
Android
Blogathon
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Call or Consume External API in Spring Boot?
Re-rendering Components in ReactJS
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 599,
"s": 28,
"text": "Have you ever created a List in Android? What did you use to make it? ListView or RecyclerView are two types of views. If you are an Android Developer it’s sure you’ve used RecyclerView at some point. In this article, we’ll go through how to update the RecyclerView with DiffUtils. What exactly is RecyclerView? RecyclerView is a more adaptable and efficient version of ListView. It is a container for displaying a larger data set of views that can be recycled and scrolled very quickly. Before we go into Diff Util, let’s have a look at the RecyclerView implementation."
},
{
"code": null,
"e": 697,
"s": 599,
"text": "Let’s make an Activity MainActivity and include the following code in the activity main.xml file:"
},
{
"code": null,
"e": 701,
"s": 697,
"text": "XML"
},
{
"code": "<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".GeeksforGeeksActivity\"> <androidx.recyclerview.widget.RecyclerView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/gfgRecyclerView\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 1439,
"s": 701,
"text": null
},
{
"code": null,
"e": 1492,
"s": 1439,
"text": "Let’s make a data model class and a Data Source now,"
},
{
"code": null,
"e": 1499,
"s": 1492,
"text": "Kotlin"
},
{
"code": "data class GeeksCourses(val courseNumber: Int, val courseRating: Int, val courseName: String)",
"e": 1593,
"s": 1499,
"text": null
},
{
"code": null,
"e": 1628,
"s": 1593,
"text": "and the data source appears to be,"
},
{
"code": null,
"e": 1635,
"s": 1628,
"text": "Kotlin"
},
{
"code": "object geeksforGeeks { val courseList: List<Course> get() { val course = ArrayList<Rating>() course.add(Rating(1, 10, \"GeeksforGeeks\")) course.add(Rating(2, 12, \"Android Dev\")) course.add(Rating(3, 5, \"DSA\")) return course }}",
"e": 1933,
"s": 1635,
"text": null
},
{
"code": null,
"e": 1992,
"s": 1933,
"text": "Let’s make an adaptor now to set the list in RecyclerView."
},
{
"code": null,
"e": 1999,
"s": 1992,
"text": "Kotlin"
},
{
"code": "class CourseAdapter : RecyclerView.Adapter<CourseAdapter.ViewHolder>() { private val courses = ArrayList<Course>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.course_list, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val Course = courses[position] holder.name_text.text = Course.name } fun setData(courses: List<Course>) { courses.clear() courses.addAll(courses) } override fun getItemCount(): Int { return courses.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val name_text: TextView = itemView.findViewById(R.id.name_text) }}",
"e": 2840,
"s": 1999,
"text": null
},
{
"code": null,
"e": 2899,
"s": 2840,
"text": "What if we need to update the list with fresh information?"
},
{
"code": null,
"e": 2921,
"s": 2899,
"text": "We’ll refer to it as,"
},
{
"code": null,
"e": 2928,
"s": 2921,
"text": "Kotlin"
},
{
"code": "adapter.setData(/** any new data on courses**/)",
"e": 2976,
"s": 2928,
"text": null
},
{
"code": null,
"e": 3011,
"s": 2976,
"text": "and make a call from MainActivity,"
},
{
"code": null,
"e": 3018,
"s": 3011,
"text": "Kotlin"
},
{
"code": "adapter.notifyDataSetChanged()",
"e": 3049,
"s": 3018,
"text": null
},
{
"code": null,
"e": 3140,
"s": 3049,
"text": "GeekTip #1: The recyclerview will be updated with the new set of data as a result of this."
},
{
"code": null,
"e": 3257,
"s": 3140,
"text": "But, since notifyDataSetChanged was performing the work for you, why did you require DiffUtils? Let’s talk about it."
},
{
"code": null,
"e": 3444,
"s": 3257,
"text": "There is no way for the RecyclerView to know what the real changes are if notifyDataSetChanged() is used. As a result, all visible views are rebuilt. This is an extremely costly surgery."
},
{
"code": null,
"e": 3562,
"s": 3444,
"text": "During this procedure, a new instance of the adapter is generated. As a result, the process is highly time-consuming."
},
{
"code": null,
"e": 3640,
"s": 3562,
"text": "To address this, Android introduced DiffUtils as part of its support library."
},
{
"code": null,
"e": 3764,
"s": 3640,
"text": "It’s a utility class that helps us to perform complex tasks easily, Eugene Myers’ algorithm is the foundation of DiffUtils."
},
{
"code": null,
"e": 3928,
"s": 3764,
"text": "DiffUtils is used to track changes made to the RecyclerView Adapter. DiffUtil notifies the RecyclerView of any changes to the data set using the following methods:"
},
{
"code": null,
"e": 4011,
"s": 3928,
"text": "notifyItemMovednotifyItemRangeChangednotifyItemRangeInsertednotifyItemRangeRemoved"
},
{
"code": null,
"e": 4027,
"s": 4011,
"text": "notifyItemMoved"
},
{
"code": null,
"e": 4050,
"s": 4027,
"text": "notifyItemRangeChanged"
},
{
"code": null,
"e": 4074,
"s": 4050,
"text": "notifyItemRangeInserted"
},
{
"code": null,
"e": 4097,
"s": 4074,
"text": "notifyItemRangeRemoved"
},
{
"code": null,
"e": 4357,
"s": 4097,
"text": "These techniques are significantly more efficient than notifyDataSetChanged(). However, in order for DiffUtils to function in the project, we must give information about the old and new lists. DiffUtil is used for this. Request a callback. We’ll make a class."
},
{
"code": null,
"e": 4364,
"s": 4357,
"text": "Kotlin"
},
{
"code": "class CoursesCallback(private val oldList: List<Course>, private val newList: List<Course>) : DiffUtil.Callback() { override fun getCourseNew(): Int = oldList.size override fun getNewListSize(): Int = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].courseNumber=== newList.get(newItemPosition).rateIndex } override fun areContentsTheSame(oldCourse: Int, newPosition: Int): Boolean { val (_, value, name) = oldList[oldCourse] val (_, value1, name1) = newList[newPosition] return name == name1 && value == value1 } @Nullable override fun geeksPayload(oldCourse: Int, newPosition: Int): Any? { return super.geeksPayload(oldCourse, newPosition) }}",
"e": 5151,
"s": 4364,
"text": null
},
{
"code": null,
"e": 5157,
"s": 5151,
"text": "Here,"
},
{
"code": null,
"e": 5223,
"s": 5157,
"text": "getOldCourse(): This function returns the length of the old list."
},
{
"code": null,
"e": 5268,
"s": 5223,
"text": "getNewCourse(): Returns the new list’s size."
},
{
"code": null,
"e": 5425,
"s": 5268,
"text": "areItemsTheSame(oldPosition:Int, newPosition:Int): Called by the DiffUtil to determine whether two objects in the old and new lists represent the same Item."
},
{
"code": null,
"e": 5715,
"s": 5425,
"text": "areContentsTheSame(oldPosition:Int, newPosition:Int): Determines if two objects have the same data. Depending on your UI, you may modify its behavior. DiffUtil calls this function only if areItemsTheSame returns true. In our example, we’re contrasting the name and price of a certain item."
},
{
"code": null,
"e": 5945,
"s": 5715,
"text": "obtaingeeksPayload(oldPosition:Int, newPosition:Int): If areItemTheSame returns true and areContentsTheSame returns false, the condition is satisfied. Diff This method is called by Util to obtain a payload about the modification."
},
{
"code": null,
"e": 6005,
"s": 5945,
"text": "To utilize this, we change the setData function in Adapter."
},
{
"code": null,
"e": 6012,
"s": 6005,
"text": "Kotlin"
},
{
"code": "fun setCourses(newCourse: List<Courses>) { val diffCallback = CoursesDiffCallback(ratings, newCourse) val diffCourses = DiffUtil.calculateDiff(diffCallback) courses.clear() courses.addAll(newCourse) diffResult.dispatchUpdatesTo(this)}",
"e": 6262,
"s": 6012,
"text": null
},
{
"code": null,
"e": 6406,
"s": 6262,
"text": "The performance chart below shows that using DiffUtil is superior in the case of RecyclerView. These findings are based on the Nexus 6P with M-"
},
{
"code": null,
"e": 6976,
"s": 6406,
"text": "100 items and 10 modifications: average: 0.39 milliseconds, median: 0.35 milliseconds3.82 ms for 100 items and 100 modifications, 3.75 ms for the median.2.09 ms for 100 items and 100 changes without movements, with a median of 2.06 ms.1000 items and 50 modifications: average: 4.67 milliseconds, median: 4.59 milliseconds1000 things and 50 changes with no moves: 3.59 ms on average, 3.50 ms on average1000 items and 200 modifications: 27.07 milliseconds, median: 26.92 milliseconds1000 items and 200 changes without moves: 13.54 milliseconds, median: 13.36 milliseconds"
},
{
"code": null,
"e": 7062,
"s": 6976,
"text": "100 items and 10 modifications: average: 0.39 milliseconds, median: 0.35 milliseconds"
},
{
"code": null,
"e": 7131,
"s": 7062,
"text": "3.82 ms for 100 items and 100 modifications, 3.75 ms for the median."
},
{
"code": null,
"e": 7214,
"s": 7131,
"text": "2.09 ms for 100 items and 100 changes without movements, with a median of 2.06 ms."
},
{
"code": null,
"e": 7301,
"s": 7214,
"text": "1000 items and 50 modifications: average: 4.67 milliseconds, median: 4.59 milliseconds"
},
{
"code": null,
"e": 7382,
"s": 7301,
"text": "1000 things and 50 changes with no moves: 3.59 ms on average, 3.50 ms on average"
},
{
"code": null,
"e": 7463,
"s": 7382,
"text": "1000 items and 200 modifications: 27.07 milliseconds, median: 26.92 milliseconds"
},
{
"code": null,
"e": 7552,
"s": 7463,
"text": "1000 items and 200 changes without moves: 13.54 milliseconds, median: 13.36 milliseconds"
},
{
"code": null,
"e": 7696,
"s": 7552,
"text": "Because of the specified limitation, the maximum size of the list is 226. This is how DiffUtils may be used to update the list in RecyclerView."
},
{
"code": null,
"e": 7711,
"s": 7696,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 7718,
"s": 7711,
"text": "Picked"
},
{
"code": null,
"e": 7726,
"s": 7718,
"text": "Android"
},
{
"code": null,
"e": 7736,
"s": 7726,
"text": "Blogathon"
},
{
"code": null,
"e": 7743,
"s": 7736,
"text": "Kotlin"
},
{
"code": null,
"e": 7751,
"s": 7743,
"text": "Android"
},
{
"code": null,
"e": 7849,
"s": 7751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7918,
"s": 7849,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7950,
"s": 7918,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7989,
"s": 7950,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8038,
"s": 7989,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8080,
"s": 8038,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 8132,
"s": 8080,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 8167,
"s": 8132,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 8201,
"s": 8167,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 8242,
"s": 8201,
"text": "How to Connect Python with SQL Database?"
}
] |
YAML - Collections and Structures | YAML includes block collections which use indentation for scope. Here, each entry begins with a new line. Block sequences in collections indicate each entry with a dash and space (-). In YAML, block collections styles are not denoted by any specific indicator. Block collection in YAML can distinguished from other scalar quantities with an identification of key value pair included in them.
Mappings are the representation of key value as included in JSON structure. It is used often in multi-lingual support systems and creation of API in mobile applications. Mappings use key value pair representation with the usage of colon and space (:).
Consider an example of sequence of scalars, for example a list of ball players as shown below −
- Mark Joseph
- James Stephen
- Ken Griffey
The following example shows mapping scalars to scalars −
hr: 87
avg: 0.298
rbi: 149
The following example shows mapping scalars to sequences −
European:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves
Collections can be used for sequence mappings which are shown below −
-
name: Mark Joseph
hr: 87
avg: 0.278
-
name: James Stephen
hr: 63
avg: 0.288
With collections, YAML includes flow styles using explicit indicators instead of using indentation to denote space. The flow sequence in collections is written as comma separated list enclosed in square brackets. The best illustration for collection which is included in PHP frameworks like symphony.
[PHP, Perl, Python]
These collections are stored in documents. The separation of documents in YAML is denoted with three hyphens or dashes (---). The end of document is marked with three dots (...).
The separation of documents in YAML is denoted by three dashes (---). The end of document is represented with three dots (...).
The document representation is referred as structure format which is mentioned below −
# Ranking of 1998 home runs
---
- Mark Joseph
- James Stephen
- Ken Griffey
# Team ranking
---
- Chicago Cubs
- St Louis Cardinals
A question mark with a combination of space indicates a complex mapping in structure. Within a block collection, a user can include structure with a dash, colon and question mark. The following example shows the mapping between sequences −
- 2001-07-23
? [ New York Yankees,Atlanta Braves ]
: [ 2001-07-02, 2001-08-12, 2001-08-14] | [
{
"code": null,
"e": 2574,
"s": 2182,
"text": "YAML includes block collections which use indentation for scope. Here, each entry begins with a new line. Block sequences in collections indicate each entry with a dash and space (-). In YAML, block collections styles are not denoted by any specific indicator. Block collection in YAML can distinguished from other scalar quantities with an identification of key value pair included in them."
},
{
"code": null,
"e": 2826,
"s": 2574,
"text": "Mappings are the representation of key value as included in JSON structure. It is used often in multi-lingual support systems and creation of API in mobile applications. Mappings use key value pair representation with the usage of colon and space (:)."
},
{
"code": null,
"e": 2922,
"s": 2826,
"text": "Consider an example of sequence of scalars, for example a list of ball players as shown below −"
},
{
"code": null,
"e": 2967,
"s": 2922,
"text": "- Mark Joseph\n- James Stephen\n- Ken Griffey\n"
},
{
"code": null,
"e": 3024,
"s": 2967,
"text": "The following example shows mapping scalars to scalars −"
},
{
"code": null,
"e": 3052,
"s": 3024,
"text": "hr: 87\navg: 0.298\nrbi: 149\n"
},
{
"code": null,
"e": 3111,
"s": 3052,
"text": "The following example shows mapping scalars to sequences −"
},
{
"code": null,
"e": 3234,
"s": 3111,
"text": "European:\n- Boston Red Sox\n- Detroit Tigers\n- New York Yankees\n\nnational:\n- New York Mets\n- Chicago Cubs\n- Atlanta Braves\n"
},
{
"code": null,
"e": 3304,
"s": 3234,
"text": "Collections can be used for sequence mappings which are shown below −"
},
{
"code": null,
"e": 3383,
"s": 3304,
"text": "-\nname: Mark Joseph\nhr: 87\navg: 0.278\n-\nname: James Stephen\nhr: 63\navg: 0.288\n"
},
{
"code": null,
"e": 3684,
"s": 3383,
"text": "With collections, YAML includes flow styles using explicit indicators instead of using indentation to denote space. The flow sequence in collections is written as comma separated list enclosed in square brackets. The best illustration for collection which is included in PHP frameworks like symphony."
},
{
"code": null,
"e": 3705,
"s": 3684,
"text": "[PHP, Perl, Python]\n"
},
{
"code": null,
"e": 3884,
"s": 3705,
"text": "These collections are stored in documents. The separation of documents in YAML is denoted with three hyphens or dashes (---). The end of document is marked with three dots (...)."
},
{
"code": null,
"e": 4012,
"s": 3884,
"text": "The separation of documents in YAML is denoted by three dashes (---). The end of document is represented with three dots (...)."
},
{
"code": null,
"e": 4099,
"s": 4012,
"text": "The document representation is referred as structure format which is mentioned below −"
},
{
"code": null,
"e": 4233,
"s": 4099,
"text": "# Ranking of 1998 home runs\n---\n- Mark Joseph\n- James Stephen\n- Ken Griffey \n\n# Team ranking\n---\n- Chicago Cubs\n- St Louis Cardinals\n"
},
{
"code": null,
"e": 4473,
"s": 4233,
"text": "A question mark with a combination of space indicates a complex mapping in structure. Within a block collection, a user can include structure with a dash, colon and question mark. The following example shows the mapping between sequences −"
}
] |
Design Pattern - Transfer Object Pattern | The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot. Following are the entities of this type of design pattern.
Business Object - Business Service fills the Transfer Object with data.
Business Object - Business Service fills the Transfer Object with data.
Transfer Object - Simple POJO having methods to set/get attributes only.
Transfer Object - Simple POJO having methods to set/get attributes only.
Client - Client either requests or sends the Transfer Object to Business Object.
Client - Client either requests or sends the Transfer Object to Business Object.
We are going to create a StudentBO as Business Object,Student as Transfer Object representing our entities.
TransferObjectPatternDemo, our demo class, is acting as a client here and will use StudentBO and Student to demonstrate Transfer Object Design Pattern.
Create Transfer Object.
StudentVO.java
public class StudentVO {
private String name;
private int rollNo;
StudentVO(String name, int rollNo){
this.name = name;
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
Create Business Object.
StudentBO.java
import java.util.ArrayList;
import java.util.List;
public class StudentBO {
//list is working as a database
List<StudentVO> students;
public StudentBO(){
students = new ArrayList<StudentVO>();
StudentVO student1 = new StudentVO("Robert",0);
StudentVO student2 = new StudentVO("John",1);
students.add(student1);
students.add(student2);
}
public void deleteStudent(StudentVO student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from database");
}
//retrive list of students from the database
public List<StudentVO> getAllStudents() {
return students;
}
public StudentVO getStudent(int rollNo) {
return students.get(rollNo);
}
public void updateStudent(StudentVO student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo() +", updated in the database");
}
}
Use the StudentBO to demonstrate Transfer Object Design Pattern.
TransferObjectPatternDemo.java
public class TransferObjectPatternDemo {
public static void main(String[] args) {
StudentBO studentBusinessObject = new StudentBO();
//print all students
for (StudentVO student : studentBusinessObject.getAllStudents()) {
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
//update student
StudentVO student = studentBusinessObject.getAllStudents().get(0);
student.setName("Michael");
studentBusinessObject.updateStudent(student);
//get the student
student = studentBusinessObject.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
}
}
Verify the output.
Student: [RollNo : 0, Name : Robert ]
Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ] | [
{
"code": null,
"e": 3561,
"s": 2885,
"text": "The Transfer Object pattern is used when we want to pass data with multiple attributes in one shot from client to server. Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values in database in one shot. Following are the entities of this type of design pattern."
},
{
"code": null,
"e": 3633,
"s": 3561,
"text": "Business Object - Business Service fills the Transfer Object with data."
},
{
"code": null,
"e": 3705,
"s": 3633,
"text": "Business Object - Business Service fills the Transfer Object with data."
},
{
"code": null,
"e": 3778,
"s": 3705,
"text": "Transfer Object - Simple POJO having methods to set/get attributes only."
},
{
"code": null,
"e": 3851,
"s": 3778,
"text": "Transfer Object - Simple POJO having methods to set/get attributes only."
},
{
"code": null,
"e": 3932,
"s": 3851,
"text": "Client - Client either requests or sends the Transfer Object to Business Object."
},
{
"code": null,
"e": 4013,
"s": 3932,
"text": "Client - Client either requests or sends the Transfer Object to Business Object."
},
{
"code": null,
"e": 4122,
"s": 4013,
"text": "We are going to create a StudentBO as Business Object,Student as Transfer Object representing our entities.\n"
},
{
"code": null,
"e": 4275,
"s": 4122,
"text": "TransferObjectPatternDemo, our demo class, is acting as a client here and will use StudentBO and Student to demonstrate Transfer Object Design Pattern."
},
{
"code": null,
"e": 4299,
"s": 4275,
"text": "Create Transfer Object."
},
{
"code": null,
"e": 4314,
"s": 4299,
"text": "StudentVO.java"
},
{
"code": null,
"e": 4735,
"s": 4314,
"text": "public class StudentVO {\n private String name;\n private int rollNo;\n\n StudentVO(String name, int rollNo){\n this.name = name;\n this.rollNo = rollNo;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getRollNo() {\n return rollNo;\n }\n\n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n}"
},
{
"code": null,
"e": 4759,
"s": 4735,
"text": "Create Business Object."
},
{
"code": null,
"e": 4774,
"s": 4759,
"text": "StudentBO.java"
},
{
"code": null,
"e": 5787,
"s": 4774,
"text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class StudentBO {\n\t\n //list is working as a database\n List<StudentVO> students;\n\n public StudentBO(){\n students = new ArrayList<StudentVO>();\n StudentVO student1 = new StudentVO(\"Robert\",0);\n StudentVO student2 = new StudentVO(\"John\",1);\n students.add(student1);\n students.add(student2);\t\t\n }\n public void deleteStudent(StudentVO student) {\n students.remove(student.getRollNo());\n System.out.println(\"Student: Roll No \" + student.getRollNo() + \", deleted from database\");\n }\n\n //retrive list of students from the database\n public List<StudentVO> getAllStudents() {\n return students;\n }\n\n public StudentVO getStudent(int rollNo) {\n return students.get(rollNo);\n }\n\n public void updateStudent(StudentVO student) {\n students.get(student.getRollNo()).setName(student.getName());\n System.out.println(\"Student: Roll No \" + student.getRollNo() +\", updated in the database\");\n }\n}"
},
{
"code": null,
"e": 5852,
"s": 5787,
"text": "Use the StudentBO to demonstrate Transfer Object Design Pattern."
},
{
"code": null,
"e": 5883,
"s": 5852,
"text": "TransferObjectPatternDemo.java"
},
{
"code": null,
"e": 6629,
"s": 5883,
"text": "public class TransferObjectPatternDemo {\n public static void main(String[] args) {\n StudentBO studentBusinessObject = new StudentBO();\n\n //print all students\n for (StudentVO student : studentBusinessObject.getAllStudents()) {\n System.out.println(\"Student: [RollNo : \" + student.getRollNo() + \", Name : \" + student.getName() + \" ]\");\n }\n\n //update student\n StudentVO student = studentBusinessObject.getAllStudents().get(0);\n student.setName(\"Michael\");\n studentBusinessObject.updateStudent(student);\n\n //get the student\n student = studentBusinessObject.getStudent(0);\n System.out.println(\"Student: [RollNo : \" + student.getRollNo() + \", Name : \" + student.getName() + \" ]\");\n }\n}"
},
{
"code": null,
"e": 6648,
"s": 6629,
"text": "Verify the output."
}
] |
Extracting filenames from a path in MySQL? | To extract filenames from a path MySQL, you can use SUBSTRING_INDEX(). The syntax is as follows −
SELECT SUBSTRING_INDEX(ypurColumnName, '\\', -1) as anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ExtractFileNameDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> AllProgrammingFilePath varchar(100)
-> );
Query OK, 0 rows affected (0.50 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\Users\\John\\AddTwoNumberProgram.java');
Query OK, 1 row affected (0.13 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('E:\\CProgram\\MasterMindGame.c');
Query OK, 1 row affected (0.23 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('F:\\WebApplication\\WebApp.php');
Query OK, 1 row affected (0.19 sec)
mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\Users\\John\\Desktop\\AllMySQLScript.sql');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from ExtractFileNameDemo;
The following is the output −
+----+------------------------------------------+
| Id | AllProgrammingFilePath |
+----+------------------------------------------+
| 1 | C:\Users\John\AddTwoNumberProgram.java |
| 2 | E:\CProgram\MasterMindGame.c |
| 3 | F:\WebApplication\WebApp.php |
| 4 | C:\Users\John\Desktop\AllMySQLScript.sql |
+----+------------------------------------------+
4 rows in set (0.00 sec)
Here is the query to extract file names from a path in MySQL −
mysql> select SUBSTRING_INDEX(AllProgrammingFilePath, '\\', -1) as AllFileName from ExtractFileNameDemo;
The following is the output −
+--------------------------+
| AllFileName |
+--------------------------+
| AddTwoNumberProgram.java |
| MasterMindGame.c |
| WebApp.php |
| AllMySQLScript.sql |
+--------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1285,
"s": 1187,
"text": "To extract filenames from a path MySQL, you can use SUBSTRING_INDEX(). The syntax is as follows −"
},
{
"code": null,
"e": 1370,
"s": 1285,
"text": "SELECT SUBSTRING_INDEX(ypurColumnName, '\\\\', -1) as anyAliasName FROM yourTableName;"
},
{
"code": null,
"e": 1469,
"s": 1370,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1655,
"s": 1469,
"text": "mysql> create table ExtractFileNameDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> AllProgrammingFilePath varchar(100)\n -> );\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1748,
"s": 1655,
"text": "Now you can insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2337,
"s": 1748,
"text": "mysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\\\Users\\\\John\\\\AddTwoNumberProgram.java');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('E:\\\\CProgram\\\\MasterMindGame.c');\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('F:\\\\WebApplication\\\\WebApp.php');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into ExtractFileNameDemo(AllProgrammingFilePath) values('C:\\\\Users\\\\John\\\\Desktop\\\\AllMySQLScript.sql');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2424,
"s": 2337,
"text": "Display all records from the table using a select statement. The query is as follows −"
},
{
"code": null,
"e": 2465,
"s": 2424,
"text": "mysql> select *from ExtractFileNameDemo;"
},
{
"code": null,
"e": 2495,
"s": 2465,
"text": "The following is the output −"
},
{
"code": null,
"e": 2920,
"s": 2495,
"text": "+----+------------------------------------------+\n| Id | AllProgrammingFilePath |\n+----+------------------------------------------+\n| 1 | C:\\Users\\John\\AddTwoNumberProgram.java |\n| 2 | E:\\CProgram\\MasterMindGame.c |\n| 3 | F:\\WebApplication\\WebApp.php |\n| 4 | C:\\Users\\John\\Desktop\\AllMySQLScript.sql |\n+----+------------------------------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2983,
"s": 2920,
"text": "Here is the query to extract file names from a path in MySQL −"
},
{
"code": null,
"e": 3088,
"s": 2983,
"text": "mysql> select SUBSTRING_INDEX(AllProgrammingFilePath, '\\\\', -1) as AllFileName from ExtractFileNameDemo;"
},
{
"code": null,
"e": 3118,
"s": 3088,
"text": "The following is the output −"
},
{
"code": null,
"e": 3375,
"s": 3118,
"text": "+--------------------------+\n| AllFileName |\n+--------------------------+\n| AddTwoNumberProgram.java |\n| MasterMindGame.c |\n| WebApp.php |\n| AllMySQLScript.sql |\n+--------------------------+\n4 rows in set (0.00 sec)"
}
] |
Minimum number of swaps required to sort an array | Set 2 | 03 Mar, 2021
Given an array of N distinct elements, find the minimum number of swaps required to sort the array.
Note: The problem is not asking to sort the array by the minimum number of swaps. The problem is to find the minimum swaps in which the array can be sorted.
Examples:
Input: arr[] = {4, 3, 2, 1}
Output: 2
Explanation: Swap index 0 with 3 and 1 with
2 to get the sorted array {1, 2, 3, 4}.
Input: arr[] = { 3, 5, 2, 4, 6, 8}
Output: 3
Explanation:
Swap 4 and 5 so array = 3, 4, 2, 5, 6, 8
Swap 2 and 3 so array = 2, 4, 3, 5, 6, 8
Swap 4 and 3 so array = 2, 3, 4, 5, 6, 8
So the array is sorted.
This problem is already discussed in the previous article using graph. In this article another approach to solve this problem is discussed which is slightly different from the cycle approach.
Approach: The idea is to create a vector of pair in C++ with first element as array values and second element as array indices. The next step is to sort the vector of pair according to the first element of the pair. After that traverse the vector and check if the index mapped with the value is correct or not, if not then keep swapping until the element is placed correctly and keep counting the number of swaps.
Algorithm:
Create a vector of pairs and traverse the array and for every element of the array insert a element-index pair in the vectorTraverse the vector from start to the end (loop counter is i).For every element of the pair where the second element(index) is not equal to i. Swap the ith element of the vector with the second element(index) th element of the vectorIf the second element(index) is equal to i then skip the iteration of the loop.if after the swap the second element(index) is not equal to i then decrement i.Increment the counter.
Create a vector of pairs and traverse the array and for every element of the array insert a element-index pair in the vector
Traverse the vector from start to the end (loop counter is i).
For every element of the pair where the second element(index) is not equal to i. Swap the ith element of the vector with the second element(index) th element of the vector
If the second element(index) is equal to i then skip the iteration of the loop.
if after the swap the second element(index) is not equal to i then decrement i.
Increment the counter.
Implementation:
C++
Java
Python3
C#
// C++ program to find the minimum number// of swaps required to sort an array// of distinct element #include<bits/stdc++.h>using namespace std; // Function to find minimum swaps to// sort an arrayint findMinSwap(int arr[] , int n){ // Declare a vector of pair vector<pair<int,int>> vec(n); for(int i=0;i<n;i++) { vec[i].first=arr[i]; vec[i].second=i; } // Sort the vector w.r.t the first // element of pair sort(vec.begin(),vec.end()); int ans=0,c=0,j; for(int i=0;i<n;i++) { // If the element is already placed // correct, then continue if(vec[i].second==i) continue; else { // swap with its respective index swap(vec[i].first,vec[vec[i].second].first); swap(vec[i].second,vec[vec[i].second].second); } // swap until the correct // index matches if(i!=vec[i].second) --i; // each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver codeint main(){ int arr[] = {1, 5, 4, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout<<findMinSwap(arr,n); return 0;}
// Java program to find the minimum number // of swaps required to sort an array// of distinct elementimport java.util.*;class GFG{ static class Point implements Comparable<Point>{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int compareTo(Point other) { return this.x - other.x; }} // Function to find minimum swaps to // sort an arraystatic int findMinSwap(int[] arr, int n){ // Declare a vector of pair List<Point> vec = new ArrayList<Point>(); for(int i = 0; i < n; i++) { vec.add(new Point(arr[i], i)); } // Sort the vector w.r.t the first // element of pair Collections.sort(vec); int ans = 0; for(int i = 0; i < n; i++) { // If the element is already placed // correct, then continue if (vec.get(i).y == i) continue; else { // Swap with its respective index Point temp = vec.get(vec.get(i).y); vec.set(vec.get(i).y,vec.get(i)); vec.set(i, temp); } // Swap until the correct // index matches if (i != vec.get(i).y) --i; // Each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver Codepublic static void main(String []args){ int[] arr = { 1, 5, 4, 3, 2 }; int n = arr.length; System.out.println(findMinSwap(arr,n));}} // This code is contributed by Pratham76
# Python3 program to find the minimum number# of swaps required to sort an array# of distinct element # Function to find minimum swaps to# sort an arraydef findMinSwap(arr, n): # Declare a vector of pair vec = [] for i in range(n): vec.append([arr[i], i]) # Sort the vector w.r.t the first # element of pair vec = sorted(vec) ans, c, j = -1, 0, 0 for i in range(n): # If the element is already placed # correct, then continue if(vec[i][1] == i): continue else: # swap with its respective index vec[i][0], vec[vec[i][1]][1] = \ vec[vec[i][1]][1], vec[i][0] vec[i][1], vec[vec[i][1]][1] = \ vec[vec[i][1]][1], vec[i][1] # swap until the correct # index matches if(i != vec[i][1]): i -= 1 # each swap makes one element # move to its correct index, # so increment answer ans += 1 return ans # Driver codearr = [1, 5, 4, 3, 2]n = len(arr)print(findMinSwap(arr,n)) # This code is contributed by mohit kumar 29
// C# program to find the minimum number // of swaps required to sort an array// of distinct elementusing System;using System.Collections.Generic; class GFG{ // Function to find minimum swaps to // sort an arraystatic int findMinSwap(int[] arr, int n){ // Declare a vector of pair List<Tuple<int, int>> vec = new List<Tuple<int, int>>(); for(int i = 0; i < n; i++) { vec.Add(new Tuple<int, int>(arr[i], i)); } // Sort the vector w.r.t the first // element of pair vec.Sort(); int ans = 0; for(int i = 0; i < n; i++) { // If the element is already placed // correct, then continue if (vec[i].Item2 == i) continue; else { // Swap with its respective index Tuple<int, int> temp = vec[vec[i].Item2]; vec[vec[i].Item2] = vec[i]; vec[i] = temp; } // Swap until the correct // index matches if (i != vec[i].Item2) --i; // Each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver Codestatic void Main(){ int[] arr = { 1, 5, 4, 3, 2 }; int n = arr.Length; Console.Write(findMinSwap(arr,n));}} // This code is contributed by divyeshrabadiya07
2
Complexity Analysis:
Time Complexity: O(n Log n). Time required to sort the array is n log n.
Auxiliary Space: O(n). An extra array or vector is created. So, the space complexity is O(n )
mohit kumar 29
mv15
andrew1234
divyeshrabadiya07
pratham76
ujjwalmittal
Constructive Algorithms
cpp-pair
cpp-vector
Sorting Quiz
Arrays
C++ Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Introduction to Data Structures
Search an element in a sorted and rotated array
Find Second largest element in an array
Count Inversions in an array | Set 1 (Using Merge Sort)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "Given an array of N distinct elements, find the minimum number of swaps required to sort the array."
},
{
"code": null,
"e": 311,
"s": 154,
"text": "Note: The problem is not asking to sort the array by the minimum number of swaps. The problem is to find the minimum swaps in which the array can be sorted."
},
{
"code": null,
"e": 322,
"s": 311,
"text": "Examples: "
},
{
"code": null,
"e": 651,
"s": 322,
"text": "Input: arr[] = {4, 3, 2, 1}\nOutput: 2\nExplanation: Swap index 0 with 3 and 1 with\n2 to get the sorted array {1, 2, 3, 4}.\n\nInput: arr[] = { 3, 5, 2, 4, 6, 8}\nOutput: 3\nExplanation: \nSwap 4 and 5 so array = 3, 4, 2, 5, 6, 8\nSwap 2 and 3 so array = 2, 4, 3, 5, 6, 8\nSwap 4 and 3 so array = 2, 3, 4, 5, 6, 8\nSo the array is sorted."
},
{
"code": null,
"e": 843,
"s": 651,
"text": "This problem is already discussed in the previous article using graph. In this article another approach to solve this problem is discussed which is slightly different from the cycle approach."
},
{
"code": null,
"e": 1257,
"s": 843,
"text": "Approach: The idea is to create a vector of pair in C++ with first element as array values and second element as array indices. The next step is to sort the vector of pair according to the first element of the pair. After that traverse the vector and check if the index mapped with the value is correct or not, if not then keep swapping until the element is placed correctly and keep counting the number of swaps."
},
{
"code": null,
"e": 1269,
"s": 1257,
"text": "Algorithm: "
},
{
"code": null,
"e": 1807,
"s": 1269,
"text": "Create a vector of pairs and traverse the array and for every element of the array insert a element-index pair in the vectorTraverse the vector from start to the end (loop counter is i).For every element of the pair where the second element(index) is not equal to i. Swap the ith element of the vector with the second element(index) th element of the vectorIf the second element(index) is equal to i then skip the iteration of the loop.if after the swap the second element(index) is not equal to i then decrement i.Increment the counter."
},
{
"code": null,
"e": 1932,
"s": 1807,
"text": "Create a vector of pairs and traverse the array and for every element of the array insert a element-index pair in the vector"
},
{
"code": null,
"e": 1995,
"s": 1932,
"text": "Traverse the vector from start to the end (loop counter is i)."
},
{
"code": null,
"e": 2167,
"s": 1995,
"text": "For every element of the pair where the second element(index) is not equal to i. Swap the ith element of the vector with the second element(index) th element of the vector"
},
{
"code": null,
"e": 2247,
"s": 2167,
"text": "If the second element(index) is equal to i then skip the iteration of the loop."
},
{
"code": null,
"e": 2327,
"s": 2247,
"text": "if after the swap the second element(index) is not equal to i then decrement i."
},
{
"code": null,
"e": 2350,
"s": 2327,
"text": "Increment the counter."
},
{
"code": null,
"e": 2367,
"s": 2350,
"text": "Implementation: "
},
{
"code": null,
"e": 2371,
"s": 2367,
"text": "C++"
},
{
"code": null,
"e": 2376,
"s": 2371,
"text": "Java"
},
{
"code": null,
"e": 2384,
"s": 2376,
"text": "Python3"
},
{
"code": null,
"e": 2387,
"s": 2384,
"text": "C#"
},
{
"code": "// C++ program to find the minimum number// of swaps required to sort an array// of distinct element #include<bits/stdc++.h>using namespace std; // Function to find minimum swaps to// sort an arrayint findMinSwap(int arr[] , int n){ // Declare a vector of pair vector<pair<int,int>> vec(n); for(int i=0;i<n;i++) { vec[i].first=arr[i]; vec[i].second=i; } // Sort the vector w.r.t the first // element of pair sort(vec.begin(),vec.end()); int ans=0,c=0,j; for(int i=0;i<n;i++) { // If the element is already placed // correct, then continue if(vec[i].second==i) continue; else { // swap with its respective index swap(vec[i].first,vec[vec[i].second].first); swap(vec[i].second,vec[vec[i].second].second); } // swap until the correct // index matches if(i!=vec[i].second) --i; // each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver codeint main(){ int arr[] = {1, 5, 4, 3, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout<<findMinSwap(arr,n); return 0;}",
"e": 3654,
"s": 2387,
"text": null
},
{
"code": "// Java program to find the minimum number // of swaps required to sort an array// of distinct elementimport java.util.*;class GFG{ static class Point implements Comparable<Point>{ public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int compareTo(Point other) { return this.x - other.x; }} // Function to find minimum swaps to // sort an arraystatic int findMinSwap(int[] arr, int n){ // Declare a vector of pair List<Point> vec = new ArrayList<Point>(); for(int i = 0; i < n; i++) { vec.add(new Point(arr[i], i)); } // Sort the vector w.r.t the first // element of pair Collections.sort(vec); int ans = 0; for(int i = 0; i < n; i++) { // If the element is already placed // correct, then continue if (vec.get(i).y == i) continue; else { // Swap with its respective index Point temp = vec.get(vec.get(i).y); vec.set(vec.get(i).y,vec.get(i)); vec.set(i, temp); } // Swap until the correct // index matches if (i != vec.get(i).y) --i; // Each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver Codepublic static void main(String []args){ int[] arr = { 1, 5, 4, 3, 2 }; int n = arr.length; System.out.println(findMinSwap(arr,n));}} // This code is contributed by Pratham76",
"e": 5303,
"s": 3654,
"text": null
},
{
"code": "# Python3 program to find the minimum number# of swaps required to sort an array# of distinct element # Function to find minimum swaps to# sort an arraydef findMinSwap(arr, n): # Declare a vector of pair vec = [] for i in range(n): vec.append([arr[i], i]) # Sort the vector w.r.t the first # element of pair vec = sorted(vec) ans, c, j = -1, 0, 0 for i in range(n): # If the element is already placed # correct, then continue if(vec[i][1] == i): continue else: # swap with its respective index vec[i][0], vec[vec[i][1]][1] = \\ vec[vec[i][1]][1], vec[i][0] vec[i][1], vec[vec[i][1]][1] = \\ vec[vec[i][1]][1], vec[i][1] # swap until the correct # index matches if(i != vec[i][1]): i -= 1 # each swap makes one element # move to its correct index, # so increment answer ans += 1 return ans # Driver codearr = [1, 5, 4, 3, 2]n = len(arr)print(findMinSwap(arr,n)) # This code is contributed by mohit kumar 29",
"e": 6424,
"s": 5303,
"text": null
},
{
"code": "// C# program to find the minimum number // of swaps required to sort an array// of distinct elementusing System;using System.Collections.Generic; class GFG{ // Function to find minimum swaps to // sort an arraystatic int findMinSwap(int[] arr, int n){ // Declare a vector of pair List<Tuple<int, int>> vec = new List<Tuple<int, int>>(); for(int i = 0; i < n; i++) { vec.Add(new Tuple<int, int>(arr[i], i)); } // Sort the vector w.r.t the first // element of pair vec.Sort(); int ans = 0; for(int i = 0; i < n; i++) { // If the element is already placed // correct, then continue if (vec[i].Item2 == i) continue; else { // Swap with its respective index Tuple<int, int> temp = vec[vec[i].Item2]; vec[vec[i].Item2] = vec[i]; vec[i] = temp; } // Swap until the correct // index matches if (i != vec[i].Item2) --i; // Each swap makes one element // move to its correct index, // so increment answer ans++; } return ans;} // Driver Codestatic void Main(){ int[] arr = { 1, 5, 4, 3, 2 }; int n = arr.Length; Console.Write(findMinSwap(arr,n));}} // This code is contributed by divyeshrabadiya07",
"e": 7896,
"s": 6424,
"text": null
},
{
"code": null,
"e": 7898,
"s": 7896,
"text": "2"
},
{
"code": null,
"e": 7920,
"s": 7898,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 7993,
"s": 7920,
"text": "Time Complexity: O(n Log n). Time required to sort the array is n log n."
},
{
"code": null,
"e": 8087,
"s": 7993,
"text": "Auxiliary Space: O(n). An extra array or vector is created. So, the space complexity is O(n )"
},
{
"code": null,
"e": 8102,
"s": 8087,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8107,
"s": 8102,
"text": "mv15"
},
{
"code": null,
"e": 8118,
"s": 8107,
"text": "andrew1234"
},
{
"code": null,
"e": 8136,
"s": 8118,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 8146,
"s": 8136,
"text": "pratham76"
},
{
"code": null,
"e": 8159,
"s": 8146,
"text": "ujjwalmittal"
},
{
"code": null,
"e": 8183,
"s": 8159,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 8192,
"s": 8183,
"text": "cpp-pair"
},
{
"code": null,
"e": 8203,
"s": 8192,
"text": "cpp-vector"
},
{
"code": null,
"e": 8216,
"s": 8203,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 8223,
"s": 8216,
"text": "Arrays"
},
{
"code": null,
"e": 8236,
"s": 8223,
"text": "C++ Programs"
},
{
"code": null,
"e": 8243,
"s": 8236,
"text": "Arrays"
},
{
"code": null,
"e": 8341,
"s": 8243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8364,
"s": 8341,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 8396,
"s": 8364,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8444,
"s": 8396,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 8484,
"s": 8444,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 8540,
"s": 8484,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 8575,
"s": 8540,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 8609,
"s": 8575,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 8653,
"s": 8609,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 8712,
"s": 8653,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to Fix: ValueError: cannot convert float NaN to integer | 24 Dec, 2021
In this article we will discuss how to fix the value error – cannot convert float NaN to integer in Python.
In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer.
Let’s see the error and explore the methods to deal with it.
Dataset in use:
Let’s check the error when converting from float type (marks column) to integer type. We can convert by using astype() function
Example: Depicting the error
Python3
# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]}) # convert to integer typedataframe['marks'].astype(int)
Output:
ValueError: Cannot convert non-finite values (NA or inf) to integer
Because the NaN values are not possible to convert the dataframe. So in order to fix this issue, we have to remove NaN values
Here we are going to remove NaN values from the dataframe column by using dropna() function. This function will remove the rows that contain NaN values.
Syntax:
dataframe.dropna()
Example: Dealing with error
Python3
# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]})# display data typeprint(dataframe['marks'] .dtype) # drop the NaN valuesdataframe = dataframe.dropna() # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype
Output:
We can replace NaN values with 0 to get rid of NaN values. This is done by using fillna() function. This function will check the NaN values in the dataframe columns and fill the given value.
Syntax:
dataframe.fillna(0)
Example: Dealing with the error
Python3
# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]})# display data typeprint(dataframe['marks'] .dtype) # replace NaN values with 0dataframe = dataframe.fillna(0) # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype
Output:
Here we are using NumPy to convert NaN values to 0 numbers.
Syntax:
numpy.nan_to_num(numpy.nal)
Example: Dealing with the error
Python3
# import modulesimport numpy # create an nan valuedata = numpy.nan # displayprint(data) # convert man to valuefinal = numpy.nan_to_num(data) # displayfinal
Output:
nan
0.0
We can create nan value as NaN, this does not create any error while converting float to integer.
Syntax:
numpy.NaN
Example: Dealing with the error
Python3
# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.NaN, 67.8, 89, numpy.NaN]})# display data typeprint(dataframe['marks'] .dtype) # replace NaN values with 0dataframe = dataframe.fillna(0) # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype
Output:
float64
name marks
0 sireesha 90.3
1 gnanesh 0.0
2 sridevi 67.8
3 vijay 89.0
4 sreemukhi 0.0
dtype('int64')
sagar0719kumar
Picked
Python How-to-fix
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": "\n24 Dec, 2021"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "In this article we will discuss how to fix the value error – cannot convert float NaN to integer in Python."
},
{
"code": null,
"e": 300,
"s": 136,
"text": "In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer."
},
{
"code": null,
"e": 361,
"s": 300,
"text": "Let’s see the error and explore the methods to deal with it."
},
{
"code": null,
"e": 377,
"s": 361,
"text": "Dataset in use:"
},
{
"code": null,
"e": 505,
"s": 377,
"text": "Let’s check the error when converting from float type (marks column) to integer type. We can convert by using astype() function"
},
{
"code": null,
"e": 534,
"s": 505,
"text": "Example: Depicting the error"
},
{
"code": null,
"e": 542,
"s": 534,
"text": "Python3"
},
{
"code": "# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]}) # convert to integer typedataframe['marks'].astype(int)",
"e": 887,
"s": 542,
"text": null
},
{
"code": null,
"e": 895,
"s": 887,
"text": "Output:"
},
{
"code": null,
"e": 963,
"s": 895,
"text": "ValueError: Cannot convert non-finite values (NA or inf) to integer"
},
{
"code": null,
"e": 1089,
"s": 963,
"text": "Because the NaN values are not possible to convert the dataframe. So in order to fix this issue, we have to remove NaN values"
},
{
"code": null,
"e": 1242,
"s": 1089,
"text": "Here we are going to remove NaN values from the dataframe column by using dropna() function. This function will remove the rows that contain NaN values."
},
{
"code": null,
"e": 1250,
"s": 1242,
"text": "Syntax:"
},
{
"code": null,
"e": 1269,
"s": 1250,
"text": "dataframe.dropna()"
},
{
"code": null,
"e": 1298,
"s": 1269,
"text": "Example: Dealing with error "
},
{
"code": null,
"e": 1306,
"s": 1298,
"text": "Python3"
},
{
"code": "# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]})# display data typeprint(dataframe['marks'] .dtype) # drop the NaN valuesdataframe = dataframe.dropna() # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype",
"e": 1902,
"s": 1306,
"text": null
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Output:"
},
{
"code": null,
"e": 2101,
"s": 1910,
"text": "We can replace NaN values with 0 to get rid of NaN values. This is done by using fillna() function. This function will check the NaN values in the dataframe columns and fill the given value."
},
{
"code": null,
"e": 2109,
"s": 2101,
"text": "Syntax:"
},
{
"code": null,
"e": 2129,
"s": 2109,
"text": "dataframe.fillna(0)"
},
{
"code": null,
"e": 2161,
"s": 2129,
"text": "Example: Dealing with the error"
},
{
"code": null,
"e": 2169,
"s": 2161,
"text": "Python3"
},
{
"code": "# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.nan, 67.8, 89, numpy.nan]})# display data typeprint(dataframe['marks'] .dtype) # replace NaN values with 0dataframe = dataframe.fillna(0) # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype",
"e": 2771,
"s": 2169,
"text": null
},
{
"code": null,
"e": 2779,
"s": 2771,
"text": "Output:"
},
{
"code": null,
"e": 2839,
"s": 2779,
"text": "Here we are using NumPy to convert NaN values to 0 numbers."
},
{
"code": null,
"e": 2847,
"s": 2839,
"text": "Syntax:"
},
{
"code": null,
"e": 2875,
"s": 2847,
"text": "numpy.nan_to_num(numpy.nal)"
},
{
"code": null,
"e": 2907,
"s": 2875,
"text": "Example: Dealing with the error"
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Python3"
},
{
"code": "# import modulesimport numpy # create an nan valuedata = numpy.nan # displayprint(data) # convert man to valuefinal = numpy.nan_to_num(data) # displayfinal",
"e": 3071,
"s": 2915,
"text": null
},
{
"code": null,
"e": 3079,
"s": 3071,
"text": "Output:"
},
{
"code": null,
"e": 3087,
"s": 3079,
"text": "nan\n0.0"
},
{
"code": null,
"e": 3185,
"s": 3087,
"text": "We can create nan value as NaN, this does not create any error while converting float to integer."
},
{
"code": null,
"e": 3193,
"s": 3185,
"text": "Syntax:"
},
{
"code": null,
"e": 3203,
"s": 3193,
"text": "numpy.NaN"
},
{
"code": null,
"e": 3235,
"s": 3203,
"text": "Example: Dealing with the error"
},
{
"code": null,
"e": 3243,
"s": 3235,
"text": "Python3"
},
{
"code": "# import pandasimport pandas # import numpyimport numpy # create a dataframedataframe = pandas.DataFrame({'name': ['sireesha', 'gnanesh', 'sridevi', 'vijay', 'sreemukhi'], 'marks': [90.3, numpy.NaN, 67.8, 89, numpy.NaN]})# display data typeprint(dataframe['marks'] .dtype) # replace NaN values with 0dataframe = dataframe.fillna(0) # displayprint(dataframe) # convert to integer type for marks columndataframe['marks'] = dataframe['marks'].astype(int) # display data typedataframe['marks'] .dtype",
"e": 3845,
"s": 3243,
"text": null
},
{
"code": null,
"e": 3853,
"s": 3845,
"text": "Output:"
},
{
"code": null,
"e": 3996,
"s": 3853,
"text": "float64\n name marks\n0 sireesha 90.3\n1 gnanesh 0.0\n2 sridevi 67.8\n3 vijay 89.0\n4 sreemukhi 0.0\ndtype('int64')"
},
{
"code": null,
"e": 4011,
"s": 3996,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4018,
"s": 4011,
"text": "Picked"
},
{
"code": null,
"e": 4036,
"s": 4018,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 4043,
"s": 4036,
"text": "Python"
},
{
"code": null,
"e": 4141,
"s": 4043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4173,
"s": 4141,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4200,
"s": 4173,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4221,
"s": 4200,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4244,
"s": 4221,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4275,
"s": 4244,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4331,
"s": 4275,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4373,
"s": 4331,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4415,
"s": 4373,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4454,
"s": 4415,
"text": "Python | Get unique values from a list"
}
] |
How to prevent SQL Injection in PHP ? | 31 May, 2021
In this article, we are going to discuss how to prevent SQL injection in PHP. The prerequisite of this topic is that you are having XAMPP in your computer.
SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker).
In this type of technique, the hacker or attacker uses some special characters which convert the SQL query into a new SQL query and the attacker can manipulate the query by entering more kinds of keywords.
Let us make a SQL injection scenario then we will learn how to fix it.
Step 1: So, let’s start by creating a database –
CREATE DATABASE GFG;
Step 2: Use this database –
USE GFG;
Step 3: Create a login credentials table in GFG database –
CREATE TABLE users(
id int(10) PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255),
password VARCHAR(255)
);
Step 4: Insert some data into database –
INSERT INTO users VALUES(1, 'idevesh', '1234');
INSERT INTO users VALUES(2, 'geeksforgeeks', 'gfg');
Data After insertion
Step 5: Now create a PHP script for login page –
(a) Create a DB Connection File (dbconnection.php) –
PHP
<?php $db = mysqli_connect("localhost","root","","GFG"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error();}?>
(b) Create a HTML form to input from the USER –
PHP
<!DOCTYPE html><html> <head> <title>GFG SQL Injection Article</title> <link rel="stylesheet" type="text/css" href="style.css"></head> <body> <div id="form"> <h1>LOGIN FOR SQL INJECTION</h1> <form name="form" action="verifyLogin.php" method="POST"> <p> <label> USER NAME: </label> <input type="text" id="user" name="userid" /> </p> <p> <label> PASSWORD: </label> <input type="text" id="pass" name="password" /> </p> <p> <input type="submit" id="button" value="Login" /> </p> </form> </div></body> </html>
(c) Create a file verifyLogin.php for validating the user input –
PHP
<?php include 'dbconnection.php';$userid = $_POST['userid'];$password = $_POST['password'];$sql = "SELECT * FROM users WHERE username = '$userid' AND password = '$password'";$result = mysqli_query($db, $sql) or die(mysqli_error($db));$num = mysqli_fetch_array($result); if($num > 0) { echo "Login Success";}else { echo "Wrong User id or password";}?>
Step 6: Now we will pass a poisoned password to get entry into the user profile –
Poisoned password = ' or 'a'='a
So, as you can see the above-mentioned poisoned string can make any user login in the geeksforgeeks username so this is called SQL Injection.
Now to avoid this type of SQL injection, we need to sanitize the password input and username input using mysqli_real_escape_string() function.
The mysqli_real_escape_string() function takes the special characters as they were as an input from the user and doesn’t consider them as query usage.
So new code for verifyLogin.php will be –
PHP
<?php include 'dbconnection.php';$userid = $_POST['userid'];$password = $_POST['password']; $sanitized_userid = mysqli_real_escape_string($db, $userid); $sanitized_password = mysqli_real_escape_string($db, $password); $sql = "SELECT * FROM users WHERE username = '" . $sanitized_userid . "' AND password = '" . $sanitized_password . "'"; $result = mysqli_query($db, $sql) or die(mysqli_error($db)); $num = mysqli_fetch_array($result); if($num > 0) { echo "Login Success";}else { echo "Wrong User id or password";} ?>
PHP-function
PHP-MySQL
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
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": 53,
"s": 25,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 209,
"s": 53,
"text": "In this article, we are going to discuss how to prevent SQL injection in PHP. The prerequisite of this topic is that you are having XAMPP in your computer."
},
{
"code": null,
"e": 429,
"s": 209,
"text": "SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker)."
},
{
"code": null,
"e": 635,
"s": 429,
"text": "In this type of technique, the hacker or attacker uses some special characters which convert the SQL query into a new SQL query and the attacker can manipulate the query by entering more kinds of keywords."
},
{
"code": null,
"e": 706,
"s": 635,
"text": "Let us make a SQL injection scenario then we will learn how to fix it."
},
{
"code": null,
"e": 758,
"s": 708,
"text": "Step 1: So, let’s start by creating a database – "
},
{
"code": null,
"e": 779,
"s": 758,
"text": "CREATE DATABASE GFG;"
},
{
"code": null,
"e": 807,
"s": 779,
"text": "Step 2: Use this database –"
},
{
"code": null,
"e": 816,
"s": 807,
"text": "USE GFG;"
},
{
"code": null,
"e": 876,
"s": 816,
"text": "Step 3: Create a login credentials table in GFG database – "
},
{
"code": null,
"e": 996,
"s": 876,
"text": "CREATE TABLE users( \n id int(10) PRIMARY KEY AUTO_INCREMENT,\n username VARCHAR(255),\n password VARCHAR(255)\n);"
},
{
"code": null,
"e": 1038,
"s": 996,
"text": "Step 4: Insert some data into database – "
},
{
"code": null,
"e": 1139,
"s": 1038,
"text": "INSERT INTO users VALUES(1, 'idevesh', '1234');\nINSERT INTO users VALUES(2, 'geeksforgeeks', 'gfg');"
},
{
"code": null,
"e": 1160,
"s": 1139,
"text": "Data After insertion"
},
{
"code": null,
"e": 1210,
"s": 1160,
"text": "Step 5: Now create a PHP script for login page – "
},
{
"code": null,
"e": 1264,
"s": 1210,
"text": "(a) Create a DB Connection File (dbconnection.php) – "
},
{
"code": null,
"e": 1268,
"s": 1264,
"text": "PHP"
},
{
"code": "<?php $db = mysqli_connect(\"localhost\",\"root\",\"\",\"GFG\"); if (mysqli_connect_errno()) { echo \"Failed to connect to MySQL: \" . mysqli_connect_error();}?>",
"e": 1433,
"s": 1268,
"text": null
},
{
"code": null,
"e": 1484,
"s": 1435,
"text": "(b) Create a HTML form to input from the USER – "
},
{
"code": null,
"e": 1488,
"s": 1484,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html> <head> <title>GFG SQL Injection Article</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head> <body> <div id=\"form\"> <h1>LOGIN FOR SQL INJECTION</h1> <form name=\"form\" action=\"verifyLogin.php\" method=\"POST\"> <p> <label> USER NAME: </label> <input type=\"text\" id=\"user\" name=\"userid\" /> </p> <p> <label> PASSWORD: </label> <input type=\"text\" id=\"pass\" name=\"password\" /> </p> <p> <input type=\"submit\" id=\"button\" value=\"Login\" /> </p> </form> </div></body> </html>",
"e": 2255,
"s": 1488,
"text": null
},
{
"code": null,
"e": 2322,
"s": 2255,
"text": "(c) Create a file verifyLogin.php for validating the user input – "
},
{
"code": null,
"e": 2326,
"s": 2322,
"text": "PHP"
},
{
"code": "<?php include 'dbconnection.php';$userid = $_POST['userid'];$password = $_POST['password'];$sql = \"SELECT * FROM users WHERE username = '$userid' AND password = '$password'\";$result = mysqli_query($db, $sql) or die(mysqli_error($db));$num = mysqli_fetch_array($result); if($num > 0) { echo \"Login Success\";}else { echo \"Wrong User id or password\";}?>",
"e": 2689,
"s": 2326,
"text": null
},
{
"code": null,
"e": 2772,
"s": 2689,
"text": "Step 6: Now we will pass a poisoned password to get entry into the user profile – "
},
{
"code": null,
"e": 2804,
"s": 2772,
"text": "Poisoned password = ' or 'a'='a"
},
{
"code": null,
"e": 2946,
"s": 2804,
"text": "So, as you can see the above-mentioned poisoned string can make any user login in the geeksforgeeks username so this is called SQL Injection."
},
{
"code": null,
"e": 3089,
"s": 2946,
"text": "Now to avoid this type of SQL injection, we need to sanitize the password input and username input using mysqli_real_escape_string() function."
},
{
"code": null,
"e": 3240,
"s": 3089,
"text": "The mysqli_real_escape_string() function takes the special characters as they were as an input from the user and doesn’t consider them as query usage."
},
{
"code": null,
"e": 3283,
"s": 3240,
"text": "So new code for verifyLogin.php will be – "
},
{
"code": null,
"e": 3287,
"s": 3283,
"text": "PHP"
},
{
"code": "<?php include 'dbconnection.php';$userid = $_POST['userid'];$password = $_POST['password']; $sanitized_userid = mysqli_real_escape_string($db, $userid); $sanitized_password = mysqli_real_escape_string($db, $password); $sql = \"SELECT * FROM users WHERE username = '\" . $sanitized_userid . \"' AND password = '\" . $sanitized_password . \"'\"; $result = mysqli_query($db, $sql) or die(mysqli_error($db)); $num = mysqli_fetch_array($result); if($num > 0) { echo \"Login Success\";}else { echo \"Wrong User id or password\";} ?>",
"e": 3858,
"s": 3287,
"text": null
},
{
"code": null,
"e": 3871,
"s": 3858,
"text": "PHP-function"
},
{
"code": null,
"e": 3881,
"s": 3871,
"text": "PHP-MySQL"
},
{
"code": null,
"e": 3895,
"s": 3881,
"text": "PHP-Questions"
},
{
"code": null,
"e": 3902,
"s": 3895,
"text": "Picked"
},
{
"code": null,
"e": 3906,
"s": 3902,
"text": "PHP"
},
{
"code": null,
"e": 3923,
"s": 3906,
"text": "Web Technologies"
},
{
"code": null,
"e": 3927,
"s": 3923,
"text": "PHP"
},
{
"code": null,
"e": 4025,
"s": 3927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4070,
"s": 4025,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 4094,
"s": 4070,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 4146,
"s": 4094,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 4196,
"s": 4146,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4236,
"s": 4196,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4269,
"s": 4236,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4331,
"s": 4269,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4392,
"s": 4331,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4442,
"s": 4392,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PyQt5 QListWidget – Getting Current Item | 01 Aug, 2020
In this article we will see how we can get the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item.Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method.
In order to do this we will use currentItem method with the list widget object.
Syntax : list_widget.currentItem()
Argument : It takes no argument
Return : It returns QListWidgetItem object
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting current item value = list_widget.currentItem() # setting text to the label label.setText("Current Item : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "In this article we will see how we can get the current item of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item.Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method."
},
{
"code": null,
"e": 564,
"s": 484,
"text": "In order to do this we will use currentItem method with the list widget object."
},
{
"code": null,
"e": 599,
"s": 564,
"text": "Syntax : list_widget.currentItem()"
},
{
"code": null,
"e": 631,
"s": 599,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 674,
"s": 631,
"text": "Return : It returns QListWidgetItem object"
},
{
"code": null,
"e": 702,
"s": 674,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting current item value = list_widget.currentItem() # setting text to the label label.setText(\"Current Item : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2273,
"s": 702,
"text": null
},
{
"code": null,
"e": 2282,
"s": 2273,
"text": "Output :"
},
{
"code": null,
"e": 2306,
"s": 2282,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 2317,
"s": 2306,
"text": "Python-gui"
},
{
"code": null,
"e": 2329,
"s": 2317,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2336,
"s": 2329,
"text": "Python"
},
{
"code": null,
"e": 2434,
"s": 2336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2452,
"s": 2434,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2494,
"s": 2452,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2516,
"s": 2494,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2542,
"s": 2516,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2574,
"s": 2542,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2603,
"s": 2574,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2630,
"s": 2603,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2660,
"s": 2630,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2696,
"s": 2660,
"text": "Convert integer to string in Python"
}
] |
MATLAB - The Nested switch Statements | It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
The syntax for a nested switch statement is as follows −
switch(ch1)
case 'A'
fprintf('This A is part of outer switch');
switch(ch2)
case 'A'
fprintf('This A is part of inner switch' );
case 'B'
fprintf('This B is part of inner switch' );
end
case 'B'
fprintf('This B is part of outer switch' );
end
Create a script file and type the following code in it −
a = 100;
b = 200;
switch(a)
case 100
fprintf('This is part of outer switch %d\n', a );
switch(b)
case 200
fprintf('This is part of inner switch %d\n', a );
end
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
When you run the file, it displays −
This is part of outer switch 100
This is part of inner switch 100
Exact value of a is : 100
Exact value of b is : 200 | [
{
"code": null,
"e": 2466,
"s": 2275,
"text": "It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise."
},
{
"code": null,
"e": 2523,
"s": 2466,
"text": "The syntax for a nested switch statement is as follows −"
},
{
"code": null,
"e": 2850,
"s": 2523,
"text": "switch(ch1) \n case 'A' \n fprintf('This A is part of outer switch');\n switch(ch2) \n case 'A'\n fprintf('This A is part of inner switch' );\n \n case 'B' \n fprintf('This B is part of inner switch' );\n end \n case 'B'\n fprintf('This B is part of outer switch' );\nend"
},
{
"code": null,
"e": 2907,
"s": 2850,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 3203,
"s": 2907,
"text": "a = 100;\nb = 200;\nswitch(a) \n case 100 \n fprintf('This is part of outer switch %d\\n', a );\n switch(b) \n case 200\n fprintf('This is part of inner switch %d\\n', a );\n end\nend\n\nfprintf('Exact value of a is : %d\\n', a );\nfprintf('Exact value of b is : %d\\n', b );"
},
{
"code": null,
"e": 3240,
"s": 3203,
"text": "When you run the file, it displays −"
}
] |
Docker – EXPOSE Instruction | 28 Oct, 2020
The EXPOSE instruction exposes a particular port with a specified protocol inside a Docker Container. In the simplest term, the EXPOSE instruction tells Docker to get all its information required during the runtime from a specified Port. These ports can be either TCP or UDP, but it’s TCP by default. It is also important to understand that the EXPOSE instruction only acts as an information platform (like Documentation) between the creator of the Docker image and the individual running the Container. Some points to be noted are:
It can use TCP or UDP protocol to expose the port.
Default Protocol is TCP if no other protocol is specified.
It does not map ports on the host machine.
It can be overridden using the publish flag (-p) while starting a Container.
The syntax to EXPOSE the ports by specifying a protocol is:
Syntax: EXPOSE <port>/<protocol>
In this article, we are going to discuss some practical examples of how to use EXPOSE instruction in your Dockerfile and overriding it using the publish flag while starting a Docker Container.
Follow the below steps to implement the EXPOSE instruction in a docker container:
Let’s create a Dockerfile with two EXPOSE Instructions, one with TCP protocol and the other with UDP protocol.
FROM ubuntu:latest
EXPOSE 80/tcp
EXPOSE 80/udp
To build the Docker Image using the above Dockerfile, you can use the Docker Build command.
sudo docker build -t expose-demo .
To run the Docker Container, you can use the Docker run command.
sudo docker run -it expose-demo bash
To verify the ports exposed, you can use the Docker inspect command.
sudo docker image inspect --format='' expose-demo
In the above screenshot, you can see the ExposedPorts object contains two exposed ports that we have specified in the Dockerfile.
To publish all the exposed ports, you can use the -p flag.
sudo docker run -P -d expose-demo
You can just the list containers to check the published ports using the following command. But make sure that the Container is running.
sudo docker start <container-id>
sudo docker container ls
To conclude, in this article, we discussed how to use the EXPOSE instruction inside a Dockerfile to expose ports of a Container using a specified protocol and use -p flag to publish the ports.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Fuzzy Logic | Introduction
Monolithic vs Microservices architecture
Mounting a Volume Inside Docker Container | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 564,
"s": 28,
"text": "The EXPOSE instruction exposes a particular port with a specified protocol inside a Docker Container. In the simplest term, the EXPOSE instruction tells Docker to get all its information required during the runtime from a specified Port. These ports can be either TCP or UDP, but it’s TCP by default. It is also important to understand that the EXPOSE instruction only acts as an information platform (like Documentation) between the creator of the Docker image and the individual running the Container. Some points to be noted are: "
},
{
"code": null,
"e": 615,
"s": 564,
"text": "It can use TCP or UDP protocol to expose the port."
},
{
"code": null,
"e": 674,
"s": 615,
"text": "Default Protocol is TCP if no other protocol is specified."
},
{
"code": null,
"e": 717,
"s": 674,
"text": "It does not map ports on the host machine."
},
{
"code": null,
"e": 794,
"s": 717,
"text": "It can be overridden using the publish flag (-p) while starting a Container."
},
{
"code": null,
"e": 854,
"s": 794,
"text": "The syntax to EXPOSE the ports by specifying a protocol is:"
},
{
"code": null,
"e": 888,
"s": 854,
"text": "Syntax: EXPOSE <port>/<protocol>\n"
},
{
"code": null,
"e": 1081,
"s": 888,
"text": "In this article, we are going to discuss some practical examples of how to use EXPOSE instruction in your Dockerfile and overriding it using the publish flag while starting a Docker Container."
},
{
"code": null,
"e": 1163,
"s": 1081,
"text": "Follow the below steps to implement the EXPOSE instruction in a docker container:"
},
{
"code": null,
"e": 1274,
"s": 1163,
"text": "Let’s create a Dockerfile with two EXPOSE Instructions, one with TCP protocol and the other with UDP protocol."
},
{
"code": null,
"e": 1322,
"s": 1274,
"text": "FROM ubuntu:latest\nEXPOSE 80/tcp\nEXPOSE 80/udp\n"
},
{
"code": null,
"e": 1414,
"s": 1322,
"text": "To build the Docker Image using the above Dockerfile, you can use the Docker Build command."
},
{
"code": null,
"e": 1450,
"s": 1414,
"text": "sudo docker build -t expose-demo .\n"
},
{
"code": null,
"e": 1515,
"s": 1450,
"text": "To run the Docker Container, you can use the Docker run command."
},
{
"code": null,
"e": 1553,
"s": 1515,
"text": "sudo docker run -it expose-demo bash\n"
},
{
"code": null,
"e": 1622,
"s": 1553,
"text": "To verify the ports exposed, you can use the Docker inspect command."
},
{
"code": null,
"e": 1674,
"s": 1622,
"text": "sudo docker image inspect --format='' expose-demo \n"
},
{
"code": null,
"e": 1804,
"s": 1674,
"text": "In the above screenshot, you can see the ExposedPorts object contains two exposed ports that we have specified in the Dockerfile."
},
{
"code": null,
"e": 1863,
"s": 1804,
"text": "To publish all the exposed ports, you can use the -p flag."
},
{
"code": null,
"e": 1898,
"s": 1863,
"text": "sudo docker run -P -d expose-demo\n"
},
{
"code": null,
"e": 2034,
"s": 1898,
"text": "You can just the list containers to check the published ports using the following command. But make sure that the Container is running."
},
{
"code": null,
"e": 2093,
"s": 2034,
"text": "sudo docker start <container-id>\nsudo docker container ls\n"
},
{
"code": null,
"e": 2286,
"s": 2093,
"text": "To conclude, in this article, we discussed how to use the EXPOSE instruction inside a Dockerfile to expose ports of a Container using a specified protocol and use -p flag to publish the ports."
},
{
"code": null,
"e": 2303,
"s": 2286,
"text": "Docker Container"
},
{
"code": null,
"e": 2309,
"s": 2303,
"text": "linux"
},
{
"code": null,
"e": 2335,
"s": 2309,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2433,
"s": 2335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2469,
"s": 2433,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2493,
"s": 2469,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2537,
"s": 2493,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2573,
"s": 2537,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2608,
"s": 2573,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2649,
"s": 2608,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 2697,
"s": 2649,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 2724,
"s": 2697,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 2765,
"s": 2724,
"text": "Monolithic vs Microservices architecture"
}
] |
Count Values in Pandas Dataframe - GeeksforGeeks | 09 Aug, 2021
In this article, we are going to count values in Pandas dataframe. First, we will create a data frame, and then we will count the values of different attributes.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:
axis {0 or ‘index’, 1 or ‘columns’}: default 0 Counts are generated for each column if axis=0 or axis=’index’ and counts are generated for each row if axis=1 or axis=”columns”.
level (nt or str, optional): If the axis is a MultiIndex, count along a particular level, collapsing into a DataFrame. A str specifies the level name.
numeric_only (boolean, default False): It includes only int, float or boolean value.
Returns: It returns count of non-null values and if level is used it returns dataframe
Step-by-step approach:
Step 1: Importing libraries.
Python3
# importing librariesimport numpy as npimport pandas as pd
Step 2: Creating Dataframe
Python3
# Creating dataframe with# some missing valuesNaN = np.nandataframe = pd.DataFrame({'Name': ['Shobhit', 'Vaibhav', 'Vimal', 'Sourabh', 'Rahul', 'Shobhit'], 'Physics': [11, 12, 13, 14, NaN, 11], 'Chemistry': [10, 14, NaN, 18, 20, 10], 'Math': [13, 10, 15, NaN, NaN, 13]}) display(dataframe)
Output:
Created Dataframe
Step 3: In this step, we just simply use the .count() function to count all the values of different columns.
Python3
# using dataframe.count()# to count all valuesdataframe.count()
Output:
We can see that there is a difference in count value as we have missing values. There are 5 values in the Name column,4 in Physics and Chemistry, and 3 in Math. In this case, it uses it’s an argument with its default values.
Step 4: If we want to count all the values with respect to row then we have to pass axis=1 or ‘columns’.
Python3
# we can pass either axis=1 or# axos='columns' to count with respect to rowprint(dataframe.count(axis = 1)) print(dataframe.count(axis = 'columns'))
Output:
count with respect to row
Step 5: Now if we want to count null values in our dataframe.
Python3
# it will give the count# of individual columns count of null valuesprint(dataframe.isnull().sum()) # it will give the total null# values present in our dataframeprint("Total Null values count: ", dataframe.isnull().sum().sum())
Output:
Step 6:. Some examples to use .count()
Now we want to count no of students whose physics marks are greater than 11.
Python3
# count of student with greater# than 11 marks in physicsprint("Count of students with physics marks greater than 11 is->", dataframe[dataframe['Physics'] > 11]['Name'].count()) # resultant of above dataframedataframe[dataframe['Physics']>11]
Output:
Physics>11
Count of students whose physics marks are greater than 10,chemistry marks are greater than 11 and math marks are greater than 9.
Python3
# Count of students whose physics marks# are greater than 10,chemistry marks are# greater than 11 and math marks are greater than 9.print("Count of students ->", dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)]['Name'].count()) # dataframe of above resultdataframe[(dataframe['Physics'] > 10 ) & (dataframe['Chemistry'] > 11 ) & (dataframe['Math'] > 9 )]
Output:
Physics>10 ,Chemistry>11,Maths>9
Below is the full implementation:
Python3
# importing Librariesimport pandas as pdimport numpy as np # Creating dataframe using dictionaryNaN = np.nandataframe = pd.DataFrame({'Name': ['Shobhit', 'Vaibhav', 'Vimal', 'Sourabh', 'Rahul', 'Shobhit'], 'Physics': [11, 12, 13, 14, NaN, 11], 'Chemistry': [10, 14, NaN, 18, 20, 10], 'Math': [13, 10, 15, NaN, NaN, 13]}) print("Created Dataframe")print(dataframe) # finding Count of all columnsprint("Count of all values wrt columns")print(dataframe.count()) # Count according to rowsprint("Count of all values wrt rows")print(dataframe.count(axis=1))print(dataframe.count(axis='columns')) # count of null valuesprint("Null Values counts ")print(dataframe.isnull().sum())print("Total null values", dataframe.isnull().sum().sum()) # count of student with greater# than 11 marks in physicsprint("Count of students with physics marks greater than 11 is->", dataframe[dataframe['Physics'] > 11]['Name'].count()) # resultant of above dataframeprint(dataframe[dataframe['Physics'] > 11])print("Count of students ->", dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)]['Name'].count()) print(dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)])
Output:
akshaysingh98088
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.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
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
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 24454,
"s": 24292,
"text": "In this article, we are going to count values in Pandas dataframe. First, we will create a data frame, and then we will count the values of different attributes."
},
{
"code": null,
"e": 24518,
"s": 24454,
"text": "Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)"
},
{
"code": null,
"e": 24530,
"s": 24518,
"text": "Parameters:"
},
{
"code": null,
"e": 24707,
"s": 24530,
"text": "axis {0 or ‘index’, 1 or ‘columns’}: default 0 Counts are generated for each column if axis=0 or axis=’index’ and counts are generated for each row if axis=1 or axis=”columns”."
},
{
"code": null,
"e": 24858,
"s": 24707,
"text": "level (nt or str, optional): If the axis is a MultiIndex, count along a particular level, collapsing into a DataFrame. A str specifies the level name."
},
{
"code": null,
"e": 24943,
"s": 24858,
"text": "numeric_only (boolean, default False): It includes only int, float or boolean value."
},
{
"code": null,
"e": 25030,
"s": 24943,
"text": "Returns: It returns count of non-null values and if level is used it returns dataframe"
},
{
"code": null,
"e": 25053,
"s": 25030,
"text": "Step-by-step approach:"
},
{
"code": null,
"e": 25082,
"s": 25053,
"text": "Step 1: Importing libraries."
},
{
"code": null,
"e": 25090,
"s": 25082,
"text": "Python3"
},
{
"code": "# importing librariesimport numpy as npimport pandas as pd",
"e": 25149,
"s": 25090,
"text": null
},
{
"code": null,
"e": 25176,
"s": 25149,
"text": "Step 2: Creating Dataframe"
},
{
"code": null,
"e": 25184,
"s": 25176,
"text": "Python3"
},
{
"code": "# Creating dataframe with# some missing valuesNaN = np.nandataframe = pd.DataFrame({'Name': ['Shobhit', 'Vaibhav', 'Vimal', 'Sourabh', 'Rahul', 'Shobhit'], 'Physics': [11, 12, 13, 14, NaN, 11], 'Chemistry': [10, 14, NaN, 18, 20, 10], 'Math': [13, 10, 15, NaN, NaN, 13]}) display(dataframe)",
"e": 25617,
"s": 25184,
"text": null
},
{
"code": null,
"e": 25625,
"s": 25617,
"text": "Output:"
},
{
"code": null,
"e": 25643,
"s": 25625,
"text": "Created Dataframe"
},
{
"code": null,
"e": 25752,
"s": 25643,
"text": "Step 3: In this step, we just simply use the .count() function to count all the values of different columns."
},
{
"code": null,
"e": 25760,
"s": 25752,
"text": "Python3"
},
{
"code": "# using dataframe.count()# to count all valuesdataframe.count()",
"e": 25824,
"s": 25760,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25824,
"text": "Output:"
},
{
"code": null,
"e": 26057,
"s": 25832,
"text": "We can see that there is a difference in count value as we have missing values. There are 5 values in the Name column,4 in Physics and Chemistry, and 3 in Math. In this case, it uses it’s an argument with its default values."
},
{
"code": null,
"e": 26162,
"s": 26057,
"text": "Step 4: If we want to count all the values with respect to row then we have to pass axis=1 or ‘columns’."
},
{
"code": null,
"e": 26170,
"s": 26162,
"text": "Python3"
},
{
"code": "# we can pass either axis=1 or# axos='columns' to count with respect to rowprint(dataframe.count(axis = 1)) print(dataframe.count(axis = 'columns'))",
"e": 26319,
"s": 26170,
"text": null
},
{
"code": null,
"e": 26327,
"s": 26319,
"text": "Output:"
},
{
"code": null,
"e": 26353,
"s": 26327,
"text": "count with respect to row"
},
{
"code": null,
"e": 26415,
"s": 26353,
"text": "Step 5: Now if we want to count null values in our dataframe."
},
{
"code": null,
"e": 26423,
"s": 26415,
"text": "Python3"
},
{
"code": "# it will give the count# of individual columns count of null valuesprint(dataframe.isnull().sum()) # it will give the total null# values present in our dataframeprint(\"Total Null values count: \", dataframe.isnull().sum().sum())",
"e": 26657,
"s": 26423,
"text": null
},
{
"code": null,
"e": 26665,
"s": 26657,
"text": "Output:"
},
{
"code": null,
"e": 26704,
"s": 26665,
"text": "Step 6:. Some examples to use .count()"
},
{
"code": null,
"e": 26781,
"s": 26704,
"text": "Now we want to count no of students whose physics marks are greater than 11."
},
{
"code": null,
"e": 26789,
"s": 26781,
"text": "Python3"
},
{
"code": "# count of student with greater# than 11 marks in physicsprint(\"Count of students with physics marks greater than 11 is->\", dataframe[dataframe['Physics'] > 11]['Name'].count()) # resultant of above dataframedataframe[dataframe['Physics']>11]",
"e": 27037,
"s": 26789,
"text": null
},
{
"code": null,
"e": 27045,
"s": 27037,
"text": "Output:"
},
{
"code": null,
"e": 27056,
"s": 27045,
"text": "Physics>11"
},
{
"code": null,
"e": 27185,
"s": 27056,
"text": "Count of students whose physics marks are greater than 10,chemistry marks are greater than 11 and math marks are greater than 9."
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Python3"
},
{
"code": "# Count of students whose physics marks# are greater than 10,chemistry marks are# greater than 11 and math marks are greater than 9.print(\"Count of students ->\", dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)]['Name'].count()) # dataframe of above resultdataframe[(dataframe['Physics'] > 10 ) & (dataframe['Chemistry'] > 11 ) & (dataframe['Math'] > 9 )]",
"e": 27649,
"s": 27193,
"text": null
},
{
"code": null,
"e": 27657,
"s": 27649,
"text": "Output:"
},
{
"code": null,
"e": 27690,
"s": 27657,
"text": "Physics>10 ,Chemistry>11,Maths>9"
},
{
"code": null,
"e": 27724,
"s": 27690,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 27732,
"s": 27724,
"text": "Python3"
},
{
"code": "# importing Librariesimport pandas as pdimport numpy as np # Creating dataframe using dictionaryNaN = np.nandataframe = pd.DataFrame({'Name': ['Shobhit', 'Vaibhav', 'Vimal', 'Sourabh', 'Rahul', 'Shobhit'], 'Physics': [11, 12, 13, 14, NaN, 11], 'Chemistry': [10, 14, NaN, 18, 20, 10], 'Math': [13, 10, 15, NaN, NaN, 13]}) print(\"Created Dataframe\")print(dataframe) # finding Count of all columnsprint(\"Count of all values wrt columns\")print(dataframe.count()) # Count according to rowsprint(\"Count of all values wrt rows\")print(dataframe.count(axis=1))print(dataframe.count(axis='columns')) # count of null valuesprint(\"Null Values counts \")print(dataframe.isnull().sum())print(\"Total null values\", dataframe.isnull().sum().sum()) # count of student with greater# than 11 marks in physicsprint(\"Count of students with physics marks greater than 11 is->\", dataframe[dataframe['Physics'] > 11]['Name'].count()) # resultant of above dataframeprint(dataframe[dataframe['Physics'] > 11])print(\"Count of students ->\", dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)]['Name'].count()) print(dataframe[(dataframe['Physics'] > 10) & (dataframe['Chemistry'] > 11) & (dataframe['Math'] > 9)])",
"e": 29179,
"s": 27732,
"text": null
},
{
"code": null,
"e": 29187,
"s": 29179,
"text": "Output:"
},
{
"code": null,
"e": 29204,
"s": 29187,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 29228,
"s": 29204,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 29251,
"s": 29228,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 29265,
"s": 29251,
"text": "Python-pandas"
},
{
"code": null,
"e": 29272,
"s": 29265,
"text": "Python"
},
{
"code": null,
"e": 29370,
"s": 29272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29379,
"s": 29370,
"text": "Comments"
},
{
"code": null,
"e": 29392,
"s": 29379,
"text": "Old Comments"
},
{
"code": null,
"e": 29424,
"s": 29392,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29479,
"s": 29424,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29535,
"s": 29479,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29577,
"s": 29535,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29619,
"s": 29577,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29658,
"s": 29619,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29680,
"s": 29658,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29701,
"s": 29680,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 29732,
"s": 29701,
"text": "Python | os.path.join() method"
}
] |
How to Integrate PayPal SDK in Android? - GeeksforGeeks | 26 Jul, 2021
PayPal is one of the famous payment gateway integration which is one of the famous payment gateways across the world used in so many applications and websites. In this article, we will take a look at implementing this PayPal SDK in our app.
We will be building a simple application in which we will be displaying a simple EditText and a Button. From that EditText we will be getting the amount entered by the user and then after clicking on the button we will call PayPal to make payment. With the help of the PayPal UI, we will be able to make payments from the card as well as the PayPal account. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Navigate to the URL below to create your sandbox account
Navigate to this URL and log in with your PayPal username and password. After that, you will get to see the below page. On that page, we have to create our SandBox account with some basic details which are shown in the below form.
After filling in all the details. Click on Create Account option to create your SandBox account.
Step 2: Creating a new app to generate Client ID
Navigate to this URL and inside this add your app name
Inside this screen, we have to add our App Name and select it as Merchant and then click on Create app option to create a new app. After that, you will get to see the Client ID which we have to use in our application. Now we will move towards Android Part.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependency in build.gradle
Navigate to the app > Gradle Scripts > build.gradle and add the below dependency in the dependencies section.
implementation 'com.paypal.sdk:paypal-android-sdk:2.14.2'
After adding this dependency now sync your project and we will move towards working with the XML file.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
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" tools:context=".MainActivity"> <!--Edit text for entering the amount--> <EditText android:id="@+id/idEdtAmount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="50dp" android:layout_marginEnd="20dp" android:hint="Enter Amount to be Paid" android:inputType="numberDecimal" /> <!--button for making a payment--> <Button android:id="@+id/idBtnPay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idEdtAmount" android:layout_centerInParent="true" android:layout_marginTop="10dp" android:text="Make Payment" /> <!--text view for displaying payment status--> <TextView android:id="@+id/idTVStatus" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idBtnPay" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:padding="5dp" android:textAlignment="center" android:textColor="@color/purple_200" android:textSize="20sp" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.paypal.android.sdk.payments.PayPalConfiguration;import com.paypal.android.sdk.payments.PayPalPayment;import com.paypal.android.sdk.payments.PayPalService;import com.paypal.android.sdk.payments.PaymentActivity;import com.paypal.android.sdk.payments.PaymentConfirmation; import org.json.JSONException;import org.json.JSONObject; import java.math.BigDecimal; public class MainActivity extends AppCompatActivity { public static final String clientKey = "Enter your client id here"; public static final int PAYPAL_REQUEST_CODE = 123; // Paypal Configuration Object private static PayPalConfiguration config = new PayPalConfiguration() // Start with mock environment. When ready, // switch to sandbox (ENVIRONMENT_SANDBOX) // or live (ENVIRONMENT_PRODUCTION) .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX) // on below line we are passing a client id. .clientId(clientKey); private EditText amountEdt; private TextView paymentTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing our variables. amountEdt = findViewById(R.id.idEdtAmount); // creating a variable for button, edit text and status tv. Button makePaymentBtn = findViewById(R.id.idBtnPay); paymentTV = findViewById(R.id.idTVStatus); // on below line adding click listener to our make payment button. makePaymentBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to get payment. getPayment(); } }); } private void getPayment() { // Getting the amount from editText String amount = amountEdt.getText().toString(); // Creating a paypal payment on below line. PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(amount)), "USD", "Course Fees", PayPalPayment.PAYMENT_INTENT_SALE); // Creating Paypal Payment activity intent Intent intent = new Intent(this, PaymentActivity.class); //putting the paypal configuration to the intent intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config); // Putting paypal payment to the intent intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment); // Starting the intent activity for result // the request code will be used on the method onActivityResult startActivityForResult(intent, PAYPAL_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // If the result is from paypal if (requestCode == PAYPAL_REQUEST_CODE) { // If the result is OK i.e. user has not canceled the payment if (resultCode == Activity.RESULT_OK) { // Getting the payment confirmation PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION); // if confirmation is not null if (confirm != null) { try { // Getting the payment details String paymentDetails = confirm.toJSONObject().toString(4); // on below line we are extracting json response and displaying it in a text view. JSONObject payObj = new JSONObject(paymentDetails); String payID = payObj.getJSONObject("response").getString("id"); String state = payObj.getJSONObject("response").getString("state"); paymentTV.setText("Payment " + state + "\n with payment id is " + payID); } catch (JSONException e) { // handling json exception on below line Log.e("Error", "an extremely unlikely failure occurred: ", e); } } } else if (resultCode == Activity.RESULT_CANCELED) { // on below line we are checking the payment status. Log.i("paymentExample", "The user canceled."); } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) { // on below line when the invalid paypal config is submitted. Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs."); } } }}
Now run your app and see the output of the app.
Output:
Note: As my PayPal account is not verified so the payments will not be done on my side.
gabaa406
akshaysingh98088
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
Flutter - Custom Bottom Navigation Bar
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java | [
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 25277,
"s": 25036,
"text": "PayPal is one of the famous payment gateway integration which is one of the famous payment gateways across the world used in so many applications and websites. In this article, we will take a look at implementing this PayPal SDK in our app."
},
{
"code": null,
"e": 25802,
"s": 25277,
"text": "We will be building a simple application in which we will be displaying a simple EditText and a Button. From that EditText we will be getting the amount entered by the user and then after clicking on the button we will call PayPal to make payment. With the help of the PayPal UI, we will be able to make payments from the card as well as the PayPal account. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25868,
"s": 25802,
"text": "Step 1: Navigate to the URL below to create your sandbox account "
},
{
"code": null,
"e": 26100,
"s": 25868,
"text": "Navigate to this URL and log in with your PayPal username and password. After that, you will get to see the below page. On that page, we have to create our SandBox account with some basic details which are shown in the below form. "
},
{
"code": null,
"e": 26198,
"s": 26100,
"text": "After filling in all the details. Click on Create Account option to create your SandBox account. "
},
{
"code": null,
"e": 26247,
"s": 26198,
"text": "Step 2: Creating a new app to generate Client ID"
},
{
"code": null,
"e": 26302,
"s": 26247,
"text": "Navigate to this URL and inside this add your app name"
},
{
"code": null,
"e": 26561,
"s": 26302,
"text": "Inside this screen, we have to add our App Name and select it as Merchant and then click on Create app option to create a new app. After that, you will get to see the Client ID which we have to use in our application. Now we will move towards Android Part. "
},
{
"code": null,
"e": 26590,
"s": 26561,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26752,
"s": 26590,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26794,
"s": 26752,
"text": "Step 2: Adding dependency in build.gradle"
},
{
"code": null,
"e": 26904,
"s": 26794,
"text": "Navigate to the app > Gradle Scripts > build.gradle and add the below dependency in the dependencies section."
},
{
"code": null,
"e": 26962,
"s": 26904,
"text": "implementation 'com.paypal.sdk:paypal-android-sdk:2.14.2'"
},
{
"code": null,
"e": 27065,
"s": 26962,
"text": "After adding this dependency now sync your project and we will move towards working with the XML file."
},
{
"code": null,
"e": 27113,
"s": 27065,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27256,
"s": 27113,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 27260,
"s": 27256,
"text": "XML"
},
{
"code": "<?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\" tools:context=\".MainActivity\"> <!--Edit text for entering the amount--> <EditText android:id=\"@+id/idEdtAmount\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"20dp\" android:hint=\"Enter Amount to be Paid\" android:inputType=\"numberDecimal\" /> <!--button for making a payment--> <Button android:id=\"@+id/idBtnPay\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtAmount\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"10dp\" android:text=\"Make Payment\" /> <!--text view for displaying payment status--> <TextView android:id=\"@+id/idTVStatus\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnPay\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_marginEnd=\"20dp\" android:padding=\"5dp\" android:textAlignment=\"center\" android:textColor=\"@color/purple_200\" android:textSize=\"20sp\" /> </RelativeLayout>",
"e": 28781,
"s": 27260,
"text": null
},
{
"code": null,
"e": 28832,
"s": 28784,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 29024,
"s": 28834,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 29031,
"s": 29026,
"text": "Java"
},
{
"code": "import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.paypal.android.sdk.payments.PayPalConfiguration;import com.paypal.android.sdk.payments.PayPalPayment;import com.paypal.android.sdk.payments.PayPalService;import com.paypal.android.sdk.payments.PaymentActivity;import com.paypal.android.sdk.payments.PaymentConfirmation; import org.json.JSONException;import org.json.JSONObject; import java.math.BigDecimal; public class MainActivity extends AppCompatActivity { public static final String clientKey = \"Enter your client id here\"; public static final int PAYPAL_REQUEST_CODE = 123; // Paypal Configuration Object private static PayPalConfiguration config = new PayPalConfiguration() // Start with mock environment. When ready, // switch to sandbox (ENVIRONMENT_SANDBOX) // or live (ENVIRONMENT_PRODUCTION) .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX) // on below line we are passing a client id. .clientId(clientKey); private EditText amountEdt; private TextView paymentTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing our variables. amountEdt = findViewById(R.id.idEdtAmount); // creating a variable for button, edit text and status tv. Button makePaymentBtn = findViewById(R.id.idBtnPay); paymentTV = findViewById(R.id.idTVStatus); // on below line adding click listener to our make payment button. makePaymentBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method to get payment. getPayment(); } }); } private void getPayment() { // Getting the amount from editText String amount = amountEdt.getText().toString(); // Creating a paypal payment on below line. PayPalPayment payment = new PayPalPayment(new BigDecimal(String.valueOf(amount)), \"USD\", \"Course Fees\", PayPalPayment.PAYMENT_INTENT_SALE); // Creating Paypal Payment activity intent Intent intent = new Intent(this, PaymentActivity.class); //putting the paypal configuration to the intent intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config); // Putting paypal payment to the intent intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment); // Starting the intent activity for result // the request code will be used on the method onActivityResult startActivityForResult(intent, PAYPAL_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // If the result is from paypal if (requestCode == PAYPAL_REQUEST_CODE) { // If the result is OK i.e. user has not canceled the payment if (resultCode == Activity.RESULT_OK) { // Getting the payment confirmation PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION); // if confirmation is not null if (confirm != null) { try { // Getting the payment details String paymentDetails = confirm.toJSONObject().toString(4); // on below line we are extracting json response and displaying it in a text view. JSONObject payObj = new JSONObject(paymentDetails); String payID = payObj.getJSONObject(\"response\").getString(\"id\"); String state = payObj.getJSONObject(\"response\").getString(\"state\"); paymentTV.setText(\"Payment \" + state + \"\\n with payment id is \" + payID); } catch (JSONException e) { // handling json exception on below line Log.e(\"Error\", \"an extremely unlikely failure occurred: \", e); } } } else if (resultCode == Activity.RESULT_CANCELED) { // on below line we are checking the payment status. Log.i(\"paymentExample\", \"The user canceled.\"); } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) { // on below line when the invalid paypal config is submitted. Log.i(\"paymentExample\", \"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.\"); } } }}",
"e": 34089,
"s": 29031,
"text": null
},
{
"code": null,
"e": 34140,
"s": 34092,
"text": "Now run your app and see the output of the app."
},
{
"code": null,
"e": 34150,
"s": 34142,
"text": "Output:"
},
{
"code": null,
"e": 34240,
"s": 34152,
"text": "Note: As my PayPal account is not verified so the payments will not be done on my side."
},
{
"code": null,
"e": 34251,
"s": 34242,
"text": "gabaa406"
},
{
"code": null,
"e": 34268,
"s": 34251,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 34276,
"s": 34268,
"text": "Android"
},
{
"code": null,
"e": 34281,
"s": 34276,
"text": "Java"
},
{
"code": null,
"e": 34286,
"s": 34281,
"text": "Java"
},
{
"code": null,
"e": 34294,
"s": 34286,
"text": "Android"
},
{
"code": null,
"e": 34392,
"s": 34294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34401,
"s": 34392,
"text": "Comments"
},
{
"code": null,
"e": 34414,
"s": 34401,
"text": "Old Comments"
},
{
"code": null,
"e": 34456,
"s": 34414,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 34494,
"s": 34456,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 34544,
"s": 34494,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 34583,
"s": 34544,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34656,
"s": 34583,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 34671,
"s": 34656,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34715,
"s": 34671,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34737,
"s": 34715,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34773,
"s": 34737,
"text": "Arrays.sort() in Java with examples"
}
] |
C# | UInt32 Struct - GeeksforGeeks | 01 May, 2019
In C#, UInt32 struct is used to represent 32-bit unsigned integers(also termed as uint data type) starting from range 0 to 4,294,967,295. It also provides different types of methods to compare instances of this type, convert the value of an instance to its String representation, convert the String representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt32 struct inherits the ValueType class which inherits the Object class.
Example:
// C# program to illustrate the // fields of UInt32 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 32-bit integer uint val = 4294967295; // Checking the unsigned integer if (val.Equals(UInt32.MinValue)) { Console.WriteLine("Equal to MinValue!"); } else if (val.Equals(UInt32.MaxValue)) { Console.WriteLine("Equal to MaxValue!"); } else { Console.WriteLine("Not Equal!"); } }}
Equal to MaxValue!
Example:
// C# program to illustrate how to get the// hash code of the 32-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt32 variable uint myval = 33453242; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine("The hash code of myval is: {0}", res); }}
The hash code of myval is: 33453242
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uint32?view=netframework-4.8
CSharp-UInt32-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Delegates
C# | Data Types
C# | Abstract Classes
C# | Replace() Method | [
{
"code": null,
"e": 24210,
"s": 24182,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 24693,
"s": 24210,
"text": "In C#, UInt32 struct is used to represent 32-bit unsigned integers(also termed as uint data type) starting from range 0 to 4,294,967,295. It also provides different types of methods to compare instances of this type, convert the value of an instance to its String representation, convert the String representation of a number to an instance of this type, etc. This struct is defined under System namespace. UInt32 struct inherits the ValueType class which inherits the Object class."
},
{
"code": null,
"e": 24702,
"s": 24693,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // fields of UInt32 structusing System; class GFG { // Main Method static public void Main() { // Unsigned 32-bit integer uint val = 4294967295; // Checking the unsigned integer if (val.Equals(UInt32.MinValue)) { Console.WriteLine(\"Equal to MinValue!\"); } else if (val.Equals(UInt32.MaxValue)) { Console.WriteLine(\"Equal to MaxValue!\"); } else { Console.WriteLine(\"Not Equal!\"); } }}",
"e": 25251,
"s": 24702,
"text": null
},
{
"code": null,
"e": 25271,
"s": 25251,
"text": "Equal to MaxValue!\n"
},
{
"code": null,
"e": 25280,
"s": 25271,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to get the// hash code of the 32-bit Unsigned integerusing System; class GFG { // Main Method static public void Main() { // UInt32 variable uint myval = 33453242; // Get the hash code // Using GetHashCode Method int res = myval.GetHashCode(); Console.WriteLine(\"The hash code of myval is: {0}\", res); }}",
"e": 25678,
"s": 25280,
"text": null
},
{
"code": null,
"e": 25715,
"s": 25678,
"text": "The hash code of myval is: 33453242\n"
},
{
"code": null,
"e": 25726,
"s": 25715,
"text": "Reference:"
},
{
"code": null,
"e": 25806,
"s": 25726,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.uint32?view=netframework-4.8"
},
{
"code": null,
"e": 25827,
"s": 25806,
"text": "CSharp-UInt32-Struct"
},
{
"code": null,
"e": 25830,
"s": 25827,
"text": "C#"
},
{
"code": null,
"e": 25928,
"s": 25830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25937,
"s": 25928,
"text": "Comments"
},
{
"code": null,
"e": 25950,
"s": 25937,
"text": "Old Comments"
},
{
"code": null,
"e": 25968,
"s": 25950,
"text": "C# | Constructors"
},
{
"code": null,
"e": 25990,
"s": 25968,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26021,
"s": 25990,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26067,
"s": 26021,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26090,
"s": 26067,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26130,
"s": 26090,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 26145,
"s": 26130,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26161,
"s": 26145,
"text": "C# | Data Types"
},
{
"code": null,
"e": 26183,
"s": 26161,
"text": "C# | Abstract Classes"
}
] |
Doubling the value | Practice | GeeksforGeeks | Given an array and an integer B, traverse the array (from the beginning) and if the element in array is B, double B and continue traversal. Find the value of B after the complete traversal.
Example 1:
Input:
N = 5, B = 2
arr[] = {1 2 3 4 8}
Output: 16
Explanation: B is initially 2. We get 2 at
the 1st index, hence B becomes 4.
Next, we get B at the 3rd index, hence B
becomes 8. Next, we get B at 4-th index,
hence B becomes 16.
Example 1:
Input:
N = 5, B = 3
arr[] = {1 2 3 4 8}
Output: 6
Explanation: B is initially 3. We get 3 at
the 2nd index, hence B becomes 6.
Your Task:
You don't need to read input or print anything. Your task is to complete the function solve () which takes the array arr[], its size N and an integer B as inputs and returns the final value of B after the complete traversal of the array.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1<=N<=50
1<=B<=1000
1<=arr[i]<=1018
0
tejudupi2 months ago
def solve(self,n : int, a : list, b : int): # Complete this function for i in range(n): if arr[i]== b: b =2 * b return b
0
ramdurgasais3 months ago
for item in a :
if item == b : b *= 2
return b
0
ayazmrz983 months ago
long solve(int n, long A[], long b)
{
for(int i=0;i<n;i++)
{
if(A[i]==b)
{
b=b*2;
}
}
return b;
}
0
pjodhani33 months ago
long long solve(int n, long long a[], long long b) { for(int i=0; i< n; i++) { if(a[i] == b) { b= 2*b; } } return b; }
0
diptendunandi3 months ago
long long solve(int n, long long arr[], long long b)
{
//code here.
for(long long i=0;i<n;i++){
if(arr[i]==b){
b=b*2;
}
}
return b;
}
0
abythankachan3143 months ago
Python code:
def solve(self,n:int,a:list,b:int):
for t in a:
if t==b:
b=b*2
return b
0
indrathegodofthunder3 months ago
////. PYTHON ////
class Solution: def solve(self,n : int, a : list, b : int): sorted(a) for num in a: if num == b: b = b * 2 return b
0
thanhtai016263 months ago
Majority. It only success when array sorted?
0
mukulvyasg4 months ago
python
class Solution:
def solve(self,n : int, a : list, b : int):
a.sort()
while b in a :
b = 2*b
return b
0
nikhillko024 months ago
def solve(self,n : int, a : list, b : int): # Complete this function for i in a: if i==b: b=2*b return b
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": 416,
"s": 226,
"text": "Given an array and an integer B, traverse the array (from the beginning) and if the element in array is B, double B and continue traversal. Find the value of B after the complete traversal."
},
{
"code": null,
"e": 427,
"s": 416,
"text": "Example 1:"
},
{
"code": null,
"e": 661,
"s": 427,
"text": "Input:\nN = 5, B = 2\narr[] = {1 2 3 4 8}\nOutput: 16\nExplanation: B is initially 2. We get 2 at\nthe 1st index, hence B becomes 4. \nNext, we get B at the 3rd index, hence B \nbecomes 8. Next, we get B at 4-th index, \nhence B becomes 16.\n"
},
{
"code": null,
"e": 672,
"s": 661,
"text": "Example 1:"
},
{
"code": null,
"e": 799,
"s": 672,
"text": "Input:\nN = 5, B = 3\narr[] = {1 2 3 4 8}\nOutput: 6\nExplanation: B is initially 3. We get 3 at\nthe 2nd index, hence B becomes 6."
},
{
"code": null,
"e": 1049,
"s": 799,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function solve () which takes the array arr[], its size N and an integer B as inputs and returns the final value of B after the complete traversal of the array."
},
{
"code": null,
"e": 1114,
"s": 1049,
"text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1164,
"s": 1114,
"text": "\nConstraints:\n1<=N<=50\n1<=B<=1000\n1<=arr[i]<=1018"
},
{
"code": null,
"e": 1166,
"s": 1164,
"text": "0"
},
{
"code": null,
"e": 1187,
"s": 1166,
"text": "tejudupi2 months ago"
},
{
"code": null,
"e": 1351,
"s": 1187,
"text": "def solve(self,n : int, a : list, b : int): # Complete this function for i in range(n): if arr[i]== b: b =2 * b return b "
},
{
"code": null,
"e": 1353,
"s": 1351,
"text": "0"
},
{
"code": null,
"e": 1378,
"s": 1353,
"text": "ramdurgasais3 months ago"
},
{
"code": null,
"e": 1435,
"s": 1378,
"text": "for item in a : \n if item == b : b *= 2\nreturn b "
},
{
"code": null,
"e": 1437,
"s": 1435,
"text": "0"
},
{
"code": null,
"e": 1459,
"s": 1437,
"text": "ayazmrz983 months ago"
},
{
"code": null,
"e": 1651,
"s": 1459,
"text": " long solve(int n, long A[], long b)\n {\n for(int i=0;i<n;i++)\n {\n if(A[i]==b)\n {\n b=b*2;\n }\n }\n \n return b;\n }"
},
{
"code": null,
"e": 1653,
"s": 1651,
"text": "0"
},
{
"code": null,
"e": 1675,
"s": 1653,
"text": "pjodhani33 months ago"
},
{
"code": null,
"e": 1879,
"s": 1675,
"text": "long long solve(int n, long long a[], long long b) { for(int i=0; i< n; i++) { if(a[i] == b) { b= 2*b; } } return b; } "
},
{
"code": null,
"e": 1881,
"s": 1879,
"text": "0"
},
{
"code": null,
"e": 1907,
"s": 1881,
"text": "diptendunandi3 months ago"
},
{
"code": null,
"e": 2121,
"s": 1907,
"text": "long long solve(int n, long long arr[], long long b)\n {\n //code here.\n for(long long i=0;i<n;i++){\n if(arr[i]==b){\n b=b*2;\n }\n }\n return b;\n }"
},
{
"code": null,
"e": 2123,
"s": 2121,
"text": "0"
},
{
"code": null,
"e": 2152,
"s": 2123,
"text": "abythankachan3143 months ago"
},
{
"code": null,
"e": 2165,
"s": 2152,
"text": "Python code:"
},
{
"code": null,
"e": 2201,
"s": 2165,
"text": "def solve(self,n:int,a:list,b:int):"
},
{
"code": null,
"e": 2216,
"s": 2201,
"text": " for t in a:"
},
{
"code": null,
"e": 2232,
"s": 2216,
"text": " if t==b:"
},
{
"code": null,
"e": 2249,
"s": 2232,
"text": " b=b*2"
},
{
"code": null,
"e": 2261,
"s": 2249,
"text": " return b"
},
{
"code": null,
"e": 2263,
"s": 2261,
"text": "0"
},
{
"code": null,
"e": 2296,
"s": 2263,
"text": "indrathegodofthunder3 months ago"
},
{
"code": null,
"e": 2317,
"s": 2296,
"text": "////. PYTHON ////"
},
{
"code": null,
"e": 2482,
"s": 2321,
"text": "class Solution: def solve(self,n : int, a : list, b : int): sorted(a) for num in a: if num == b: b = b * 2 return b "
},
{
"code": null,
"e": 2484,
"s": 2482,
"text": "0"
},
{
"code": null,
"e": 2510,
"s": 2484,
"text": "thanhtai016263 months ago"
},
{
"code": null,
"e": 2555,
"s": 2510,
"text": "Majority. It only success when array sorted?"
},
{
"code": null,
"e": 2557,
"s": 2555,
"text": "0"
},
{
"code": null,
"e": 2580,
"s": 2557,
"text": "mukulvyasg4 months ago"
},
{
"code": null,
"e": 2587,
"s": 2580,
"text": "python"
},
{
"code": null,
"e": 2726,
"s": 2589,
"text": "class Solution:\n def solve(self,n : int, a : list, b : int):\n a.sort()\n while b in a :\n b = 2*b\n return b"
},
{
"code": null,
"e": 2728,
"s": 2726,
"text": "0"
},
{
"code": null,
"e": 2752,
"s": 2728,
"text": "nikhillko024 months ago"
},
{
"code": null,
"e": 2900,
"s": 2752,
"text": " def solve(self,n : int, a : list, b : int): # Complete this function for i in a: if i==b: b=2*b return b"
},
{
"code": null,
"e": 3046,
"s": 2900,
"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": 3082,
"s": 3046,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3092,
"s": 3082,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3102,
"s": 3092,
"text": "\nContest\n"
},
{
"code": null,
"e": 3165,
"s": 3102,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3313,
"s": 3165,
"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": 3521,
"s": 3313,
"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": 3627,
"s": 3521,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Add a row at top in pandas DataFrame | In Pandas a DataFrame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can create a DataFrame using list, dict, series and another DataFrame. But when we want to add a new row to an already created DataFrame, it is achieved through a in-built method like append which add it at the end of the DataFrame. In this article we will find ways to add the new row DataFrame at the top of the DataFrame using some tricks involving the index of the elements in the DataFrame.
Let's first create a new DataFrame in Pandas shown as below.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
print df
Running the above code gives us the following result -
Age Gender Name
0 28 MTom
1 34 MJack
2 29 FMary
3 42 F Ricky
Approach 1 - The first approach we follow to add a new row at the top of the above DataFrame is to convert the new incoming row to a DataFrame and concat it with the existing DataFrame while resetting the index values. Because of Index reset the new row gets added at the top.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
top_row = pd.DataFrame({'Name':['Lavina'],'Age':[2],'Gender':['F']})
# Concat with old DataFrame and reset the Index.
df = pd.concat([top_row, df]).reset_index(drop = True)
print df
Running the above code gives us the following result -
Age Gender Name
0 2 F Lavina
1 28 M Tom
2 34 M Jack
3 29 F Mary
4 42 F Ricky
Approach 2 - In this approach we use the Dataframe.iloc[] method which allows us to add a new row at the index position 0. In the below example we are adding a new row as a list by mentioning the index value for the .loc method as 0 which is the index value for the first row.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}
df = pd.DataFrame(data)
# Add a new row at index position 0 with values provided in list
df.iloc[0] = ['7', 'F','Piyu']
print df
Running the above code gives us the following result:
Age Gender Name
0 7 F Piyu
1 34 M Jack
2 29 F Mary
3 42 F Ricky | [
{
"code": null,
"e": 1584,
"s": 1062,
"text": "In Pandas a DataFrame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can create a DataFrame using list, dict, series and another DataFrame. But when we want to add a new row to an already created DataFrame, it is achieved through a in-built method like append which add it at the end of the DataFrame. In this article we will find ways to add the new row DataFrame at the top of the DataFrame using some tricks involving the index of the elements in the DataFrame."
},
{
"code": null,
"e": 1645,
"s": 1584,
"text": "Let's first create a new DataFrame in Pandas shown as below."
},
{
"code": null,
"e": 1794,
"s": 1645,
"text": "import pandas as pd\ndata = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}\ndf = pd.DataFrame(data)\nprint df"
},
{
"code": null,
"e": 1849,
"s": 1794,
"text": "Running the above code gives us the following result -"
},
{
"code": null,
"e": 1989,
"s": 1849,
"text": "Age Gender Name\n0 28 MTom\n1 34 MJack\n2 29 FMary\n3 42 F Ricky"
},
{
"code": null,
"e": 2266,
"s": 1989,
"text": "Approach 1 - The first approach we follow to add a new row at the top of the above DataFrame is to convert the new incoming row to a DataFrame and concat it with the existing DataFrame while resetting the index values. Because of Index reset the new row gets added at the top."
},
{
"code": null,
"e": 2588,
"s": 2266,
"text": "import pandas as pd\ndata = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}\ndf = pd.DataFrame(data)\ntop_row = pd.DataFrame({'Name':['Lavina'],'Age':[2],'Gender':['F']})\n# Concat with old DataFrame and reset the Index.\ndf = pd.concat([top_row, df]).reset_index(drop = True)\nprint df"
},
{
"code": null,
"e": 2643,
"s": 2588,
"text": "Running the above code gives us the following result -"
},
{
"code": null,
"e": 2861,
"s": 2643,
"text": " Age Gender Name\n0 2 F Lavina\n1 28 M Tom\n2 34 M Jack\n3 29 F Mary\n4 42 F Ricky"
},
{
"code": null,
"e": 3138,
"s": 2861,
"text": "Approach 2 - In this approach we use the Dataframe.iloc[] method which allows us to add a new row at the index position 0. In the below example we are adding a new row as a list by mentioning the index value for the .loc method as 0 which is the index value for the first row."
},
{
"code": null,
"e": 3383,
"s": 3138,
"text": "import pandas as pd\ndata = {'Name':['Tom', 'Jack', 'Mary', 'Ricky'],'Age':[28,34,29,42],'Gender':['M','M','F','F']}\ndf = pd.DataFrame(data)\n# Add a new row at index position 0 with values provided in list\ndf.iloc[0] = ['7', 'F','Piyu']\nprint df"
},
{
"code": null,
"e": 3437,
"s": 3383,
"text": "Running the above code gives us the following result:"
},
{
"code": null,
"e": 3573,
"s": 3437,
"text": " Age Gender Name\n0 7 F Piyu\n1 34 M Jack\n2 29 F Mary\n3 42 F Ricky"
}
] |
3-Way QuickSort (Dutch National Flag) - GeeksforGeeks | 14 Dec, 2021
In simple QuickSort algorithm, we select an element as pivot, partition the array around a pivot and recur for subarrays on the left and right of the pivot. Consider an array which has many redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as a pivot in Simple Quick Sort, we fix only one 4 and recursively process remaining occurrences.The idea of 3 way Quick Sort is to process all occurrences of the pivot and is based on Dutch National Flag algorithm.
In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts:
a) arr[l..i] elements less than pivot.
b) arr[i+1..j-1] elements equal to pivot.
c) arr[j..r] elements greater than pivot.
Below is the implementation of the above algorithm.
C++
Java
C#
Javascript
Python3
// C++ program for 3-way quick sort#include <bits/stdc++.h>using namespace std; /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */void partition(int a[], int l, int r, int& i, int& j){ i = l - 1, j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right swap(a[i], a[j]); // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; swap(a[p], a[i]); } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; swap(a[j], a[q]); } } // Move pivot element to its correct index swap(a[i], a[r]); // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) swap(a[k], a[j]); // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(a[i], a[k]);} // 3-way partition based quick sortvoid quicksort(int a[], int l, int r){ if (r <= l) return; int i, j; // Note that i and j are passed as reference partition(a, l, r, i, j); // Recur quicksort(a, l, j); quicksort(a, i, r);} // A utility function to print an arrayvoid printarr(int a[], int n){ for (int i = 0; i < n; ++i) printf("%d ", a[i]); printf("\n");} // Driver codeint main(){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = sizeof(a) / sizeof(int); // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); return 0;}
// Java program for 3-way quick sortimport java.util.*;class GFG{ static int i, j; /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */static void partition(int a[], int l, int r){ i = l - 1; j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right int temp = a[i]; a[i] = a[j]; a[j] = temp; // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; temp = a[i]; a[i] = a[p]; a[p] = temp; } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; temp = a[q]; a[q] = a[j]; a[j] = temp; } } // Move pivot element to its correct index int temp = a[i]; a[i] = a[r]; a[r] = temp; // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) { temp = a[k]; a[k] = a[j]; a[j] = temp; } // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) { temp = a[i]; a[i] = a[k]; a[k] = temp; }} // 3-way partition based quick sortstatic void quicksort(int a[], int l, int r){ if (r <= l) return; i = 0; j = 0; // Note that i and j are passed as reference partition(a, l, r); // Recur quicksort(a, l, j); quicksort(a, i, r);} // A utility function to print an arraystatic void printarr(int a[], int n){ for (int i = 0; i < n; ++i) System.out.printf("%d ", a[i]); System.out.printf("\n");} // Driver codepublic static void main(String[] args){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = a.length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size);}} // This code is contributed by Rajput-Ji
// C# program for 3-way quick sortusing System; class GFG { // A function which is used to swap values static void swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */ public static void partition(int[] a, int l, int r, ref int i, ref int j) { i = l - 1; j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater // than or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller // than or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater // goes on right swap(ref a[i], ref a[j]); // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; swap(ref a[p], ref a[i]); } // Move all same right occurrence of pivot to // end of array and keep count using q if (a[j] == v) { q--; swap(ref a[j], ref a[q]); } } // Move pivot element to its correct index swap(ref a[i], ref a[r]); // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) swap(ref a[k], ref a[j]); // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(ref a[i], ref a[k]); } // 3-way partition based quick sort public static void quicksort(int[] a, int l, int r) { if (r <= l) return; int i = 0, j = 0; // Note that i and j are passed as reference partition(a, l, r, ref i, ref j); // Recur quicksort(a, l, j); quicksort(a, i, r); } // A utility function to print an array public static void printarr(int[] a, int n) { for (int i = 0; i < n; ++i) Console.Write(a[i] + " "); Console.Write("\n"); } // Driver code static void Main() { int[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = a.Length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); } // This code is contributed by DrRoot_}
<script>// javascript program for 3-way quick sort var i, j; /* * This function partitions a in three parts a) a[l..i] contains all elements * smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) * a[j..r] contains all elements greater than pivot */ function partition(a , l , r) { i = l - 1; j = r; var p = l - 1, q = r; var v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right var temp = a[i]; a[i] = a[j]; a[j] = temp; // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; temp = a[i]; a[i] = a[p]; a[p] = temp; } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; temp = a[q]; a[q] = a[j]; a[j] = temp; } } // Move pivot element to its correct index var temp = a[i]; a[i] = a[r]; a[r] = temp; // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (k = l; k < p; k++, j--) { temp = a[k]; a[k] = a[j]; a[j] = temp; } // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (k = r - 1; k > q; k--, i++) { temp = a[i]; a[i] = a[k]; a[k] = temp; } } // 3-way partition based quick sort function quicksort(a , l , r) { if (r <= l) return; i = 0; j = 0; // Note that i and j are passed as reference partition(a, l, r); // Recur quicksort(a, l, j); quicksort(a, i, r); } // A utility function to print an array function printarr(a , n) { for (i = 0; i < n; ++i) document.write(" "+ a[i]); document.write("<br/>"); } // Driver code var a = [ 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 ]; var size = a.length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size);// This code contributed by aashish1995</script>
'''This function partitions a[] in three parts a) a[first..start] contains all elements smaller than pivot b) a[start+1..mid-1] contains all occurrences of pivot c) a[mid..last] contains all elements greater than pivot '''def partition(arr, first, last, start, mid): pivot = arr[last] end = last # Iterate while mid is not greater than end. while (mid[0] <= end): # Inter Change position of element at the starting if it's value is less than pivot. if (arr[mid[0]] < pivot): arr[mid[0]], arr[start[0]] = arr[start[0]], arr[mid[0]] mid[0] = mid[0] + 1 start[0] = start[0] + 1 # Inter Change position of element at the end if it's value is greater than pivot. elif (arr[mid[0]] > pivot): arr[mid[0]], arr[end] = arr[end], arr[mid[0]] end = end - 1 else: mid[0] = mid[0] + 1 # Function to sort the array elements in 3 casesdef quicksort(arr,first,last): # First case when an array contain only 1 element if (first >= last): return # Second case when an array contain only 2 elements if (last == first + 1): if (arr[first] > arr[last]): arr[first], arr[last] = arr[last], arr[first] return # Third case when an array contain more than 2 elements start = [first] mid = [first] # Function to partition the array. partition(arr, first, last, start, mid) # Recursively sort sublist containing elements that are less than the pivot. quicksort(arr, first, start[0] - 1) # Recursively sort sublist containing elements that are more than the pivot quicksort(arr, mid[0], last) # Code Start from herearr = [4,9,4,4,1,9,4,4,9,4,4,1,4] # Call the quicksort function.quicksort(arr,0,len(arr) - 1) # print arr after sorting the elementsprint(arr)
4 9 4 4 1 9 4 4 9 4 4 1 4
1 1 4 4 4 4 4 4 4 4 9 9 9
Time Complexity: O(N * log(N))
Where ‘N’ is the number of elements in the given array/list
The average number of recursive calls made to the quicksort function is log N, and every time the function is called we are traversing the given array/list which requires O(N) time. Thus, the total time complexity is O(N * log (N)).
Space Complexity: O(log N)
where ‘N’ is the number of elements in the given array/list.
Thanks to Utkarsh for suggesting above implementation.
Another Implementation using Dutch National Flag Algorithm
C++
C#
// C++ program for 3-way quick sort#include <bits/stdc++.h>using namespace std; void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printarr(int a[], int n){ for (int i = 0; i < n; ++i) printf("%d ", a[i]); printf("\n");} /* This function partitions a[] in three partsa) a[l..i] contains all elements smaller than pivotb) a[i+1..j-1] contains all occurrences of pivotc) a[j..r] contains all elements greater than pivot */ // It uses Dutch National Flag Algorithmvoid partition(int a[], int low, int high, int& i, int& j){ // To handle 2 elements if (high - low <= 1) { if (a[high] < a[low]) swap(&a[high], &a[low]); i = low; j = high; return; } int mid = low; int pivot = a[high]; while (mid <= high) { if (a[mid] < pivot) swap(&a[low++], &a[mid++]); else if (a[mid] == pivot) mid++; else if (a[mid] > pivot) swap(&a[mid], &a[high--]); } // update i and j i = low - 1; j = mid; // or high+1} // 3-way partition based quick sortvoid quicksort(int a[], int low, int high){ if (low >= high) // 1 or 0 elements return; int i, j; // Note that i and j are passed as reference partition(a, low, high, i, j); // Recur two halves quicksort(a, low, i); quicksort(a, j, high);} // Driver Codeint main(){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; // int a[] = {4, 39, 54, 14, 31, 89, 44, 34, 59, 64, 64, // 11, 41}; int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // int a[] = {91, 82, 73, 64, 55, 46, 37, 28, 19, 10}; // int a[] = {4, 9, 4, 4, 9, 1, 1, 1}; int size = sizeof(a) / sizeof(int); // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); return 0;}
// C# program for 3-way quick sortusing System; class GFG { // A function which is used to swap values static void swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } // A utility function to print an array public static void printarr(int[] a, int n) { for (int i = 0; i < n; ++i) Console.Write(a[i] + " "); Console.Write("\n"); } /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */ // It uses Dutch National Flag Algorithm public static void partition(int[] a, int low, int high, ref int i, ref int j) { // To handle 2 elements if (high - low <= 1) { if (a[high] < a[low]) swap(ref a[high], ref a[low]); i = low; j = high; return; } int mid = low; int pivot = a[high]; while (mid <= high) { if (a[mid] < pivot) swap(ref a[low++], ref a[mid++]); else if (a[mid] == pivot) mid++; else if (a[mid] > pivot) swap(ref a[mid], ref a[high--]); } // update i and j i = low - 1; j = mid; // or high+1 } // 3-way partition based quick sort public static void quicksort(int[] a, int low, int high) { if (low >= high) // 1 or 0 elements return; int i = 0, j = 0; // Note that i and j are passed as reference partition(a, low, high, ref i, ref j); // Recur two halves quicksort(a, low, i); quicksort(a, j, high); } // Driver code static void Main() { int[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; // int[] a = {4, 39, 54, 14, 31, 89, 44, 34, 59, 64, // 64, 11, 41}; int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, // 10}; int[] a = {91, 82, 73, 64, 55, 46, 37, 28, // 19, 10}; int[] a = {4, 9, 4, 4, 9, 1, 1, 1}; int size = a.Length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); } // This code is contributed by DrRoot_}
4 9 4 4 1 9 4 4 9 4 4 1 4
1 1 4 4 4 4 4 4 4 4 9 9 9
Thanks Aditya Goel for this implementation.Reference: http://algs4.cs.princeton.edu/lectures/23DemoPartitioning.pdf http://www.sorting-algorithms.com/quick-sort-3-wayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DrRoot_
arnavvarshney
technicallynoob
Rajput-Ji
aashish1995
9sujal1221
surinderdawra388
Quick Sort
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Chocolate Distribution Problem
Count Inversions in an array | Set 1 (Using Merge Sort)
k largest(or smallest) elements in an array
Python Program for Bubble Sort
sort() in Python
Bucket Sort
Merge Sort for Linked Lists
Python List sort() method
Find a triplet that sum to a given value | [
{
"code": null,
"e": 26227,
"s": 26199,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 26741,
"s": 26227,
"text": "In simple QuickSort algorithm, we select an element as pivot, partition the array around a pivot and recur for subarrays on the left and right of the pivot. Consider an array which has many redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as a pivot in Simple Quick Sort, we fix only one 4 and recursively process remaining occurrences.The idea of 3 way Quick Sort is to process all occurrences of the pivot and is based on Dutch National Flag algorithm. "
},
{
"code": null,
"e": 26926,
"s": 26741,
"text": "In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts:\na) arr[l..i] elements less than pivot.\nb) arr[i+1..j-1] elements equal to pivot.\nc) arr[j..r] elements greater than pivot."
},
{
"code": null,
"e": 26978,
"s": 26926,
"text": "Below is the implementation of the above algorithm."
},
{
"code": null,
"e": 26982,
"s": 26978,
"text": "C++"
},
{
"code": null,
"e": 26987,
"s": 26982,
"text": "Java"
},
{
"code": null,
"e": 26990,
"s": 26987,
"text": "C#"
},
{
"code": null,
"e": 27001,
"s": 26990,
"text": "Javascript"
},
{
"code": null,
"e": 27009,
"s": 27001,
"text": "Python3"
},
{
"code": "// C++ program for 3-way quick sort#include <bits/stdc++.h>using namespace std; /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */void partition(int a[], int l, int r, int& i, int& j){ i = l - 1, j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right swap(a[i], a[j]); // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; swap(a[p], a[i]); } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; swap(a[j], a[q]); } } // Move pivot element to its correct index swap(a[i], a[r]); // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) swap(a[k], a[j]); // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(a[i], a[k]);} // 3-way partition based quick sortvoid quicksort(int a[], int l, int r){ if (r <= l) return; int i, j; // Note that i and j are passed as reference partition(a, l, r, i, j); // Recur quicksort(a, l, j); quicksort(a, i, r);} // A utility function to print an arrayvoid printarr(int a[], int n){ for (int i = 0; i < n; ++i) printf(\"%d \", a[i]); printf(\"\\n\");} // Driver codeint main(){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = sizeof(a) / sizeof(int); // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); return 0;}",
"e": 29346,
"s": 27009,
"text": null
},
{
"code": "// Java program for 3-way quick sortimport java.util.*;class GFG{ static int i, j; /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */static void partition(int a[], int l, int r){ i = l - 1; j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right int temp = a[i]; a[i] = a[j]; a[j] = temp; // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; temp = a[i]; a[i] = a[p]; a[p] = temp; } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; temp = a[q]; a[q] = a[j]; a[j] = temp; } } // Move pivot element to its correct index int temp = a[i]; a[i] = a[r]; a[r] = temp; // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) { temp = a[k]; a[k] = a[j]; a[j] = temp; } // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) { temp = a[i]; a[i] = a[k]; a[k] = temp; }} // 3-way partition based quick sortstatic void quicksort(int a[], int l, int r){ if (r <= l) return; i = 0; j = 0; // Note that i and j are passed as reference partition(a, l, r); // Recur quicksort(a, l, j); quicksort(a, i, r);} // A utility function to print an arraystatic void printarr(int a[], int n){ for (int i = 0; i < n; ++i) System.out.printf(\"%d \", a[i]); System.out.printf(\"\\n\");} // Driver codepublic static void main(String[] args){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = a.length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size);}} // This code is contributed by Rajput-Ji",
"e": 32040,
"s": 29346,
"text": null
},
{
"code": "// C# program for 3-way quick sortusing System; class GFG { // A function which is used to swap values static void swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */ public static void partition(int[] a, int l, int r, ref int i, ref int j) { i = l - 1; j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater // than or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller // than or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater // goes on right swap(ref a[i], ref a[j]); // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; swap(ref a[p], ref a[i]); } // Move all same right occurrence of pivot to // end of array and keep count using q if (a[j] == v) { q--; swap(ref a[j], ref a[q]); } } // Move pivot element to its correct index swap(ref a[i], ref a[r]); // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) swap(ref a[k], ref a[j]); // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(ref a[i], ref a[k]); } // 3-way partition based quick sort public static void quicksort(int[] a, int l, int r) { if (r <= l) return; int i = 0, j = 0; // Note that i and j are passed as reference partition(a, l, r, ref i, ref j); // Recur quicksort(a, l, j); quicksort(a, i, r); } // A utility function to print an array public static void printarr(int[] a, int n) { for (int i = 0; i < n; ++i) Console.Write(a[i] + \" \"); Console.Write(\"\\n\"); } // Driver code static void Main() { int[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = a.Length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); } // This code is contributed by DrRoot_}",
"e": 35050,
"s": 32040,
"text": null
},
{
"code": "<script>// javascript program for 3-way quick sort var i, j; /* * This function partitions a in three parts a) a[l..i] contains all elements * smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) * a[j..r] contains all elements greater than pivot */ function partition(a , l , r) { i = l - 1; j = r; var p = l - 1, q = r; var v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right var temp = a[i]; a[i] = a[j]; a[j] = temp; // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; temp = a[i]; a[i] = a[p]; a[p] = temp; } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; temp = a[q]; a[q] = a[j]; a[j] = temp; } } // Move pivot element to its correct index var temp = a[i]; a[i] = a[r]; a[r] = temp; // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (k = l; k < p; k++, j--) { temp = a[k]; a[k] = a[j]; a[j] = temp; } // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (k = r - 1; k > q; k--, i++) { temp = a[i]; a[i] = a[k]; a[k] = temp; } } // 3-way partition based quick sort function quicksort(a , l , r) { if (r <= l) return; i = 0; j = 0; // Note that i and j are passed as reference partition(a, l, r); // Recur quicksort(a, l, j); quicksort(a, i, r); } // A utility function to print an array function printarr(a , n) { for (i = 0; i < n; ++i) document.write(\" \"+ a[i]); document.write(\"<br/>\"); } // Driver code var a = [ 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 ]; var size = a.length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size);// This code contributed by aashish1995</script>",
"e": 37960,
"s": 35050,
"text": null
},
{
"code": "'''This function partitions a[] in three parts a) a[first..start] contains all elements smaller than pivot b) a[start+1..mid-1] contains all occurrences of pivot c) a[mid..last] contains all elements greater than pivot '''def partition(arr, first, last, start, mid): pivot = arr[last] end = last # Iterate while mid is not greater than end. while (mid[0] <= end): # Inter Change position of element at the starting if it's value is less than pivot. if (arr[mid[0]] < pivot): arr[mid[0]], arr[start[0]] = arr[start[0]], arr[mid[0]] mid[0] = mid[0] + 1 start[0] = start[0] + 1 # Inter Change position of element at the end if it's value is greater than pivot. elif (arr[mid[0]] > pivot): arr[mid[0]], arr[end] = arr[end], arr[mid[0]] end = end - 1 else: mid[0] = mid[0] + 1 # Function to sort the array elements in 3 casesdef quicksort(arr,first,last): # First case when an array contain only 1 element if (first >= last): return # Second case when an array contain only 2 elements if (last == first + 1): if (arr[first] > arr[last]): arr[first], arr[last] = arr[last], arr[first] return # Third case when an array contain more than 2 elements start = [first] mid = [first] # Function to partition the array. partition(arr, first, last, start, mid) # Recursively sort sublist containing elements that are less than the pivot. quicksort(arr, first, start[0] - 1) # Recursively sort sublist containing elements that are more than the pivot quicksort(arr, mid[0], last) # Code Start from herearr = [4,9,4,4,1,9,4,4,9,4,4,1,4] # Call the quicksort function.quicksort(arr,0,len(arr) - 1) # print arr after sorting the elementsprint(arr)",
"e": 39932,
"s": 37960,
"text": null
},
{
"code": null,
"e": 40012,
"s": 39932,
"text": "4 9 4 4 1 9 4 4 9 4 4 1 4 \n1 1 4 4 4 4 4 4 4 4 9 9 9 "
},
{
"code": null,
"e": 40043,
"s": 40012,
"text": "Time Complexity: O(N * log(N))"
},
{
"code": null,
"e": 40103,
"s": 40043,
"text": "Where ‘N’ is the number of elements in the given array/list"
},
{
"code": null,
"e": 40336,
"s": 40103,
"text": "The average number of recursive calls made to the quicksort function is log N, and every time the function is called we are traversing the given array/list which requires O(N) time. Thus, the total time complexity is O(N * log (N))."
},
{
"code": null,
"e": 40363,
"s": 40336,
"text": "Space Complexity: O(log N)"
},
{
"code": null,
"e": 40424,
"s": 40363,
"text": "where ‘N’ is the number of elements in the given array/list."
},
{
"code": null,
"e": 40479,
"s": 40424,
"text": "Thanks to Utkarsh for suggesting above implementation."
},
{
"code": null,
"e": 40538,
"s": 40479,
"text": "Another Implementation using Dutch National Flag Algorithm"
},
{
"code": null,
"e": 40542,
"s": 40538,
"text": "C++"
},
{
"code": null,
"e": 40545,
"s": 40542,
"text": "C#"
},
{
"code": "// C++ program for 3-way quick sort#include <bits/stdc++.h>using namespace std; void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printarr(int a[], int n){ for (int i = 0; i < n; ++i) printf(\"%d \", a[i]); printf(\"\\n\");} /* This function partitions a[] in three partsa) a[l..i] contains all elements smaller than pivotb) a[i+1..j-1] contains all occurrences of pivotc) a[j..r] contains all elements greater than pivot */ // It uses Dutch National Flag Algorithmvoid partition(int a[], int low, int high, int& i, int& j){ // To handle 2 elements if (high - low <= 1) { if (a[high] < a[low]) swap(&a[high], &a[low]); i = low; j = high; return; } int mid = low; int pivot = a[high]; while (mid <= high) { if (a[mid] < pivot) swap(&a[low++], &a[mid++]); else if (a[mid] == pivot) mid++; else if (a[mid] > pivot) swap(&a[mid], &a[high--]); } // update i and j i = low - 1; j = mid; // or high+1} // 3-way partition based quick sortvoid quicksort(int a[], int low, int high){ if (low >= high) // 1 or 0 elements return; int i, j; // Note that i and j are passed as reference partition(a, low, high, i, j); // Recur two halves quicksort(a, low, i); quicksort(a, j, high);} // Driver Codeint main(){ int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; // int a[] = {4, 39, 54, 14, 31, 89, 44, 34, 59, 64, 64, // 11, 41}; int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // int a[] = {91, 82, 73, 64, 55, 46, 37, 28, 19, 10}; // int a[] = {4, 9, 4, 4, 9, 1, 1, 1}; int size = sizeof(a) / sizeof(int); // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); return 0;}",
"e": 42393,
"s": 40545,
"text": null
},
{
"code": "// C# program for 3-way quick sortusing System; class GFG { // A function which is used to swap values static void swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } // A utility function to print an array public static void printarr(int[] a, int n) { for (int i = 0; i < n; ++i) Console.Write(a[i] + \" \"); Console.Write(\"\\n\"); } /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */ // It uses Dutch National Flag Algorithm public static void partition(int[] a, int low, int high, ref int i, ref int j) { // To handle 2 elements if (high - low <= 1) { if (a[high] < a[low]) swap(ref a[high], ref a[low]); i = low; j = high; return; } int mid = low; int pivot = a[high]; while (mid <= high) { if (a[mid] < pivot) swap(ref a[low++], ref a[mid++]); else if (a[mid] == pivot) mid++; else if (a[mid] > pivot) swap(ref a[mid], ref a[high--]); } // update i and j i = low - 1; j = mid; // or high+1 } // 3-way partition based quick sort public static void quicksort(int[] a, int low, int high) { if (low >= high) // 1 or 0 elements return; int i = 0, j = 0; // Note that i and j are passed as reference partition(a, low, high, ref i, ref j); // Recur two halves quicksort(a, low, i); quicksort(a, j, high); } // Driver code static void Main() { int[] a = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; // int[] a = {4, 39, 54, 14, 31, 89, 44, 34, 59, 64, // 64, 11, 41}; int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, // 10}; int[] a = {91, 82, 73, 64, 55, 46, 37, 28, // 19, 10}; int[] a = {4, 9, 4, 4, 9, 1, 1, 1}; int size = a.Length; // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); } // This code is contributed by DrRoot_}",
"e": 44729,
"s": 42393,
"text": null
},
{
"code": null,
"e": 44783,
"s": 44729,
"text": "4 9 4 4 1 9 4 4 9 4 4 1 4 \n1 1 4 4 4 4 4 4 4 4 9 9 9 "
},
{
"code": null,
"e": 45075,
"s": 44783,
"text": "Thanks Aditya Goel for this implementation.Reference: http://algs4.cs.princeton.edu/lectures/23DemoPartitioning.pdf http://www.sorting-algorithms.com/quick-sort-3-wayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 45083,
"s": 45075,
"text": "DrRoot_"
},
{
"code": null,
"e": 45097,
"s": 45083,
"text": "arnavvarshney"
},
{
"code": null,
"e": 45113,
"s": 45097,
"text": "technicallynoob"
},
{
"code": null,
"e": 45123,
"s": 45113,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 45135,
"s": 45123,
"text": "aashish1995"
},
{
"code": null,
"e": 45146,
"s": 45135,
"text": "9sujal1221"
},
{
"code": null,
"e": 45163,
"s": 45146,
"text": "surinderdawra388"
},
{
"code": null,
"e": 45174,
"s": 45163,
"text": "Quick Sort"
},
{
"code": null,
"e": 45182,
"s": 45174,
"text": "Sorting"
},
{
"code": null,
"e": 45190,
"s": 45182,
"text": "Sorting"
},
{
"code": null,
"e": 45288,
"s": 45190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45312,
"s": 45288,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 45343,
"s": 45312,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 45399,
"s": 45343,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 45443,
"s": 45399,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 45474,
"s": 45443,
"text": "Python Program for Bubble Sort"
},
{
"code": null,
"e": 45491,
"s": 45474,
"text": "sort() in Python"
},
{
"code": null,
"e": 45503,
"s": 45491,
"text": "Bucket Sort"
},
{
"code": null,
"e": 45531,
"s": 45503,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 45557,
"s": 45531,
"text": "Python List sort() method"
}
] |
Optimizing product price using regression | by Mahbubul Alam | Towards Data Science | Price and quantity are two fundamental measures that determine the bottom line of every business, and setting the right price is one of the most important decisions a company can make. Under-pricing hurts the company’s revenue if consumers are willing to pay more and, on the other hand, over-pricing can hurt in a similar fashion if consumers are less inclined to buy the product at a higher price.
So given the tricky relationship between price and sales, where is the sweet spot — the optimum price — that maximizes product sales and earns most profit?
The purpose of this article is to answer this question by implementing a combination of the economic theory and a regression algorithm in Python environment.
We are optimizing a future price based on the relationship between historical price and sales, so the first thing we need is the past data on these two indicators. For this exercise, I’m using a time series data on historical beef sales and corresponding unit prices.
# load dataimport pandas as pdbeef = pd# view first few rowsbeef.tail(5
The dataset contains a total of 91 observations of quantity-price pairs reported on a quarterly basis.
It is customary in data science to do exploratory data analysis (EDA), but I’m skipping that part to focus on modeling. Nevertheless, I strongly encourage taking this extra step to make sure you understand the data before building models.
We need to import libraries for three reasons: manipulating data, building the model, and visualizing the functions.
We are importing numpy and pandas for creating and manipulating table, mtplotlib and seaborn for visualization and statsmodels API to build and run the regression model.
import numpy as npfrom pandas import DataFrameimport matplotlib.pyplot as pltimport seaborn as snsfrom statsmodels.formula.api import ols%matplotlib inline
We know that revenue depends on the quantity sold and the unit price of products.
We also know that profit is calculated by netting out costs from revenue.
Putting these two together we get the following equations:
# revenuerevenue = quantity * price # eq (1)# profitprofit = revenue - cost # eq (2)
We can rewrite the profit function by combining eq. #1 and 2 as follows:
# revised profit functionprofit = quantity * price - cost # eq (3)
Eq #3 tells us that we need three pieces of information to calculate profit: quantity, price and cost.
We first need to establish the relationship between quantity and price — the demand function. This demand function is estimated from a “demand curve” based on the linear relationship between price and quantity.
# demand curvesns.lmplot(x = "Price", y = "Quantity", data = beef, fig_reg = True, size = 4)
To find that demand curve we will fit an Ordinary Least Square (OLS) regression model.
# fit OLS modelmodel = ols("Quantity ~ Price", data = beef).fit()# print model summaryprint(model.summary())
The following are the regression results with the necessary coefficients needed for further analysis.
The coefficient we are looking for is coming from the regression model above — the intercept and the price coefficient — to measure the corresponding sales quantity. We can now plug these values into equation 3.
# plugging regression coefficientsquantity = 30.05 - 0.0465 * price # eq (5)# the profit function in eq (3) becomesprofit = (30.05 - 0.0465 * price) * price - cost # eq (6)
The next step is to find the price we are looking for from a range of options. The codes below should be intuitive, but basically what we are doing here is calculating revenue for each price and the corresponding quantity sold.
# a range of diffferent prices to find the optimum onePrice = [320, 330, 340, 350, 360, 370, 380, 390]# assuming a fixed costcost = 80Revenue = []for i in Price: quantity_demanded = 30.05 - 0.0465 * i # profit function Revenue.append((i-cost) * quantity_demanded)# create data frame of price and revenueprofit = pd.DataFrame({"Price": Price, "Revenue": Revenue})#plot revenue against priceplt.plot(profit["Price"], profit["Revenue"])
If price and revenue are plotted, we can visually identify the peak of the revenue and find the price that makes the revenue at the highest point on the curve.
So we find that the maximum revenue at different price levels is reached at $3,726 when the price is set at $360.
# price at which revenue is maximumprofit[profit['Revenue'] == profit[['Revenue'].max()]
The purpose of this article was to demonstrate how to find the price at which the revenue or profit is maximized using a combination of economic theory and statistical modeling. In the initial steps we defined the demand and profit functions, and then ran a regression to find the parameter values needed to feed into the profit/revenue function. And finally, we checked revenues under different price levels to get the price for the corresponding maximum revenue. | [
{
"code": null,
"e": 572,
"s": 172,
"text": "Price and quantity are two fundamental measures that determine the bottom line of every business, and setting the right price is one of the most important decisions a company can make. Under-pricing hurts the company’s revenue if consumers are willing to pay more and, on the other hand, over-pricing can hurt in a similar fashion if consumers are less inclined to buy the product at a higher price."
},
{
"code": null,
"e": 728,
"s": 572,
"text": "So given the tricky relationship between price and sales, where is the sweet spot — the optimum price — that maximizes product sales and earns most profit?"
},
{
"code": null,
"e": 886,
"s": 728,
"text": "The purpose of this article is to answer this question by implementing a combination of the economic theory and a regression algorithm in Python environment."
},
{
"code": null,
"e": 1154,
"s": 886,
"text": "We are optimizing a future price based on the relationship between historical price and sales, so the first thing we need is the past data on these two indicators. For this exercise, I’m using a time series data on historical beef sales and corresponding unit prices."
},
{
"code": null,
"e": 1226,
"s": 1154,
"text": "# load dataimport pandas as pdbeef = pd# view first few rowsbeef.tail(5"
},
{
"code": null,
"e": 1329,
"s": 1226,
"text": "The dataset contains a total of 91 observations of quantity-price pairs reported on a quarterly basis."
},
{
"code": null,
"e": 1568,
"s": 1329,
"text": "It is customary in data science to do exploratory data analysis (EDA), but I’m skipping that part to focus on modeling. Nevertheless, I strongly encourage taking this extra step to make sure you understand the data before building models."
},
{
"code": null,
"e": 1685,
"s": 1568,
"text": "We need to import libraries for three reasons: manipulating data, building the model, and visualizing the functions."
},
{
"code": null,
"e": 1855,
"s": 1685,
"text": "We are importing numpy and pandas for creating and manipulating table, mtplotlib and seaborn for visualization and statsmodels API to build and run the regression model."
},
{
"code": null,
"e": 2011,
"s": 1855,
"text": "import numpy as npfrom pandas import DataFrameimport matplotlib.pyplot as pltimport seaborn as snsfrom statsmodels.formula.api import ols%matplotlib inline"
},
{
"code": null,
"e": 2093,
"s": 2011,
"text": "We know that revenue depends on the quantity sold and the unit price of products."
},
{
"code": null,
"e": 2167,
"s": 2093,
"text": "We also know that profit is calculated by netting out costs from revenue."
},
{
"code": null,
"e": 2226,
"s": 2167,
"text": "Putting these two together we get the following equations:"
},
{
"code": null,
"e": 2311,
"s": 2226,
"text": "# revenuerevenue = quantity * price # eq (1)# profitprofit = revenue - cost # eq (2)"
},
{
"code": null,
"e": 2384,
"s": 2311,
"text": "We can rewrite the profit function by combining eq. #1 and 2 as follows:"
},
{
"code": null,
"e": 2451,
"s": 2384,
"text": "# revised profit functionprofit = quantity * price - cost # eq (3)"
},
{
"code": null,
"e": 2554,
"s": 2451,
"text": "Eq #3 tells us that we need three pieces of information to calculate profit: quantity, price and cost."
},
{
"code": null,
"e": 2765,
"s": 2554,
"text": "We first need to establish the relationship between quantity and price — the demand function. This demand function is estimated from a “demand curve” based on the linear relationship between price and quantity."
},
{
"code": null,
"e": 2858,
"s": 2765,
"text": "# demand curvesns.lmplot(x = \"Price\", y = \"Quantity\", data = beef, fig_reg = True, size = 4)"
},
{
"code": null,
"e": 2945,
"s": 2858,
"text": "To find that demand curve we will fit an Ordinary Least Square (OLS) regression model."
},
{
"code": null,
"e": 3054,
"s": 2945,
"text": "# fit OLS modelmodel = ols(\"Quantity ~ Price\", data = beef).fit()# print model summaryprint(model.summary())"
},
{
"code": null,
"e": 3156,
"s": 3054,
"text": "The following are the regression results with the necessary coefficients needed for further analysis."
},
{
"code": null,
"e": 3368,
"s": 3156,
"text": "The coefficient we are looking for is coming from the regression model above — the intercept and the price coefficient — to measure the corresponding sales quantity. We can now plug these values into equation 3."
},
{
"code": null,
"e": 3541,
"s": 3368,
"text": "# plugging regression coefficientsquantity = 30.05 - 0.0465 * price # eq (5)# the profit function in eq (3) becomesprofit = (30.05 - 0.0465 * price) * price - cost # eq (6)"
},
{
"code": null,
"e": 3769,
"s": 3541,
"text": "The next step is to find the price we are looking for from a range of options. The codes below should be intuitive, but basically what we are doing here is calculating revenue for each price and the corresponding quantity sold."
},
{
"code": null,
"e": 4212,
"s": 3769,
"text": "# a range of diffferent prices to find the optimum onePrice = [320, 330, 340, 350, 360, 370, 380, 390]# assuming a fixed costcost = 80Revenue = []for i in Price: quantity_demanded = 30.05 - 0.0465 * i # profit function Revenue.append((i-cost) * quantity_demanded)# create data frame of price and revenueprofit = pd.DataFrame({\"Price\": Price, \"Revenue\": Revenue})#plot revenue against priceplt.plot(profit[\"Price\"], profit[\"Revenue\"])"
},
{
"code": null,
"e": 4372,
"s": 4212,
"text": "If price and revenue are plotted, we can visually identify the peak of the revenue and find the price that makes the revenue at the highest point on the curve."
},
{
"code": null,
"e": 4486,
"s": 4372,
"text": "So we find that the maximum revenue at different price levels is reached at $3,726 when the price is set at $360."
},
{
"code": null,
"e": 4575,
"s": 4486,
"text": "# price at which revenue is maximumprofit[profit['Revenue'] == profit[['Revenue'].max()]"
}
] |
AbstractCollection toString() method in Java with Examples - GeeksforGeeks | 19 Dec, 2018
The toString() method of JavaAbstractClass is used to return a string representation of the elements of the Collection.
The String representation comprises a list representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.
Syntax:
Object.toString();
Parameter The method does not take any parameters.
Return This method returns a string representation of the collection.
Below examples illustrate the toString() method:
Example 1:
// Java program to demonstrate// Abstract Collection toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty AbstractCollection AbstractCollection<String> abs = new PriorityQueue<String>(); // Use add() method // to add elements to the Collection abs.add("Welcome"); abs.add("To"); abs.add("Geeks"); abs.add("For"); abs.add("Geeks"); // Using toString() method System.out.println(abs.toString()); }}
[For, Geeks, To, Welcome, Geeks]
Example 2:
// Java program to demonstrate// Abstract Collection toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty AbstractCollection AbstractCollection<Integer> abs = new PriorityQueue<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }}
[10, 20, 30, 40]
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/AbstractCollection.html#toString–
Java - util package
Java-AbstractCollection
Java-Collections
Java-Functions
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java | [
{
"code": null,
"e": 23227,
"s": 23199,
"text": "\n19 Dec, 2018"
},
{
"code": null,
"e": 23347,
"s": 23227,
"text": "The toString() method of JavaAbstractClass is used to return a string representation of the elements of the Collection."
},
{
"code": null,
"e": 23643,
"s": 23347,
"text": "The String representation comprises a list representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation."
},
{
"code": null,
"e": 23651,
"s": 23643,
"text": "Syntax:"
},
{
"code": null,
"e": 23670,
"s": 23651,
"text": "Object.toString();"
},
{
"code": null,
"e": 23721,
"s": 23670,
"text": "Parameter The method does not take any parameters."
},
{
"code": null,
"e": 23791,
"s": 23721,
"text": "Return This method returns a string representation of the collection."
},
{
"code": null,
"e": 23840,
"s": 23791,
"text": "Below examples illustrate the toString() method:"
},
{
"code": null,
"e": 23851,
"s": 23840,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// Abstract Collection toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty AbstractCollection AbstractCollection<String> abs = new PriorityQueue<String>(); // Use add() method // to add elements to the Collection abs.add(\"Welcome\"); abs.add(\"To\"); abs.add(\"Geeks\"); abs.add(\"For\"); abs.add(\"Geeks\"); // Using toString() method System.out.println(abs.toString()); }}",
"e": 24424,
"s": 23851,
"text": null
},
{
"code": null,
"e": 24458,
"s": 24424,
"text": "[For, Geeks, To, Welcome, Geeks]\n"
},
{
"code": null,
"e": 24469,
"s": 24458,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// Abstract Collection toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty AbstractCollection AbstractCollection<Integer> abs = new PriorityQueue<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }}",
"e": 25002,
"s": 24469,
"text": null
},
{
"code": null,
"e": 25020,
"s": 25002,
"text": "[10, 20, 30, 40]\n"
},
{
"code": null,
"e": 25117,
"s": 25020,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/AbstractCollection.html#toString–"
},
{
"code": null,
"e": 25137,
"s": 25117,
"text": "Java - util package"
},
{
"code": null,
"e": 25161,
"s": 25137,
"text": "Java-AbstractCollection"
},
{
"code": null,
"e": 25178,
"s": 25161,
"text": "Java-Collections"
},
{
"code": null,
"e": 25193,
"s": 25178,
"text": "Java-Functions"
},
{
"code": null,
"e": 25200,
"s": 25193,
"text": "Picked"
},
{
"code": null,
"e": 25205,
"s": 25200,
"text": "Java"
},
{
"code": null,
"e": 25210,
"s": 25205,
"text": "Java"
},
{
"code": null,
"e": 25227,
"s": 25210,
"text": "Java-Collections"
},
{
"code": null,
"e": 25325,
"s": 25227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25334,
"s": 25325,
"text": "Comments"
},
{
"code": null,
"e": 25347,
"s": 25334,
"text": "Old Comments"
},
{
"code": null,
"e": 25362,
"s": 25347,
"text": "Arrays in Java"
},
{
"code": null,
"e": 25406,
"s": 25362,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 25428,
"s": 25406,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 25453,
"s": 25428,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 25489,
"s": 25453,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 25540,
"s": 25489,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25570,
"s": 25540,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25601,
"s": 25570,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25633,
"s": 25601,
"text": "Initialize an ArrayList in Java"
}
] |
Tips and Tricks to Work with Text Files in Python | Towards Data Science | Computer programs make our lives easy. We can perform a complex task within a blink of an eye with the blessings of a few lines of instructions. Among many complex tasks, working and manipulating text is one of the most important tasks done by the computer. Today, one of the hot topics is Natural Language Processing (NLP) where text processing is a must. In this article, we will discuss some basic and super easy syntax for formatting and working with texts and text files. It may be considered the first step of learning Natural Language Processing (NLP) with python. In the upcoming articles, we will discuss NLP step by step.
It’s time to move forward to our main agenda of the article. We will make our hands dirty with some basic coding examples which may help us practically. Let’s begin..........
[Full jupyter notebook link is given at the end of the article]
i. f-strings offer several benefits over the older .format() string method.For one, you can bring outside variables immediately into a string rather than pass them through as keyword arguments:
name = 'Zubair'# Using the old .format() method:print('My name is {var}.'.format(var=name))# Using f-strings:print(f'My name is {name}.')
The code generates the following outputs
If you want to have a string representation of the variable just insert !r within {}.
print(f'My name is {name!r}')
The output will be — My name is ‘Zubair’
ii. Use of f-string and dictionary.
d = {'a':123,'b':456}print(f"Address: {d['a']} Main Street")
It will show the dictionary element against the dictionary key ‘a’ . The output for the code is — Address: 123 Main Street .
[N.B. Be careful not to let quotation marks in the replacement fields conflict with the quoting used in the outer string.]
If you use only “” or ‘’, it will cause an error as above.
iii. Minimum Widths, Alignment and Padding with f-string
You can pass arguments inside a nested set of curly braces to set a minimum width for the field, the alignment and even padding characters. Consider the following codes
library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)]for book in library: print(f'{book[0]:{10}} {book[1]:{8}} {book[2]:{7}}')
Output:
Author Topic Pages Twain Rafting 601Feynman Physics 95Hamilton Mythology 144
Here the first three lines align, except Pages follows a default left-alignment while numbers are right-aligned. Also, the fourth line's page number is pushed to the right as Mythology exceeds the minimum field width of 8. When setting minimum field widths make sure to take the longest item into account.
To set the alignment, use the character < for left-align, ^ for center, > for right.To set padding, precede the alignment character with the padding character (- and . are common choices).
Let’s make some adjustments:
for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:>{7}}') # here > was added
Output
Author Topic PagesTwain Rafting 601Feynman Physics 95Hamilton Mythology 144
Centring the 3rd column
for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:^{7}}') # here ^ was added
Output
Author Topic Pages Twain Rafting 601 Feynman Physics 95 Hamilton Mythology 144
Adding some ....
for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:.>{7}}') # here .> was added
Output
Author Topic ..PagesTwain Rafting ....601Feynman Physics .....95Hamilton Mythology ....144
iv. Date Formatting with f-string
You can do various formatting with f-strings. An example is shown below.
from datetime import datetimetoday = datetime(year=2018, month=1, day=27)print(f'{today:%B %d, %Y}')
For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings
i. Creating a File with IPython
This function is specific to jupyter notebooks! Alternatively, quickly create a simple .txt file with Sublime text editor.
%%writefile test.txtHello, this is a quick test file.This is the second line of the file.
The above code will create a txt file with the same directory of the Jupyter Notebook name test.txt
ii. Python Opening a File
# Open the text.txt file we created earliermy_file = open('test.txt')
You may get an error message if you mistype the file name or provide the wrong directory. So be careful. Now, read the file.
# We can now read the filemy_file.read()
Output
'Hello, this is a quick test file.\nThis is the second line of the file.'
But if you run the my_file.read() code again, it will output only ‘’ . But why?
This happens because you can imagine the reading “cursor” is at the end of the file after having read it. So there is nothing left to read. We can reset the “cursor” like this:
# Seek to the start of file (index 0)my_file.seek(0)
Now, the cursor is reset to the beginning of the text file. If we run the my_file.read() code again we will get the output ‘Hello, this is a quick test file.\nThis is the second line of the file.’ .
iii. Reading line by line
You can read a file line by line using the .readlines() method. Use caution with large files, since everything will be held in memory.
# Readlines returns a list of the lines in the filemy_file.seek(0)my_file.readlines()
Output
['Hello, this is a quick test file.\n', 'This is the second line of the file.'
iv. Writing to a File
By default, the open() function will only allow us to read the file. We need to pass the argument 'w' to write over the file. For example:
# Add a second argument to the function, 'w' which stands for write.# Passing 'w+' lets us read and write to the filemy_file = open('test.txt','w+')
Opening a file with ‘w’ or ‘w+’ *truncates the original*, meaning that anything that was in the original file **is deleted**!
# Write to the filemy_file.write('This is a new first line')
The above command writes ‘This is a new first line’ the created file.
v. Appending to a File
Passing the argument 'a' opens the file and puts the pointer at the end, so anything written is appended. Like 'w+', 'a+' lets us read and write to a file. If the file does not exist, one will be created.
my_file = open('test.txt','a+')my_file.write('\nThis line is being appended to test.txt')my_file.write('\nAnd another line here.')
The above code will append the text at the end of the existing text in the test.txt file.
vi. Aliases and Context Managers
You can assign temporary variable names as aliases, and manage the opening and closing of files automatically using a context manager:
with open('test.txt','r') as txt: first_line = txt.readlines()[0]print(first_line)
This code will print the first sentence of test.txt file. For this time the output is This is a new first line
[N.B. The with ... as ...: context manager automatically closed test.txt after assigning the first line of text to first_line:]
If we try to read the test.txt, it will show an error message because the file has been closed automatically
vii. Iterating through a File
with open('test.txt','r') as txt: for line in txt: print(line, end='') # the end='' argument removes extra linebreaks
Output
This is a new first lineThis line is being appended to test.txtAnd another line here.This is more text being appended to test.txtAnd another line here.
The syntaxes are easy but super helpful. We always jump onto sophisticated learning materials but there exist so many tiny things which can make our life easy. And the above article explains some of the useful techniques to play with text which might be helpful for text formatting. However, these techniques will be very helpful for Natural Language Processing. The write-ups will be continued and heading towards basic to advance of NLP.
The full jupyter notebook for the article is available here.
Some chosen interesting article for your further reading
towardsdatascience.com
towardsdatascience.com
If you enjoy the article, follow me on medium for more.
Connect me on LinkedIn for collaboration. | [
{
"code": null,
"e": 804,
"s": 172,
"text": "Computer programs make our lives easy. We can perform a complex task within a blink of an eye with the blessings of a few lines of instructions. Among many complex tasks, working and manipulating text is one of the most important tasks done by the computer. Today, one of the hot topics is Natural Language Processing (NLP) where text processing is a must. In this article, we will discuss some basic and super easy syntax for formatting and working with texts and text files. It may be considered the first step of learning Natural Language Processing (NLP) with python. In the upcoming articles, we will discuss NLP step by step."
},
{
"code": null,
"e": 979,
"s": 804,
"text": "It’s time to move forward to our main agenda of the article. We will make our hands dirty with some basic coding examples which may help us practically. Let’s begin.........."
},
{
"code": null,
"e": 1043,
"s": 979,
"text": "[Full jupyter notebook link is given at the end of the article]"
},
{
"code": null,
"e": 1237,
"s": 1043,
"text": "i. f-strings offer several benefits over the older .format() string method.For one, you can bring outside variables immediately into a string rather than pass them through as keyword arguments:"
},
{
"code": null,
"e": 1375,
"s": 1237,
"text": "name = 'Zubair'# Using the old .format() method:print('My name is {var}.'.format(var=name))# Using f-strings:print(f'My name is {name}.')"
},
{
"code": null,
"e": 1416,
"s": 1375,
"text": "The code generates the following outputs"
},
{
"code": null,
"e": 1502,
"s": 1416,
"text": "If you want to have a string representation of the variable just insert !r within {}."
},
{
"code": null,
"e": 1532,
"s": 1502,
"text": "print(f'My name is {name!r}')"
},
{
"code": null,
"e": 1573,
"s": 1532,
"text": "The output will be — My name is ‘Zubair’"
},
{
"code": null,
"e": 1609,
"s": 1573,
"text": "ii. Use of f-string and dictionary."
},
{
"code": null,
"e": 1670,
"s": 1609,
"text": "d = {'a':123,'b':456}print(f\"Address: {d['a']} Main Street\")"
},
{
"code": null,
"e": 1795,
"s": 1670,
"text": "It will show the dictionary element against the dictionary key ‘a’ . The output for the code is — Address: 123 Main Street ."
},
{
"code": null,
"e": 1918,
"s": 1795,
"text": "[N.B. Be careful not to let quotation marks in the replacement fields conflict with the quoting used in the outer string.]"
},
{
"code": null,
"e": 1977,
"s": 1918,
"text": "If you use only “” or ‘’, it will cause an error as above."
},
{
"code": null,
"e": 2034,
"s": 1977,
"text": "iii. Minimum Widths, Alignment and Padding with f-string"
},
{
"code": null,
"e": 2203,
"s": 2034,
"text": "You can pass arguments inside a nested set of curly braces to set a minimum width for the field, the alignment and even padding characters. Consider the following codes"
},
{
"code": null,
"e": 2407,
"s": 2203,
"text": "library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)]for book in library: print(f'{book[0]:{10}} {book[1]:{8}} {book[2]:{7}}')"
},
{
"code": null,
"e": 2415,
"s": 2407,
"text": "Output:"
},
{
"code": null,
"e": 2525,
"s": 2415,
"text": "Author Topic Pages Twain Rafting 601Feynman Physics 95Hamilton Mythology 144"
},
{
"code": null,
"e": 2831,
"s": 2525,
"text": "Here the first three lines align, except Pages follows a default left-alignment while numbers are right-aligned. Also, the fourth line's page number is pushed to the right as Mythology exceeds the minimum field width of 8. When setting minimum field widths make sure to take the longest item into account."
},
{
"code": null,
"e": 3020,
"s": 2831,
"text": "To set the alignment, use the character < for left-align, ^ for center, > for right.To set padding, precede the alignment character with the padding character (- and . are common choices)."
},
{
"code": null,
"e": 3049,
"s": 3020,
"text": "Let’s make some adjustments:"
},
{
"code": null,
"e": 3197,
"s": 3049,
"text": "for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:>{7}}') # here > was added"
},
{
"code": null,
"e": 3204,
"s": 3197,
"text": "Output"
},
{
"code": null,
"e": 3321,
"s": 3204,
"text": "Author Topic PagesTwain Rafting 601Feynman Physics 95Hamilton Mythology 144"
},
{
"code": null,
"e": 3345,
"s": 3321,
"text": "Centring the 3rd column"
},
{
"code": null,
"e": 3493,
"s": 3345,
"text": "for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:^{7}}') # here ^ was added"
},
{
"code": null,
"e": 3500,
"s": 3493,
"text": "Output"
},
{
"code": null,
"e": 3615,
"s": 3500,
"text": "Author Topic Pages Twain Rafting 601 Feynman Physics 95 Hamilton Mythology 144"
},
{
"code": null,
"e": 3632,
"s": 3615,
"text": "Adding some ...."
},
{
"code": null,
"e": 3779,
"s": 3632,
"text": "for book in library: print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:.>{7}}') # here .> was added"
},
{
"code": null,
"e": 3786,
"s": 3779,
"text": "Output"
},
{
"code": null,
"e": 3903,
"s": 3786,
"text": "Author Topic ..PagesTwain Rafting ....601Feynman Physics .....95Hamilton Mythology ....144"
},
{
"code": null,
"e": 3937,
"s": 3903,
"text": "iv. Date Formatting with f-string"
},
{
"code": null,
"e": 4010,
"s": 3937,
"text": "You can do various formatting with f-strings. An example is shown below."
},
{
"code": null,
"e": 4111,
"s": 4010,
"text": "from datetime import datetimetoday = datetime(year=2018, month=1, day=27)print(f'{today:%B %d, %Y}')"
},
{
"code": null,
"e": 4228,
"s": 4111,
"text": "For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings"
},
{
"code": null,
"e": 4260,
"s": 4228,
"text": "i. Creating a File with IPython"
},
{
"code": null,
"e": 4383,
"s": 4260,
"text": "This function is specific to jupyter notebooks! Alternatively, quickly create a simple .txt file with Sublime text editor."
},
{
"code": null,
"e": 4473,
"s": 4383,
"text": "%%writefile test.txtHello, this is a quick test file.This is the second line of the file."
},
{
"code": null,
"e": 4573,
"s": 4473,
"text": "The above code will create a txt file with the same directory of the Jupyter Notebook name test.txt"
},
{
"code": null,
"e": 4599,
"s": 4573,
"text": "ii. Python Opening a File"
},
{
"code": null,
"e": 4669,
"s": 4599,
"text": "# Open the text.txt file we created earliermy_file = open('test.txt')"
},
{
"code": null,
"e": 4794,
"s": 4669,
"text": "You may get an error message if you mistype the file name or provide the wrong directory. So be careful. Now, read the file."
},
{
"code": null,
"e": 4835,
"s": 4794,
"text": "# We can now read the filemy_file.read()"
},
{
"code": null,
"e": 4842,
"s": 4835,
"text": "Output"
},
{
"code": null,
"e": 4916,
"s": 4842,
"text": "'Hello, this is a quick test file.\\nThis is the second line of the file.'"
},
{
"code": null,
"e": 4996,
"s": 4916,
"text": "But if you run the my_file.read() code again, it will output only ‘’ . But why?"
},
{
"code": null,
"e": 5173,
"s": 4996,
"text": "This happens because you can imagine the reading “cursor” is at the end of the file after having read it. So there is nothing left to read. We can reset the “cursor” like this:"
},
{
"code": null,
"e": 5226,
"s": 5173,
"text": "# Seek to the start of file (index 0)my_file.seek(0)"
},
{
"code": null,
"e": 5425,
"s": 5226,
"text": "Now, the cursor is reset to the beginning of the text file. If we run the my_file.read() code again we will get the output ‘Hello, this is a quick test file.\\nThis is the second line of the file.’ ."
},
{
"code": null,
"e": 5451,
"s": 5425,
"text": "iii. Reading line by line"
},
{
"code": null,
"e": 5586,
"s": 5451,
"text": "You can read a file line by line using the .readlines() method. Use caution with large files, since everything will be held in memory."
},
{
"code": null,
"e": 5672,
"s": 5586,
"text": "# Readlines returns a list of the lines in the filemy_file.seek(0)my_file.readlines()"
},
{
"code": null,
"e": 5679,
"s": 5672,
"text": "Output"
},
{
"code": null,
"e": 5758,
"s": 5679,
"text": "['Hello, this is a quick test file.\\n', 'This is the second line of the file.'"
},
{
"code": null,
"e": 5780,
"s": 5758,
"text": "iv. Writing to a File"
},
{
"code": null,
"e": 5919,
"s": 5780,
"text": "By default, the open() function will only allow us to read the file. We need to pass the argument 'w' to write over the file. For example:"
},
{
"code": null,
"e": 6068,
"s": 5919,
"text": "# Add a second argument to the function, 'w' which stands for write.# Passing 'w+' lets us read and write to the filemy_file = open('test.txt','w+')"
},
{
"code": null,
"e": 6194,
"s": 6068,
"text": "Opening a file with ‘w’ or ‘w+’ *truncates the original*, meaning that anything that was in the original file **is deleted**!"
},
{
"code": null,
"e": 6255,
"s": 6194,
"text": "# Write to the filemy_file.write('This is a new first line')"
},
{
"code": null,
"e": 6325,
"s": 6255,
"text": "The above command writes ‘This is a new first line’ the created file."
},
{
"code": null,
"e": 6348,
"s": 6325,
"text": "v. Appending to a File"
},
{
"code": null,
"e": 6553,
"s": 6348,
"text": "Passing the argument 'a' opens the file and puts the pointer at the end, so anything written is appended. Like 'w+', 'a+' lets us read and write to a file. If the file does not exist, one will be created."
},
{
"code": null,
"e": 6684,
"s": 6553,
"text": "my_file = open('test.txt','a+')my_file.write('\\nThis line is being appended to test.txt')my_file.write('\\nAnd another line here.')"
},
{
"code": null,
"e": 6774,
"s": 6684,
"text": "The above code will append the text at the end of the existing text in the test.txt file."
},
{
"code": null,
"e": 6807,
"s": 6774,
"text": "vi. Aliases and Context Managers"
},
{
"code": null,
"e": 6942,
"s": 6807,
"text": "You can assign temporary variable names as aliases, and manage the opening and closing of files automatically using a context manager:"
},
{
"code": null,
"e": 7028,
"s": 6942,
"text": "with open('test.txt','r') as txt: first_line = txt.readlines()[0]print(first_line)"
},
{
"code": null,
"e": 7139,
"s": 7028,
"text": "This code will print the first sentence of test.txt file. For this time the output is This is a new first line"
},
{
"code": null,
"e": 7267,
"s": 7139,
"text": "[N.B. The with ... as ...: context manager automatically closed test.txt after assigning the first line of text to first_line:]"
},
{
"code": null,
"e": 7376,
"s": 7267,
"text": "If we try to read the test.txt, it will show an error message because the file has been closed automatically"
},
{
"code": null,
"e": 7406,
"s": 7376,
"text": "vii. Iterating through a File"
},
{
"code": null,
"e": 7535,
"s": 7406,
"text": "with open('test.txt','r') as txt: for line in txt: print(line, end='') # the end='' argument removes extra linebreaks"
},
{
"code": null,
"e": 7542,
"s": 7535,
"text": "Output"
},
{
"code": null,
"e": 7694,
"s": 7542,
"text": "This is a new first lineThis line is being appended to test.txtAnd another line here.This is more text being appended to test.txtAnd another line here."
},
{
"code": null,
"e": 8134,
"s": 7694,
"text": "The syntaxes are easy but super helpful. We always jump onto sophisticated learning materials but there exist so many tiny things which can make our life easy. And the above article explains some of the useful techniques to play with text which might be helpful for text formatting. However, these techniques will be very helpful for Natural Language Processing. The write-ups will be continued and heading towards basic to advance of NLP."
},
{
"code": null,
"e": 8195,
"s": 8134,
"text": "The full jupyter notebook for the article is available here."
},
{
"code": null,
"e": 8252,
"s": 8195,
"text": "Some chosen interesting article for your further reading"
},
{
"code": null,
"e": 8275,
"s": 8252,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8298,
"s": 8275,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8354,
"s": 8298,
"text": "If you enjoy the article, follow me on medium for more."
}
] |
Clock Skew in synchronous digital circuit systems - GeeksforGeeks | 17 Jan, 2022
In Synchronous circuits where all the logic elements share the same clock signal, it becomes imperative to design these elements as close to the clock source as possible because a system-on-chip, FPGA, CPLD contain Billions of transistors. Even though these distances are minute due to their sheer number there is a propagation delay which leads to the clock signal arriving at different parts of the chip at different times. This is called Clock Skew.
In Digital Circuit Design a ” Sequentially Adjacent ” circuit is one where if a pulse emitted from a common source is supposed to arrive at the same time. Using this definition we can write a mathematical expression for clock skew as
Sequentially Adjacent Circuit
Non-Sequentially Adjacent Circuit.
Ta(Time of arrival of clock pulse at component a) Tb(Time of arrival of clock pulse at component b)
Then,
Clock skew Ts = Ta - Tb
Factors causing Clock Skew :
Interconnect Length
Temperature Variations
Capacitive Coupling
Material Imperfections
Differences in input capacitance on the clock inputs
Types of Clock Skew :
Positive Skew – This occurs when the receiving register receives the clock pulse later than it is required.
Negative Skew – This occurs when the receiving register receives the clock pulse earlier than required.
Types of Clock Skews
varshagumber28
DIgital Logic & Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python? | [
{
"code": null,
"e": 22635,
"s": 22607,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 23089,
"s": 22635,
"text": "In Synchronous circuits where all the logic elements share the same clock signal, it becomes imperative to design these elements as close to the clock source as possible because a system-on-chip, FPGA, CPLD contain Billions of transistors. Even though these distances are minute due to their sheer number there is a propagation delay which leads to the clock signal arriving at different parts of the chip at different times. This is called Clock Skew. "
},
{
"code": null,
"e": 23324,
"s": 23089,
"text": "In Digital Circuit Design a ” Sequentially Adjacent ” circuit is one where if a pulse emitted from a common source is supposed to arrive at the same time. Using this definition we can write a mathematical expression for clock skew as "
},
{
"code": null,
"e": 23356,
"s": 23326,
"text": "Sequentially Adjacent Circuit"
},
{
"code": null,
"e": 23393,
"s": 23358,
"text": "Non-Sequentially Adjacent Circuit."
},
{
"code": null,
"e": 23494,
"s": 23393,
"text": "Ta(Time of arrival of clock pulse at component a) Tb(Time of arrival of clock pulse at component b) "
},
{
"code": null,
"e": 23502,
"s": 23494,
"text": "Then, "
},
{
"code": null,
"e": 23527,
"s": 23502,
"text": "Clock skew Ts = Ta - Tb "
},
{
"code": null,
"e": 23558,
"s": 23527,
"text": "Factors causing Clock Skew : "
},
{
"code": null,
"e": 23580,
"s": 23558,
"text": "Interconnect Length "
},
{
"code": null,
"e": 23605,
"s": 23580,
"text": "Temperature Variations "
},
{
"code": null,
"e": 23627,
"s": 23605,
"text": "Capacitive Coupling "
},
{
"code": null,
"e": 23652,
"s": 23627,
"text": "Material Imperfections "
},
{
"code": null,
"e": 23707,
"s": 23652,
"text": "Differences in input capacitance on the clock inputs "
},
{
"code": null,
"e": 23731,
"s": 23707,
"text": "Types of Clock Skew : "
},
{
"code": null,
"e": 23841,
"s": 23731,
"text": "Positive Skew – This occurs when the receiving register receives the clock pulse later than it is required. "
},
{
"code": null,
"e": 23947,
"s": 23841,
"text": "Negative Skew – This occurs when the receiving register receives the clock pulse earlier than required. "
},
{
"code": null,
"e": 23970,
"s": 23949,
"text": "Types of Clock Skews"
},
{
"code": null,
"e": 23987,
"s": 23972,
"text": "varshagumber28"
},
{
"code": null,
"e": 24010,
"s": 23987,
"text": "DIgital Logic & Design"
},
{
"code": null,
"e": 24108,
"s": 24010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24117,
"s": 24108,
"text": "Comments"
},
{
"code": null,
"e": 24130,
"s": 24117,
"text": "Old Comments"
},
{
"code": null,
"e": 24183,
"s": 24130,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 24242,
"s": 24183,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 24303,
"s": 24242,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 24380,
"s": 24303,
"text": "Find number of rectangles that can be formed from a given set of coordinates"
},
{
"code": null,
"e": 24418,
"s": 24380,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 24476,
"s": 24418,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 24538,
"s": 24476,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 24618,
"s": 24538,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 24659,
"s": 24618,
"text": "C Program to read contents of Whole File"
}
] |
Minimum number of given operations required to make two strings equal using C++. | Given two strings str1 and str2, both strings contain characters ‘a’ and ‘b’. Both strings are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert the first string into the second string by doing the minimum number of the following operations −
If _ is at a position I then _ can be swapped with a character at position i+1 or i-1
If _ is at a position I then _ can be swapped with a character at position i+1 or i-1
If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2
If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2
Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2
Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2
If str1 = “aba_a” and str2 = “_baaa” then we require 2 moves to transform str1 to str2 −
1. str1 = “ab_aa” (Swapped str1[2] with str1[3])
2. str2 = “_baaa” (Swapped str1[0] with str1[2])
1. Apply a simple Breadth First Search over the string and an element of the queue used for BFS will contain the pair str, pos where pos is the position of _ in the string str.
2. Also maintain a map namely ‘vis’ which will store the string as key and the minimum moves to get to the string as value.
3. For every string str from the queue, generate a new string tmp based on the four conditions given and update the vis map as vis[tmp] = vis[str] + 1.
4. Repeat the above steps until the queue is empty or the required string is generated i.e. tmp == B
5. If the required string is generated, then return vis[str] + 1 which is the minimum number of operations required to change A to B.
#include <iostream>
#include <string>
#include <unordered_map>
#include <queue>
using namespace std;
int transformString(string str, string f){
unordered_map<string, int> vis;
int n;
n = str.length();
int pos = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == '_') {
pos = i;
break;
}
}
queue<pair<string, int> > q;
q.push({ str, pos });
vis[str] = 0;
while (!q.empty()) {
string ss = q.front().first;
int pp = q.front().second;
int dist = vis[ss];
q.pop();
if (pp > 0) {
swap(ss[pp], ss[pp - 1]);
if (!vis.count(ss)) {
if (ss == f) {
return dist + 1;
break;
}
vis[ss] = dist + 1;
q.push({ ss, pp - 1 });
}
swap(ss[pp], ss[pp - 1]);
}
if (pp < n - 1) {
swap(ss[pp], ss[pp + 1]);
if (!vis.count(ss)) {
if (ss == f) {
return dist + 1;
break;
}
vis[ss] = dist + 1;
q.push({ ss, pp + 1 });
}
swap(ss[pp], ss[pp + 1]);
}
if (pp > 1 && ss[pp - 1] != ss[pp - 2]) {
swap(ss[pp], ss[pp - 2]);
if (!vis.count(ss)) {
if (ss == f) {
return dist + 1;
break;
}
vis[ss] = dist + 1;
q.push({ ss, pp - 2 });
}
swap(ss[pp], ss[pp - 2]);
}
if (pp < n - 2 && ss[pp + 1] != ss[pp + 2]) {
swap(ss[pp], ss[pp + 2]);
if (!vis.count(ss)) {
if (ss == f) {
return dist + 1;
break;
}
vis[ss] = dist + 1;
q.push({ ss, pp + 2 });
}
swap(ss[pp], ss[pp + 2]);
}
}
return 0;
}
int main(){
string str1 = "aba_a";
string str2 = "_baaa";
cout << "Minimum required moves: " << transformString(str1, str2) << endl;
return 0;
}
When you compile and execute the above program. It generates the following output −
Minimum required moves: 2 | [
{
"code": null,
"e": 1346,
"s": 1062,
"text": "Given two strings str1 and str2, both strings contain characters ‘a’ and ‘b’. Both strings are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert the first string into the second string by doing the minimum number of the following operations −"
},
{
"code": null,
"e": 1432,
"s": 1346,
"text": "If _ is at a position I then _ can be swapped with a character at position i+1 or i-1"
},
{
"code": null,
"e": 1518,
"s": 1432,
"text": "If _ is at a position I then _ can be swapped with a character at position i+1 or i-1"
},
{
"code": null,
"e": 1633,
"s": 1518,
"text": "If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2"
},
{
"code": null,
"e": 1748,
"s": 1633,
"text": "If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2"
},
{
"code": null,
"e": 1874,
"s": 1748,
"text": "Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2"
},
{
"code": null,
"e": 2000,
"s": 1874,
"text": "Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2"
},
{
"code": null,
"e": 2089,
"s": 2000,
"text": "If str1 = “aba_a” and str2 = “_baaa” then we require 2 moves to transform str1 to str2 −"
},
{
"code": null,
"e": 2187,
"s": 2089,
"text": "1. str1 = “ab_aa” (Swapped str1[2] with str1[3])\n2. str2 = “_baaa” (Swapped str1[0] with str1[2])"
},
{
"code": null,
"e": 2875,
"s": 2187,
"text": "1. Apply a simple Breadth First Search over the string and an element of the queue used for BFS will contain the pair str, pos where pos is the position of _ in the string str.\n2. Also maintain a map namely ‘vis’ which will store the string as key and the minimum moves to get to the string as value.\n3. For every string str from the queue, generate a new string tmp based on the four conditions given and update the vis map as vis[tmp] = vis[str] + 1.\n4. Repeat the above steps until the queue is empty or the required string is generated i.e. tmp == B\n5. If the required string is generated, then return vis[str] + 1 which is the minimum number of operations required to change A to B."
},
{
"code": null,
"e": 4783,
"s": 2875,
"text": "#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <queue>\nusing namespace std;\nint transformString(string str, string f){\n unordered_map<string, int> vis;\n int n;\n n = str.length();\n int pos = 0;\n for (int i = 0; i < str.length(); i++) {\n if (str[i] == '_') {\n pos = i;\n break;\n }\n }\n queue<pair<string, int> > q;\n q.push({ str, pos });\n vis[str] = 0;\n while (!q.empty()) {\n string ss = q.front().first;\n int pp = q.front().second;\n int dist = vis[ss];\n q.pop();\n if (pp > 0) {\n swap(ss[pp], ss[pp - 1]);\n if (!vis.count(ss)) {\n if (ss == f) {\n return dist + 1;\n break;\n }\n vis[ss] = dist + 1;\n q.push({ ss, pp - 1 });\n }\n swap(ss[pp], ss[pp - 1]);\n }\n if (pp < n - 1) {\n swap(ss[pp], ss[pp + 1]);\n if (!vis.count(ss)) {\n if (ss == f) {\n return dist + 1;\n break;\n }\n vis[ss] = dist + 1;\n q.push({ ss, pp + 1 });\n }\n swap(ss[pp], ss[pp + 1]);\n }\n if (pp > 1 && ss[pp - 1] != ss[pp - 2]) {\n swap(ss[pp], ss[pp - 2]);\n if (!vis.count(ss)) {\n if (ss == f) {\n return dist + 1;\n break;\n }\n vis[ss] = dist + 1;\n q.push({ ss, pp - 2 });\n }\n swap(ss[pp], ss[pp - 2]);\n }\n if (pp < n - 2 && ss[pp + 1] != ss[pp + 2]) {\n swap(ss[pp], ss[pp + 2]);\n if (!vis.count(ss)) {\n if (ss == f) {\n return dist + 1;\n break;\n }\n vis[ss] = dist + 1;\n q.push({ ss, pp + 2 });\n }\n swap(ss[pp], ss[pp + 2]);\n }\n }\n return 0;\n}\nint main(){\n string str1 = \"aba_a\";\n string str2 = \"_baaa\";\n cout << \"Minimum required moves: \" << transformString(str1, str2) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 4867,
"s": 4783,
"text": "When you compile and execute the above program. It generates the following output −"
},
{
"code": null,
"e": 4893,
"s": 4867,
"text": "Minimum required moves: 2"
}
] |
C Program for Reversal algorithm for array rotation | An algorithm is a set of instructions that are performed in order to solve the given problem. Here, we will discuss the reversal algorithm for array rotation and create a program for a reversal algorithm.
Now, let's get to some terms that we need to know to solve this problem −
Array − A container of elements of the same data type. The size (number of elements) of the array is fixed at the time of the declaration of the array.
Array rotation − Rotating an array is changing the order of the elements of the array. Increasing the index of the element by one and changing the index of the last element to 0 and so on.
Example of array rotation,
Array[] = {3, 6, 8,1, 4, 10}
Rotated 2 times gives,
Array[] = {4, 10, 3, 6, 8, 1, 4}
Reversal Algorithm
One of the algorithms for array rotation is the reversal algorithm. In this algorithm, subarrays are created and reversed to perform the rotation of the array. Subarrays are created, rotated individually and then joined together and reversed back to get the rotated array.
Input : array arr[] , positions that are needed to be rotated r , length of array n.
Step 1: Split the array into two sub arrays of 0 - (d-1) and d - (n-1) size, a1 [d] and a2[n-d];
Step 2: Reverse both arrays using the reverse method.
Step 3: Join a1 and a2 back to get an array of original size.
Step 4: Reverse this joined array to get the rotated array.
Step 5: Print the array using the standard output method.
Example,
arr[] = {1 ,4, 2, 8, 3, 6, 5}, d = 3, n = 7
a1[] = {1,4,2} ; a2 = {8,3,6,5}
a1r[] = {2,4,1} // reversed a1
a2r[] = {5,6,3,8} // reversed a2
ar[] = {2,4,1,5,6,3,8} // a1r+a2r
arr[] = {8,3,6,5,1,4,2} // final answer.
Live Demo
#include <stdio.h>
void reverse(int arr[], int start, int end){
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main(){
int arr[] = { 54, 67, 12, 76, 25, 16, 34 };
int n = 7;
int d = 2;
printf("The initial array is :\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
reverse(arr, 0, d - 1);
reverse(arr, d, n - 1);
reverse(arr, 0, n - 1);
printf("\nThe left reversed array by %d elements is:\n",d);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
The initial array is :
54 67 12 76 25 16 34
The left reversed array by 2 elements is:
12 76 25 16 34 54 67 | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "An algorithm is a set of instructions that are performed in order to solve the given problem. Here, we will discuss the reversal algorithm for array rotation and create a program for a reversal algorithm."
},
{
"code": null,
"e": 1341,
"s": 1267,
"text": "Now, let's get to some terms that we need to know to solve this problem −"
},
{
"code": null,
"e": 1493,
"s": 1341,
"text": "Array − A container of elements of the same data type. The size (number of elements) of the array is fixed at the time of the declaration of the array."
},
{
"code": null,
"e": 1682,
"s": 1493,
"text": "Array rotation − Rotating an array is changing the order of the elements of the array. Increasing the index of the element by one and changing the index of the last element to 0 and so on."
},
{
"code": null,
"e": 1709,
"s": 1682,
"text": "Example of array rotation,"
},
{
"code": null,
"e": 1794,
"s": 1709,
"text": "Array[] = {3, 6, 8,1, 4, 10}\nRotated 2 times gives,\nArray[] = {4, 10, 3, 6, 8, 1, 4}"
},
{
"code": null,
"e": 1813,
"s": 1794,
"text": "Reversal Algorithm"
},
{
"code": null,
"e": 2086,
"s": 1813,
"text": "One of the algorithms for array rotation is the reversal algorithm. In this algorithm, subarrays are created and reversed to perform the rotation of the array. Subarrays are created, rotated individually and then joined together and reversed back to get the rotated array."
},
{
"code": null,
"e": 2502,
"s": 2086,
"text": "Input : array arr[] , positions that are needed to be rotated r , length of array n.\nStep 1: Split the array into two sub arrays of 0 - (d-1) and d - (n-1) size, a1 [d] and a2[n-d];\nStep 2: Reverse both arrays using the reverse method.\nStep 3: Join a1 and a2 back to get an array of original size.\nStep 4: Reverse this joined array to get the rotated array.\nStep 5: Print the array using the standard output method."
},
{
"code": null,
"e": 2511,
"s": 2502,
"text": "Example,"
},
{
"code": null,
"e": 2728,
"s": 2511,
"text": "arr[] = {1 ,4, 2, 8, 3, 6, 5}, d = 3, n = 7\na1[] = {1,4,2} ; a2 = {8,3,6,5}\na1r[] = {2,4,1} // reversed a1\na2r[] = {5,6,3,8} // reversed a2\nar[] = {2,4,1,5,6,3,8} // a1r+a2r\narr[] = {8,3,6,5,1,4,2} // final answer."
},
{
"code": null,
"e": 2739,
"s": 2728,
"text": " Live Demo"
},
{
"code": null,
"e": 3358,
"s": 2739,
"text": "#include <stdio.h>\nvoid reverse(int arr[], int start, int end){\n int temp;\n while (start < end) {\n temp = arr[start];\n arr[start] = arr[end];\n arr[end] = temp;\n start++;\n end--;\n }\n}\nint main(){\n int arr[] = { 54, 67, 12, 76, 25, 16, 34 };\n int n = 7;\n int d = 2;\n printf(\"The initial array is :\\n\");\n for (int i = 0; i < n; i++)\n printf(\"%d \", arr[i]);\n reverse(arr, 0, d - 1);\n reverse(arr, d, n - 1);\n reverse(arr, 0, n - 1);\n printf(\"\\nThe left reversed array by %d elements is:\\n\",d);\n for (int i = 0; i < n; i++)\n printf(\"%d \", arr[i]);\n return 0;\n}"
},
{
"code": null,
"e": 3465,
"s": 3358,
"text": "The initial array is :\n54 67 12 76 25 16 34\nThe left reversed array by 2 elements is:\n12 76 25 16 34 54 67"
}
] |
JDBC - SQL Syntax | Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries.
SQL is supported by almost any database you will likely use, and it allows you to write database code independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database.
For a detailed understanding on SQL, you can read our MySQL Tutorial.
The CREATE DATABASE statement is used for creating a new database. The syntax is −
SQL> CREATE DATABASE DATABASE_NAME;
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
The DROP DATABASE statement is used for deleting an existing database. The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note − To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database.
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the
respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
The following SQL INSERT statement inserts a new row in the Employees database created earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL UPDATE statement changes the age column of the employee whose id is 100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators.
The following SQL DELETE statement deletes the record of the employee whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;
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": 2357,
"s": 2162,
"text": "Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries."
},
{
"code": null,
"e": 2501,
"s": 2357,
"text": "SQL is supported by almost any database you will likely use, and it allows you to write database code independently of the underlying database."
},
{
"code": null,
"e": 2749,
"s": 2501,
"text": "This chapter gives an overview of SQL, which is a prerequisite to understand JDBC concepts. After going through this chapter, you will be able to Create, Create, Read, Update, and Delete (often referred to as CRUD operations) data from a database."
},
{
"code": null,
"e": 2819,
"s": 2749,
"text": "For a detailed understanding on SQL, you can read our MySQL Tutorial."
},
{
"code": null,
"e": 2902,
"s": 2819,
"text": "The CREATE DATABASE statement is used for creating a new database. The syntax is −"
},
{
"code": null,
"e": 2939,
"s": 2902,
"text": "SQL> CREATE DATABASE DATABASE_NAME;\n"
},
{
"code": null,
"e": 2998,
"s": 2939,
"text": "The following SQL statement creates a Database named EMP −"
},
{
"code": null,
"e": 3024,
"s": 2998,
"text": "SQL> CREATE DATABASE EMP;"
},
{
"code": null,
"e": 3111,
"s": 3024,
"text": "The DROP DATABASE statement is used for deleting an existing database. The syntax is −"
},
{
"code": null,
"e": 3146,
"s": 3111,
"text": "SQL> DROP DATABASE DATABASE_NAME;\n"
},
{
"code": null,
"e": 3327,
"s": 3146,
"text": "Note − To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database."
},
{
"code": null,
"e": 3404,
"s": 3327,
"text": "The CREATE TABLE statement is used for creating a new table. The syntax is −"
},
{
"code": null,
"e": 3544,
"s": 3404,
"text": "SQL> CREATE TABLE table_name\n(\n column_name column_data_type,\n column_name column_data_type,\n column_name column_data_type\n ...\n);\n"
},
{
"code": null,
"e": 3624,
"s": 3544,
"text": "The following SQL statement creates a table named Employees with four columns −"
},
{
"code": null,
"e": 3765,
"s": 3624,
"text": "SQL> CREATE TABLE Employees\n(\n id INT NOT NULL,\n age INT NOT NULL,\n first VARCHAR(255),\n last VARCHAR(255),\n PRIMARY KEY ( id )\n);"
},
{
"code": null,
"e": 3846,
"s": 3765,
"text": "The DROP TABLE statement is used for deleting an existing table. The syntax is −"
},
{
"code": null,
"e": 3875,
"s": 3846,
"text": "SQL> DROP TABLE table_name;\n"
},
{
"code": null,
"e": 3937,
"s": 3875,
"text": "The following SQL statement deletes a table named Employees −"
},
{
"code": null,
"e": 3964,
"s": 3937,
"text": "SQL> DROP TABLE Employees;"
},
{
"code": null,
"e": 4115,
"s": 3964,
"text": "The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the\nrespective columns −"
},
{
"code": null,
"e": 4176,
"s": 4115,
"text": "SQL> INSERT INTO table_name VALUES (column1, column2, ...);\n"
},
{
"code": null,
"e": 4273,
"s": 4176,
"text": "The following SQL INSERT statement inserts a new row in the Employees database created earlier −"
},
{
"code": null,
"e": 4333,
"s": 4273,
"text": "SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');"
},
{
"code": null,
"e": 4423,
"s": 4333,
"text": "The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −"
},
{
"code": null,
"e": 4510,
"s": 4423,
"text": "SQL> SELECT column_name, column_name, ...\n FROM table_name\n WHERE conditions;\n"
},
{
"code": null,
"e": 4635,
"s": 4510,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 4754,
"s": 4635,
"text": "The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 −"
},
{
"code": null,
"e": 4826,
"s": 4754,
"text": "SQL> SELECT first, last, age \n FROM Employees \n WHERE id = 100;"
},
{
"code": null,
"e": 4954,
"s": 4826,
"text": "The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara −"
},
{
"code": null,
"e": 5037,
"s": 4954,
"text": "SQL> SELECT first, last, age \n FROM Employees \n WHERE first LIKE '%Zara%';"
},
{
"code": null,
"e": 5109,
"s": 5037,
"text": "The UPDATE statement is used to update data. The syntax for UPDATE is −"
},
{
"code": null,
"e": 5211,
"s": 5109,
"text": "SQL> UPDATE table_name\n SET column_name = value, column_name = value, ...\n WHERE conditions;\n"
},
{
"code": null,
"e": 5336,
"s": 5211,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 5428,
"s": 5336,
"text": "The following SQL UPDATE statement changes the age column of the employee whose id is 100 −"
},
{
"code": null,
"e": 5475,
"s": 5428,
"text": "SQL> UPDATE Employees SET age=20 WHERE id=100;"
},
{
"code": null,
"e": 5559,
"s": 5475,
"text": "The DELETE statement is used to delete data from tables. The syntax for DELETE is −"
},
{
"code": null,
"e": 5606,
"s": 5559,
"text": "SQL> DELETE FROM table_name WHERE conditions;\n"
},
{
"code": null,
"e": 5731,
"s": 5606,
"text": "The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators."
},
{
"code": null,
"e": 5819,
"s": 5731,
"text": "The following SQL DELETE statement deletes the record of the employee whose id is 100 −"
},
{
"code": null,
"e": 5860,
"s": 5819,
"text": "SQL> DELETE FROM Employees WHERE id=100;"
},
{
"code": null,
"e": 5893,
"s": 5860,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5909,
"s": 5893,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5942,
"s": 5909,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5958,
"s": 5942,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5993,
"s": 5958,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6007,
"s": 5993,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6041,
"s": 6007,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6055,
"s": 6041,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6092,
"s": 6055,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6107,
"s": 6092,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6140,
"s": 6107,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6159,
"s": 6140,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6166,
"s": 6159,
"text": " Print"
},
{
"code": null,
"e": 6177,
"s": 6166,
"text": " Add Notes"
}
] |
How to plot rows of a data frame as lines in R? | To plot row of a data frame as lines, we can use matplot function but we would need to transpose the data frame because transposed values of the data frame will be read as columns and the matplot function plot the columns not rows. For example, if we have a data frame called df then the plot of rows as lines can be created by using the command −
matplot(t(df),type="l")
Consider the below data frame −
Live Demo
> x1<-rpois(5,2)
> x2<-rpois(5,5)
> x3<-rpois(5,3)
> df1<-data.frame(x1,x2,x3)
> df1
x1 x2 x3
1 0 9 5
2 3 4 2
3 0 2 1
4 3 7 3
5 5 10 3
Creating plot of rows in df1 as lines −
> matplot(t(df1),type="l")
Live Demo
> y1<-rnorm(3)
> y2<-rnorm(3)
> y3<-rnorm(3)
> df2<-data.frame(y1,y2,y3)
> df2
y1 y2 y3
1 -0.9992381 -1.3802480 -0.7228096
2 1.3677936 0.1813761 1.3711921
3 0.8905198 -1.0607813 0.3895616
1 -0.9992381 -1.3802480 -0.7228096
2 1.3677936 0.1813761 1.3711921
3 0.8905198 -1.0607813 0.3895616
Creating plot of rows in df2 as lines −
> matplot(t(df2),type="l") | [
{
"code": null,
"e": 1410,
"s": 1062,
"text": "To plot row of a data frame as lines, we can use matplot function but we would need to transpose the data frame because transposed values of the data frame will be read as columns and the matplot function plot the columns not rows. For example, if we have a data frame called df then the plot of rows as lines can be created by using the command −"
},
{
"code": null,
"e": 1434,
"s": 1410,
"text": "matplot(t(df),type=\"l\")"
},
{
"code": null,
"e": 1466,
"s": 1434,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1476,
"s": 1466,
"text": "Live Demo"
},
{
"code": null,
"e": 1561,
"s": 1476,
"text": "> x1<-rpois(5,2)\n> x2<-rpois(5,5)\n> x3<-rpois(5,3)\n> df1<-data.frame(x1,x2,x3)\n> df1"
},
{
"code": null,
"e": 1627,
"s": 1561,
"text": " x1 x2 x3\n1 0 9 5\n2 3 4 2\n3 0 2 1\n4 3 7 3\n5 5 10 3"
},
{
"code": null,
"e": 1667,
"s": 1627,
"text": "Creating plot of rows in df1 as lines −"
},
{
"code": null,
"e": 1694,
"s": 1667,
"text": "> matplot(t(df1),type=\"l\")"
},
{
"code": null,
"e": 1704,
"s": 1694,
"text": "Live Demo"
},
{
"code": null,
"e": 1783,
"s": 1704,
"text": "> y1<-rnorm(3)\n> y2<-rnorm(3)\n> y3<-rnorm(3)\n> df2<-data.frame(y1,y2,y3)\n> df2"
},
{
"code": null,
"e": 2028,
"s": 1783,
"text": " y1 y2 y3\n1 -0.9992381 -1.3802480 -0.7228096\n2 1.3677936 0.1813761 1.3711921\n3 0.8905198 -1.0607813 0.3895616\n1 -0.9992381 -1.3802480 -0.7228096\n2 1.3677936 0.1813761 1.3711921\n3 0.8905198 -1.0607813 0.3895616"
},
{
"code": null,
"e": 2068,
"s": 2028,
"text": "Creating plot of rows in df2 as lines −"
},
{
"code": null,
"e": 2095,
"s": 2068,
"text": "> matplot(t(df2),type=\"l\")"
}
] |
Bare Repositories in Git - GeeksforGeeks | 29 Dec, 2019
Repositories in Git are a snapshot of the folder in which you are working on your project. You can track the progress and changes made to the project by making commits and also revert changes if not satisfactory.Repositories can be divided into two types based on the usage on a server. These are:
Non-bare Repositories
Bare Repositories
What is a Non-bare repository?A non-bare or default git repository has a .git folder, which is the backbone of the repository where all the important files for tracking the changes in the folders are stored. It stores the hashes of commits made in the branches and a file where the hash of the latest commit is stored.The file structure of the default repository should look something like this:
-- Default_Repo*
|-- .git*
| |-- hooks*
| |-- info*
| |-- logs*
| |-- objects*
| |-- refs*
| |-- COMMIT_EDITMSG
| |-- config
| |-- description
| |-- HEAD
| |-- index
|-- example.txt
*: Folders
As you can see, the .git folder contains all the required files for tracking the project folder. The default repository is always used for local repositories. What is a bare repository?A bare repository is the same as default, but no commits can be made in a bare repository. The changes made in projects cannot be tracked by a bare repository as it doesn’t have a working tree. A working tree is a directory in which all the project files/sub-directories reside. Bare repository is essentially a .git folder with a specific folder where all the project files reside.Practically speaking everything in the repository apart from .git is a part of working tree. To create a bare repository, navigate to the chosen directory in bash (for linux users) or command prompt (for windows users) and type:
>mkdir FileName.git
>cd FileName.git
>git init –bare
The file structure of the bare repository should look like this:
-- BareRepo.git*
|-- hooks*
|-- info*
|-- logs*
|-- objects*
|-- refs*
|-- COMMIT_EDITMSG
|-- config
|-- description
|-- HEAD
|-- index
*: Folders
Note: This is the exact same file structure of .git folder in non-bare repository
It is important to note that all bare repositories have .git extension (E.g. notice BareRepo.git). Since you cannot commit, or make changes to it, bare repositories are pretty useless on their own. But then why does it exist? When people collaborate to work on a project, they need a central repository where all the tracked changes are stored and prevent any conflict between the versions of the project on other’s computers. A central repository also means that any new contributor can clone the repository into a local one without getting any unsaved changes or conflicting work of others (in short, no mess). A central repository was strictly supposed to be something like a reference repository.
This requires one to use a remote repository as a central one, and initially, only Bare repositories could be used as remote repositories. With the latest changes in git, central repositories need not be bare, hence not many people know about it properly.The only possible operations on the Bare Repository are Pushing or Cloning. Using a Bare RepositoryA bare repository is linked with a local repository, hence the files in .git of local repo should match with the files in the bare repo. First, create a bare repository (See section for the code snippet).Then, create a local repository folder and clone the bare repository:
>cd C:/Users/example/repositories
>git clone C:/Users/example/BareRepo.git
Cloning into 'BareRepo'...
warning: You appear to have cloned an empty repository.
done.
Don’t worry about the warning. The cloned repository will have the same name as that of the Bare Repository, navigate to that folder and add project files and commit changes. Then push the changes to the bare repository:
>git add *
>git commit -m “First commit”
[master (root-commit) ffdf43f] First Commit
1 file changed, 1 insertion(+)
create mode 100644 example.txt
>git push c:/users/example/BareRepo.git
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 293 bytes | 97.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To c:/users/example /BareRepo.git
* [new branch] master -> master
And thus, your local repo has been linked to the Bare Repository. In case you already have some files in the project directory, directly initialize the project folder as a git repository, then push its changes to a bare repository (make sure that the Bare repository is not linked to any other project or is newly created). Another way is to clone your working project repository into a bare one:
>cd “Central Repositories”
>git clone –bare ../../..../Default_Repo
Cloning into bare repository 'Default_Repo.git'...
done.
Why is only Bare Repository used as a Central Repository for syncing work?Central Repositories use bare repositories only because git doesn’t allow you to push to a non-bare repository as the working tree will become inconsistent.To demonstrate why you can’t push to a non-bare repository:
>cd C:/Users/example/repositories
>mkdir RepoTest
>cd RepoTest
>git init
Initialized empty Git repository in C:/Users/example/repositories/RepoTest/.git/
>cd ../BareRepo
>git push ../RepoTest
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 293 bytes | 146.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: is denied, because it will make the index and work tree inconsistent
remote: with what you pushed, and will require 'git reset --hard' to match
remote: the work tree to HEAD.
remote:
remote: You can set the 'receive.denyCurrentBranch' configuration variable
remote: to 'ignore' or 'warn' in the remote repository to allow pushing into
remote: its current branch; however, this is not recommended unless you
remote: arranged to update its work tree to match what you pushed in some
remote: other way.
remote:
remote: To squelch this message and still keep the default behaviour, set
remote: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ../RepoTest
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '../RepoTest'
But if you still want to be stubborn about it, you can read the warning and go to the non-bare repository where you wish to push and set receive.denyCurrentBranch to ignore and then push the changes.
>cd ../RepoTest
>git config receive.denyCurrentBranch ignore
>cd ../Default_Repo
>git push ../RepoTest
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 293 bytes | 146.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To ../RepoTest
* [new branch] master -> master
But, using this will give you more problems, as you keeping pushing to remote repo, you’ll notice that only the commit head points to keeps changing (along with other files in .git), but your working tree will remain the same. The only way to remove the inconsistency of index and working tree is by using the command:
>git reset –hard
Unless you want to do this every time you push changes to the remote repository, it is recommended to use a bare repository.A bare repository takes much less space to store the same information along with the tracked changes than a non-bare repository. Hence, its storage consumption is the most efficient. Therefore, only a bare repository is suited to serve as a remote or central repository.
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Set Git Username and Password in GitBash?
Difference Between Git Push Origin and Git Push Origin Master
How to Undo a Commit in Git ?
Using GitHub with SSH (Secure Shell)
How to Push Git Branch to Remote?
How to Export Eclipse projects to GitHub?
How to Clone Android Project from GitHub in Android Studio?
What is README.md File?
Top 10 GitHub Alternatives That You Can Consider
GIT | An Introduction to Github | [
{
"code": null,
"e": 23809,
"s": 23781,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 24107,
"s": 23809,
"text": "Repositories in Git are a snapshot of the folder in which you are working on your project. You can track the progress and changes made to the project by making commits and also revert changes if not satisfactory.Repositories can be divided into two types based on the usage on a server. These are:"
},
{
"code": null,
"e": 24129,
"s": 24107,
"text": "Non-bare Repositories"
},
{
"code": null,
"e": 24147,
"s": 24129,
"text": "Bare Repositories"
},
{
"code": null,
"e": 24543,
"s": 24147,
"text": "What is a Non-bare repository?A non-bare or default git repository has a .git folder, which is the backbone of the repository where all the important files for tracking the changes in the folders are stored. It stores the hashes of commits made in the branches and a file where the hash of the latest commit is stored.The file structure of the default repository should look something like this:"
},
{
"code": null,
"e": 24894,
"s": 24543,
"text": "\n -- Default_Repo* \n |-- .git* \n | |-- hooks* \n | |-- info* \n | |-- logs* \n | |-- objects* \n | |-- refs* \n | |-- COMMIT_EDITMSG \n | |-- config \n | |-- description \n | |-- HEAD \n | |-- index \n |-- example.txt \n\n*: Folders "
},
{
"code": null,
"e": 25690,
"s": 24894,
"text": "As you can see, the .git folder contains all the required files for tracking the project folder. The default repository is always used for local repositories. What is a bare repository?A bare repository is the same as default, but no commits can be made in a bare repository. The changes made in projects cannot be tracked by a bare repository as it doesn’t have a working tree. A working tree is a directory in which all the project files/sub-directories reside. Bare repository is essentially a .git folder with a specific folder where all the project files reside.Practically speaking everything in the repository apart from .git is a part of working tree. To create a bare repository, navigate to the chosen directory in bash (for linux users) or command prompt (for windows users) and type:"
},
{
"code": null,
"e": 25749,
"s": 25690,
"text": " \n>mkdir FileName.git \n>cd FileName.git \n>git init –bare \n"
},
{
"code": null,
"e": 25814,
"s": 25749,
"text": "The file structure of the bare repository should look like this:"
},
{
"code": null,
"e": 26114,
"s": 25814,
"text": "-- BareRepo.git* \n |-- hooks* \n |-- info* \n |-- logs* \n |-- objects* \n |-- refs* \n |-- COMMIT_EDITMSG \n |-- config \n |-- description \n |-- HEAD \n |-- index \n\n*: Folders "
},
{
"code": null,
"e": 26196,
"s": 26114,
"text": "Note: This is the exact same file structure of .git folder in non-bare repository"
},
{
"code": null,
"e": 26897,
"s": 26196,
"text": "It is important to note that all bare repositories have .git extension (E.g. notice BareRepo.git). Since you cannot commit, or make changes to it, bare repositories are pretty useless on their own. But then why does it exist? When people collaborate to work on a project, they need a central repository where all the tracked changes are stored and prevent any conflict between the versions of the project on other’s computers. A central repository also means that any new contributor can clone the repository into a local one without getting any unsaved changes or conflicting work of others (in short, no mess). A central repository was strictly supposed to be something like a reference repository."
},
{
"code": null,
"e": 27525,
"s": 26897,
"text": "This requires one to use a remote repository as a central one, and initially, only Bare repositories could be used as remote repositories. With the latest changes in git, central repositories need not be bare, hence not many people know about it properly.The only possible operations on the Bare Repository are Pushing or Cloning. Using a Bare RepositoryA bare repository is linked with a local repository, hence the files in .git of local repo should match with the files in the bare repo. First, create a bare repository (See section for the code snippet).Then, create a local repository folder and clone the bare repository:"
},
{
"code": null,
"e": 27696,
"s": 27525,
"text": " \n>cd C:/Users/example/repositories \n>git clone C:/Users/example/BareRepo.git \nCloning into 'BareRepo'...\nwarning: You appear to have cloned an empty repository. \ndone. \n"
},
{
"code": null,
"e": 27917,
"s": 27696,
"text": "Don’t worry about the warning. The cloned repository will have the same name as that of the Bare Repository, navigate to that folder and add project files and commit changes. Then push the changes to the bare repository:"
},
{
"code": null,
"e": 28437,
"s": 27917,
"text": ">git add * \n>git commit -m “First commit” \n[master (root-commit) ffdf43f] First Commit \n 1 file changed, 1 insertion(+) \n create mode 100644 example.txt \n>git push c:/users/example/BareRepo.git \nEnumerating objects: 3, done. \nCounting objects: 100% (3/3), done. \nDelta compression using up to 4 threads \nCompressing objects: 100% (2/2), done. \nWriting objects: 100% (3/3), 293 bytes | 97.00 KiB/s, done. \nTotal 3 (delta 0), reused 0 (delta 0) \nTo c:/users/example /BareRepo.git \n * [new branch] master -> master \n"
},
{
"code": null,
"e": 28834,
"s": 28437,
"text": "And thus, your local repo has been linked to the Bare Repository. In case you already have some files in the project directory, directly initialize the project folder as a git repository, then push its changes to a bare repository (make sure that the Bare repository is not linked to any other project or is newly created). Another way is to clone your working project repository into a bare one:"
},
{
"code": null,
"e": 28964,
"s": 28834,
"text": ">cd “Central Repositories” \n>git clone –bare ../../..../Default_Repo \nCloning into bare repository 'Default_Repo.git'... \ndone. \n"
},
{
"code": null,
"e": 29255,
"s": 28964,
"text": " Why is only Bare Repository used as a Central Repository for syncing work?Central Repositories use bare repositories only because git doesn’t allow you to push to a non-bare repository as the working tree will become inconsistent.To demonstrate why you can’t push to a non-bare repository:"
},
{
"code": null,
"e": 30671,
"s": 29255,
"text": ">cd C:/Users/example/repositories \n>mkdir RepoTest \n>cd RepoTest \n>git init \nInitialized empty Git repository in C:/Users/example/repositories/RepoTest/.git/ \n>cd ../BareRepo \n>git push ../RepoTest \nEnumerating objects: 3, done. \nCounting objects: 100% (3/3), done. \nDelta compression using up to 4 threads \nCompressing objects: 100% (2/2), done. \nWriting objects: 100% (3/3), 293 bytes | 146.00 KiB/s, done. \nTotal 3 (delta 0), reused 0 (delta 0) \nremote: error: refusing to update checked out branch: refs/heads/master \nremote: error: By default, updating the current branch in a non-bare repository \nremote: is denied, because it will make the index and work tree inconsistent \nremote: with what you pushed, and will require 'git reset --hard' to match \nremote: the work tree to HEAD. \nremote: \nremote: You can set the 'receive.denyCurrentBranch' configuration variable \nremote: to 'ignore' or 'warn' in the remote repository to allow pushing into \nremote: its current branch; however, this is not recommended unless you \nremote: arranged to update its work tree to match what you pushed in some \nremote: other way. \nremote: \nremote: To squelch this message and still keep the default behaviour, set \nremote: 'receive.denyCurrentBranch' configuration variable to 'refuse'. \nTo ../RepoTest \n ! [remote rejected] master -> master (branch is currently checked out) \nerror: failed to push some refs to '../RepoTest'\n"
},
{
"code": null,
"e": 30871,
"s": 30671,
"text": "But if you still want to be stubborn about it, you can read the warning and go to the non-bare repository where you wish to push and set receive.denyCurrentBranch to ignore and then push the changes."
},
{
"code": null,
"e": 31284,
"s": 30871,
"text": ">cd ../RepoTest \n>git config receive.denyCurrentBranch ignore \n>cd ../Default_Repo \n>git push ../RepoTest \nEnumerating objects: 3, done. \nCounting objects: 100% (3/3), done. \nDelta compression using up to 4 threads \nCompressing objects: 100% (2/2), done. \nWriting objects: 100% (3/3), 293 bytes | 146.00 KiB/s, done. \nTotal 3 (delta 0), reused 0 (delta 0) \nTo ../RepoTest \n * [new branch] master -> master \n"
},
{
"code": null,
"e": 31603,
"s": 31284,
"text": "But, using this will give you more problems, as you keeping pushing to remote repo, you’ll notice that only the commit head points to keeps changing (along with other files in .git), but your working tree will remain the same. The only way to remove the inconsistency of index and working tree is by using the command:"
},
{
"code": null,
"e": 31621,
"s": 31603,
"text": ">git reset –hard "
},
{
"code": null,
"e": 32016,
"s": 31621,
"text": "Unless you want to do this every time you push changes to the remote repository, it is recommended to use a bare repository.A bare repository takes much less space to store the same information along with the tracked changes than a non-bare repository. Hence, its storage consumption is the most efficient. Therefore, only a bare repository is suited to serve as a remote or central repository."
},
{
"code": null,
"e": 32020,
"s": 32016,
"text": "Git"
},
{
"code": null,
"e": 32118,
"s": 32020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32127,
"s": 32118,
"text": "Comments"
},
{
"code": null,
"e": 32140,
"s": 32127,
"text": "Old Comments"
},
{
"code": null,
"e": 32189,
"s": 32140,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 32251,
"s": 32189,
"text": "Difference Between Git Push Origin and Git Push Origin Master"
},
{
"code": null,
"e": 32281,
"s": 32251,
"text": "How to Undo a Commit in Git ?"
},
{
"code": null,
"e": 32318,
"s": 32281,
"text": "Using GitHub with SSH (Secure Shell)"
},
{
"code": null,
"e": 32352,
"s": 32318,
"text": "How to Push Git Branch to Remote?"
},
{
"code": null,
"e": 32394,
"s": 32352,
"text": "How to Export Eclipse projects to GitHub?"
},
{
"code": null,
"e": 32454,
"s": 32394,
"text": "How to Clone Android Project from GitHub in Android Studio?"
},
{
"code": null,
"e": 32478,
"s": 32454,
"text": "What is README.md File?"
},
{
"code": null,
"e": 32527,
"s": 32478,
"text": "Top 10 GitHub Alternatives That You Can Consider"
}
] |
Elm - Environment Setup | This chapter discusses steps to install Elm on Windows, Mac and Linux platforms.
Consider the steps shown below to install Elm in your local environment.
Step 1 − Install node
Since elm is compiled to JavaScript, the target machine should have node installed. Refer to TutorialsPoint NodeJS course for steps to setup node and npm
Step 2 − Install elm
Execute the following command on the terminal to install elm. Note that the stable version of elm was 0.18 at the time of writing this course.
npm install -g [email protected]
After installation, execute the following command to verify the version of Elm.
C:\Users\dell>elm --version
0.18.0
Step 2 − Install the Editor
The development environment used here is Visual Studio Code (Windows platform).
Visual Studio Code is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VSCode is available at
In this section, we will discuss the steps to install Elm on Windows.
Download https://code.visualstudio.com/. for Windows.
Double-click on VSCodeSetup.exe to launch the setup process. This will only take a minute.
You may directly traverse to the file’s path by right clicking on File → Open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer.
Visual Studio Code’s Mac OS X specific installation guide can be found at VSCode Installation-MAC.
Visual Studio Code’s Linux specific installation guide can be found at VSCode Installation-Linux.
Step 4 − Install the elm Extension
Install the elm extension in VSCode as shown below.
REPL stands for Read Eval Print Loop. It represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode.
Elm comes bundled with a REPL environment. It performs the following tasks −
Read − Reads user's input, parses the input into elm data-structure, and stores in memory.
Read − Reads user's input, parses the input into elm data-structure, and stores in memory.
Eval − Takes and evaluates the data structure.
Eval − Takes and evaluates the data structure.
Print − Prints the result.
Print − Prints the result.
Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal.
Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal.
A simple example to add two numbers in REPL is shown below −
Open the VSCode terminal and type the command elm REPL.
The REPL terminal waits for the user to enter some input. Enter the following expression 10 + 20. The REPL environment processes the input as given below −
Reads numbers 10 and 20 from user.
Reads numbers 10 and 20 from user.
Evaluates using the + operator.
Evaluates using the + operator.
Prints result as 30.
Prints result as 30.
Loops for next user input. Here we exit from loop.
Loops for next user input. Here we exit from loop.
27 Lectures
2.5 hours
Ahmed Elfakharany
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1961,
"s": 1880,
"text": "This chapter discusses steps to install Elm on Windows, Mac and Linux platforms."
},
{
"code": null,
"e": 2034,
"s": 1961,
"text": "Consider the steps shown below to install Elm in your local environment."
},
{
"code": null,
"e": 2056,
"s": 2034,
"text": "Step 1 − Install node"
},
{
"code": null,
"e": 2210,
"s": 2056,
"text": "Since elm is compiled to JavaScript, the target machine should have node installed. Refer to TutorialsPoint NodeJS course for steps to setup node and npm"
},
{
"code": null,
"e": 2231,
"s": 2210,
"text": "Step 2 − Install elm"
},
{
"code": null,
"e": 2374,
"s": 2231,
"text": "Execute the following command on the terminal to install elm. Note that the stable version of elm was 0.18 at the time of writing this course."
},
{
"code": null,
"e": 2399,
"s": 2374,
"text": "npm install -g [email protected]\n"
},
{
"code": null,
"e": 2479,
"s": 2399,
"text": "After installation, execute the following command to verify the version of Elm."
},
{
"code": null,
"e": 2515,
"s": 2479,
"text": "C:\\Users\\dell>elm --version\n0.18.0\n"
},
{
"code": null,
"e": 2543,
"s": 2515,
"text": "Step 2 − Install the Editor"
},
{
"code": null,
"e": 2623,
"s": 2543,
"text": "The development environment used here is Visual Studio Code (Windows platform)."
},
{
"code": null,
"e": 2766,
"s": 2623,
"text": "Visual Studio Code is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VSCode is available at"
},
{
"code": null,
"e": 2836,
"s": 2766,
"text": "In this section, we will discuss the steps to install Elm on Windows."
},
{
"code": null,
"e": 2890,
"s": 2836,
"text": "Download https://code.visualstudio.com/. for Windows."
},
{
"code": null,
"e": 2981,
"s": 2890,
"text": "Double-click on VSCodeSetup.exe to launch the setup process. This will only take a minute."
},
{
"code": null,
"e": 3156,
"s": 2981,
"text": "You may directly traverse to the file’s path by right clicking on File → Open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer."
},
{
"code": null,
"e": 3255,
"s": 3156,
"text": "Visual Studio Code’s Mac OS X specific installation guide can be found at VSCode Installation-MAC."
},
{
"code": null,
"e": 3353,
"s": 3255,
"text": "Visual Studio Code’s Linux specific installation guide can be found at VSCode Installation-Linux."
},
{
"code": null,
"e": 3388,
"s": 3353,
"text": "Step 4 − Install the elm Extension"
},
{
"code": null,
"e": 3440,
"s": 3388,
"text": "Install the elm extension in VSCode as shown below."
},
{
"code": null,
"e": 3648,
"s": 3440,
"text": "REPL stands for Read Eval Print Loop. It represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode."
},
{
"code": null,
"e": 3725,
"s": 3648,
"text": "Elm comes bundled with a REPL environment. It performs the following tasks −"
},
{
"code": null,
"e": 3816,
"s": 3725,
"text": "Read − Reads user's input, parses the input into elm data-structure, and stores in memory."
},
{
"code": null,
"e": 3907,
"s": 3816,
"text": "Read − Reads user's input, parses the input into elm data-structure, and stores in memory."
},
{
"code": null,
"e": 3954,
"s": 3907,
"text": "Eval − Takes and evaluates the data structure."
},
{
"code": null,
"e": 4001,
"s": 3954,
"text": "Eval − Takes and evaluates the data structure."
},
{
"code": null,
"e": 4028,
"s": 4001,
"text": "Print − Prints the result."
},
{
"code": null,
"e": 4055,
"s": 4028,
"text": "Print − Prints the result."
},
{
"code": null,
"e": 4171,
"s": 4055,
"text": "Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal."
},
{
"code": null,
"e": 4287,
"s": 4171,
"text": "Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal."
},
{
"code": null,
"e": 4348,
"s": 4287,
"text": "A simple example to add two numbers in REPL is shown below −"
},
{
"code": null,
"e": 4404,
"s": 4348,
"text": "Open the VSCode terminal and type the command elm REPL."
},
{
"code": null,
"e": 4560,
"s": 4404,
"text": "The REPL terminal waits for the user to enter some input. Enter the following expression 10 + 20. The REPL environment processes the input as given below −"
},
{
"code": null,
"e": 4595,
"s": 4560,
"text": "Reads numbers 10 and 20 from user."
},
{
"code": null,
"e": 4630,
"s": 4595,
"text": "Reads numbers 10 and 20 from user."
},
{
"code": null,
"e": 4662,
"s": 4630,
"text": "Evaluates using the + operator."
},
{
"code": null,
"e": 4694,
"s": 4662,
"text": "Evaluates using the + operator."
},
{
"code": null,
"e": 4715,
"s": 4694,
"text": "Prints result as 30."
},
{
"code": null,
"e": 4736,
"s": 4715,
"text": "Prints result as 30."
},
{
"code": null,
"e": 4787,
"s": 4736,
"text": "Loops for next user input. Here we exit from loop."
},
{
"code": null,
"e": 4838,
"s": 4787,
"text": "Loops for next user input. Here we exit from loop."
},
{
"code": null,
"e": 4873,
"s": 4838,
"text": "\n 27 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4892,
"s": 4873,
"text": " Ahmed Elfakharany"
},
{
"code": null,
"e": 4899,
"s": 4892,
"text": " Print"
},
{
"code": null,
"e": 4910,
"s": 4899,
"text": " Add Notes"
}
] |
Advanced Encryption Standard (AES) - GeeksforGeeks | 11 Feb, 2022
Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S National Institute of Standards and Technology (NIST) in 2001. AES is widely used today as it is a much stronger than DES and triple DES despite being harder to implement.
Points to remember
AES is a block cipher.
The key size can be 128/192/256 bits.
Encrypts data in blocks of 128 bits each.
That means it takes 128 bits as input and outputs 128 bits of encrypted cipher text as output. AES relies on substitution-permutation network principle which means it is performed using a series of linked operations which involves replacing and shuffling of the input data.
Working of the cipher :AES performs operations on bytes of data rather than in bits. Since the block size is 128 bits, the cipher processes 128 bits (or 16 bytes) of the input data at a time.
The number of rounds depends on the key length as follows :
128 bit key – 10 rounds
192 bit key – 12 rounds
256 bit key – 14 rounds
Creation of Round keys :A Key Schedule algorithm is used to calculate all the round keys from the key. So the initial key is used to create many different round keys which will be used in the corresponding round of the encryption.
Encryption :AES considers each block as a 16 byte (4 byte x 4 byte = 128 ) grid in a column major arrangement.
[ b0 | b4 | b8 | b12 |
| b1 | b5 | b9 | b13 |
| b2 | b6 | b10| b14 |
| b3 | b7 | b11| b15 ]
Each round comprises of 4 steps :
SubBytes
ShiftRows
MixColumns
Add Round Key
The last round doesn’t have the MixColumns round.
The SubBytes does the substitution and ShiftRows and MixColumns performs the permutation in the algorithm.
SubBytes :This step implements the substitution.
In this step each byte is substituted by another byte. Its performed using a lookup table also called the S-box. This substitution is done in a way that a byte is never substituted by itself and also not substituted by another byte which is a compliment of the current byte. The result of this step is a 16 byte (4 x 4 ) matrix like before.
The next two steps implement the permutation.
ShiftRows :This step is just as it sounds. Each row is shifted a particular number of times.
The first row is not shifted
The second row is shifted once to the left.
The third row is shifted twice to the left.
The fourth row is shifted thrice to the left.
(A left circular shift is performed.)
[ b0 | b1 | b2 | b3 ] [ b0 | b1 | b2 | b3 ]
| b4 | b5 | b6 | b7 | -> | b5 | b6 | b7 | b4 |
| b8 | b9 | b10 | b11 | | b10 | b11 | b8 | b9 |
[ b12 | b13 | b14 | b15 ] [ b15 | b12 | b13 | b14 ]
MixColumns :This step is basically a matrix multiplication. Each column is multiplied with a specific matrix and thus the position of each byte in the column is changed as a result.
This step is skipped in the last round.
[ c0 ] [ 2 3 1 1 ] [ b0 ]
| c1 | = | 1 2 3 1 | | b1 |
| c2 | | 1 1 2 3 | | b2 |
[ c3 ] [ 3 1 1 2 ] [ b3 ]
Add Round Keys :Now the resultant output of the previous stage is XOR-ed with the corresponding round key. Here, the 16 bytes is not considered as a grid but just as 128 bits of data.
After all these rounds 128 bits of encrypted data is given back as output. This process is repeated until all the data to be encrypted undergoes this process.
Decryption :The stages in the rounds can be easily undone as these stages have an opposite to it which when performed reverts the changes.Each 128 blocks goes through the 10,12 or 14 rounds depending on the key size.
The stages of each round in decryption is as follows :
Add round key
Inverse MixColumns
ShiftRows
Inverse SubByte
The decryption process is the encryption process done in reverse so i will explain the steps with notable differences.
Inverse MixColumns : This step is similar to the MixColumns step in encryption, but differs in the matrix used to carry out the operation.
[ b0 ] [ 14 11 13 9 ] [ c0 ]
| b1 | = | 9 14 11 13 | | c1 |
| b2 | | 13 9 14 11 | | c2 |
[ b3 ] [ 11 13 9 14 ] [ c3 ]
Inverse SubBytes :Inverse S-box is used as a lookup table and using which the bytes are substituted during decryption.
Summary : AES instruction set is now integrated into the CPU (offers throughput of several GB/s)to improve the speed and security of applications that use AES for encryption and decryption. Even though its been 20 years since its introduction we have failed to break the AES algorithm as it is infeasible even with the current technology. Till date the only vulnerability remains in the implementation of the algorithm.
nishanishanth5464
fumenoid
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Active and Passive attacks in Information Security
Cryptography and its Types
Multiple Access Protocols in Computer Network
Intrusion Detection System (IDS)
GSM in Wireless Communication
Architecture of Internet of Things (IoT)
Bluetooth
Congestion Control in Computer Networks
Block Cipher modes of Operation
Difference between Circuit Switching and Packet Switching | [
{
"code": null,
"e": 24143,
"s": 24115,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 24430,
"s": 24143,
"text": "Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S National Institute of Standards and Technology (NIST) in 2001. AES is widely used today as it is a much stronger than DES and triple DES despite being harder to implement."
},
{
"code": null,
"e": 24449,
"s": 24430,
"text": "Points to remember"
},
{
"code": null,
"e": 24472,
"s": 24449,
"text": "AES is a block cipher."
},
{
"code": null,
"e": 24510,
"s": 24472,
"text": "The key size can be 128/192/256 bits."
},
{
"code": null,
"e": 24552,
"s": 24510,
"text": "Encrypts data in blocks of 128 bits each."
},
{
"code": null,
"e": 24826,
"s": 24552,
"text": "That means it takes 128 bits as input and outputs 128 bits of encrypted cipher text as output. AES relies on substitution-permutation network principle which means it is performed using a series of linked operations which involves replacing and shuffling of the input data."
},
{
"code": null,
"e": 25018,
"s": 24826,
"text": "Working of the cipher :AES performs operations on bytes of data rather than in bits. Since the block size is 128 bits, the cipher processes 128 bits (or 16 bytes) of the input data at a time."
},
{
"code": null,
"e": 25078,
"s": 25018,
"text": "The number of rounds depends on the key length as follows :"
},
{
"code": null,
"e": 25102,
"s": 25078,
"text": "128 bit key – 10 rounds"
},
{
"code": null,
"e": 25126,
"s": 25102,
"text": "192 bit key – 12 rounds"
},
{
"code": null,
"e": 25150,
"s": 25126,
"text": "256 bit key – 14 rounds"
},
{
"code": null,
"e": 25381,
"s": 25150,
"text": "Creation of Round keys :A Key Schedule algorithm is used to calculate all the round keys from the key. So the initial key is used to create many different round keys which will be used in the corresponding round of the encryption."
},
{
"code": null,
"e": 25492,
"s": 25381,
"text": "Encryption :AES considers each block as a 16 byte (4 byte x 4 byte = 128 ) grid in a column major arrangement."
},
{
"code": null,
"e": 25584,
"s": 25492,
"text": "[ b0 | b4 | b8 | b12 |\n| b1 | b5 | b9 | b13 |\n| b2 | b6 | b10| b14 |\n| b3 | b7 | b11| b15 ]"
},
{
"code": null,
"e": 25618,
"s": 25584,
"text": "Each round comprises of 4 steps :"
},
{
"code": null,
"e": 25627,
"s": 25618,
"text": "SubBytes"
},
{
"code": null,
"e": 25637,
"s": 25627,
"text": "ShiftRows"
},
{
"code": null,
"e": 25648,
"s": 25637,
"text": "MixColumns"
},
{
"code": null,
"e": 25662,
"s": 25648,
"text": "Add Round Key"
},
{
"code": null,
"e": 25712,
"s": 25662,
"text": "The last round doesn’t have the MixColumns round."
},
{
"code": null,
"e": 25819,
"s": 25712,
"text": "The SubBytes does the substitution and ShiftRows and MixColumns performs the permutation in the algorithm."
},
{
"code": null,
"e": 25869,
"s": 25819,
"text": "SubBytes :This step implements the substitution."
},
{
"code": null,
"e": 26210,
"s": 25869,
"text": "In this step each byte is substituted by another byte. Its performed using a lookup table also called the S-box. This substitution is done in a way that a byte is never substituted by itself and also not substituted by another byte which is a compliment of the current byte. The result of this step is a 16 byte (4 x 4 ) matrix like before."
},
{
"code": null,
"e": 26256,
"s": 26210,
"text": "The next two steps implement the permutation."
},
{
"code": null,
"e": 26349,
"s": 26256,
"text": "ShiftRows :This step is just as it sounds. Each row is shifted a particular number of times."
},
{
"code": null,
"e": 26378,
"s": 26349,
"text": "The first row is not shifted"
},
{
"code": null,
"e": 26422,
"s": 26378,
"text": "The second row is shifted once to the left."
},
{
"code": null,
"e": 26466,
"s": 26422,
"text": "The third row is shifted twice to the left."
},
{
"code": null,
"e": 26512,
"s": 26466,
"text": "The fourth row is shifted thrice to the left."
},
{
"code": null,
"e": 26550,
"s": 26512,
"text": "(A left circular shift is performed.)"
},
{
"code": null,
"e": 26790,
"s": 26550,
"text": "[ b0 | b1 | b2 | b3 ] [ b0 | b1 | b2 | b3 ]\n| b4 | b5 | b6 | b7 | -> | b5 | b6 | b7 | b4 |\n| b8 | b9 | b10 | b11 | | b10 | b11 | b8 | b9 |\n[ b12 | b13 | b14 | b15 ] [ b15 | b12 | b13 | b14 ]"
},
{
"code": null,
"e": 26972,
"s": 26790,
"text": "MixColumns :This step is basically a matrix multiplication. Each column is multiplied with a specific matrix and thus the position of each byte in the column is changed as a result."
},
{
"code": null,
"e": 27012,
"s": 26972,
"text": "This step is skipped in the last round."
},
{
"code": null,
"e": 27167,
"s": 27012,
"text": "[ c0 ] [ 2 3 1 1 ] [ b0 ]\n| c1 | = | 1 2 3 1 | | b1 |\n| c2 | | 1 1 2 3 | | b2 |\n[ c3 ] [ 3 1 1 2 ] [ b3 ]"
},
{
"code": null,
"e": 27351,
"s": 27167,
"text": "Add Round Keys :Now the resultant output of the previous stage is XOR-ed with the corresponding round key. Here, the 16 bytes is not considered as a grid but just as 128 bits of data."
},
{
"code": null,
"e": 27510,
"s": 27351,
"text": "After all these rounds 128 bits of encrypted data is given back as output. This process is repeated until all the data to be encrypted undergoes this process."
},
{
"code": null,
"e": 27727,
"s": 27510,
"text": "Decryption :The stages in the rounds can be easily undone as these stages have an opposite to it which when performed reverts the changes.Each 128 blocks goes through the 10,12 or 14 rounds depending on the key size."
},
{
"code": null,
"e": 27782,
"s": 27727,
"text": "The stages of each round in decryption is as follows :"
},
{
"code": null,
"e": 27796,
"s": 27782,
"text": "Add round key"
},
{
"code": null,
"e": 27815,
"s": 27796,
"text": "Inverse MixColumns"
},
{
"code": null,
"e": 27825,
"s": 27815,
"text": "ShiftRows"
},
{
"code": null,
"e": 27841,
"s": 27825,
"text": "Inverse SubByte"
},
{
"code": null,
"e": 27960,
"s": 27841,
"text": "The decryption process is the encryption process done in reverse so i will explain the steps with notable differences."
},
{
"code": null,
"e": 28099,
"s": 27960,
"text": "Inverse MixColumns : This step is similar to the MixColumns step in encryption, but differs in the matrix used to carry out the operation."
},
{
"code": null,
"e": 28273,
"s": 28099,
"text": "[ b0 ] [ 14 11 13 9 ] [ c0 ]\n| b1 | = | 9 14 11 13 | | c1 |\n| b2 | | 13 9 14 11 | | c2 |\n[ b3 ] [ 11 13 9 14 ] [ c3 ]"
},
{
"code": null,
"e": 28392,
"s": 28273,
"text": "Inverse SubBytes :Inverse S-box is used as a lookup table and using which the bytes are substituted during decryption."
},
{
"code": null,
"e": 28812,
"s": 28392,
"text": "Summary : AES instruction set is now integrated into the CPU (offers throughput of several GB/s)to improve the speed and security of applications that use AES for encryption and decryption. Even though its been 20 years since its introduction we have failed to break the AES algorithm as it is infeasible even with the current technology. Till date the only vulnerability remains in the implementation of the algorithm."
},
{
"code": null,
"e": 28830,
"s": 28812,
"text": "nishanishanth5464"
},
{
"code": null,
"e": 28839,
"s": 28830,
"text": "fumenoid"
},
{
"code": null,
"e": 28852,
"s": 28839,
"text": "cryptography"
},
{
"code": null,
"e": 28870,
"s": 28852,
"text": "Computer Networks"
},
{
"code": null,
"e": 28883,
"s": 28870,
"text": "cryptography"
},
{
"code": null,
"e": 28901,
"s": 28883,
"text": "Computer Networks"
},
{
"code": null,
"e": 28999,
"s": 28901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29008,
"s": 28999,
"text": "Comments"
},
{
"code": null,
"e": 29021,
"s": 29008,
"text": "Old Comments"
},
{
"code": null,
"e": 29072,
"s": 29021,
"text": "Active and Passive attacks in Information Security"
},
{
"code": null,
"e": 29099,
"s": 29072,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 29145,
"s": 29099,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 29178,
"s": 29145,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 29208,
"s": 29178,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 29249,
"s": 29208,
"text": "Architecture of Internet of Things (IoT)"
},
{
"code": null,
"e": 29259,
"s": 29249,
"text": "Bluetooth"
},
{
"code": null,
"e": 29299,
"s": 29259,
"text": "Congestion Control in Computer Networks"
},
{
"code": null,
"e": 29331,
"s": 29299,
"text": "Block Cipher modes of Operation"
}
] |
How to build a simple time series dashboard in Python with Panel, Altair and a Jupyter Notebook | by Ben Dexter Cooley | Towards Data Science | I’ve been using Altair for over a year now, and it has quickly become my go-to charting library in Python. I love the built-in interactivity of the plots and the fact that the syntax is built on the Grammar of Graphics.
Altair even has some built-in interactivity through using Vega widgets. However, I have found this to be limiting at times and it doesn’t really allow me to create layouts the way I would want to for a dashboard.
Then I found Panel. Panel calls itself a “high-level app and dashboarding solution for Python” and it’s part of the HoloViz ecosystem managed by Anaconda. I’d heard of HoloViz before (and it’s relative overview site, PyViz), but never really spent the time to dive into the landscape. So here we go!
At first glance, what I love about Panel is that it is plotting-library-agnostic — it supports nearly all visualization libraries. So you don’t have to be a loyal Altair user to learn a bit about making dashboards in this post. That being said, compared to the other code samples in the Panel example gallery, I think the integration with Altair feels really intuitive.
Here are a few other really nice things about Panel:
It’s reactive (updates automatically!)
It’s declarative (readable code)
Supports different layouts (flexible)
Fully deployable to a server (shareable)
Jupyter Notebook compatible (but not dependent...Altair, however, is dependent on Jupyter. So I don’t advise trying this tutorial in something else.)
Here’s what we are going to build: the simplest of little dashboards, composed of an area chart and two filters. We’ll also add a title and subtitle for good measure. All within a Jupyter Notebook.
This tutorial will break the code into chunks and walk through it bit-by-bit, but if you just want dive into the full code (with comments), the Github repo is here.
Now for the code!
First, as always, import those dependent libraries. Here’s what you need:
import panel as pnimport altair as altfrom altair import datumimport pandas as pdfrom vega_datasets import dataimport datetime as dt
Updated August 27: please make sure that your Altair package is version 3.2 or above, otherwise you’ll get some data formatting errors.
Then we need to add two special lines of code, one for Altair and one for Panel. The first tells Altair to set the Vega-Lite rendered to Jupyter Notebook (if you’re using Jupyter Lab, check the Altair docs for alternative). The second line tells Panel to accept Vega (which powers Altair) as an extension. You can learn more about how extensions work in the components section of the Panel docs.
alt.renderers.enable(‘default’)pn.extension(‘vega’)
Since we’re using some sample data from the vega_datasets package, let’s preview our dataframe.
Now the fun part: let’s make some widgets! We’ll be making a dropdown and a date range slider to filter our data.
The dropdown widget takes two parameters: a title for your widget and the “options”.
# create list of company names (tickers) to use as optionstickers = [‘AAPL’, ‘GOOG’, ‘IBM’, ‘MSFT’]# this creates the dropdown widgetticker = pn.widgets.Select(name=’Company’, options=tickers)
Then we’ll create the date range slider. You can access this using the same pn.widgets method. The range slider takes four parameters: start date, end date, default starting date and default ending date.
# this creates the date range sliderdate_range_slider = pn.widgets.DateRangeSlider(name=’Date Range Slider’,start=dt.datetime(2001, 1, 1), end=dt.datetime(2010, 1, 1),value=(dt.datetime(2001, 1, 1), dt.datetime(2010, 1, 1)))
Widgets done! Now let’s add a title and subtitle, so it’s clear to someone else what this dashboard is about. Panel uses Markdown so it’s easy to specify headings.
title = ‘### Stock Price Dashboard’subtitle = ‘This dashboard allows you to select a company and date range to see stock prices.’
Note that we are just declaring variables at this point. Nothing has been built. But now, we start to get into the dashboard-building stuff.
To create a reactive dashboard, we need to tell our Panel object what to “depend” on. This effectively tells Panel to listen for changes in our widgets, and then reload the chart. This line will act as a decorator for the function: the ticker.param.value and date_range_slider.param.value will be used within our get_plot() function, specifically the Altair bit to manipulate the chart.
@pn.depends(ticker.param.value, date_range_slider.param.value)
We’re reactive. Now it’s time to create the plot directly below this line. Let’s write a function that does all our plotting dirty work. This will contain all the data shaping/manipulating as well as the code that creates out Altair chart. We will split this code into three parts using comments: 1) format data, 2) create pandas filters and 3) create Altair object.
def get_plot(ticker, date_range): # Load and format the data df = source # define df df[‘date’] = pd.to_datetime(df[‘date’]) # create date filter using values from the range slider # store the first and last date range slider value in a var start_date = date_range_slider.value[0] end_date = date_range_slider.value[1] # create filter mask for the dataframe mask = (df[‘date’] > start_date) & (df[‘date’] <= end_date) df = df.loc[mask] # filter the dataframe # create the Altair chart object chart = alt.Chart(df).mark_line().encode(x=’date’, y=‘price’, tooltip=alt.Tooltip([‘date’,’price’])).transform_filter((datum.symbol == ticker) # this ties in the filter ) return chart
Almost there! Now we need to create our final Panel object. Panel objects can consist of rows and columns. Since this is a simple little dashboard, we will just use two columns.
First we create our single row. Then, we fill it with the contents of two columns. Our first column will contain our 1) title, 2) subtitle, 3) dropdown and 4) date slider. The second column will display the chart.
dashboard = pn.Row(pn.Column(title, subtitle, ticker, date_range_slider),get_plot # our draw chart function!)
And we’re done! Simply call your dashboard variable and see your tiny little app in all of its beauty.
Another cool thing about Panel is it’s ability to deploy apps through a Bokeh server. For now, we’ll simply take our dashboard and add it as a “servable” local app for Bokeh so we can test our dashboard functionality. For all the details on deploying, check out the extensive deploy and export Panel page and the Bokeh docs on running a Bokeh server.
Adding this line of code:
dashboard.servable()
Will make your dashboard discoverable to Bokeh server. Now we’ll need to pop over to the command line to start our server. Run the below code to start your server as a localhost. The “ — show” command just tells Bokeh to pop open a new tab in the browser with your app displayed as soon as the server is ready. You can copy/paste this line into the terminal:
panel serve --show panel-altair-demo.ipynb
And there it is! Our little stock price app. Of course, this is using a standard, demo dataset. But hopefully you can start to see how you can plug in your dataset and create a more useful application. Think of the three columns of the dataframe simply as placeholders:
symbol → <your categorical variable>
date → <your dates and/or times>
price → <your values>
Even better, you can create a dashboard with multiple charts included. All without leaving the comfort of you cozy Jupyter Notebook.
I’m pumped to dive into Panel in more detail to start making more complex dashboards, quick prototypes, internal tools, etc. Happy coding!
The Panel documentation has a fantastic gallery of examples to get started with, so head on over to see what else is possible. This tutorial relies heavily on the Altair example, but I have adapted the code to what I feel is a cleaner version which should help for adapting to different datasets and chart types. I also added the date range slider as a new widget. ICYMI full commented code is in this repo. | [
{
"code": null,
"e": 392,
"s": 172,
"text": "I’ve been using Altair for over a year now, and it has quickly become my go-to charting library in Python. I love the built-in interactivity of the plots and the fact that the syntax is built on the Grammar of Graphics."
},
{
"code": null,
"e": 605,
"s": 392,
"text": "Altair even has some built-in interactivity through using Vega widgets. However, I have found this to be limiting at times and it doesn’t really allow me to create layouts the way I would want to for a dashboard."
},
{
"code": null,
"e": 905,
"s": 605,
"text": "Then I found Panel. Panel calls itself a “high-level app and dashboarding solution for Python” and it’s part of the HoloViz ecosystem managed by Anaconda. I’d heard of HoloViz before (and it’s relative overview site, PyViz), but never really spent the time to dive into the landscape. So here we go!"
},
{
"code": null,
"e": 1275,
"s": 905,
"text": "At first glance, what I love about Panel is that it is plotting-library-agnostic — it supports nearly all visualization libraries. So you don’t have to be a loyal Altair user to learn a bit about making dashboards in this post. That being said, compared to the other code samples in the Panel example gallery, I think the integration with Altair feels really intuitive."
},
{
"code": null,
"e": 1328,
"s": 1275,
"text": "Here are a few other really nice things about Panel:"
},
{
"code": null,
"e": 1367,
"s": 1328,
"text": "It’s reactive (updates automatically!)"
},
{
"code": null,
"e": 1400,
"s": 1367,
"text": "It’s declarative (readable code)"
},
{
"code": null,
"e": 1438,
"s": 1400,
"text": "Supports different layouts (flexible)"
},
{
"code": null,
"e": 1479,
"s": 1438,
"text": "Fully deployable to a server (shareable)"
},
{
"code": null,
"e": 1629,
"s": 1479,
"text": "Jupyter Notebook compatible (but not dependent...Altair, however, is dependent on Jupyter. So I don’t advise trying this tutorial in something else.)"
},
{
"code": null,
"e": 1827,
"s": 1629,
"text": "Here’s what we are going to build: the simplest of little dashboards, composed of an area chart and two filters. We’ll also add a title and subtitle for good measure. All within a Jupyter Notebook."
},
{
"code": null,
"e": 1992,
"s": 1827,
"text": "This tutorial will break the code into chunks and walk through it bit-by-bit, but if you just want dive into the full code (with comments), the Github repo is here."
},
{
"code": null,
"e": 2010,
"s": 1992,
"text": "Now for the code!"
},
{
"code": null,
"e": 2084,
"s": 2010,
"text": "First, as always, import those dependent libraries. Here’s what you need:"
},
{
"code": null,
"e": 2217,
"s": 2084,
"text": "import panel as pnimport altair as altfrom altair import datumimport pandas as pdfrom vega_datasets import dataimport datetime as dt"
},
{
"code": null,
"e": 2353,
"s": 2217,
"text": "Updated August 27: please make sure that your Altair package is version 3.2 or above, otherwise you’ll get some data formatting errors."
},
{
"code": null,
"e": 2749,
"s": 2353,
"text": "Then we need to add two special lines of code, one for Altair and one for Panel. The first tells Altair to set the Vega-Lite rendered to Jupyter Notebook (if you’re using Jupyter Lab, check the Altair docs for alternative). The second line tells Panel to accept Vega (which powers Altair) as an extension. You can learn more about how extensions work in the components section of the Panel docs."
},
{
"code": null,
"e": 2801,
"s": 2749,
"text": "alt.renderers.enable(‘default’)pn.extension(‘vega’)"
},
{
"code": null,
"e": 2897,
"s": 2801,
"text": "Since we’re using some sample data from the vega_datasets package, let’s preview our dataframe."
},
{
"code": null,
"e": 3011,
"s": 2897,
"text": "Now the fun part: let’s make some widgets! We’ll be making a dropdown and a date range slider to filter our data."
},
{
"code": null,
"e": 3096,
"s": 3011,
"text": "The dropdown widget takes two parameters: a title for your widget and the “options”."
},
{
"code": null,
"e": 3289,
"s": 3096,
"text": "# create list of company names (tickers) to use as optionstickers = [‘AAPL’, ‘GOOG’, ‘IBM’, ‘MSFT’]# this creates the dropdown widgetticker = pn.widgets.Select(name=’Company’, options=tickers)"
},
{
"code": null,
"e": 3493,
"s": 3289,
"text": "Then we’ll create the date range slider. You can access this using the same pn.widgets method. The range slider takes four parameters: start date, end date, default starting date and default ending date."
},
{
"code": null,
"e": 3718,
"s": 3493,
"text": "# this creates the date range sliderdate_range_slider = pn.widgets.DateRangeSlider(name=’Date Range Slider’,start=dt.datetime(2001, 1, 1), end=dt.datetime(2010, 1, 1),value=(dt.datetime(2001, 1, 1), dt.datetime(2010, 1, 1)))"
},
{
"code": null,
"e": 3882,
"s": 3718,
"text": "Widgets done! Now let’s add a title and subtitle, so it’s clear to someone else what this dashboard is about. Panel uses Markdown so it’s easy to specify headings."
},
{
"code": null,
"e": 4012,
"s": 3882,
"text": "title = ‘### Stock Price Dashboard’subtitle = ‘This dashboard allows you to select a company and date range to see stock prices.’"
},
{
"code": null,
"e": 4153,
"s": 4012,
"text": "Note that we are just declaring variables at this point. Nothing has been built. But now, we start to get into the dashboard-building stuff."
},
{
"code": null,
"e": 4540,
"s": 4153,
"text": "To create a reactive dashboard, we need to tell our Panel object what to “depend” on. This effectively tells Panel to listen for changes in our widgets, and then reload the chart. This line will act as a decorator for the function: the ticker.param.value and date_range_slider.param.value will be used within our get_plot() function, specifically the Altair bit to manipulate the chart."
},
{
"code": null,
"e": 4603,
"s": 4540,
"text": "@pn.depends(ticker.param.value, date_range_slider.param.value)"
},
{
"code": null,
"e": 4970,
"s": 4603,
"text": "We’re reactive. Now it’s time to create the plot directly below this line. Let’s write a function that does all our plotting dirty work. This will contain all the data shaping/manipulating as well as the code that creates out Altair chart. We will split this code into three parts using comments: 1) format data, 2) create pandas filters and 3) create Altair object."
},
{
"code": null,
"e": 5705,
"s": 4970,
"text": "def get_plot(ticker, date_range): # Load and format the data df = source # define df df[‘date’] = pd.to_datetime(df[‘date’]) # create date filter using values from the range slider # store the first and last date range slider value in a var start_date = date_range_slider.value[0] end_date = date_range_slider.value[1] # create filter mask for the dataframe mask = (df[‘date’] > start_date) & (df[‘date’] <= end_date) df = df.loc[mask] # filter the dataframe # create the Altair chart object chart = alt.Chart(df).mark_line().encode(x=’date’, y=‘price’, tooltip=alt.Tooltip([‘date’,’price’])).transform_filter((datum.symbol == ticker) # this ties in the filter ) return chart"
},
{
"code": null,
"e": 5883,
"s": 5705,
"text": "Almost there! Now we need to create our final Panel object. Panel objects can consist of rows and columns. Since this is a simple little dashboard, we will just use two columns."
},
{
"code": null,
"e": 6097,
"s": 5883,
"text": "First we create our single row. Then, we fill it with the contents of two columns. Our first column will contain our 1) title, 2) subtitle, 3) dropdown and 4) date slider. The second column will display the chart."
},
{
"code": null,
"e": 6207,
"s": 6097,
"text": "dashboard = pn.Row(pn.Column(title, subtitle, ticker, date_range_slider),get_plot # our draw chart function!)"
},
{
"code": null,
"e": 6310,
"s": 6207,
"text": "And we’re done! Simply call your dashboard variable and see your tiny little app in all of its beauty."
},
{
"code": null,
"e": 6661,
"s": 6310,
"text": "Another cool thing about Panel is it’s ability to deploy apps through a Bokeh server. For now, we’ll simply take our dashboard and add it as a “servable” local app for Bokeh so we can test our dashboard functionality. For all the details on deploying, check out the extensive deploy and export Panel page and the Bokeh docs on running a Bokeh server."
},
{
"code": null,
"e": 6687,
"s": 6661,
"text": "Adding this line of code:"
},
{
"code": null,
"e": 6708,
"s": 6687,
"text": "dashboard.servable()"
},
{
"code": null,
"e": 7067,
"s": 6708,
"text": "Will make your dashboard discoverable to Bokeh server. Now we’ll need to pop over to the command line to start our server. Run the below code to start your server as a localhost. The “ — show” command just tells Bokeh to pop open a new tab in the browser with your app displayed as soon as the server is ready. You can copy/paste this line into the terminal:"
},
{
"code": null,
"e": 7110,
"s": 7067,
"text": "panel serve --show panel-altair-demo.ipynb"
},
{
"code": null,
"e": 7380,
"s": 7110,
"text": "And there it is! Our little stock price app. Of course, this is using a standard, demo dataset. But hopefully you can start to see how you can plug in your dataset and create a more useful application. Think of the three columns of the dataframe simply as placeholders:"
},
{
"code": null,
"e": 7417,
"s": 7380,
"text": "symbol → <your categorical variable>"
},
{
"code": null,
"e": 7450,
"s": 7417,
"text": "date → <your dates and/or times>"
},
{
"code": null,
"e": 7472,
"s": 7450,
"text": "price → <your values>"
},
{
"code": null,
"e": 7605,
"s": 7472,
"text": "Even better, you can create a dashboard with multiple charts included. All without leaving the comfort of you cozy Jupyter Notebook."
},
{
"code": null,
"e": 7744,
"s": 7605,
"text": "I’m pumped to dive into Panel in more detail to start making more complex dashboards, quick prototypes, internal tools, etc. Happy coding!"
}
] |
How to align Placeholder Text in HTML ? - GeeksforGeeks | 11 Dec, 2018
The placeholder attribute specifies a short hint that describes the expected value of a input field / textarea. The short hint is displayed in the field before the user enters a value. In most of the browsers, placeholder texts are usually aligned in left. The selector uses text-align property to set the text alignment in the placeholder.This selector can change browser to browser. For example:
For Chrome, Mozilla, and Opera Browsers:::placeholder
::placeholder
For Internet Explorer::-ms-input-placeholder
:-ms-input-placeholder
Example 1: This example describes only placeholder alignment, it does not align placeholder value.
<!DOCTYPE html><html> <head> <title>Change Placeholder alignment</title> <style> input[type="email"]::placeholder { /* Firefox, Chrome, Opera */ text-align: center; } input[type="text"]::placeholder { /* Firefox, Chrome, Opera */ text-align: right; } input[type="tel"]::placeholder { /* Firefox, Chrome, Opera */ text-align: left; } input[type="email"]:-ms-input-placeholder { /* Internet Explorer 10-11 */ text-align: center; } input[type="email"]::-ms-input-placeholder { /* Microsoft Edge */ text-align: center; } body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h3>Placeholder Text Alignment</h3> <p>Center Aligned<br><input type="email" placeholder="Email"></p><br> <p>Right Aligned<br><input type="text" placeholder="Name"></p><br> <p>Left Aligned<br><input type="tel" placeholder="Phone Number"></p> </body></html>
Output:
Example 2: This example describes the placeholder and placeholder value align.
<!DOCTYPE html><html> <head> <title>Change Placeholder alignment</title> <style> input[type="email"]{ text-align: center; } input[type="text"] { text-align: right; } input[type="tel"] { text-align: left; } body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h3>Placeholder Text Alignment</h3> <p>Center Aligned<br><input type="email" placeholder="Email"></p><br> <p>Right Aligned<br><input type="text" placeholder="Name"></p><br> <p>Left Aligned<br><input type="tel" placeholder="Phone Number"></p> </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.
HTML-Misc
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 23862,
"s": 23834,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 24260,
"s": 23862,
"text": "The placeholder attribute specifies a short hint that describes the expected value of a input field / textarea. The short hint is displayed in the field before the user enters a value. In most of the browsers, placeholder texts are usually aligned in left. The selector uses text-align property to set the text alignment in the placeholder.This selector can change browser to browser. For example:"
},
{
"code": null,
"e": 24314,
"s": 24260,
"text": "For Chrome, Mozilla, and Opera Browsers:::placeholder"
},
{
"code": null,
"e": 24328,
"s": 24314,
"text": "::placeholder"
},
{
"code": null,
"e": 24373,
"s": 24328,
"text": "For Internet Explorer::-ms-input-placeholder"
},
{
"code": null,
"e": 24396,
"s": 24373,
"text": ":-ms-input-placeholder"
},
{
"code": null,
"e": 24495,
"s": 24396,
"text": "Example 1: This example describes only placeholder alignment, it does not align placeholder value."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Placeholder alignment</title> <style> input[type=\"email\"]::placeholder { /* Firefox, Chrome, Opera */ text-align: center; } input[type=\"text\"]::placeholder { /* Firefox, Chrome, Opera */ text-align: right; } input[type=\"tel\"]::placeholder { /* Firefox, Chrome, Opera */ text-align: left; } input[type=\"email\"]:-ms-input-placeholder { /* Internet Explorer 10-11 */ text-align: center; } input[type=\"email\"]::-ms-input-placeholder { /* Microsoft Edge */ text-align: center; } body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h3>Placeholder Text Alignment</h3> <p>Center Aligned<br><input type=\"email\" placeholder=\"Email\"></p><br> <p>Right Aligned<br><input type=\"text\" placeholder=\"Name\"></p><br> <p>Left Aligned<br><input type=\"tel\" placeholder=\"Phone Number\"></p> </body></html> ",
"e": 25924,
"s": 24495,
"text": null
},
{
"code": null,
"e": 25932,
"s": 25924,
"text": "Output:"
},
{
"code": null,
"e": 26011,
"s": 25932,
"text": "Example 2: This example describes the placeholder and placeholder value align."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Placeholder alignment</title> <style> input[type=\"email\"]{ text-align: center; } input[type=\"text\"] { text-align: right; } input[type=\"tel\"] { text-align: left; } body { text-align:center; } h1 { color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h3>Placeholder Text Alignment</h3> <p>Center Aligned<br><input type=\"email\" placeholder=\"Email\"></p><br> <p>Right Aligned<br><input type=\"text\" placeholder=\"Name\"></p><br> <p>Left Aligned<br><input type=\"tel\" placeholder=\"Phone Number\"></p> </body></html> ",
"e": 26881,
"s": 26011,
"text": null
},
{
"code": null,
"e": 26889,
"s": 26881,
"text": "Output:"
},
{
"code": null,
"e": 27026,
"s": 26889,
"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": 27036,
"s": 27026,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27040,
"s": 27036,
"text": "CSS"
},
{
"code": null,
"e": 27045,
"s": 27040,
"text": "HTML"
},
{
"code": null,
"e": 27064,
"s": 27045,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27081,
"s": 27064,
"text": "Web Technologies"
},
{
"code": null,
"e": 27108,
"s": 27081,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27113,
"s": 27108,
"text": "HTML"
},
{
"code": null,
"e": 27211,
"s": 27113,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27220,
"s": 27211,
"text": "Comments"
},
{
"code": null,
"e": 27233,
"s": 27220,
"text": "Old Comments"
},
{
"code": null,
"e": 27295,
"s": 27233,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27345,
"s": 27295,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27403,
"s": 27345,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27451,
"s": 27403,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27488,
"s": 27451,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27550,
"s": 27488,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27600,
"s": 27550,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27660,
"s": 27600,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27708,
"s": 27660,
"text": "How to update Node.js and NPM to next version ?"
}
] |
C library function - fwrite() | The C library function size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) writes data from the array pointed to, by ptr to the given stream.
Following is the declaration for fwrite() function.
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr − This is the pointer to the array of elements to be written.
ptr − This is the pointer to the array of elements to be written.
size − This is the size in bytes of each element to be written.
size − This is the size in bytes of each element to be written.
nmemb − This is the number of elements, each one with a size of size bytes.
nmemb − This is the number of elements, each one with a size of size bytes.
stream − This is the pointer to a FILE object that specifies an output stream.
stream − This is the pointer to a FILE object that specifies an output stream.
This function returns the total number of elements successfully returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, it will show an error.
The following example shows the usage of fwrite() function.
#include<stdio.h>
int main () {
FILE *fp;
char str[] = "This is tutorialspoint.com";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt which will have following content −
This is tutorialspoint.com
Now let's see the content of the above file using the following program −
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Let us compile and run the above program to produce the following result −
This is tutorialspoint.com
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": 2169,
"s": 2007,
"text": "The C library function size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) writes data from the array pointed to, by ptr to the given stream."
},
{
"code": null,
"e": 2221,
"s": 2169,
"text": "Following is the declaration for fwrite() function."
},
{
"code": null,
"e": 2293,
"s": 2221,
"text": "size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)"
},
{
"code": null,
"e": 2359,
"s": 2293,
"text": "ptr − This is the pointer to the array of elements to be written."
},
{
"code": null,
"e": 2425,
"s": 2359,
"text": "ptr − This is the pointer to the array of elements to be written."
},
{
"code": null,
"e": 2489,
"s": 2425,
"text": "size − This is the size in bytes of each element to be written."
},
{
"code": null,
"e": 2553,
"s": 2489,
"text": "size − This is the size in bytes of each element to be written."
},
{
"code": null,
"e": 2629,
"s": 2553,
"text": "nmemb − This is the number of elements, each one with a size of size bytes."
},
{
"code": null,
"e": 2705,
"s": 2629,
"text": "nmemb − This is the number of elements, each one with a size of size bytes."
},
{
"code": null,
"e": 2784,
"s": 2705,
"text": "stream − This is the pointer to a FILE object that specifies an output stream."
},
{
"code": null,
"e": 2863,
"s": 2784,
"text": "stream − This is the pointer to a FILE object that specifies an output stream."
},
{
"code": null,
"e": 3060,
"s": 2863,
"text": "This function returns the total number of elements successfully returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, it will show an error."
},
{
"code": null,
"e": 3120,
"s": 3060,
"text": "The following example shows the usage of fwrite() function."
},
{
"code": null,
"e": 3323,
"s": 3120,
"text": "#include<stdio.h>\n\nint main () {\n FILE *fp;\n char str[] = \"This is tutorialspoint.com\";\n\n fp = fopen( \"file.txt\" , \"w\" );\n fwrite(str , 1 , sizeof(str) , fp );\n\n fclose(fp);\n \n return(0);\n}"
},
{
"code": null,
"e": 3433,
"s": 3323,
"text": "Let us compile and run the above program that will create a file file.txt which will have following content −"
},
{
"code": null,
"e": 3461,
"s": 3433,
"text": "This is tutorialspoint.com\n"
},
{
"code": null,
"e": 3535,
"s": 3461,
"text": "Now let's see the content of the above file using the following program −"
},
{
"code": null,
"e": 3766,
"s": 3535,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}"
},
{
"code": null,
"e": 3841,
"s": 3766,
"text": "Let us compile and run the above program to produce the following result −"
},
{
"code": null,
"e": 3869,
"s": 3841,
"text": "This is tutorialspoint.com\n"
},
{
"code": null,
"e": 3902,
"s": 3869,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3917,
"s": 3902,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3952,
"s": 3917,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3967,
"s": 3952,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4002,
"s": 3967,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4016,
"s": 4002,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4049,
"s": 4016,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4067,
"s": 4049,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 4102,
"s": 4067,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4121,
"s": 4102,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 4154,
"s": 4121,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4166,
"s": 4154,
"text": " Amit Diwan"
},
{
"code": null,
"e": 4173,
"s": 4166,
"text": " Print"
},
{
"code": null,
"e": 4184,
"s": 4173,
"text": " Add Notes"
}
] |
Aptean Interview Experience (On-Campus 2020) - GeeksforGeeks | 08 Oct, 2020
Aptean visited my campus for two positions, one was a position of Software Developer, and the other was as a Software Developer Intern. They conducted four rounds in total, and they are as listed below.
Round 1: An online Criteria cognitive aptitude test with 40 Questions and given time of 20 minutes followed by a Personality Assessment test which was untimed. The test was conducted on HireBridge.
Round 2: Students who cleared round 1 were allowed for Round 2. Round 2 was a Coding round conducted on the HackerEarth platform. It consisted of 20 questions out of which 18 questions were based on the concepts of DBMS, CN, and Data structure & algorithm. The remaining 2 questions were based on coding.
Question 1: The stock’s problem. N transactions are made in a trading market. The minimum value of the profit earned in a single transaction is X and the maximum value of the profit earned in a single transaction is Y. You must find the number of different possible profits that can be made in N transactions.
Input format: A single line containing 3 space-separated integers N,X,Y respectively.
Output format: Print the answer to the problem in a single line.
Constraints:
Input: 3 13 15
Output : 3
Explanation:
There is 3 transaction with the minimum as 13 and maximum as 15.
All the possibilities for profits made on those 3 transactions are as follows.
(13,13,15), (13,14,15), (13,15,15)
So, we have three possible values for the total profit made: 41, 42, 43.
Python code if you ever encounter the above question.
Question 2: Optimum Jumps. You are given an array A of N integers. You have to find the minimum cost that is required to cross the array by jumping from one element to another. You need to start from the first element of the array and you can jump in both directions, but the length of the forwarding jump must be two andlength of the backward jump must be one.
The cost of forwarding and backward jump is the value of the element from which you are jumping, that is, the cost of jumping from ith Index to (i+2)th and the cost of jumping from ith Index to (i-1)th Index is the value of ith Element of the array A.
If you are at the last element of the array then you can jump out of the array and cost of that jump will be the value of the last element of array A.
Input format:
First line: N(size of the array)
Second line: N space seperated integers of the array.
Output format:
Print the cost in a single line.
Constraints:
1<=N<=105
1 <= A[i] <= 109
Input: 5
1 2 3 4 100
Output: 10
Explanation:
The cost of the forward jump from 1st Element to 3rd Element is 1.
The cost of the backward jump from 3rd Element to 2nd Element is 3.
The cost of the forward jump from 2nd Element to 4th Element is 2.
The cost of the forward jump from 4th Element to out of the array is 4.
Total cost = 1 + 3 + 2 + 4 = 10
Use https://codeforces.com/blog/entry/81142 link as a reference if you are stuck anywhere.
Round 3: This round was a Techno-Managerial round. In this, I was invited for an interview over Skype. The interviewer started with a short introduction about himself, and he made me comfortable by having a small talk with me and then and then he went ahead with some technical questions. He asked me to choose a language and I picked Python but he was expecting me to choose C++ and java. So, I told him I am comfortable with Java as well. He continued with some questions related to Java and OOP concepts. Here are some questions that I remember
Key differences between Java and Python?Explain JDK, JRE, and JVM?What are constructors in Java?Why pointers are not used in Java?What is the JIT compiler in Java?What is Object-Oriented Programming?Difference between String, StringBuilder, and StringBuffer.What is Polymorphism?What are runtime and compile-time polymorphism? Explain with an example.What are the different types of inheritance in Java?Why multiple inheritance is not supported in Java?What is method overloading and method overriding?What are association, aggregation, and composition?What does String... stand for in Java?What are dangling pointers?What are lvalues and rvalues?What is a static variable?What is call by value and call by reference?
Key differences between Java and Python?
Explain JDK, JRE, and JVM?
What are constructors in Java?
Why pointers are not used in Java?
What is the JIT compiler in Java?
What is Object-Oriented Programming?
Difference between String, StringBuilder, and StringBuffer.
What is Polymorphism?
What are runtime and compile-time polymorphism? Explain with an example.
What are the different types of inheritance in Java?
Why multiple inheritance is not supported in Java?
What is method overloading and method overriding?
What are association, aggregation, and composition?
What does String... stand for in Java?
What are dangling pointers?
What are lvalues and rvalues?
What is a static variable?
What is call by value and call by reference?
He asked me to share my screen and write a SQL query. Find the 2nd largest salary from the employee table.
He asked me to write an example code implementing Polymorphism and Inheritance using both Java and Python. While I was writing the code he asked me some questions related to my resume and the projects mentioned on my resume. After this, he started asking me questions based on some real-life and office related scenarios and wanted to know how i will be reacting in those situations. E.g. He asked if I am dealing with two customers having equal priority and both of them gives me a task to complete within a very small time frame. Which one I would prefer doing and why provided only one task can be done in the given time frame, and then he asked a few more questions related to this scenario. He gave me some more similar scenarios and went ahead with the questions.
He also asked me questions related to the Organisation I was interviewing for. Like what does the company do, Where are headquaters of the company, Who is the CEO, In which area of Bengaluru is the office of the company located?
He concluded by asking if I had any questions for him.
Round 4: It was a telephonic interview conducted by HR. Firstly, she asked me to introduce myself, and then she asked me about my hobbies and family background. Then she asked if I am available and interested in the offered position.
I was fortunate enough that I made through all the rounds and offered the position of a Software Developer at Aptean.
Tips: Have a decent CGPA above 8 and a good CV. Don’t fake your resume and don’t lie in your interviews. Just go through all your projects and activities mentioned on your resume right before the interview. Practice on GeeksforGeeks, HackerRank, interviewBit for coding questions, and revise the basic probability and aptitude concepts beforehand. The company mainly focuses on the Data structure and Algorithms so brush up all the topics. Just be confident and keep a smile on your face.
Aptean
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Infosys Interview Experience for DSE 2022
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience (Off-Campus) 2022
Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ
Amazon Interview Experience for SDE-1 | [
{
"code": null,
"e": 25516,
"s": 25488,
"text": "\n08 Oct, 2020"
},
{
"code": null,
"e": 25719,
"s": 25516,
"text": "Aptean visited my campus for two positions, one was a position of Software Developer, and the other was as a Software Developer Intern. They conducted four rounds in total, and they are as listed below."
},
{
"code": null,
"e": 25918,
"s": 25719,
"text": "Round 1: An online Criteria cognitive aptitude test with 40 Questions and given time of 20 minutes followed by a Personality Assessment test which was untimed. The test was conducted on HireBridge. "
},
{
"code": null,
"e": 26224,
"s": 25918,
"text": "Round 2: Students who cleared round 1 were allowed for Round 2. Round 2 was a Coding round conducted on the HackerEarth platform. It consisted of 20 questions out of which 18 questions were based on the concepts of DBMS, CN, and Data structure & algorithm. The remaining 2 questions were based on coding. "
},
{
"code": null,
"e": 26534,
"s": 26224,
"text": "Question 1: The stock’s problem. N transactions are made in a trading market. The minimum value of the profit earned in a single transaction is X and the maximum value of the profit earned in a single transaction is Y. You must find the number of different possible profits that can be made in N transactions."
},
{
"code": null,
"e": 26620,
"s": 26534,
"text": "Input format: A single line containing 3 space-separated integers N,X,Y respectively."
},
{
"code": null,
"e": 26685,
"s": 26620,
"text": "Output format: Print the answer to the problem in a single line."
},
{
"code": null,
"e": 26698,
"s": 26685,
"text": "Constraints:"
},
{
"code": null,
"e": 26725,
"s": 26698,
"text": "Input: 3 13 15\nOutput : 3\n"
},
{
"code": null,
"e": 26738,
"s": 26725,
"text": "Explanation:"
},
{
"code": null,
"e": 26803,
"s": 26738,
"text": "There is 3 transaction with the minimum as 13 and maximum as 15."
},
{
"code": null,
"e": 26882,
"s": 26803,
"text": "All the possibilities for profits made on those 3 transactions are as follows."
},
{
"code": null,
"e": 26917,
"s": 26882,
"text": "(13,13,15), (13,14,15), (13,15,15)"
},
{
"code": null,
"e": 26990,
"s": 26917,
"text": "So, we have three possible values for the total profit made: 41, 42, 43."
},
{
"code": null,
"e": 27044,
"s": 26990,
"text": "Python code if you ever encounter the above question."
},
{
"code": null,
"e": 27406,
"s": 27044,
"text": "Question 2: Optimum Jumps. You are given an array A of N integers. You have to find the minimum cost that is required to cross the array by jumping from one element to another. You need to start from the first element of the array and you can jump in both directions, but the length of the forwarding jump must be two andlength of the backward jump must be one."
},
{
"code": null,
"e": 27658,
"s": 27406,
"text": "The cost of forwarding and backward jump is the value of the element from which you are jumping, that is, the cost of jumping from ith Index to (i+2)th and the cost of jumping from ith Index to (i-1)th Index is the value of ith Element of the array A."
},
{
"code": null,
"e": 27810,
"s": 27658,
"text": "If you are at the last element of the array then you can jump out of the array and cost of that jump will be the value of the last element of array A. "
},
{
"code": null,
"e": 27824,
"s": 27810,
"text": "Input format:"
},
{
"code": null,
"e": 27857,
"s": 27824,
"text": "First line: N(size of the array)"
},
{
"code": null,
"e": 27911,
"s": 27857,
"text": "Second line: N space seperated integers of the array."
},
{
"code": null,
"e": 27926,
"s": 27911,
"text": "Output format:"
},
{
"code": null,
"e": 27959,
"s": 27926,
"text": "Print the cost in a single line."
},
{
"code": null,
"e": 27972,
"s": 27959,
"text": "Constraints:"
},
{
"code": null,
"e": 27983,
"s": 27972,
"text": "1<=N<=105 "
},
{
"code": null,
"e": 28000,
"s": 27983,
"text": "1 <= A[i] <= 109"
},
{
"code": null,
"e": 28040,
"s": 28000,
"text": "Input: 5\n 1 2 3 4 100\nOutput: 10\n"
},
{
"code": null,
"e": 28053,
"s": 28040,
"text": "Explanation:"
},
{
"code": null,
"e": 28120,
"s": 28053,
"text": "The cost of the forward jump from 1st Element to 3rd Element is 1."
},
{
"code": null,
"e": 28188,
"s": 28120,
"text": "The cost of the backward jump from 3rd Element to 2nd Element is 3."
},
{
"code": null,
"e": 28255,
"s": 28188,
"text": "The cost of the forward jump from 2nd Element to 4th Element is 2."
},
{
"code": null,
"e": 28327,
"s": 28255,
"text": "The cost of the forward jump from 4th Element to out of the array is 4."
},
{
"code": null,
"e": 28359,
"s": 28327,
"text": "Total cost = 1 + 3 + 2 + 4 = 10"
},
{
"code": null,
"e": 28450,
"s": 28359,
"text": "Use https://codeforces.com/blog/entry/81142 link as a reference if you are stuck anywhere."
},
{
"code": null,
"e": 28998,
"s": 28450,
"text": "Round 3: This round was a Techno-Managerial round. In this, I was invited for an interview over Skype. The interviewer started with a short introduction about himself, and he made me comfortable by having a small talk with me and then and then he went ahead with some technical questions. He asked me to choose a language and I picked Python but he was expecting me to choose C++ and java. So, I told him I am comfortable with Java as well. He continued with some questions related to Java and OOP concepts. Here are some questions that I remember"
},
{
"code": null,
"e": 29716,
"s": 28998,
"text": "Key differences between Java and Python?Explain JDK, JRE, and JVM?What are constructors in Java?Why pointers are not used in Java?What is the JIT compiler in Java?What is Object-Oriented Programming?Difference between String, StringBuilder, and StringBuffer.What is Polymorphism?What are runtime and compile-time polymorphism? Explain with an example.What are the different types of inheritance in Java?Why multiple inheritance is not supported in Java?What is method overloading and method overriding?What are association, aggregation, and composition?What does String... stand for in Java?What are dangling pointers?What are lvalues and rvalues?What is a static variable?What is call by value and call by reference?"
},
{
"code": null,
"e": 29757,
"s": 29716,
"text": "Key differences between Java and Python?"
},
{
"code": null,
"e": 29784,
"s": 29757,
"text": "Explain JDK, JRE, and JVM?"
},
{
"code": null,
"e": 29815,
"s": 29784,
"text": "What are constructors in Java?"
},
{
"code": null,
"e": 29850,
"s": 29815,
"text": "Why pointers are not used in Java?"
},
{
"code": null,
"e": 29884,
"s": 29850,
"text": "What is the JIT compiler in Java?"
},
{
"code": null,
"e": 29921,
"s": 29884,
"text": "What is Object-Oriented Programming?"
},
{
"code": null,
"e": 29981,
"s": 29921,
"text": "Difference between String, StringBuilder, and StringBuffer."
},
{
"code": null,
"e": 30003,
"s": 29981,
"text": "What is Polymorphism?"
},
{
"code": null,
"e": 30076,
"s": 30003,
"text": "What are runtime and compile-time polymorphism? Explain with an example."
},
{
"code": null,
"e": 30129,
"s": 30076,
"text": "What are the different types of inheritance in Java?"
},
{
"code": null,
"e": 30180,
"s": 30129,
"text": "Why multiple inheritance is not supported in Java?"
},
{
"code": null,
"e": 30230,
"s": 30180,
"text": "What is method overloading and method overriding?"
},
{
"code": null,
"e": 30282,
"s": 30230,
"text": "What are association, aggregation, and composition?"
},
{
"code": null,
"e": 30321,
"s": 30282,
"text": "What does String... stand for in Java?"
},
{
"code": null,
"e": 30349,
"s": 30321,
"text": "What are dangling pointers?"
},
{
"code": null,
"e": 30379,
"s": 30349,
"text": "What are lvalues and rvalues?"
},
{
"code": null,
"e": 30406,
"s": 30379,
"text": "What is a static variable?"
},
{
"code": null,
"e": 30451,
"s": 30406,
"text": "What is call by value and call by reference?"
},
{
"code": null,
"e": 30559,
"s": 30451,
"text": "He asked me to share my screen and write a SQL query. Find the 2nd largest salary from the employee table."
},
{
"code": null,
"e": 31330,
"s": 30559,
"text": "He asked me to write an example code implementing Polymorphism and Inheritance using both Java and Python. While I was writing the code he asked me some questions related to my resume and the projects mentioned on my resume. After this, he started asking me questions based on some real-life and office related scenarios and wanted to know how i will be reacting in those situations. E.g. He asked if I am dealing with two customers having equal priority and both of them gives me a task to complete within a very small time frame. Which one I would prefer doing and why provided only one task can be done in the given time frame, and then he asked a few more questions related to this scenario. He gave me some more similar scenarios and went ahead with the questions."
},
{
"code": null,
"e": 31559,
"s": 31330,
"text": "He also asked me questions related to the Organisation I was interviewing for. Like what does the company do, Where are headquaters of the company, Who is the CEO, In which area of Bengaluru is the office of the company located?"
},
{
"code": null,
"e": 31614,
"s": 31559,
"text": "He concluded by asking if I had any questions for him."
},
{
"code": null,
"e": 31848,
"s": 31614,
"text": "Round 4: It was a telephonic interview conducted by HR. Firstly, she asked me to introduce myself, and then she asked me about my hobbies and family background. Then she asked if I am available and interested in the offered position."
},
{
"code": null,
"e": 31966,
"s": 31848,
"text": "I was fortunate enough that I made through all the rounds and offered the position of a Software Developer at Aptean."
},
{
"code": null,
"e": 32457,
"s": 31966,
"text": "Tips: Have a decent CGPA above 8 and a good CV. Don’t fake your resume and don’t lie in your interviews. Just go through all your projects and activities mentioned on your resume right before the interview. Practice on GeeksforGeeks, HackerRank, interviewBit for coding questions, and revise the basic probability and aptitude concepts beforehand. The company mainly focuses on the Data structure and Algorithms so brush up all the topics. Just be confident and keep a smile on your face. "
},
{
"code": null,
"e": 32464,
"s": 32457,
"text": "Aptean"
},
{
"code": null,
"e": 32474,
"s": 32464,
"text": "Marketing"
},
{
"code": null,
"e": 32484,
"s": 32474,
"text": "On-Campus"
},
{
"code": null,
"e": 32506,
"s": 32484,
"text": "Interview Experiences"
},
{
"code": null,
"e": 32604,
"s": 32506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32655,
"s": 32604,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 32697,
"s": 32655,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 32725,
"s": 32697,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 32797,
"s": 32725,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 32839,
"s": 32797,
"text": "Infosys Interview Experience for DSE 2022"
},
{
"code": null,
"e": 32877,
"s": 32839,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 32927,
"s": 32877,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 32973,
"s": 32927,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 33049,
"s": 32973,
"text": "Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ"
}
] |
Subsets and Splits