title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to setup a Web server like Tomcat to test JSP pages?
Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine − Download the latest version of Tomcat from https://tomcat.apache.org/. Download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on the Windows machine − %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. Upon execution, you will receive the following output − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/. Tomcat can be stopped by executing the following commands on the Windows machine − %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
[ { "code": null, "e": 1336, "s": 1062, "text": "Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine −" }, { "code": null, "e": 1407, "s": 1336, "text": "Download the latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 1478, "s": 1407, "text": "Download the latest version of Tomcat from https://tomcat.apache.org/." }, { "code": null, "e": 1751, "s": 1478, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 2024, "s": 1751, "text": "Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations." }, { "code": null, "e": 2107, "s": 2024, "text": "Tomcat can be started by executing the following commands on the Windows machine −" }, { "code": null, "e": 2184, "s": 2107, "text": "%CATALINA_HOME%\\bin\\startup.bat\n\nor\n\nC:\\apache-tomcat-5.5.29\\bin\\startup.bat" }, { "code": null, "e": 2287, "s": 2184, "text": "Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 2369, "s": 2287, "text": "$CATALINA_HOME/bin/startup.sh\n\nor\n\n/usr/local/apache-tomcat-5.5.29/bin/startup.sh" }, { "code": null, "e": 2501, "s": 2369, "text": "After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/." }, { "code": null, "e": 2557, "s": 2501, "text": "Upon execution, you will receive the following output −" }, { "code": null, "e": 2727, "s": 2557, "text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/." }, { "code": null, "e": 2810, "s": 2727, "text": "Tomcat can be stopped by executing the following commands on the Windows machine −" }, { "code": null, "e": 2880, "s": 2810, "text": "%CATALINA_HOME%\\bin\\shutdown\nor\n\nC:\\apache-tomcat-5.5.29\\bin\\shutdown" }, { "code": null, "e": 2979, "s": 2880, "text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 3063, "s": 2979, "text": "$CATALINA_HOME/bin/shutdown.sh\n\nor\n\n/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh" } ]
How to enable Bootstrap tooltip on disabled button ? - GeeksforGeeks
19 Jan, 2022 Button or link elements with disabled class and attribute is not interactive. It means users cannot focus, hover, or click them to trigger a tooltip (or popover) or any functions. Use the following approaches to enable a tooltip on disabled-buttons. Using jQuery Using HTML Using CSS Initializing tooltip: By default tooltips is initialized by selecting the specified element and call the tooltip() method using jQuery. Then add a title attribute to that specified element which contains what text to be displayed inside tooltip. To position the tooltip data-placement attribute must be added to that specified element with top/bottom/right/left as its values. // Initializing the tooltip $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); Note: By default data-toggle=”tooltip” will enable tooltip of disabled button. Approach: Initialize tooltips in bootstrap disabled buttons with the specified element and call the tooltip() method. To trigger tooltip on disabled button by wraping them in <span> span tag and <div> div tag and then adding ‘data-toggle’,’data-placement’ and ‘title’ attributes to it along with its values respectively. Example: This example illustrates triggering tooltip by wraping disabled button inside div and span tag. <!DOCTYPE html><html lang="en"> <head> <title>Disabled Button Tooltip</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .disabled { pointer-events: all !important; } </style></head> <body style="text-align:center;"> <div class="container pt-5"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Disabled buttons wrapped inside an elements </h4> <div class="d-inline-block" tabindex="0" data-toggle="tooltip" data-placement="bottom" title="This button is disabled"> <button type="button" class="btn btn-warning" style="pointer-events: none;" disabled> Button wrapped in Div tag </button> </div> <span class="d-inline-block" tabindex="0" data-toggle="tooltip" data-placement="right" title="This button is disabled"> <button class="btn btn-outline-warning" style="pointer-events: none;"type="button" disabled> Button wrapped in span tag </button> </span> </div> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> </body> </html> Output: Example 2: This example uses HTML to display tooltip information about the content on any disabled button. For this, just disable the button and add the title attribute on it. <!DOCTYPE html><html> <head> <title> Tooltip on disabled button </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Tooltip on Disabled button</h3> <div> <button disabled="disabled" title="My Tooltip"> Disabled Button </button> <button title="Here it's common">Not Disabaled</button> </div> </center></body> </html> Output: Example 3: Trigger tooltip on disabled bootstrap buttons using CSS. <!DOCTYPE html><html><title>Disabled Button Tooltip</title> <style> .tooltip1 { position: relative !important; display: inline-block !important; width: 175px !important; font-size: 14px; } .tooltip1 .tooltiptext { visibility: hidden; width: 120px !important; background-color: black !important; color: #fff !important; text-align: center !important; border-radius: 6px !important; padding: 5px 0 !important; position: absolute !important; z-index: 1 !important; top: -5px !important; left: 110% !important; } .tooltip1 .tooltiptext::after { content: ""; position: absolute !important; top: 50% !important; right: 100% !important; margin-top: -5px !important; border-width: 5px !important; border-style: solid !important; border-color: transparent black transparent transparent !important; } .tooltip1:hover .tooltiptext { visibility: visible !important; }</style> <body style="text-align:center;"> <div class="container pt-5"> <h1 style="color:green;"> GeeksforGeeks </h1> <h4> Trigger tooltip on disabled bootstrap buttons using CSS </h4> <button class="btn btn-outline-info tooltip1 " disabled> Hover over me <span class="tooltip1 tooltiptext"> disabled button </span> </button> </div> </body> </html> Output: simmytarika5 Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? 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 execute PHP code using command line ? How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) What is web socket and how it is different from the HTTP?
[ { "code": null, "e": 26279, "s": 26251, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26529, "s": 26279, "text": "Button or link elements with disabled class and attribute is not interactive. It means users cannot focus, hover, or click them to trigger a tooltip (or popover) or any functions. Use the following approaches to enable a tooltip on disabled-buttons." }, { "code": null, "e": 26542, "s": 26529, "text": "Using jQuery" }, { "code": null, "e": 26553, "s": 26542, "text": "Using HTML" }, { "code": null, "e": 26563, "s": 26553, "text": "Using CSS" }, { "code": null, "e": 26585, "s": 26563, "text": "Initializing tooltip:" }, { "code": null, "e": 26809, "s": 26585, "text": "By default tooltips is initialized by selecting the specified element and call the tooltip() method using jQuery. Then add a title attribute to that specified element which contains what text to be displayed inside tooltip." }, { "code": null, "e": 26940, "s": 26809, "text": "To position the tooltip data-placement attribute must be added to that specified element with top/bottom/right/left as its values." }, { "code": null, "e": 27054, "s": 26940, "text": "// Initializing the tooltip\n$(document).ready(function() { \n $('[data-toggle=\"tooltip\"]').tooltip(); \n}); \n" }, { "code": null, "e": 27133, "s": 27054, "text": "Note: By default data-toggle=”tooltip” will enable tooltip of disabled button." }, { "code": null, "e": 27143, "s": 27133, "text": "Approach:" }, { "code": null, "e": 27251, "s": 27143, "text": "Initialize tooltips in bootstrap disabled buttons with the specified element and call the tooltip() method." }, { "code": null, "e": 27454, "s": 27251, "text": "To trigger tooltip on disabled button by wraping them in <span> span tag and <div> div tag and then adding ‘data-toggle’,’data-placement’ and ‘title’ attributes to it along with its values respectively." }, { "code": null, "e": 27559, "s": 27454, "text": "Example: This example illustrates triggering tooltip by wraping disabled button inside div and span tag." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Disabled Button Tooltip</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .disabled { pointer-events: all !important; } </style></head> <body style=\"text-align:center;\"> <div class=\"container pt-5\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Disabled buttons wrapped inside an elements </h4> <div class=\"d-inline-block\" tabindex=\"0\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"This button is disabled\"> <button type=\"button\" class=\"btn btn-warning\" style=\"pointer-events: none;\" disabled> Button wrapped in Div tag </button> </div> <span class=\"d-inline-block\" tabindex=\"0\" data-toggle=\"tooltip\" data-placement=\"right\" title=\"This button is disabled\"> <button class=\"btn btn-outline-warning\" style=\"pointer-events: none;\"type=\"button\" disabled> Button wrapped in span tag </button> </span> </div> <script> $(document).ready(function() { $('[data-toggle=\"tooltip\"]').tooltip(); }); </script> </body> </html> ", "e": 29341, "s": 27559, "text": null }, { "code": null, "e": 29349, "s": 29341, "text": "Output:" }, { "code": null, "e": 29525, "s": 29349, "text": "Example 2: This example uses HTML to display tooltip information about the content on any disabled button. For this, just disable the button and add the title attribute on it." }, { "code": "<!DOCTYPE html><html> <head> <title> Tooltip on disabled button </title> <style> h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Tooltip on Disabled button</h3> <div> <button disabled=\"disabled\" title=\"My Tooltip\"> Disabled Button </button> <button title=\"Here it's common\">Not Disabaled</button> </div> </center></body> </html> ", "e": 30015, "s": 29525, "text": null }, { "code": null, "e": 30023, "s": 30015, "text": "Output:" }, { "code": null, "e": 30091, "s": 30023, "text": "Example 3: Trigger tooltip on disabled bootstrap buttons using CSS." }, { "code": "<!DOCTYPE html><html><title>Disabled Button Tooltip</title> <style> .tooltip1 { position: relative !important; display: inline-block !important; width: 175px !important; font-size: 14px; } .tooltip1 .tooltiptext { visibility: hidden; width: 120px !important; background-color: black !important; color: #fff !important; text-align: center !important; border-radius: 6px !important; padding: 5px 0 !important; position: absolute !important; z-index: 1 !important; top: -5px !important; left: 110% !important; } .tooltip1 .tooltiptext::after { content: \"\"; position: absolute !important; top: 50% !important; right: 100% !important; margin-top: -5px !important; border-width: 5px !important; border-style: solid !important; border-color: transparent black transparent transparent !important; } .tooltip1:hover .tooltiptext { visibility: visible !important; }</style> <body style=\"text-align:center;\"> <div class=\"container pt-5\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h4> Trigger tooltip on disabled bootstrap buttons using CSS </h4> <button class=\"btn btn-outline-info tooltip1 \" disabled> Hover over me <span class=\"tooltip1 tooltiptext\"> disabled button </span> </button> </div> </body> </html>", "e": 31639, "s": 30091, "text": null }, { "code": null, "e": 31647, "s": 31639, "text": "Output:" }, { "code": null, "e": 31660, "s": 31647, "text": "simmytarika5" }, { "code": null, "e": 31667, "s": 31660, "text": "Picked" }, { "code": null, "e": 31684, "s": 31667, "text": "Web Technologies" }, { "code": null, "e": 31711, "s": 31684, "text": "Web technologies Questions" }, { "code": null, "e": 31809, "s": 31711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31849, "s": 31809, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31894, "s": 31849, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31937, "s": 31894, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31998, "s": 31937, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32070, "s": 31998, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32110, "s": 32070, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32155, "s": 32110, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 32205, "s": 32155, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 32242, "s": 32205, "text": "Types of CSS (Cascading Style Sheet)" } ]
How to create a list of object in Python class - GeeksforGeeks
29 Dec, 2020 We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let’s try to understand it better with the help of examples. Example #1: # Python3 code here creating classclass geeks: def __init__(self, name, roll): self.name = name self.roll = roll # creating list list = [] # appending instances to list list.append( geeks('Akash', 2) )list.append( geeks('Deependra', 40) )list.append( geeks('Reaper', 44) ) for obj in list: print( obj.name, obj.roll, sep =' ' ) # We can also access instances attributes# as list[0].name, list[0].roll and so on. Akash 2 Deependra 40 Reaper 44 Example #2: # Python3 code here for creating classclass geeks: def __init__(self, x, y): self.x = x self.y = y def Sum(self): print( self.x + self.y ) # creating list list = [] # appending instances to list list.append( geeks(2, 3) )list.append( geeks(12, 13) )list.append( geeks(22, 33) ) for obj in list: # calling method obj.Sum() # We can also access instances method# as list[0].Sum() , list[1].Sum() and so on. 5 25 55 bagamramyasri Python Oops-programs Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 24550, "s": 24522, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24887, "s": 24550, "text": "We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let’s try to understand it better with the help of examples." }, { "code": null, "e": 24899, "s": 24887, "text": "Example #1:" }, { "code": "# Python3 code here creating classclass geeks: def __init__(self, name, roll): self.name = name self.roll = roll # creating list list = [] # appending instances to list list.append( geeks('Akash', 2) )list.append( geeks('Deependra', 40) )list.append( geeks('Reaper', 44) ) for obj in list: print( obj.name, obj.roll, sep =' ' ) # We can also access instances attributes# as list[0].name, list[0].roll and so on.", "e": 25346, "s": 24899, "text": null }, { "code": null, "e": 25378, "s": 25346, "text": "Akash 2\nDeependra 40\nReaper 44\n" }, { "code": null, "e": 25392, "s": 25380, "text": "Example #2:" }, { "code": "# Python3 code here for creating classclass geeks: def __init__(self, x, y): self.x = x self.y = y def Sum(self): print( self.x + self.y ) # creating list list = [] # appending instances to list list.append( geeks(2, 3) )list.append( geeks(12, 13) )list.append( geeks(22, 33) ) for obj in list: # calling method obj.Sum() # We can also access instances method# as list[0].Sum() , list[1].Sum() and so on.", "e": 25856, "s": 25392, "text": null }, { "code": null, "e": 25865, "s": 25856, "text": "5\n25\n55\n" }, { "code": null, "e": 25879, "s": 25865, "text": "bagamramyasri" }, { "code": null, "e": 25900, "s": 25879, "text": "Python Oops-programs" }, { "code": null, "e": 25911, "s": 25900, "text": "Python-OOP" }, { "code": null, "e": 25918, "s": 25911, "text": "Python" }, { "code": null, "e": 26016, "s": 25918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26034, "s": 26016, "text": "Python Dictionary" }, { "code": null, "e": 26069, "s": 26034, "text": "Read a file line by line in Python" }, { "code": null, "e": 26101, "s": 26069, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26143, "s": 26101, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26169, "s": 26143, "text": "Python String | replace()" }, { "code": null, "e": 26213, "s": 26169, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26250, "s": 26213, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26279, "s": 26250, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26321, "s": 26279, "text": "Check if element exists in list in Python" } ]
Find one extra character in a string - GeeksforGeeks
21 Jul, 2021 Given two strings which are of lengths n and n+1. The second string contains all the character of the first string, but there is one extra character. Your task to find the extra character in the second string.Examples : Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B contain all the element there is a one extra character which is e Input : string strA = "kxml"; string strB = "klxml"; Output : l string B contain all the element there is a one extra character which is l Method 1(Brute Force):- Check with two for loop. Time Complexity:- O(n^2) Space Complexity:- O(1). Method 2(Hash Map):- Create an empty hash table and insert all character of second string. Now remove all characters of first string. Remaining character is the extra character.Time Complexity:- O(n) Auxiliary Space:- O(n). C++ Java Python3 C# Javascript // CPP program to find extra character in one// string#include <bits/stdc++.h>using namespace std; char findExtraCharcter(string strA, string strB){ // store string values in map unordered_map<char, int> m1; // store second string in map with frequency for (int i = 0; i < strB.length(); i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.length(); i++) m1[strA[i]]--; for (auto h1 = m1.begin(); h1 != m1.end(); h1++) { // if the frequency is 1 then this // character is which is added extra if (h1->second == 1) return h1->first; }} int main(){ // given string string strA = "abcd"; string strB = "cbdad"; // find Extra Character cout << findExtraCharcter(strA, strB);} // Java program to find extra character in one// stringclass GFG{ static char findExtraCharcter(char []strA, char[] strB){ // store string values in map int[] m1 = new int[256]; // store second string in map with frequency for (int i = 0; i < strB.length; i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.length; i++) m1[strA[i]]--; for (int i=0;i<m1.length;i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i]== 1) return (char) i; } return Character.MIN_VALUE;} // Driver codepublic static void main(String[] args){ // given string String strA = "abcd"; String strB = "cbdad"; // find Extra Character System.out.println(findExtraCharcter(strA.toCharArray(), strB.toCharArray())); }} // This code is contributed by 29AjayKumar # Python3 program to find extra character# in one stringdef findExtraCharacter(strA, strB): # store string values in map m1 = {} # store second string in map # with frequency for i in strB: if i in m1: m1[i] += 1 else: m1[i] = 1 # store first string in map # with frequency for i in strA: m1[i] -= 1 for h1 in m1: # if the frequency is 1 then this # character is which is added extra if m1[h1] == 1: return h1 # Driver Codeif __name__ == "__main__": # given string strA = 'abcd' strB = 'cbdad' # find Extra Character print(findExtraCharacter(strA, strB)) # This code is contributed by# sanjeev2552 // C# program to find extra character in one// stringusing System; class GFG{ static char findExtraCharcter(char []strA, char[] strB){ // store string values in map int[] m1 = new int[256]; // store second string in map with frequency for (int i = 0; i < strB.Length; i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.Length; i++) m1[strA[i]]--; for (int i = 0; i < m1.Length; i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i]== 1) return (char) i; } return char.MinValue;} // Driver codepublic static void Main(String[] args){ // given string String strA = "abcd"; String strB = "cbdad"; // find Extra Character Console.WriteLine(findExtraCharcter(strA.ToCharArray(), strB.ToCharArray())); }} // This code is contributed by Rajput-Ji <script>// JavaScript program to find extra character in one// stringfunction findExtraCharcter(strA,strB){ // store string values in map let m1 = new Array(256); for(let i = 0; i < 256; i++) m1[i] = 0; // store second string in map with frequency for (let i = 0; i < strB.length; i++) m1[strB[i].charCodeAt(0)]++; // store first string in map with frequency for (let i = 0; i < strA.length; i++) m1[strA[i].charCodeAt(0)]--; for (let i = 0; i < m1.length; i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i] == 1) return String.fromCharCode(i); } return Number.MIN_VALUE;} // given stringlet strA = "abcd";let strB = "cbdad"; // find Extra Characterdocument.write(findExtraCharcter(strA.split(""), strB.split(""))); // This code is contributed by rag2127</script> d Method 3(Bits):- traverse first and second string from starting with xor operation at the end you get the character which is extra. Time Complexity:- O(n+n+1) Space Complexity:- O(1). C++ Java Python 3 C# PHP Javascript // CPP program to find extra character in one// string#include <iostream>using namespace std; char findExtraCharcter(string strA, string strB){ // result store the result int res = 0, i; // traverse string A till end and // xor with res for (i = 0; i < strA.length(); i++) { // xor with res res ^= strA[i]; } // traverse string B till end and // xor with res for (i = 0; i < strB.length(); i++) { // xor with res res ^= strB[i]; } // print result at the end return ((char)(res));} int main(){ // given string string strA = "abcd"; string strB = "cbdad"; cout << findExtraCharcter(strA, strB); return 0;} // Java program to find extra// character in one stringimport java.io.*; class GFG { static char findExtraCharcter(String strA, String strB) { // result store the result int res = 0, i; // traverse string A till // end and xor with res for (i = 0; i < strA.length(); i++) { // xor with res res ^= strA.charAt(i); } // traverse string B till end and // xor with res for (i = 0; i < strB.length(); i++) { // xor with res res ^= strB.charAt(i); } // print result at the end return ((char)(res)); } // Driver code public static void main(String args[]) { // given string String strA = "abcd"; String strB = "cbdad"; System.out.println(findExtraCharcter(strA, strB)); }} /*This code is contributed by Nikita Tiwari.*/ # Python 3 program to find# extra character in one string def findExtraCharcter(strA, strB) : # result store the result res = 0 # traverse string A till # end and xor with res for i in range(0,len(strA)) : # xor with res res =res ^ (ord)(strA[i]) # traverse string B till # end and xor with res for i in range(0,len(strB)) : # xor with res res = res ^ (ord)(strB[i]) # print result at the end return ((chr)(res)); # given stringstrA = "abcd"strB = "cbdad"print(findExtraCharcter(strA, strB)) # This code is contributed by Nikita Tiwari. // C# program to find extra character// in one stringusing System; class GFG { static char findExtraCharcter(string strA, string strB) { // result store the result int res = 0, i; // traverse string A till end and // xor with res for (i = 0; i < strA.Length; i++) { // xor with res res ^= strA[i]; } // traverse string B till end and // xor with res for (i = 0; i < strB.Length; i++) { // xor with res res ^= strB[i]; } // print result at the end return ((char)(res)); } // Driver Code public static void Main() { // given string string strA = "abcd"; string strB = "cbdad"; Console.WriteLine( findExtraCharcter(strA, strB)); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP program to find extra character in// one string function findExtraCharcter($strA, $strB){ // result store the result $res = 0; // traverse string A till end and // xor with res for ($i = 0; $i < strlen($strA); $i++) { // xor with res $res ^= ord($strA[$i]); } // traverse string B till end and // xor with res for ($i = 0; $i < strlen($strB); $i++) { // xor with res $res ^= ord($strB[$i]); } // print result at the end return $res;} // Driver code$strA = "abcd";$strB = "cbdad";echo chr(findExtraCharcter($strA, $strB)); // This code is contributed by Manish Shaw// (manishshaw1)?> <script>// Javascript program to find extra character in// one string function findExtraCharcter(strA, strB){ // result store the result let res = 0; // traverse string A till end and // xor with res for (let i = 0; i < strA.length; i++) { // xor with res res ^= strA.charCodeAt(i); } // traverse string B till end and // xor with res for (let i = 0; i < strB.length; i++) { // xor with res res ^= strB.charCodeAt(i); } // print result at the end return res;} // Driver codelet strA = "abcd";let strB = "cbdad";document.write(String.fromCharCode(findExtraCharcter(strA, strB))); // This code is contributed by gfgking</script> d Method 4(Character Code):- Add the character codes of both the strings. Minus character codes of smaller string from larger string and convert the result integer into character.Time Complexity:- O(n) Auxiliary Space:- O(1). C++ Java Python3 C# Javascript // C++ program to find extra// character in one string#include<bits/stdc++.h>using namespace std; char findExtraCharacter(string s1, string s2){ string smallStr; string largeStr; // Determine string with extra character. if(s1.size() > s2.size()) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.size(); i++) { smallStrCodeTotal += smallStr[i]; largeStrCodeTotal += largeStr[i]; } // Add last character code of large string. largeStrCodeTotal += largeStr[i]; // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar;} // Driver codeint main(){ string s1 = "abcd"; string s2 = "cbdae"; char extraChar = findExtraCharacter(s1, s2); cout<<"Extra character: " <<(extraChar)<<endl; return 0;} // This code is contributed by Princi Singh // Java program to find extra// character in one string public class Test { private static char findExtraCharacter(String s1, String s2) { String smallStr; String largeStr; // Determine String with extra character. if(s1.length() > s2.length()) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.length(); i++) { smallStrCodeTotal += smallStr.charAt(i); largeStrCodeTotal += largeStr.charAt(i); } // Add last character code of large String. largeStrCodeTotal += largeStr.charAt(i); // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar; } public static void main(String[] args) { String s1 = "abcd"; String s2 = "cbdae"; char extraChar = findExtraCharacter(s1, s2); System.out.println("Extra character: " + extraChar); }} /*This code is contributed by Amol Bhosale.*/ # Python Program to find extra character in one stringdef findExtraCharacter(s1,s2): smallStr = "" largeStr = "" # Determine string with extra character if(len(s1) > len(s2)): smallStr = s2 largeStr = s1 else: smallStr = s1 largeStr = s2 smallStrCodeTotal = 0 largeStrCodeTotal = 0 i = 0 # Add Character codes of both the strings while(i < len(smallStr)): smallStrCodeTotal += ord(smallStr[i]) largeStrCodeTotal += ord(largeStr[i]) i += 1 # Add last character code of large string largeStrCodeTotal += ord(largeStr[i]) # Minus the character code of smaller string # from the character code of large string # The result will be the extra character code intChar = largeStrCodeTotal - smallStrCodeTotal return chr(intChar) # Driver codes1 = "abcd"s2 = "cbdae"extraChar = findExtraCharacter(s1, s2)print("Extra Character:", extraChar) # This code is contributed by simranjenny84 // C# program to find extra// character in one stringusing System; class GFG{ private static char findExtraCharacter(String s1, String s2) { String smallStr; String largeStr; // Determine String with extra character. if(s1.Length > s2.Length) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.Length; i++) { smallStrCodeTotal += smallStr[i]; largeStrCodeTotal += largeStr[i]; } // Add last character code of large String. largeStrCodeTotal += largeStr[i]; // Minus the character code of smaller string // from the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar; } public static void Main(String[] args) { String s1 = "abcd"; String s2 = "cbdae"; char extraChar = findExtraCharacter(s1, s2); Console.WriteLine("Extra character: " + extraChar); }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to find extra// character in one stringfunction findExtraCharacter(s1, s2){ let smallStr; let largeStr; // Determine String with extra character. if(s1.length > s2.length) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } let smallStrCodeTotal = 0; let largeStrCodeTotal = 0; let i = 0; // Add character codes of both the strings for(; i < smallStr.length; i++) { smallStrCodeTotal += smallStr[i].charCodeAt(0); largeStrCodeTotal += largeStr[i].charCodeAt(0); } // Add last character code of large String. largeStrCodeTotal += largeStr[i].charCodeAt(0); // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. let intChar = largeStrCodeTotal - smallStrCodeTotal; return String.fromCharCode(intChar);} let s1 = "abcd";let s2 = "cbdae"; let extraChar = findExtraCharacter(s1, s2);document.write("Extra character: " + extraChar); // This code is contributed by avanitrachhadiya2155</script> Extra character: e YouTubeGeeksforGeeks507K subscribersFind one extra character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NrvoNxLThg0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Nikita tiwari manishshaw1 ashuk1992 samyakjain677 AmolBhosale1 princi singh 29AjayKumar Rajput-Ji princiraj1992 nidhi_biet sanjeev2552 simranjenny84 gfgking rag2127 avanitrachhadiya2155 Bitwise-XOR frequency-counting Bit Magic Strings Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Bit Fields in C 1's and 2's complement of a Binary Number Divide two integers without using multiplication, division and mod operator Check whether K-th bit is set or not Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26367, "s": 26339, "text": "\n21 Jul, 2021" }, { "code": null, "e": 26589, "s": 26367, "text": "Given two strings which are of lengths n and n+1. The second string contains all the character of the first string, but there is one extra character. Your task to find the extra character in the second string.Examples : " }, { "code": null, "e": 26886, "s": 26589, "text": "Input : string strA = \"abcd\";\n string strB = \"cbdae\";\nOutput : e\nstring B contain all the element \nthere is a one extra character which is e\n\nInput : string strA = \"kxml\";\n string strB = \"klxml\";\nOutput : l\nstring B contain all the element \nthere is a one extra character which is l" }, { "code": null, "e": 27213, "s": 26888, "text": "Method 1(Brute Force):- Check with two for loop. Time Complexity:- O(n^2) Space Complexity:- O(1). Method 2(Hash Map):- Create an empty hash table and insert all character of second string. Now remove all characters of first string. Remaining character is the extra character.Time Complexity:- O(n) Auxiliary Space:- O(n). " }, { "code": null, "e": 27217, "s": 27213, "text": "C++" }, { "code": null, "e": 27222, "s": 27217, "text": "Java" }, { "code": null, "e": 27230, "s": 27222, "text": "Python3" }, { "code": null, "e": 27233, "s": 27230, "text": "C#" }, { "code": null, "e": 27244, "s": 27233, "text": "Javascript" }, { "code": "// CPP program to find extra character in one// string#include <bits/stdc++.h>using namespace std; char findExtraCharcter(string strA, string strB){ // store string values in map unordered_map<char, int> m1; // store second string in map with frequency for (int i = 0; i < strB.length(); i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.length(); i++) m1[strA[i]]--; for (auto h1 = m1.begin(); h1 != m1.end(); h1++) { // if the frequency is 1 then this // character is which is added extra if (h1->second == 1) return h1->first; }} int main(){ // given string string strA = \"abcd\"; string strB = \"cbdad\"; // find Extra Character cout << findExtraCharcter(strA, strB);}", "e": 28043, "s": 27244, "text": null }, { "code": "// Java program to find extra character in one// stringclass GFG{ static char findExtraCharcter(char []strA, char[] strB){ // store string values in map int[] m1 = new int[256]; // store second string in map with frequency for (int i = 0; i < strB.length; i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.length; i++) m1[strA[i]]--; for (int i=0;i<m1.length;i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i]== 1) return (char) i; } return Character.MIN_VALUE;} // Driver codepublic static void main(String[] args){ // given string String strA = \"abcd\"; String strB = \"cbdad\"; // find Extra Character System.out.println(findExtraCharcter(strA.toCharArray(), strB.toCharArray())); }} // This code is contributed by 29AjayKumar", "e": 28946, "s": 28043, "text": null }, { "code": "# Python3 program to find extra character# in one stringdef findExtraCharacter(strA, strB): # store string values in map m1 = {} # store second string in map # with frequency for i in strB: if i in m1: m1[i] += 1 else: m1[i] = 1 # store first string in map # with frequency for i in strA: m1[i] -= 1 for h1 in m1: # if the frequency is 1 then this # character is which is added extra if m1[h1] == 1: return h1 # Driver Codeif __name__ == \"__main__\": # given string strA = 'abcd' strB = 'cbdad' # find Extra Character print(findExtraCharacter(strA, strB)) # This code is contributed by# sanjeev2552", "e": 29668, "s": 28946, "text": null }, { "code": "// C# program to find extra character in one// stringusing System; class GFG{ static char findExtraCharcter(char []strA, char[] strB){ // store string values in map int[] m1 = new int[256]; // store second string in map with frequency for (int i = 0; i < strB.Length; i++) m1[strB[i]]++; // store first string in map with frequency for (int i = 0; i < strA.Length; i++) m1[strA[i]]--; for (int i = 0; i < m1.Length; i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i]== 1) return (char) i; } return char.MinValue;} // Driver codepublic static void Main(String[] args){ // given string String strA = \"abcd\"; String strB = \"cbdad\"; // find Extra Character Console.WriteLine(findExtraCharcter(strA.ToCharArray(), strB.ToCharArray())); }} // This code is contributed by Rajput-Ji", "e": 30623, "s": 29668, "text": null }, { "code": "<script>// JavaScript program to find extra character in one// stringfunction findExtraCharcter(strA,strB){ // store string values in map let m1 = new Array(256); for(let i = 0; i < 256; i++) m1[i] = 0; // store second string in map with frequency for (let i = 0; i < strB.length; i++) m1[strB[i].charCodeAt(0)]++; // store first string in map with frequency for (let i = 0; i < strA.length; i++) m1[strA[i].charCodeAt(0)]--; for (let i = 0; i < m1.length; i++) { // if the frequency is 1 then this // character is which is added extra if (m1[i] == 1) return String.fromCharCode(i); } return Number.MIN_VALUE;} // given stringlet strA = \"abcd\";let strB = \"cbdad\"; // find Extra Characterdocument.write(findExtraCharcter(strA.split(\"\"), strB.split(\"\"))); // This code is contributed by rag2127</script>", "e": 31524, "s": 30623, "text": null }, { "code": null, "e": 31526, "s": 31524, "text": "d" }, { "code": null, "e": 31713, "s": 31528, "text": "Method 3(Bits):- traverse first and second string from starting with xor operation at the end you get the character which is extra. Time Complexity:- O(n+n+1) Space Complexity:- O(1). " }, { "code": null, "e": 31717, "s": 31713, "text": "C++" }, { "code": null, "e": 31722, "s": 31717, "text": "Java" }, { "code": null, "e": 31731, "s": 31722, "text": "Python 3" }, { "code": null, "e": 31734, "s": 31731, "text": "C#" }, { "code": null, "e": 31738, "s": 31734, "text": "PHP" }, { "code": null, "e": 31749, "s": 31738, "text": "Javascript" }, { "code": "// CPP program to find extra character in one// string#include <iostream>using namespace std; char findExtraCharcter(string strA, string strB){ // result store the result int res = 0, i; // traverse string A till end and // xor with res for (i = 0; i < strA.length(); i++) { // xor with res res ^= strA[i]; } // traverse string B till end and // xor with res for (i = 0; i < strB.length(); i++) { // xor with res res ^= strB[i]; } // print result at the end return ((char)(res));} int main(){ // given string string strA = \"abcd\"; string strB = \"cbdad\"; cout << findExtraCharcter(strA, strB); return 0;}", "e": 32437, "s": 31749, "text": null }, { "code": "// Java program to find extra// character in one stringimport java.io.*; class GFG { static char findExtraCharcter(String strA, String strB) { // result store the result int res = 0, i; // traverse string A till // end and xor with res for (i = 0; i < strA.length(); i++) { // xor with res res ^= strA.charAt(i); } // traverse string B till end and // xor with res for (i = 0; i < strB.length(); i++) { // xor with res res ^= strB.charAt(i); } // print result at the end return ((char)(res)); } // Driver code public static void main(String args[]) { // given string String strA = \"abcd\"; String strB = \"cbdad\"; System.out.println(findExtraCharcter(strA, strB)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 33399, "s": 32437, "text": null }, { "code": "# Python 3 program to find# extra character in one string def findExtraCharcter(strA, strB) : # result store the result res = 0 # traverse string A till # end and xor with res for i in range(0,len(strA)) : # xor with res res =res ^ (ord)(strA[i]) # traverse string B till # end and xor with res for i in range(0,len(strB)) : # xor with res res = res ^ (ord)(strB[i]) # print result at the end return ((chr)(res)); # given stringstrA = \"abcd\"strB = \"cbdad\"print(findExtraCharcter(strA, strB)) # This code is contributed by Nikita Tiwari.", "e": 34036, "s": 33399, "text": null }, { "code": "// C# program to find extra character// in one stringusing System; class GFG { static char findExtraCharcter(string strA, string strB) { // result store the result int res = 0, i; // traverse string A till end and // xor with res for (i = 0; i < strA.Length; i++) { // xor with res res ^= strA[i]; } // traverse string B till end and // xor with res for (i = 0; i < strB.Length; i++) { // xor with res res ^= strB[i]; } // print result at the end return ((char)(res)); } // Driver Code public static void Main() { // given string string strA = \"abcd\"; string strB = \"cbdad\"; Console.WriteLine( findExtraCharcter(strA, strB)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 34976, "s": 34036, "text": null }, { "code": "<?php// PHP program to find extra character in// one string function findExtraCharcter($strA, $strB){ // result store the result $res = 0; // traverse string A till end and // xor with res for ($i = 0; $i < strlen($strA); $i++) { // xor with res $res ^= ord($strA[$i]); } // traverse string B till end and // xor with res for ($i = 0; $i < strlen($strB); $i++) { // xor with res $res ^= ord($strB[$i]); } // print result at the end return $res;} // Driver code$strA = \"abcd\";$strB = \"cbdad\";echo chr(findExtraCharcter($strA, $strB)); // This code is contributed by Manish Shaw// (manishshaw1)?>", "e": 35646, "s": 34976, "text": null }, { "code": "<script>// Javascript program to find extra character in// one string function findExtraCharcter(strA, strB){ // result store the result let res = 0; // traverse string A till end and // xor with res for (let i = 0; i < strA.length; i++) { // xor with res res ^= strA.charCodeAt(i); } // traverse string B till end and // xor with res for (let i = 0; i < strB.length; i++) { // xor with res res ^= strB.charCodeAt(i); } // print result at the end return res;} // Driver codelet strA = \"abcd\";let strB = \"cbdad\";document.write(String.fromCharCode(findExtraCharcter(strA, strB))); // This code is contributed by gfgking</script>", "e": 36350, "s": 35646, "text": null }, { "code": null, "e": 36352, "s": 36350, "text": "d" }, { "code": null, "e": 36580, "s": 36354, "text": "Method 4(Character Code):- Add the character codes of both the strings. Minus character codes of smaller string from larger string and convert the result integer into character.Time Complexity:- O(n) Auxiliary Space:- O(1). " }, { "code": null, "e": 36584, "s": 36580, "text": "C++" }, { "code": null, "e": 36589, "s": 36584, "text": "Java" }, { "code": null, "e": 36597, "s": 36589, "text": "Python3" }, { "code": null, "e": 36600, "s": 36597, "text": "C#" }, { "code": null, "e": 36611, "s": 36600, "text": "Javascript" }, { "code": " // C++ program to find extra// character in one string#include<bits/stdc++.h>using namespace std; char findExtraCharacter(string s1, string s2){ string smallStr; string largeStr; // Determine string with extra character. if(s1.size() > s2.size()) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.size(); i++) { smallStrCodeTotal += smallStr[i]; largeStrCodeTotal += largeStr[i]; } // Add last character code of large string. largeStrCodeTotal += largeStr[i]; // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar;} // Driver codeint main(){ string s1 = \"abcd\"; string s2 = \"cbdae\"; char extraChar = findExtraCharacter(s1, s2); cout<<\"Extra character: \" <<(extraChar)<<endl; return 0;} // This code is contributed by Princi Singh", "e": 37797, "s": 36611, "text": null }, { "code": "// Java program to find extra// character in one string public class Test { private static char findExtraCharacter(String s1, String s2) { String smallStr; String largeStr; // Determine String with extra character. if(s1.length() > s2.length()) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.length(); i++) { smallStrCodeTotal += smallStr.charAt(i); largeStrCodeTotal += largeStr.charAt(i); } // Add last character code of large String. largeStrCodeTotal += largeStr.charAt(i); // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar; } public static void main(String[] args) { String s1 = \"abcd\"; String s2 = \"cbdae\"; char extraChar = findExtraCharacter(s1, s2); System.out.println(\"Extra character: \" + extraChar); }} /*This code is contributed by Amol Bhosale.*/", "e": 39155, "s": 37797, "text": null }, { "code": "# Python Program to find extra character in one stringdef findExtraCharacter(s1,s2): smallStr = \"\" largeStr = \"\" # Determine string with extra character if(len(s1) > len(s2)): smallStr = s2 largeStr = s1 else: smallStr = s1 largeStr = s2 smallStrCodeTotal = 0 largeStrCodeTotal = 0 i = 0 # Add Character codes of both the strings while(i < len(smallStr)): smallStrCodeTotal += ord(smallStr[i]) largeStrCodeTotal += ord(largeStr[i]) i += 1 # Add last character code of large string largeStrCodeTotal += ord(largeStr[i]) # Minus the character code of smaller string # from the character code of large string # The result will be the extra character code intChar = largeStrCodeTotal - smallStrCodeTotal return chr(intChar) # Driver codes1 = \"abcd\"s2 = \"cbdae\"extraChar = findExtraCharacter(s1, s2)print(\"Extra Character:\", extraChar) # This code is contributed by simranjenny84", "e": 40150, "s": 39155, "text": null }, { "code": "// C# program to find extra// character in one stringusing System; class GFG{ private static char findExtraCharacter(String s1, String s2) { String smallStr; String largeStr; // Determine String with extra character. if(s1.Length > s2.Length) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } int smallStrCodeTotal = 0; int largeStrCodeTotal = 0; int i = 0; // Add character codes of both the strings for(; i < smallStr.Length; i++) { smallStrCodeTotal += smallStr[i]; largeStrCodeTotal += largeStr[i]; } // Add last character code of large String. largeStrCodeTotal += largeStr[i]; // Minus the character code of smaller string // from the character code of large string. // The result will be the extra character code. int intChar = largeStrCodeTotal - smallStrCodeTotal; return (char)intChar; } public static void Main(String[] args) { String s1 = \"abcd\"; String s2 = \"cbdae\"; char extraChar = findExtraCharacter(s1, s2); Console.WriteLine(\"Extra character: \" + extraChar); }} // This code is contributed by PrinciRaj1992", "e": 41600, "s": 40150, "text": null }, { "code": "<script>// Javascript program to find extra// character in one stringfunction findExtraCharacter(s1, s2){ let smallStr; let largeStr; // Determine String with extra character. if(s1.length > s2.length) { smallStr = s2; largeStr = s1; } else { smallStr = s1; largeStr = s2; } let smallStrCodeTotal = 0; let largeStrCodeTotal = 0; let i = 0; // Add character codes of both the strings for(; i < smallStr.length; i++) { smallStrCodeTotal += smallStr[i].charCodeAt(0); largeStrCodeTotal += largeStr[i].charCodeAt(0); } // Add last character code of large String. largeStrCodeTotal += largeStr[i].charCodeAt(0); // Minus the character code of smaller string from // the character code of large string. // The result will be the extra character code. let intChar = largeStrCodeTotal - smallStrCodeTotal; return String.fromCharCode(intChar);} let s1 = \"abcd\";let s2 = \"cbdae\"; let extraChar = findExtraCharacter(s1, s2);document.write(\"Extra character: \" + extraChar); // This code is contributed by avanitrachhadiya2155</script>", "e": 42871, "s": 41600, "text": null }, { "code": null, "e": 42890, "s": 42871, "text": "Extra character: e" }, { "code": null, "e": 43727, "s": 42892, "text": "YouTubeGeeksforGeeks507K subscribersFind one extra character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NrvoNxLThg0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 43741, "s": 43727, "text": "Nikita tiwari" }, { "code": null, "e": 43753, "s": 43741, "text": "manishshaw1" }, { "code": null, "e": 43763, "s": 43753, "text": "ashuk1992" }, { "code": null, "e": 43777, "s": 43763, "text": "samyakjain677" }, { "code": null, "e": 43790, "s": 43777, "text": "AmolBhosale1" }, { "code": null, "e": 43803, "s": 43790, "text": "princi singh" }, { "code": null, "e": 43815, "s": 43803, "text": "29AjayKumar" }, { "code": null, "e": 43825, "s": 43815, "text": "Rajput-Ji" }, { "code": null, "e": 43839, "s": 43825, "text": "princiraj1992" }, { "code": null, "e": 43850, "s": 43839, "text": "nidhi_biet" }, { "code": null, "e": 43862, "s": 43850, "text": "sanjeev2552" }, { "code": null, "e": 43876, "s": 43862, "text": "simranjenny84" }, { "code": null, "e": 43884, "s": 43876, "text": "gfgking" }, { "code": null, "e": 43892, "s": 43884, "text": "rag2127" }, { "code": null, "e": 43913, "s": 43892, "text": "avanitrachhadiya2155" }, { "code": null, "e": 43925, "s": 43913, "text": "Bitwise-XOR" }, { "code": null, "e": 43944, "s": 43925, "text": "frequency-counting" }, { "code": null, "e": 43954, "s": 43944, "text": "Bit Magic" }, { "code": null, "e": 43962, "s": 43954, "text": "Strings" }, { "code": null, "e": 43970, "s": 43962, "text": "Strings" }, { "code": null, "e": 43980, "s": 43970, "text": "Bit Magic" }, { "code": null, "e": 44078, "s": 43980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44129, "s": 44078, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 44145, "s": 44129, "text": "Bit Fields in C" }, { "code": null, "e": 44187, "s": 44145, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 44263, "s": 44187, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 44300, "s": 44263, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 44346, "s": 44300, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 44371, "s": 44346, "text": "Reverse a string in Java" }, { "code": null, "e": 44431, "s": 44371, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 44446, "s": 44431, "text": "C++ Data Types" } ]
Dictionary Methods in C#
Dictionary is a collection of keys and values in C#. Dictionary<TKey, TValue> is included in the System.Collection.Generics namespace. The following are the methods − Let us see how to add elements into a Dictionary and display the count. Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main() { IDictionary<int, int> d = new Dictionary<int, int>(); d.Add(1,97); d.Add(2,89); d.Add(3,77); d.Add(4,88); d.Add(5,78); d.Add(6,98); Console.WriteLine(d.Count); } } 6
[ { "code": null, "e": 1197, "s": 1062, "text": "Dictionary is a collection of keys and values in C#. Dictionary<TKey, TValue> is included in the System.Collection.Generics namespace." }, { "code": null, "e": 1229, "s": 1197, "text": "The following are the methods −" }, { "code": null, "e": 1301, "s": 1229, "text": "Let us see how to add elements into a Dictionary and display the count." }, { "code": null, "e": 1312, "s": 1301, "text": " Live Demo" }, { "code": null, "e": 1626, "s": 1312, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n IDictionary<int, int> d = new Dictionary<int, int>();\n d.Add(1,97);\n d.Add(2,89);\n d.Add(3,77);\n d.Add(4,88);\n d.Add(5,78);\n d.Add(6,98);\n Console.WriteLine(d.Count);\n }\n}" }, { "code": null, "e": 1628, "s": 1626, "text": "6" } ]
RxJS - Environment Setup
In this chapter, we are going to install RxJS. To work with RxJS, we need the following setup − NodeJS Npm RxJS package installation It is very easy to install RxJS using npm. You need to have nodejs and npm installed on your system. To verify if NodeJS and npm is installed on your system, try to execute the following command in your command prompt. E:\>node -v && npm -v v10.15.1 6.4.1 In case you are getting the version, it means nodejs and npm is installed on your system and the version is 10 and 6 right now on the system. If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The download page of nodejs will look like the following − Based on your OS, install the required package. Once nodejs is installed, npm will also be installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. To start with RxJS installation, first create a folder called rxjsproj/ where we will practice all RxJS examples. Once the folder rxjsproj/ is created, run command npm init, for project setup as shown below E:\>mkdir rxjsproj E:\>cd rxjsproj E:\rxjsproj>npm init Npm init command will ask few questions during execution, just press enter and proceed. Once the execution of npm init is done, it will create package.json inside rxjsproj/ as shown below − rxjsproj/ package.json Now you can install rxjs using below command − npm install ---save-dev rxjs E:\rxjsproj>npm install --save-dev rxjs npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN rxjsproj@1.0.0 No description npm WARN rxjsproj@1.0.0 No repository field. + rxjs@6.5.3 added 2 packages from 7 contributors and audited 2 packages in 21.89s found 0 vulnerabilities We are done with RxJS installation. Let us now try to use RxJS, for that create a folder src/ inside rxjsproj/ So, now, we will have the folder structure as shown below − rxjsproj/ node_modules/ src/ package.json Inside src/ create a file testrx.js, and write the following code − import { of } from 'rxjs; import { map } from 'rxjs/operators'; map(x => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`Output is: ${v}`)); When we go to execute the above code in command prompt, using command − node testrx.js, it will display error for import, as nodejs does not know what to do with import. To make import work with nodejs, we need to install ES6 modules package using npm as shown below − E:\rxjsproj\src>npm install --save-dev esm npm WARN rxjsproj@1.0.0 No description npm WARN rxjsproj@1.0.0 No repository field. + esm@3.2.25 added 1 package from 1 contributor and audited 3 packages in 9.32s found 0 vulnerabilities Once the package is installed, we can now execute testrx.js file as shown below − E:\rxjsproj\src>node -r esm testrx.js Output is: 1 Output is: 4 Output is: 9 We can see the output now, that shows RxJS is installed and ready to use. The above method will help us test RxJS in the command line. In case, you want to test RxJS in the browser, we would need some additional packages. Install following packages inside rxjsproj/ folder − npm install --save-dev babel-loader @babel/core @babel/preset-env webpack webpack-cli webpack-dev-server E:\rxjsproj>npm install --save-dev babel-loader @babel/core @babel/preset-env webpack webpack-cli webpack-dev-server npm WARN rxjsproj@1.0.0 No description npm WARN rxjsproj@1.0.0 No repository field. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@ 1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) + webpack-dev-server@3.8.0 + babel-loader@8.0.6 + @babel/preset-env@7.6.0 + @babel/core@7.6.0 + webpack-cli@3.3.8 + webpack@4.39.3 added 675 packages from 373 contributors and audited 10225 packages in 255.567s found 0 vulnerabilities To start the server to execute our Html file, we will use webpack-server. The command "publish" in package.json will help us start as well as pack all the js files using webpack . The packed js files which are our final js file to be used is saved at the path /dev folder. To use webpack, we need to run npm run publish command and the command is added in package.json as shown below − { "name": "rxjsproj", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "publish":"webpack && webpack-dev-server --output-public=/dev/", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.6.0", "@babel/preset-env": "^7.6.0", "babel-loader": "^8.0.6", "esm": "^3.2.25", "rxjs": "^6.5.3", "webpack": "^4.39.3", "webpack-cli": "^3.3.8", "webpack-dev-server": "^3.8.0" } } To work with webpack we must first create a file called webpack.config.js that has the configuration details for webpack to work. The details in the file are as follows − var path = require('path'); module.exports = { entry: { app: './src/testrx.js' }, output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, mode:'development', module: { rules: [ { test:/\.(js)$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['@babel/preset-env'] } } ] } }; The structure of the file is as shown above. It starts with a path that gives the current path details. var path = require('path'); //gives the current path Next is module.exports object which has properties entry, output, and module. Entry is the start point. Here, we need to give the start js file we want to compile. entry: { app: './src/testrx.js' }, path.resolve(_dirname, ‘src/testrx.js’) -- will look for src folder in the directory and testrx.js in that folder. output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, The output is an object with path and filename details.path will hold the folder in which the compiled file will be kept and the filename will tell the name of the final file to be used in your .html file. module: { rules: [ { test:/\.(js)$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['@babel/preset-env'] } } ] } Module is object with rules details which has properties i.e. test, include, loader, query. The test will hold details of all the js file ending with .js and .jsx. It has the pattern which will look for .js at the end in the entry point given. Include tells the folder to be used for looking at the files. The loader uses babel-loader for compiling code. The query has property presets which is an array with value '@babel/preset-env’. It will transpile the code as per the ES environment you need. The final folder structure will be as follows − rxjsproj/ node_modules/ src/ testrx.js index.html package.json webpack.config.js npm run publish will create dev/ folder with main_bundle.js file in it. The server will be started and you can test your index.html in the browser as shown below. Open the browser and hit the url − http://localhost:8080/ The output is shown in the console. 51 Lectures 4 hours Daniel Stern Print Add Notes Bookmark this page
[ { "code": null, "e": 1920, "s": 1824, "text": "In this chapter, we are going to install RxJS. To work with RxJS, we need the following setup −" }, { "code": null, "e": 1927, "s": 1920, "text": "NodeJS" }, { "code": null, "e": 1931, "s": 1927, "text": "Npm" }, { "code": null, "e": 1957, "s": 1931, "text": "RxJS package installation" }, { "code": null, "e": 2176, "s": 1957, "text": "It is very easy to install RxJS using npm. You need to have nodejs and npm installed on your system. To verify if NodeJS and npm is installed on your system, try to execute the following command in your command prompt." }, { "code": null, "e": 2214, "s": 2176, "text": "E:\\>node -v && npm -v\nv10.15.1\n6.4.1\n" }, { "code": null, "e": 2356, "s": 2214, "text": "In case you are getting the version, it means nodejs and npm is installed on your system and the version is 10 and 6 right now on the system." }, { "code": null, "e": 2540, "s": 2356, "text": "If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS." }, { "code": null, "e": 2599, "s": 2540, "text": "The download page of nodejs will look like the following −" }, { "code": null, "e": 2823, "s": 2599, "text": "Based on your OS, install the required package. Once nodejs is installed, npm will also be installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm." }, { "code": null, "e": 2937, "s": 2823, "text": "To start with RxJS installation, first create a folder called rxjsproj/ where we will practice all RxJS examples." }, { "code": null, "e": 3030, "s": 2937, "text": "Once the folder rxjsproj/ is created, run command npm init, for project setup as shown below" }, { "code": null, "e": 3087, "s": 3030, "text": "E:\\>mkdir rxjsproj\nE:\\>cd rxjsproj\nE:\\rxjsproj>npm init\n" }, { "code": null, "e": 3277, "s": 3087, "text": "Npm init command will ask few questions during execution, just press enter and proceed. Once the execution of npm init is done, it will create package.json inside rxjsproj/ as shown below −" }, { "code": null, "e": 3304, "s": 3277, "text": "rxjsproj/\n package.json\n" }, { "code": null, "e": 3351, "s": 3304, "text": "Now you can install rxjs using below command −" }, { "code": null, "e": 3381, "s": 3351, "text": "npm install ---save-dev rxjs\n" }, { "code": null, "e": 3696, "s": 3381, "text": "E:\\rxjsproj>npm install --save-dev rxjs\nnpm notice created a lockfile as package-lock.json. You should commit this file.\n\nnpm WARN rxjsproj@1.0.0 No description\nnpm WARN rxjsproj@1.0.0 No repository field.\n\n+ rxjs@6.5.3\nadded 2 packages from 7 contributors and audited 2 packages in 21.89s\nfound 0 vulnerabilities\n" }, { "code": null, "e": 3807, "s": 3696, "text": "We are done with RxJS installation. Let us now try to use RxJS, for that create a folder src/ inside rxjsproj/" }, { "code": null, "e": 3867, "s": 3807, "text": "So, now, we will have the folder structure as shown below −" }, { "code": null, "e": 3919, "s": 3867, "text": "rxjsproj/\n node_modules/\n src/\n package.json\n" }, { "code": null, "e": 3987, "s": 3919, "text": "Inside src/ create a file testrx.js, and write the following code −" }, { "code": null, "e": 4131, "s": 3987, "text": "import { of } from 'rxjs;\nimport { map } from 'rxjs/operators';\n\nmap(x => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`Output is: ${v}`));" }, { "code": null, "e": 4301, "s": 4131, "text": "When we go to execute the above code in command prompt, using command − node testrx.js, it will display error for import, as nodejs does not know what to do with import." }, { "code": null, "e": 4400, "s": 4301, "text": "To make import work with nodejs, we need to install ES6 modules package using npm as shown below −" }, { "code": null, "e": 4633, "s": 4400, "text": "E:\\rxjsproj\\src>npm install --save-dev esm\nnpm WARN rxjsproj@1.0.0 No description\nnpm WARN rxjsproj@1.0.0 No repository field.\n\n+ esm@3.2.25\nadded 1 package from 1 contributor and audited 3 packages in 9.32s\nfound 0 vulnerabilities\n" }, { "code": null, "e": 4715, "s": 4633, "text": "Once the package is installed, we can now execute testrx.js file as shown below −" }, { "code": null, "e": 4793, "s": 4715, "text": "E:\\rxjsproj\\src>node -r esm testrx.js\nOutput is: 1\nOutput is: 4\nOutput is: 9\n" }, { "code": null, "e": 5015, "s": 4793, "text": "We can see the output now, that shows RxJS is installed and ready to use. The above method will help us test RxJS in the command line. In case, you want to test RxJS in the browser, we would need some additional packages." }, { "code": null, "e": 5068, "s": 5015, "text": "Install following packages inside rxjsproj/ folder −" }, { "code": null, "e": 5174, "s": 5068, "text": "npm install --save-dev babel-loader @babel/core @babel/preset-env webpack webpack-cli webpack-dev-server\n" }, { "code": null, "e": 5865, "s": 5174, "text": "E:\\rxjsproj>npm install --save-dev babel-loader \n@babel/core @babel/preset-env webpack webpack-cli webpack-dev-server\n\nnpm WARN rxjsproj@1.0.0 No description\nnpm WARN rxjsproj@1.0.0 No repository field.\nnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9\n(node_modules\\fsevents):\nnpm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@\n1.2.9: wanted {\"os\":\"darwin\",\"arch\":\"any\"} (current: {\"os\":\"win32\",\"arch\":\"x64\"})\n\n+ webpack-dev-server@3.8.0\n+ babel-loader@8.0.6\n+ @babel/preset-env@7.6.0\n+ @babel/core@7.6.0\n+ webpack-cli@3.3.8\n+ webpack@4.39.3\nadded 675 packages from 373 contributors and audited 10225 packages in 255.567s\nfound 0 vulnerabilities\n" }, { "code": null, "e": 6138, "s": 5865, "text": "To start the server to execute our Html file, we will use webpack-server. The command \"publish\" in package.json will help us start as well as pack all the js files using webpack . The packed js files which are our final js file to be used is saved at the path /dev folder." }, { "code": null, "e": 6251, "s": 6138, "text": "To use webpack, we need to run npm run publish command and the command is added in package.json as shown below −" }, { "code": null, "e": 6810, "s": 6251, "text": "{\n \"name\": \"rxjsproj\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"publish\":\"webpack && webpack-dev-server --output-public=/dev/\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"@babel/core\": \"^7.6.0\",\n \"@babel/preset-env\": \"^7.6.0\",\n \"babel-loader\": \"^8.0.6\",\n \"esm\": \"^3.2.25\",\n \"rxjs\": \"^6.5.3\",\n \"webpack\": \"^4.39.3\",\n \"webpack-cli\": \"^3.3.8\",\n \"webpack-dev-server\": \"^3.8.0\"\n }\n}" }, { "code": null, "e": 6940, "s": 6810, "text": "To work with webpack we must first create a file called webpack.config.js that has the configuration details for webpack to work." }, { "code": null, "e": 6981, "s": 6940, "text": "The details in the file are as follows −" }, { "code": null, "e": 7459, "s": 6981, "text": "var path = require('path');\n\nmodule.exports = {\n entry: {\n app: './src/testrx.js'\n },\n output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n },\n mode:'development',\n module: {\n rules: [\n {\n test:/\\.(js)$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['@babel/preset-env']\n }\n }\n ]\n }\n};" }, { "code": null, "e": 7563, "s": 7459, "text": "The structure of the file is as shown above. It starts with a path that gives the current path details." }, { "code": null, "e": 7617, "s": 7563, "text": "var path = require('path'); //gives the current path\n" }, { "code": null, "e": 7781, "s": 7617, "text": "Next is module.exports object which has properties entry, output, and module. Entry is the start point. Here, we need to give the start js file we want to compile." }, { "code": null, "e": 7819, "s": 7781, "text": "entry: {\n app: './src/testrx.js'\n}," }, { "code": null, "e": 7934, "s": 7819, "text": "path.resolve(_dirname, ‘src/testrx.js’) -- will look for src folder in the directory and testrx.js in that folder." }, { "code": null, "e": 8019, "s": 7934, "text": "output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n},\n" }, { "code": null, "e": 8225, "s": 8019, "text": "The output is an object with path and filename details.path will hold the folder in which the compiled file will be kept and the filename will tell the name of the final file to be used in your .html file." }, { "code": null, "e": 8450, "s": 8225, "text": "module: {\n rules: [\n {\n test:/\\.(js)$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['@babel/preset-env']\n }\n }\n ]\n}" }, { "code": null, "e": 8694, "s": 8450, "text": "Module is object with rules details which has properties i.e. test, include, loader, query. The test will hold details of all the js file ending with .js and .jsx. It has the pattern which will look for .js at the end in the entry point given." }, { "code": null, "e": 8756, "s": 8694, "text": "Include tells the folder to be used for looking at the files." }, { "code": null, "e": 8805, "s": 8756, "text": "The loader uses babel-loader for compiling code." }, { "code": null, "e": 8949, "s": 8805, "text": "The query has property presets which is an array with value '@babel/preset-env’. It will transpile the code as per the ES environment you need." }, { "code": null, "e": 8997, "s": 8949, "text": "The final folder structure will be as follows −" }, { "code": null, "e": 9100, "s": 8997, "text": "rxjsproj/\n node_modules/\n src/\n testrx.js\n index.html\n package.json\n webpack.config.js\n" }, { "code": null, "e": 9263, "s": 9100, "text": "npm run publish will create dev/ folder with main_bundle.js file in it. The server will be started and you can test your index.html in the browser as shown below." }, { "code": null, "e": 9322, "s": 9263, "text": "Open the browser and hit the url − http://localhost:8080/" }, { "code": null, "e": 9358, "s": 9322, "text": "The output is shown in the console." }, { "code": null, "e": 9391, "s": 9358, "text": "\n 51 Lectures \n 4 hours \n" }, { "code": null, "e": 9405, "s": 9391, "text": " Daniel Stern" }, { "code": null, "e": 9412, "s": 9405, "text": " Print" }, { "code": null, "e": 9423, "s": 9412, "text": " Add Notes" } ]
Shell Script to Take a Screenshot - GeeksforGeeks
15 Apr, 2021 Sometimes we need to capture the screen for later. There are various ways to perform this task: one is achieved by using the shortcut key present in the system, and the other is by using some command-line tools. Here we are going to understand those command-line tools. Before starting the command line tools, we must know about the various shortcuts that can produce different screen outputs. Knowing all of them will help you to create the desired output image. PtrScr: PtrScr will capture the whole screen and save the image file to the Pictures folder in the Home directory. Shift + Ctr + PtrScr: This shortcut is to copy to the clipboard. Here, you can select the area to be copied. Shift + Alt + PtrScr: This shortcut captures the active window and copies it to the clipboard. Shift + PtrScr: This shortcut capture a specific area to the clipboard. Alt + PtrScr: This shortcut will capture the active window and save it to Pictures. Ctr + PtrScr: This shortcut will copy the whole screen to the clipboard. Here we have some CLI tools which can help to capture the screen. They have different variations like capturing the whole screen, capturing the active window, deciding the screenshot’s size, choosing a specific area to capture, etc. ImageMagick can read, write images in various formats like PNG, JPEG, GIF, HEIC, TIFF, DPX, EXR, Webp, Postscripts, PDF, and SVG. Various options present in ImageMagick Resize Flip Mirror Rotate Distort Shear Draw text, lines, polygons, ellipses, etc. # sudo apt install imagemagick –y Install Imagemagick Some features of scrot:- Optimized for image quality. Scrot supports multi-image formats like PNG, JPEG, JPG, GIF, etc. Capture a specific window or rectangular area using a switch. # sudo apt install scrot Install scrot Gnome screenshot features:- Capture the screen, Or a window, Or a specific area, And save it to a file. # sudo apt install gnome-screenshot Install gnome-screenshot This shell script will take various screenshot properties and then produce the screenshot according to those constraints. Some of the conditions we are going to use are the name of the screenshot, area of the screenshot, etc. The script will ask you to use any given tool and capture a specific region. Press [ 1 ] for Capturing the whole Screen using gnome-screenshot Press [ 2 ] for Capturing the Active window using the Scrot Press [ 3 ] for Capturing the Active window using the gnome-screenshot Press [ 4 ] for Capturing the Specific Area using the Scrot Press [ 5 ] for Capturing the Specific Area using the gnome-screenshot # gedit screenshotApp.sh #!/bin/bash #This is a shell script to take Screenshots echo -e " [ 1 ] for Capturing the whole Screen using gnome-screenshot \n [ 2 ] for Capturing the Active window using the Scrot \n [ 3 ] for Capturing the Active window using the gnome-screenshot \n [ 4 ] for Capturing the Specific Area using the Scrot \n [ 5 ] for Capturing the Specific Area using the gnome-screenshot \n" #Now read the user input read UserInput #Now we will use switch cases to implement the UserInput case $UserInput in 1) #command for Capturing the whole Screen using gnome-screenshot. gnome-screenshot # By default it will capture the whole screen ;; 2) #command for Capturing the Active windown using the Scrot. # syntax scrot <option> <optional filename> scrot -s # -s is to select the rectangular area or just click on the window you want to capture ;; 3) #command for Capturing the Active window using the gnome-screenshot. # syntax gnome-screenshot <option> gnome-screenshot -w # here -w is for the active window ;; 4) #command for Capturing the Specific Area using the Scrot. # syntax scrot <option> filename scrot -s myscreenshot.png # here -s is interactive window decision ;; 5) #command for Capturing the Specific Area using the gnome-screenshot. gnome-screenshot -a # here -a is for specific area ;; *) echo -e "Please Enter Correct Input \n" ;; esac # chmod +x screenshotApp.sh # ./screenshotApp.sh Whole screen output #./screenshotApp.sh Selected area using mouse Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n15 Apr, 2021" }, { "code": null, "e": 24285, "s": 24015, "text": "Sometimes we need to capture the screen for later. There are various ways to perform this task: one is achieved by using the shortcut key present in the system, and the other is by using some command-line tools. Here we are going to understand those command-line tools." }, { "code": null, "e": 24479, "s": 24285, "text": "Before starting the command line tools, we must know about the various shortcuts that can produce different screen outputs. Knowing all of them will help you to create the desired output image." }, { "code": null, "e": 24594, "s": 24479, "text": "PtrScr: PtrScr will capture the whole screen and save the image file to the Pictures folder in the Home directory." }, { "code": null, "e": 24703, "s": 24594, "text": "Shift + Ctr + PtrScr: This shortcut is to copy to the clipboard. Here, you can select the area to be copied." }, { "code": null, "e": 24798, "s": 24703, "text": "Shift + Alt + PtrScr: This shortcut captures the active window and copies it to the clipboard." }, { "code": null, "e": 24870, "s": 24798, "text": "Shift + PtrScr: This shortcut capture a specific area to the clipboard." }, { "code": null, "e": 24954, "s": 24870, "text": "Alt + PtrScr: This shortcut will capture the active window and save it to Pictures." }, { "code": null, "e": 25028, "s": 24954, "text": "Ctr + PtrScr: This shortcut will copy the whole screen to the clipboard." }, { "code": null, "e": 25261, "s": 25028, "text": "Here we have some CLI tools which can help to capture the screen. They have different variations like capturing the whole screen, capturing the active window, deciding the screenshot’s size, choosing a specific area to capture, etc." }, { "code": null, "e": 25391, "s": 25261, "text": "ImageMagick can read, write images in various formats like PNG, JPEG, GIF, HEIC, TIFF, DPX, EXR, Webp, Postscripts, PDF, and SVG." }, { "code": null, "e": 25430, "s": 25391, "text": "Various options present in ImageMagick" }, { "code": null, "e": 25437, "s": 25430, "text": "Resize" }, { "code": null, "e": 25442, "s": 25437, "text": "Flip" }, { "code": null, "e": 25449, "s": 25442, "text": "Mirror" }, { "code": null, "e": 25456, "s": 25449, "text": "Rotate" }, { "code": null, "e": 25464, "s": 25456, "text": "Distort" }, { "code": null, "e": 25470, "s": 25464, "text": "Shear" }, { "code": null, "e": 25513, "s": 25470, "text": "Draw text, lines, polygons, ellipses, etc." }, { "code": null, "e": 25547, "s": 25513, "text": "# sudo apt install imagemagick –y" }, { "code": null, "e": 25567, "s": 25547, "text": "Install Imagemagick" }, { "code": null, "e": 25592, "s": 25567, "text": "Some features of scrot:-" }, { "code": null, "e": 25621, "s": 25592, "text": "Optimized for image quality." }, { "code": null, "e": 25689, "s": 25621, "text": "Scrot supports multi-image formats like PNG, JPEG, JPG, GIF, etc." }, { "code": null, "e": 25751, "s": 25689, "text": "Capture a specific window or rectangular area using a switch." }, { "code": null, "e": 25776, "s": 25751, "text": "# sudo apt install scrot" }, { "code": null, "e": 25790, "s": 25776, "text": "Install scrot" }, { "code": null, "e": 25818, "s": 25790, "text": "Gnome screenshot features:-" }, { "code": null, "e": 25838, "s": 25818, "text": "Capture the screen," }, { "code": null, "e": 25851, "s": 25838, "text": "Or a window," }, { "code": null, "e": 25871, "s": 25851, "text": "Or a specific area," }, { "code": null, "e": 25894, "s": 25871, "text": "And save it to a file." }, { "code": null, "e": 25930, "s": 25894, "text": "# sudo apt install gnome-screenshot" }, { "code": null, "e": 25955, "s": 25930, "text": "Install gnome-screenshot" }, { "code": null, "e": 26259, "s": 25955, "text": "This shell script will take various screenshot properties and then produce the screenshot according to those constraints. Some of the conditions we are going to use are the name of the screenshot, area of the screenshot, etc. The script will ask you to use any given tool and capture a specific region." }, { "code": null, "e": 26325, "s": 26259, "text": "Press [ 1 ] for Capturing the whole Screen using gnome-screenshot" }, { "code": null, "e": 26385, "s": 26325, "text": "Press [ 2 ] for Capturing the Active window using the Scrot" }, { "code": null, "e": 26456, "s": 26385, "text": "Press [ 3 ] for Capturing the Active window using the gnome-screenshot" }, { "code": null, "e": 26516, "s": 26456, "text": "Press [ 4 ] for Capturing the Specific Area using the Scrot" }, { "code": null, "e": 26587, "s": 26516, "text": "Press [ 5 ] for Capturing the Specific Area using the gnome-screenshot" }, { "code": null, "e": 26612, "s": 26587, "text": "# gedit screenshotApp.sh" }, { "code": null, "e": 28079, "s": 26612, "text": "#!/bin/bash\n#This is a shell script to take Screenshots\necho -e \"\n[ 1 ] for Capturing the whole Screen using gnome-screenshot \\n\n[ 2 ] for Capturing the Active window using the Scrot \\n\n[ 3 ] for Capturing the Active window using the gnome-screenshot \\n\n[ 4 ] for Capturing the Specific Area using the Scrot \\n\n[ 5 ] for Capturing the Specific Area using the gnome-screenshot \\n\"\n\n#Now read the user input\nread UserInput\n\n#Now we will use switch cases to implement the UserInput\n\ncase $UserInput in\n 1)\n #command for Capturing the whole Screen using gnome-screenshot.\n gnome-screenshot\n # By default it will capture the whole screen\n ;;\n 2)\n #command for Capturing the Active windown using the Scrot.\n # syntax scrot <option> <optional filename>\n scrot -s\n # -s is to select the rectangular area or just click on the window you want to capture\n ;;\n 3)\n #command for Capturing the Active window using the gnome-screenshot.\n # syntax gnome-screenshot <option>\n gnome-screenshot -w\n # here -w is for the active window\n ;;\n 4)\n #command for Capturing the Specific Area using the Scrot.\n # syntax scrot <option> filename\n scrot -s myscreenshot.png\n # here -s is interactive window decision\n ;;\n 5)\n #command for Capturing the Specific Area using the gnome-screenshot.\n gnome-screenshot -a\n # here -a is for specific area\n ;;\n *)\n echo -e \"Please Enter Correct Input \\n\"\n ;;\nesac" }, { "code": null, "e": 28107, "s": 28079, "text": "# chmod +x screenshotApp.sh" }, { "code": null, "e": 28128, "s": 28107, "text": "# ./screenshotApp.sh" }, { "code": null, "e": 28148, "s": 28128, "text": "Whole screen output" }, { "code": null, "e": 28168, "s": 28148, "text": "#./screenshotApp.sh" }, { "code": null, "e": 28194, "s": 28168, "text": "Selected area using mouse" }, { "code": null, "e": 28201, "s": 28194, "text": "Picked" }, { "code": null, "e": 28214, "s": 28201, "text": "Shell Script" }, { "code": null, "e": 28225, "s": 28214, "text": "Linux-Unix" }, { "code": null, "e": 28323, "s": 28225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28332, "s": 28323, "text": "Comments" }, { "code": null, "e": 28345, "s": 28332, "text": "Old Comments" }, { "code": null, "e": 28380, "s": 28345, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28417, "s": 28380, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28451, "s": 28417, "text": "mv command in Linux with examples" }, { "code": null, "e": 28477, "s": 28451, "text": "Thread functions in C/C++" }, { "code": null, "e": 28503, "s": 28477, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28540, "s": 28503, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28580, "s": 28540, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 28609, "s": 28580, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28651, "s": 28609, "text": "Named Pipe or FIFO with example C program" } ]
Count Binary Substrings in C++
Suppose we have a string s, we have to find the count of contiguous substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. If substrings occur multiple times are counted the number of times they occur. So, if the input is like "11001100", then the output will be 6, as the substrings are "1100", "10","0011", "01", "1100", "10". To solve this, we will follow these steps − Define an array cnt of size 2 and fill this with 0 res := 0 for initialize i := 0, when i < length of s, update (increase i by 1), do −num := s[i] - ASCII of '0'if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0(increase cnt[num] by 1)if cnt[num] <= cnt[1 - num], then −(increase res by 1) num := s[i] - ASCII of '0' if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0 cnt[num] := 0 (increase cnt[num] by 1) if cnt[num] <= cnt[1 - num], then −(increase res by 1) (increase res by 1) return res Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int countBinarySubstrings(string s) { int cnt[2] = { 0 }; int res = 0; for (int i = 0; i < s.length(); ++i) { int num = s[i] - '0'; if (i == 0 || s[i] != s[i - 1]) cnt[num] = 0; ++cnt[num]; if (cnt[num] <= cnt[1 - num]) ++res; } return res; } }; main(){ Solution ob; cout << (ob.countBinarySubstrings("11001100")); } "11001100" 6
[ { "code": null, "e": 1341, "s": 1062, "text": "Suppose we have a string s, we have to find the count of contiguous substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. If substrings occur multiple times are counted the number of times they occur." }, { "code": null, "e": 1468, "s": 1341, "text": "So, if the input is like \"11001100\", then the output will be 6, as the substrings are \"1100\", \"10\",\"0011\", \"01\", \"1100\", \"10\"." }, { "code": null, "e": 1512, "s": 1468, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1563, "s": 1512, "text": "Define an array cnt of size 2 and fill this with 0" }, { "code": null, "e": 1572, "s": 1563, "text": "res := 0" }, { "code": null, "e": 1823, "s": 1572, "text": "for initialize i := 0, when i < length of s, update (increase i by 1), do −num := s[i] - ASCII of '0'if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0(increase cnt[num] by 1)if cnt[num] <= cnt[1 - num], then −(increase res by 1)" }, { "code": null, "e": 1850, "s": 1823, "text": "num := s[i] - ASCII of '0'" }, { "code": null, "e": 1922, "s": 1850, "text": "if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0" }, { "code": null, "e": 1936, "s": 1922, "text": "cnt[num] := 0" }, { "code": null, "e": 1961, "s": 1936, "text": "(increase cnt[num] by 1)" }, { "code": null, "e": 2016, "s": 1961, "text": "if cnt[num] <= cnt[1 - num], then −(increase res by 1)" }, { "code": null, "e": 2036, "s": 2016, "text": "(increase res by 1)" }, { "code": null, "e": 2047, "s": 2036, "text": "return res" }, { "code": null, "e": 2117, "s": 2047, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2128, "s": 2117, "text": " Live Demo" }, { "code": null, "e": 2618, "s": 2128, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int countBinarySubstrings(string s) {\n int cnt[2] = { 0 };\n int res = 0;\n for (int i = 0; i < s.length(); ++i) {\n int num = s[i] - '0';\n if (i == 0 || s[i] != s[i - 1])\n cnt[num] = 0;\n ++cnt[num];\n if (cnt[num] <= cnt[1 - num])\n ++res;\n }\n return res;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.countBinarySubstrings(\"11001100\"));\n}" }, { "code": null, "e": 2629, "s": 2618, "text": "\"11001100\"" }, { "code": null, "e": 2631, "s": 2629, "text": "6" } ]
OpenCV - Face Detection using Camera
The following program demonstrates how to detect faces using system camera and display it using JavaFX window. import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import java.io.FileNotFoundException; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import org.opencv.videoio.VideoCapture; public class faceDetectionJavaFXX extends Application { Mat matrix = null; @Override public void start(Stage stage) throws FileNotFoundException, IOException { // Capturing the snapshot from the camera faceDetectionJavaFXX obj = new faceDetectionJavaFXX(); WritableImage writableImage = obj.capureFrame(); // Saving the image obj.saveImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(400); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Capturing an image"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage capureFrame() { WritableImage writableImage = null; // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Instantiating the VideoCapture class (camera:: 0) VideoCapture capture = new VideoCapture(0); // Reading the next video frame from the camera Mat matrix = new Mat(); capture.read(matrix); // If camera is opened if(!capture.isOpened()) { System.out.println("camera not detected"); } else System.out.println("Camera detected "); // If there is next video frame if (capture.read(matrix)) { /////// Detecting the face in the snap ///// String file = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml"; CascadeClassifier classifier = new CascadeClassifier(file); MatOfRect faceDetections = new MatOfRect(); classifier.detectMultiScale(matrix, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // Drawing boxes for (Rect rect : faceDetections.toArray()) { Imgproc.rectangle( matrix, //where to draw the box new Point(rect.x, rect.y), //bottom left new Point(rect.x + rect.width, rect.y + rect.height), //top right new Scalar(0, 0, 255) //RGB colour ); } // Creating BuffredImage from the matrix BufferedImage image = new BufferedImage(matrix.width(), matrix.height(), BufferedImage.TYPE_3BYTE_BGR); WritableRaster raster = image.getRaster(); DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); byte[] data = dataBuffer.getData(); matrix.get(0, 0, data); this.matrix = matrix; // Creating the Writable Image writableImage = SwingFXUtils.toFXImage(image, null); } return writableImage; } public void saveImage() { // Saving the Image String file = "E:/OpenCV/chap23/facedetected.jpg"; // Instantiating the imagecodecs class Imgcodecs imageCodecs = new Imgcodecs(); // Saving it again imageCodecs.imwrite(file, matrix); } public static void main(String args[]) { launch(args); } } On executing the program, you will get the following output. If you open the specified path, you can see the same snapshot saved as a jpg image. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3115, "s": 3004, "text": "The following program demonstrates how to detect faces using system camera and display it using JavaFX window." }, { "code": null, "e": 7429, "s": 3115, "text": "import java.awt.image.BufferedImage;\nimport java.awt.image.DataBufferByte;\nimport java.awt.image.WritableRaster;\n\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\n\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfRect;\nimport org.opencv.core.Point;\nimport org.opencv.core.Rect;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\nimport org.opencv.objdetect.CascadeClassifier;\nimport org.opencv.videoio.VideoCapture;\n\npublic class faceDetectionJavaFXX extends Application {\n Mat matrix = null;\n\n @Override\n public void start(Stage stage) throws FileNotFoundException, IOException {\n // Capturing the snapshot from the camera\n faceDetectionJavaFXX obj = new faceDetectionJavaFXX();\n WritableImage writableImage = obj.capureFrame();\n\n // Saving the image\n obj.saveImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(400);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object\n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Capturing an image\");\n\n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n }\n public WritableImage capureFrame() {\n WritableImage writableImage = null;\n\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Instantiating the VideoCapture class (camera:: 0)\n VideoCapture capture = new VideoCapture(0);\n\n // Reading the next video frame from the camera\n Mat matrix = new Mat();\n capture.read(matrix);\n\n // If camera is opened\n if(!capture.isOpened()) {\n System.out.println(\"camera not detected\");\n } else\n System.out.println(\"Camera detected \");\n \n // If there is next video frame\n if (capture.read(matrix)) {\n /////// Detecting the face in the snap /////\n String file = \"E:/OpenCV/facedetect/lbpcascade_frontalface.xml\";\n CascadeClassifier classifier = new CascadeClassifier(file);\n\n MatOfRect faceDetections = new MatOfRect();\n classifier.detectMultiScale(matrix, faceDetections);\n System.out.println(String.format(\"Detected %s faces\",\n faceDetections.toArray().length));\n\n // Drawing boxes\n for (Rect rect : faceDetections.toArray()) {\n Imgproc.rectangle(\n matrix, //where to draw the box\n new Point(rect.x, rect.y), //bottom left\n new Point(rect.x + rect.width, rect.y + rect.height), //top right\n new Scalar(0, 0, 255) //RGB colour\n );\n }\n // Creating BuffredImage from the matrix\n BufferedImage image = new BufferedImage(matrix.width(), matrix.height(),\n BufferedImage.TYPE_3BYTE_BGR);\n \n WritableRaster raster = image.getRaster();\n DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();\n byte[] data = dataBuffer.getData();\n matrix.get(0, 0, data);\n\n this.matrix = matrix;\n \n // Creating the Writable Image\n writableImage = SwingFXUtils.toFXImage(image, null);\n }\n return writableImage;\n }\n public void saveImage() {\n // Saving the Image\n String file = \"E:/OpenCV/chap23/facedetected.jpg\";\n\n // Instantiating the imagecodecs class\n Imgcodecs imageCodecs = new Imgcodecs();\n\n // Saving it again\n imageCodecs.imwrite(file, matrix);\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 7490, "s": 7429, "text": "On executing the program, you will get the following output." }, { "code": null, "e": 7574, "s": 7490, "text": "If you open the specified path, you can see the same snapshot saved as a jpg image." }, { "code": null, "e": 7607, "s": 7574, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7624, "s": 7607, "text": " Abhilash Nelson" }, { "code": null, "e": 7657, "s": 7624, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7674, "s": 7657, "text": " Abhilash Nelson" }, { "code": null, "e": 7707, "s": 7674, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7721, "s": 7707, "text": " Spotle Learn" }, { "code": null, "e": 7753, "s": 7721, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7770, "s": 7753, "text": " Srikanth Guskra" }, { "code": null, "e": 7803, "s": 7770, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7818, "s": 7803, "text": " Haithem Gasmi" }, { "code": null, "e": 7853, "s": 7818, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7871, "s": 7853, "text": " Gianluca Mottola" }, { "code": null, "e": 7878, "s": 7871, "text": " Print" }, { "code": null, "e": 7889, "s": 7878, "text": " Add Notes" } ]
Kibana - Timelion
Timelion, also called as timeline is yet another visualization tool which is mainly used for time based data analysis. To work with timeline, we need to use simple expression language which will help us connect to the index and also perform calculations on the data to get the results we need. Timelion is used when you want to compare time related data. For example, you have a site, and you get your views daily. You want to analyse the data wherein you want to compare the current week data with previous week, i.e. Monday-Monday, Tuesday -Tuesday and so on how the views are differing and also the traffic. To start working with Timelion, click on Timelion as shown below − Timelion by default shows the timeline of all indexes as shown below − Timelion works with expression syntax. Note − es(*) => means all indexes. To get the details of function available to be used with Timelion, simply click on the textarea as shown below − It gives you the list of function to be used with the expression syntax. Once you start with Timelion, it displays a welcome message as shown below. The highlighted section i.e. Jump to the function reference, gives the details of all the functions available to be used with timelion. The Timelion welcome message is as shown below − Click on the next button and it will walk you through its basic functionality and usage. Now when you click Next, you can see the following details − Click on Help button to get the details of the function reference available for Timelion − The settings for timelion is done in Kibana Management → Advanced Settings. Click on Advanced Settings and select Timelion from Category Once Timelion is selected it will display all the necessary fields required for timelion configuration. In the following fields you can change the default index and the timefield to be used on the index − The default one is _all and timefield is @timestamp. We would leave it as it is and change the index and timefield in the timelion itself. We are going to use index:medicalvisits-26.01.2019. The following is the data displayed from timelion for 1st Jan 2017 to 31st Dec 2017 − The expression used for above visualization is as follows − .es(index=medicalvisits-26.01.2019,timefield=Visiting_Date).bars() We have used the index medicalvisits-26.01.2019 and timefield on that index is Visiting_Date and used bars function. In the following we have analyzed 2 cities for the month of jan 2017, day wise. The expression used is − .es(index=medicalvisits-26.01.2019,timefield=Visiting_Date, q=City:Sabadell).label(Sabadell),.es(index=medicalvisits-26.01.2019, timefield=Visiting_Date, q=City:Terrassa).label(Terrassa) The timeline comparison for 2 days is shown here − .es(index=medicalvisits-26.01.2019,timefield=Visiting_Date).label("August 2nd 2018"), .es(index=medicalvisits-26.01.2019,timefield=Visiting_Date,offset=-1d).label("August 1st 2018") Here we have used offset and given a difference of 1day. We have selected the current date as 2nd August 2018. So it gives data difference for 2nd Aug 2018 and 1st Aug 2018. The list of top 5 cities data for the month of Jan 2017 is shown below. The expression that we have used here is given below − .es(index=medicalvisits-26.01.2019,timefield=Visiting_Date,split=City.keyword:5) We have used split and given the field name as city and the since we need top five cities from the index we have given it as split=City.keyword:5 It gives the count of each city and lists their names as shown in the graph plotted. Print Add Notes Bookmark this page
[ { "code": null, "e": 2399, "s": 2105, "text": "Timelion, also called as timeline is yet another visualization tool which is mainly used for time based data analysis. To work with timeline, we need to use simple expression language which will help us connect to the index and also perform calculations on the data to get the results we need." }, { "code": null, "e": 2716, "s": 2399, "text": "Timelion is used when you want to compare time related data. For example, you have a site, and you get your views daily. You want to analyse the data wherein you want to compare the current week data with previous week, i.e. Monday-Monday, Tuesday -Tuesday and so on how the views are differing and also the traffic." }, { "code": null, "e": 2783, "s": 2716, "text": "To start working with Timelion, click on Timelion as shown below −" }, { "code": null, "e": 2854, "s": 2783, "text": "Timelion by default shows the timeline of all indexes as shown below −" }, { "code": null, "e": 2893, "s": 2854, "text": "Timelion works with expression syntax." }, { "code": null, "e": 2928, "s": 2893, "text": "Note − es(*) => means all indexes." }, { "code": null, "e": 3041, "s": 2928, "text": "To get the details of function available to be used with Timelion, simply click on the textarea as shown below −" }, { "code": null, "e": 3114, "s": 3041, "text": "It gives you the list of function to be used with the expression syntax." }, { "code": null, "e": 3326, "s": 3114, "text": "Once you start with Timelion, it displays a welcome message as shown below. The highlighted section i.e. Jump to the function reference, gives the details of all the functions available to be used with timelion." }, { "code": null, "e": 3375, "s": 3326, "text": "The Timelion welcome message is as shown below −" }, { "code": null, "e": 3525, "s": 3375, "text": "Click on the next button and it will walk you through its basic functionality and usage. Now when you click Next, you can see the following details −" }, { "code": null, "e": 3616, "s": 3525, "text": "Click on Help button to get the details of the function reference available for Timelion −" }, { "code": null, "e": 3692, "s": 3616, "text": "The settings for timelion is done in Kibana Management → Advanced Settings." }, { "code": null, "e": 3753, "s": 3692, "text": "Click on Advanced Settings and select Timelion from Category" }, { "code": null, "e": 3857, "s": 3753, "text": "Once Timelion is selected it will display all the necessary fields required for timelion configuration." }, { "code": null, "e": 3958, "s": 3857, "text": "In the following fields you can change the default index and the timefield to be used on the index −" }, { "code": null, "e": 4097, "s": 3958, "text": "The default one is _all and timefield is @timestamp. We would leave it as it is and change the index and timefield in the timelion itself." }, { "code": null, "e": 4235, "s": 4097, "text": "We are going to use index:medicalvisits-26.01.2019. The following is the data displayed from timelion for 1st Jan 2017 to 31st Dec 2017 −" }, { "code": null, "e": 4295, "s": 4235, "text": "The expression used for above visualization is as follows −" }, { "code": null, "e": 4363, "s": 4295, "text": ".es(index=medicalvisits-26.01.2019,timefield=Visiting_Date).bars()\n" }, { "code": null, "e": 4480, "s": 4363, "text": "We have used the index medicalvisits-26.01.2019 and timefield on that index is Visiting_Date and used bars function." }, { "code": null, "e": 4560, "s": 4480, "text": "In the following we have analyzed 2 cities for the month of jan 2017, day wise." }, { "code": null, "e": 4585, "s": 4560, "text": "The expression used is −" }, { "code": null, "e": 4774, "s": 4585, "text": ".es(index=medicalvisits-26.01.2019,timefield=Visiting_Date, \nq=City:Sabadell).label(Sabadell),.es(index=medicalvisits-26.01.2019,\ntimefield=Visiting_Date, q=City:Terrassa).label(Terrassa)\n" }, { "code": null, "e": 4825, "s": 4774, "text": "The timeline comparison for 2 days is shown here −" }, { "code": null, "e": 5008, "s": 4825, "text": ".es(index=medicalvisits-26.01.2019,timefield=Visiting_Date).label(\"August 2nd 2018\"),\n.es(index=medicalvisits-26.01.2019,timefield=Visiting_Date,offset=-1d).label(\"August 1st 2018\")\n" }, { "code": null, "e": 5182, "s": 5008, "text": "Here we have used offset and given a difference of 1day. We have selected the current date as 2nd August 2018. So it gives data difference for 2nd Aug 2018 and 1st Aug 2018." }, { "code": null, "e": 5309, "s": 5182, "text": "The list of top 5 cities data for the month of Jan 2017 is shown below. The expression that we have used here is given below −" }, { "code": null, "e": 5391, "s": 5309, "text": ".es(index=medicalvisits-26.01.2019,timefield=Visiting_Date,split=City.keyword:5)\n" }, { "code": null, "e": 5537, "s": 5391, "text": "We have used split and given the field name as city and the since we need top five cities from the index we have given it as split=City.keyword:5" }, { "code": null, "e": 5622, "s": 5537, "text": "It gives the count of each city and lists their names as shown in the graph plotted." }, { "code": null, "e": 5629, "s": 5622, "text": " Print" }, { "code": null, "e": 5640, "s": 5629, "text": " Add Notes" } ]
Bash program to check if the Number is a Prime or not
Bash also known as GNU bash is a command language and unix shell script is a command line interpreter for operating system. It was designed by Brian Fox and was a free software which replaced Bourne shell. It first released in 1989 and some became go to for login shell for linux based operating systems like macOS, Linux based softwares, etc. Prime number is a number that has only two factors i.e. the number itself and 1. For example, 2 , 3 , 5, 7 , 11 , 13 , 17 , 19 , 23 , 29.... Here we are given a number, and we need to find whether the given number is prime or not. Input : A number Output : “The number is prime ” OR “The number is not prime” based on the number. Example − Input : 23 Output : The number is prime Step 1 − Loop from 2 to n/2, i as loop variable Step 1 − Loop from 2 to n/2, i as loop variable Step 2 − if number is divisible, print “The number is not prime” and flag = 1; Step 2 − if number is divisible, print “The number is not prime” and flag = 1; Step 3 − if flag != 1, then print “The number is prime”. Step 3 − if flag != 1, then print “The number is prime”. Step 4 − Exit. Step 4 − Exit. number=53 i=2 flag=0 while test $i -le `expr $number / 2` do if test `expr $number % $i` -eq 0 then flag=1 fi i=`expr $i + 1` done if test $flag -eq 1 then echo "The number is Not Prime" else echo "The number is Prime" Fi The number is Prime
[ { "code": null, "e": 1406, "s": 1062, "text": "Bash also known as GNU bash is a command language and unix shell script is a command line interpreter for operating system. It was designed by Brian Fox and was a free software which replaced Bourne shell. It first released in 1989 and some became go to for login shell for linux based operating systems like macOS, Linux based softwares, etc." }, { "code": null, "e": 1547, "s": 1406, "text": "Prime number is a number that has only two factors i.e. the number itself and 1. For example, 2 , 3 , 5, 7 , 11 , 13 , 17 , 19 , 23 , 29...." }, { "code": null, "e": 1637, "s": 1547, "text": "Here we are given a number, and we need to find whether the given number is prime or not." }, { "code": null, "e": 1736, "s": 1637, "text": "Input : A number\nOutput : “The number is prime ” OR “The number is not prime” based on the number." }, { "code": null, "e": 1746, "s": 1736, "text": "Example −" }, { "code": null, "e": 1786, "s": 1746, "text": "Input : 23\nOutput : The number is prime" }, { "code": null, "e": 1834, "s": 1786, "text": "Step 1 − Loop from 2 to n/2, i as loop variable" }, { "code": null, "e": 1882, "s": 1834, "text": "Step 1 − Loop from 2 to n/2, i as loop variable" }, { "code": null, "e": 1961, "s": 1882, "text": "Step 2 − if number is divisible, print “The number is not prime” and flag = 1;" }, { "code": null, "e": 2040, "s": 1961, "text": "Step 2 − if number is divisible, print “The number is not prime” and flag = 1;" }, { "code": null, "e": 2097, "s": 2040, "text": "Step 3 − if flag != 1, then print “The number is prime”." }, { "code": null, "e": 2154, "s": 2097, "text": "Step 3 − if flag != 1, then print “The number is prime”." }, { "code": null, "e": 2169, "s": 2154, "text": "Step 4 − Exit." }, { "code": null, "e": 2184, "s": 2169, "text": "Step 4 − Exit." }, { "code": null, "e": 2407, "s": 2184, "text": "number=53\ni=2\nflag=0\nwhile test $i -le `expr $number / 2`\ndo\nif test `expr $number % $i` -eq 0\nthen\nflag=1\nfi\n\ni=`expr $i + 1`\ndone if test $flag -eq 1\nthen\necho \"The number is Not Prime\"\nelse\necho \"The number is Prime\"\nFi" }, { "code": null, "e": 2427, "s": 2407, "text": "The number is Prime" } ]
Python | Get sum of tuples having same first value - GeeksforGeeks
14 Feb, 2019 Given a list of tuple, the task is to sum the tuples having same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)] Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let’s discuss the different ways we can do this task. Method #1: Using map() # Python code to get sum of tuples having same first value # Initialisation of list of tupleInput = [(1, 13), (1, 190), (3, 25), (1, 12)] d = {x:0 for x, _ in Input} for name, num in Input: d[name] += num # using mapOutput = list(map(tuple, d.items())) # printing outputprint(Output) [(1, 215), (3, 25)] Method #2: Using defaultdict # Python code to sum list of tuples having same first value # Importingfrom collections import defaultdict # Initialisation of list of tupleInput = [(2, 190), (1, 13), (1, 12), (2, 14), (3, 82), (1, 70)] # Initialisation of defaultdictoutput = defaultdict(int) for k, v in Input: output[k] += v # Printing outputprint(list(output.items())) [(1, 95), (2, 204), (3, 82)] Python tuple-programs python-tuple 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 Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n14 Feb, 2019" }, { "code": null, "e": 24290, "s": 24212, "text": "Given a list of tuple, the task is to sum the tuples having same first value." }, { "code": null, "e": 24300, "s": 24290, "text": "Examples:" }, { "code": null, "e": 24457, "s": 24300, "text": "Input: [(1, 13), (2, 190), (3, 82), (1, 12)]\nOutput: [(1, 25), (2, 190), (3, 82)]\n\nInput: [(1, 13), (1, 190), (3, 25), (1, 12)]\nOutput: [(1, 215), (3, 25)]\n" }, { "code": null, "e": 24512, "s": 24457, "text": " Let’s discuss the different ways we can do this task." }, { "code": null, "e": 24535, "s": 24512, "text": "Method #1: Using map()" }, { "code": "# Python code to get sum of tuples having same first value # Initialisation of list of tupleInput = [(1, 13), (1, 190), (3, 25), (1, 12)] d = {x:0 for x, _ in Input} for name, num in Input: d[name] += num # using mapOutput = list(map(tuple, d.items())) # printing outputprint(Output)", "e": 24824, "s": 24535, "text": null }, { "code": null, "e": 24845, "s": 24824, "text": "[(1, 215), (3, 25)]\n" }, { "code": null, "e": 24875, "s": 24845, "text": " Method #2: Using defaultdict" }, { "code": "# Python code to sum list of tuples having same first value # Importingfrom collections import defaultdict # Initialisation of list of tupleInput = [(2, 190), (1, 13), (1, 12), (2, 14), (3, 82), (1, 70)] # Initialisation of defaultdictoutput = defaultdict(int) for k, v in Input: output[k] += v # Printing outputprint(list(output.items()))", "e": 25232, "s": 24875, "text": null }, { "code": null, "e": 25262, "s": 25232, "text": "[(1, 95), (2, 204), (3, 82)]\n" }, { "code": null, "e": 25284, "s": 25262, "text": "Python tuple-programs" }, { "code": null, "e": 25297, "s": 25284, "text": "python-tuple" }, { "code": null, "e": 25304, "s": 25297, "text": "Python" }, { "code": null, "e": 25402, "s": 25304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25411, "s": 25402, "text": "Comments" }, { "code": null, "e": 25424, "s": 25411, "text": "Old Comments" }, { "code": null, "e": 25456, "s": 25424, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25511, "s": 25456, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25567, "s": 25511, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25606, "s": 25567, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25648, "s": 25606, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25690, "s": 25648, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25712, "s": 25690, "text": "Defaultdict in Python" }, { "code": null, "e": 25743, "s": 25712, "text": "Python | os.path.join() method" }, { "code": null, "e": 25772, "s": 25743, "text": "Create a directory in Python" } ]
Python | Pandas Index.shape - GeeksforGeeks
20 Feb, 2019 Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.shape attribute return a tuple of the shape of the underlying data in the given Index object. Syntax: Index.shape Parameter : None Returns : tuple Example #1: Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio']) # Print the indexprint(idx) Output : Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object. # return a tuple of the shape# of data in idx objectresult = idx.shape # Print the resultprint(result) Output : As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object. Example #2 : Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900]) # Print the indexprint(idx) Output : Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object. # return a tuple of the shape# of data in idx objectresult = idx.shape # Print the resultprint(result) Output :As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object. Python pandas-indexing 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 Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n20 Feb, 2019" }, { "code": null, "e": 24365, "s": 24212, "text": "Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects." }, { "code": null, "e": 24472, "s": 24365, "text": "Pandas Index.shape attribute return a tuple of the shape of the underlying data in the given Index object." }, { "code": null, "e": 24492, "s": 24472, "text": "Syntax: Index.shape" }, { "code": null, "e": 24509, "s": 24492, "text": "Parameter : None" }, { "code": null, "e": 24525, "s": 24509, "text": "Returns : tuple" }, { "code": null, "e": 24644, "s": 24525, "text": "Example #1: Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio']) # Print the indexprint(idx)", "e": 24814, "s": 24644, "text": null }, { "code": null, "e": 24823, "s": 24814, "text": "Output :" }, { "code": null, "e": 24942, "s": 24823, "text": "Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object." }, { "code": "# return a tuple of the shape# of data in idx objectresult = idx.shape # Print the resultprint(result)", "e": 25046, "s": 24942, "text": null }, { "code": null, "e": 25055, "s": 25046, "text": "Output :" }, { "code": null, "e": 25319, "s": 25055, "text": "As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object. Example #2 : Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900]) # Print the indexprint(idx)", "e": 25478, "s": 25319, "text": null }, { "code": null, "e": 25487, "s": 25478, "text": "Output :" }, { "code": null, "e": 25606, "s": 25487, "text": "Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object." }, { "code": "# return a tuple of the shape# of data in idx objectresult = idx.shape # Print the resultprint(result)", "e": 25710, "s": 25606, "text": null }, { "code": null, "e": 25862, "s": 25710, "text": "Output :As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object." }, { "code": null, "e": 25885, "s": 25862, "text": "Python pandas-indexing" }, { "code": null, "e": 25899, "s": 25885, "text": "Python-pandas" }, { "code": null, "e": 25906, "s": 25899, "text": "Python" }, { "code": null, "e": 26004, "s": 25906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26013, "s": 26004, "text": "Comments" }, { "code": null, "e": 26026, "s": 26013, "text": "Old Comments" }, { "code": null, "e": 26058, "s": 26026, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26113, "s": 26058, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26169, "s": 26113, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26208, "s": 26169, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26250, "s": 26208, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26292, "s": 26250, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26314, "s": 26292, "text": "Defaultdict in Python" }, { "code": null, "e": 26345, "s": 26314, "text": "Python | os.path.join() method" }, { "code": null, "e": 26374, "s": 26345, "text": "Create a directory in Python" } ]
Python - How to convert this while loop to for loop?
Usin count() function in itertools module gives an iterator of evenly spaced values. The function takes two parameters. start is by default 0 and step is by default 1. Using defaults will generate infinite iterator. Use break to terminate loop. import itertools percentNumbers = [ ] finish = "n" num = "0" for x in itertools.count() : num = input("enter the mark : ") num = float(num) percentNumbers.append(num) finish = input("stop? (y/n) ") if finish=='y':break print(percentNumbers) Sample output of the above script enter the mark : 11 stop? (y/n) enter the mark : 22 stop? (y/n) enter the mark : 33 stop? (y/n) y [11.0, 22.0, 33.0]
[ { "code": null, "e": 1307, "s": 1062, "text": "Usin count() function in itertools module gives an iterator of evenly spaced values. The function takes two parameters. start is by default 0 and step is by default 1. Using defaults will generate infinite iterator. Use break to terminate loop." }, { "code": null, "e": 1568, "s": 1307, "text": "import itertools\npercentNumbers = [ ]\nfinish = \"n\"\nnum = \"0\"\nfor x in itertools.count() :\n num = input(\"enter the mark : \")\n num = float(num)\n percentNumbers.append(num)\n finish = input(\"stop? (y/n) \")\n if finish=='y':break\nprint(percentNumbers)" }, { "code": null, "e": 1602, "s": 1568, "text": "Sample output of the above script" }, { "code": null, "e": 1719, "s": 1602, "text": "enter the mark : 11\nstop? (y/n)\nenter the mark : 22\nstop? (y/n)\nenter the mark : 33\nstop? (y/n) y\n[11.0, 22.0, 33.0]" } ]
VBA - Programming Charts
Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example. Step 1 − Enter the data against which the graph has to be generated. Step 2 − Create 3 buttons - one to generate a bar graph, another to generate a pie chart, and another to generate a column chart. Step 3 − Develop a Macro to generate each one of these type of charts. ' Procedure to Generate Pie Chart Private Sub fn_generate_pie_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlPie Next cht End Sub ' Procedure to Generate Bar Graph Private Sub fn_Generate_Bar_Graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlBar Next cht End Sub ' Procedure to Generate Column Graph Private Sub fn_generate_column_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlColumn Next cht End Sub Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button. 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2040, "s": 1935, "text": "Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example." }, { "code": null, "e": 2109, "s": 2040, "text": "Step 1 − Enter the data against which the graph has to be generated." }, { "code": null, "e": 2239, "s": 2109, "text": "Step 2 − Create 3 buttons - one to generate a bar graph, another to generate a pie chart, and another to generate a column chart." }, { "code": null, "e": 2310, "s": 2239, "text": "Step 3 − Develop a Macro to generate each one of these type of charts." }, { "code": null, "e": 2912, "s": 2310, "text": "' Procedure to Generate Pie Chart\nPrivate Sub fn_generate_pie_graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlPie\n Next cht\nEnd Sub\n\n' Procedure to Generate Bar Graph\nPrivate Sub fn_Generate_Bar_Graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlBar\n Next cht\nEnd Sub\n\n' Procedure to Generate Column Graph\nPrivate Sub fn_generate_column_graph_Click()\n Dim cht As ChartObject\n For Each cht In Worksheets(1).ChartObjects\n cht.Chart.Type = xlColumn\n Next cht\nEnd Sub" }, { "code": null, "e": 3044, "s": 2912, "text": "Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button." }, { "code": null, "e": 3078, "s": 3044, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3093, "s": 3078, "text": " Pavan Lalwani" }, { "code": null, "e": 3126, "s": 3093, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3141, "s": 3126, "text": " Arnold Higuit" }, { "code": null, "e": 3176, "s": 3141, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3194, "s": 3176, "text": " Prashant Panchal" }, { "code": null, "e": 3227, "s": 3194, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3245, "s": 3227, "text": " Prashant Panchal" }, { "code": null, "e": 3278, "s": 3245, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3293, "s": 3278, "text": " Arnold Higuit" }, { "code": null, "e": 3329, "s": 3293, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3357, "s": 3329, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3364, "s": 3357, "text": " Print" }, { "code": null, "e": 3375, "s": 3364, "text": " Add Notes" } ]
Ansible - Playbooks
In this chapter, we will learn about Playbooks in Ansible. Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks. Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible. Each playbook is an aggregation of one or more plays in it. Playbooks are structured using Plays. There can be more than one play inside a playbook. The function of a play is to map a set of instructions defined against a particular host. YAML is a strict typed language; so, extra care needs to be taken while writing the YAML files. There are different YAML editors but we will prefer to use a simple editor like notepad++. Just open notepad++ and copy and paste the below yaml and change the language to YAML (Language → YAML). A YAML starts with --- (3 hyphens) Let us start by writing a sample YAML file. We will walk through each section written in a yaml file. --- name: install and configure DB hosts: testServer become: yes vars: oracle_db_port_value : 1521 tasks: -name: Install the Oracle DB yum: <code to install the DB> -name: Ensure the installed service is enabled and running service: name: <your service name> The above is a sample Playbook where we are trying to cover the basic syntax of a playbook. Save the above content in a file as test.yml. A YAML syntax needs to follow the correct indentation and one needs to be a little careful while writing the syntax. Let us now go through the different YAML tags. The different tags are described below − This tag specifies the name of the Ansible playbook. As in what this playbook will be doing. Any logical name can be given to the playbook. This tag specifies the lists of hosts or host group against which we want to run the task. The hosts field/tag is mandatory. It tells Ansible on which hosts to run the listed tasks. The tasks can be run on the same machine or on a remote machine. One can run the tasks on multiple machines and hence hosts tag can have a group of hosts’ entry as well. Vars tag lets you define the variables which you can use in your playbook. Usage is similar to variables in any programming language. All playbooks should contain tasks or a list of tasks to be executed. Tasks are a list of actions one needs to perform. A tasks field contains the name of the task. This works as the help text for the user. It is not mandatory but proves useful in debugging the playbook. Each task internally links to a piece of code called a module. A module that should be executed, and arguments that are required for the module you want to execute. 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav 4 Lectures 3.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 1850, "s": 1791, "text": "In this chapter, we will learn about Playbooks in Ansible." }, { "code": null, "e": 2142, "s": 1850, "text": "Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. Playbooks are one of the core features of Ansible and tell Ansible what to execute. They are like a to-do list for Ansible that contains a list of tasks." }, { "code": null, "e": 2327, "s": 2142, "text": "Playbooks contain the steps which the user wants to execute on a particular machine. Playbooks are run sequentially. Playbooks are the building blocks for all the use cases of Ansible." }, { "code": null, "e": 2476, "s": 2327, "text": "Each playbook is an aggregation of one or more plays in it. Playbooks are structured using Plays. There can be more than one play inside a playbook." }, { "code": null, "e": 2566, "s": 2476, "text": "The function of a play is to map a set of instructions defined against a particular host." }, { "code": null, "e": 2858, "s": 2566, "text": "YAML is a strict typed language; so, extra care needs to be taken while writing the YAML files. There are different YAML editors but we will prefer to use a simple editor like notepad++. Just open notepad++ and copy and paste the below yaml and change the language to YAML (Language → YAML)." }, { "code": null, "e": 2893, "s": 2858, "text": "A YAML starts with --- (3 hyphens)" }, { "code": null, "e": 2995, "s": 2893, "text": "Let us start by writing a sample YAML file. We will walk through each section written in a yaml file." }, { "code": null, "e": 3308, "s": 2995, "text": "--- \n name: install and configure DB\n hosts: testServer\n become: yes\n\n vars: \n oracle_db_port_value : 1521\n \n tasks:\n -name: Install the Oracle DB\n yum: <code to install the DB>\n \n -name: Ensure the installed service is enabled and running\n service:\n name: <your service name>" }, { "code": null, "e": 3563, "s": 3308, "text": "The above is a sample Playbook where we are trying to cover the basic syntax of a playbook. Save the above content in a file as test.yml. A YAML syntax needs to follow the correct indentation and one needs to be a little careful while writing the syntax." }, { "code": null, "e": 3651, "s": 3563, "text": "Let us now go through the different YAML tags. The different tags are described below −" }, { "code": null, "e": 3791, "s": 3651, "text": "This tag specifies the name of the Ansible playbook. As in what this playbook will be doing. Any logical name can be given to the playbook." }, { "code": null, "e": 4143, "s": 3791, "text": "This tag specifies the lists of hosts or host group against which we want to run the task. The hosts field/tag is mandatory. It tells Ansible on which hosts to run the listed tasks. The tasks can be run on the same machine or on a remote machine. One can run the tasks on multiple machines and hence hosts tag can have a group of hosts’ entry as well." }, { "code": null, "e": 4277, "s": 4143, "text": "Vars tag lets you define the variables which you can use in your playbook. Usage is similar to variables in any programming language." }, { "code": null, "e": 4714, "s": 4277, "text": "All playbooks should contain tasks or a list of tasks to be executed. Tasks are a list of actions one needs to perform. A tasks field contains the name of the task. This works as the help text for the user. It is not mandatory but proves useful in debugging the playbook. Each task internally links to a piece of code called a module. A module that should be executed, and arguments that are required for the module you want to execute." }, { "code": null, "e": 4747, "s": 4714, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 4759, "s": 4747, "text": " AR Shankar" }, { "code": null, "e": 4791, "s": 4759, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 4807, "s": 4791, "text": " Musab Zayadneh" }, { "code": null, "e": 4843, "s": 4807, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 4855, "s": 4843, "text": " Narendra P" }, { "code": null, "e": 4888, "s": 4855, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 4901, "s": 4888, "text": " Sagar Mehta" }, { "code": null, "e": 4934, "s": 4901, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 4947, "s": 4934, "text": " Vikas Yadav" }, { "code": null, "e": 4981, "s": 4947, "text": "\n 4 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4998, "s": 4981, "text": " GreyCampus Inc." }, { "code": null, "e": 5005, "s": 4998, "text": " Print" }, { "code": null, "e": 5016, "s": 5005, "text": " Add Notes" } ]
Customer Case Study: Building an end-to-end Speech Recognition model in PyTorch with AssemblyAI | by Ashley Binford | Towards Data Science
This post was written by Michael Nguyen, Machine Learning Research Engineer at AssemblyAI, and Niko Laskaris at Comet.ml. AssemblyAI uses Comet to log, visualize, and understand their model development pipeline. Deep Learning has changed the game in speech recognition with the introduction of end-to-end models. These models take in audio, and directly output transcriptions. Two of the most popular end-to-end models today are Deep Speech by Baidu, and Listen Attend Spell (LAS) by Google. Both Deep Speech and LAS, are recurrent neural network (RNN) based architectures with different approaches to modeling speech recognition. Deep Speech uses the Connectionist Temporal Classification (CTC) loss function to predict the speech transcript. LAS uses a sequence to sequence network architecture for its predictions. These models simplified speech recognition pipelines by taking advantage of the capacity of deep learning system to learn from large datasets. With enough data, you should, in theory, be able to build a super robust speech recognition model that can account for all the nuance in speech without having to spend a ton of time and effort hand engineering acoustic features or dealing with complex pipelines in more old-school GMM-HMM model architectures, for example. Deep learning is a fast-moving field, and Deep Speech and LAS style architectures are already quickly becoming outdated. You can read about where the industry is moving in the Latest Advancement Section below. Let’s walk through how one would build their own end-to-end speech recognition model in PyTorch. The model we’ll build is inspired by Deep Speech 2 (Baidu’s second revision of their now-famous model) with some personal improvements to the architecture. The output of the model will be a probability matrix of characters, and we’ll use that probability matrix to decode the most likely characters spoken from the audio. You can find the full code and also run the it with GPU support on Google Colaboratory. Data is one of the most important aspects of speech recognition. We’ll take raw audio waves and transform them into Mel Spectrograms. You can read more on the details about how that transformation looks from this excellent post here. For this post, you can just think of a Mel Spectrogram as essentially a picture of sound. For handling the audio data, we are going to use an extremely useful utility called torchaudio which is a library built by the PyTorch team specifically for audio data. We’ll be training on a subset of LibriSpeech, which is a corpus of read English speech data derived from audiobooks, comprising 100 hours of transcribed audio data. You can easily download this dataset using torchaudio: import torchaudio train_dataset = torchaudio.datasets.LIBRISPEECH("./", url="train-clean-100", download=True) test_dataset = torchaudio.datasets.LIBRISPEECH("./", url="test-clean", download=True) Each sample of the dataset contains the waveform, sample rate of audio, the utterance/label, and more metadata on the sample. You can view what each sample looks like from the source code here. Data augmentation is a technique used to artificially increase the diversity of your dataset in order to increase your dataset size. This strategy is especially helpful when data is scarce or if your model is overfitting. For speech recognition, you can do the standard augmentation techniques, like changing the pitch, speed, injecting noise, and adding reverb to your audio data. We found Spectrogram Augmentation (SpecAugment), to be a much simpler and more effective approach. SpecAugment, was first introduced in the paper SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition, in which the authors found that simply cutting out random blocks of consecutive time and frequency dimensions improved the models generalization abilities significantly! In PyTorch, you can use the torchaudio function FrequencyMasking to mask out the frequency dimension, and TimeMasking for the time dimension. torchaudio.transforms.FrequencyMasking()torchaudio.transforms.TimeMasking() Now that we have the data, we’ll need to transform the audio into Mel Spectrograms, and map the character labels for each audio sample into integer labels: class TextTransform: """Maps characters to integers and vice versa""" def __init__(self): char_map_str = """ ' 0 <SPACE> 1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i 10 j 11 k 12 l 13 m 14 n 15 o 16 p 17 q 18 r 19 s 20 t 21 u 22 v 23 w 24 x 25 y 26 z 27 """ self.char_map = {} self.index_map = {} for line in char_map_str.strip().split('\n'): ch, index = line.split() self.char_map[ch] = int(index) self.index_map[int(index)] = ch self.index_map[1] = ' 'def text_to_int(self, text): """ Use a character map and convert text to an integer sequence """ int_sequence = [] for c in text: if c == ' ': ch = self.char_map[''] else: ch = self.char_map[c] int_sequence.append(ch) return int_sequencedef int_to_text(self, labels): """ Use a character map and convert integer labels to an text sequence """ string = [] for i in labels: string.append(self.index_map[i]) return ''.join(string).replace('', ' ')train_audio_transforms = nn.Sequential( torchaudio.transforms.MelSpectrogram(sample_rate=16000, n_mels=128), torchaudio.transforms.FrequencyMasking(freq_mask_param=15), torchaudio.transforms.TimeMasking(time_mask_param=35))valid_audio_transforms = torchaudio.transforms.MelSpectrogram()text_transform = TextTransform()def data_processing(data, data_type="train"): spectrograms = [] labels = [] input_lengths = [] label_lengths = [] for (waveform, _, utterance, _, _, _) in data: if data_type == 'train': spec = train_audio_transforms(waveform).squeeze(0).transpose(0, 1) else: spec = valid_audio_transforms(waveform).squeeze(0).transpose(0, 1) spectrograms.append(spec) label = torch.Tensor(text_transform.text_to_int(utterance.lower())) labels.append(label) input_lengths.append(spec.shape[0]//2) label_lengths.append(len(label))spectrograms = nn.utils.rnn.pad_sequence(spectrograms, batch_first=True).unsqueeze(1).transpose(2, 3) labels = nn.utils.rnn.pad_sequence(labels, batch_first=True)return spectrograms, labels, input_lengths, label_lengths Our model will be similar to the Deep Speech 2 architecture. The model will have two main neural network modules — N layers of Residual Convolutional Neural Networks (ResCNN) to learn the relevant audio features, and a set of Bidirectional Recurrent Neural Networks (BiRNN) to leverage the learned ResCNN audio features. The model is topped off with a fully connected layer used to classify characters per time step. Convolutional Neural Networks (CNN) are great at extracting abstract features, and we’ll apply the same feature extraction power to audio spectrograms. Instead of just vanilla CNN layers, we choose to use Residual CNN layers. Residual connections (AKA skip connections) were first introduced in the paper Deep Residual Learning for Image Recognition, where the author found that you can build really deep networks with good accuracy gains if you add these connections to your CNN’s. Adding these Residual connections also helps the model learn faster and generalize better. The paper Visualizing the Loss Landscape of Neural Nets shows that networks with residual connections have a “flatter” loss surface, making it easier for models to navigate the loss landscape and find a lower and more generalizable minima. Recurrent Neural Networks (RNN) are naturally great at sequence modeling problems. RNN’s processes the audio features step by step, making a prediction for each frame while using context from previous frames. We use BiRNN’s because we want the context of not only the frame before each step, but the frames after it as well. This can help the model make better predictions, as each frame in the audio will have more information before making a prediction. We use Gated Recurrent Unit (GRU’s) variant of RNN’s as it needs less computational resources than LSTM’s, and works just as well in some cases. The model outputs a probability matrix for characters which we’ll use to feed into our decoder to extract what the model believes are the highest probability characters that were spoken. class CNNLayerNorm(nn.Module): """Layer normalization built for cnns input""" def __init__(self, n_feats): super(CNNLayerNorm, self).__init__() self.layer_norm = nn.LayerNorm(n_feats)def forward(self, x): # x (batch, channel, feature, time) x = x.transpose(2, 3).contiguous() # (batch, channel, time, feature) x = self.layer_norm(x) return x.transpose(2, 3).contiguous() # (batch, channel, feature, time)class ResidualCNN(nn.Module): """Residual CNN inspired by https://arxiv.org/pdf/1603.05027.pdf except with layer norm instead of batch norm """ def __init__(self, in_channels, out_channels, kernel, stride, dropout, n_feats): super(ResidualCNN, self).__init__()self.cnn1 = nn.Conv2d(in_channels, out_channels, kernel, stride, padding=kernel//2) self.cnn2 = nn.Conv2d(out_channels, out_channels, kernel, stride, padding=kernel//2) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.layer_norm1 = CNNLayerNorm(n_feats) self.layer_norm2 = CNNLayerNorm(n_feats)def forward(self, x): residual = x # (batch, channel, feature, time) x = self.layer_norm1(x) x = F.gelu(x) x = self.dropout1(x) x = self.cnn1(x) x = self.layer_norm2(x) x = F.gelu(x) x = self.dropout2(x) x = self.cnn2(x) x += residual return x # (batch, channel, feature, time)class BidirectionalGRU(nn.Module):def __init__(self, rnn_dim, hidden_size, dropout, batch_first): super(BidirectionalGRU, self).__init__()self.BiGRU = nn.GRU( input_size=rnn_dim, hidden_size=hidden_size, num_layers=1, batch_first=batch_first, bidirectional=True) self.layer_norm = nn.LayerNorm(rnn_dim) self.dropout = nn.Dropout(dropout)def forward(self, x): x = self.layer_norm(x) x = F.gelu(x) x, _ = self.BiGRU(x) x = self.dropout(x) return xclass SpeechRecognitionModel(nn.Module): """Speech Recognition Model Inspired by DeepSpeech 2"""def __init__(self, n_cnn_layers, n_rnn_layers, rnn_dim, n_class, n_feats, stride=2, dropout=0.1): super(SpeechRecognitionModel, self).__init__() n_feats = n_feats//2 self.cnn = nn.Conv2d(1, 32, 3, stride=stride, padding=3//2) # cnn for extracting heirachal features# n residual cnn layers with filter size of 32 self.rescnn_layers = nn.Sequential(*[ ResidualCNN(32, 32, kernel=3, stride=1, dropout=dropout, n_feats=n_feats) for _ in range(n_cnn_layers) ]) self.fully_connected = nn.Linear(n_feats*32, rnn_dim) self.birnn_layers = nn.Sequential(*[ BidirectionalGRU(rnn_dim=rnn_dim if i==0 else rnn_dim*2, hidden_size=rnn_dim, dropout=dropout, batch_first=i==0) for i in range(n_rnn_layers) ]) self.classifier = nn.Sequential( nn.Linear(rnn_dim*2, rnn_dim), # birnn returns rnn_dim*2 nn.GELU(), nn.Dropout(dropout), nn.Linear(rnn_dim, n_class) )def forward(self, x): x = self.cnn(x) x = self.rescnn_layers(x) sizes = x.size() x = x.view(sizes[0], sizes[1] * sizes[2], sizes[3]) # (batch, feature, time) x = x.transpose(1, 2) # (batch, time, feature) x = self.fully_connected(x) x = self.birnn_layers(x) x = self.classifier(x) return x The optimizer and learning rate schedule plays a very important role in getting our model to converge to the best point. Picking the right optimizer and scheduler can also save you compute time, and help your model generalize better to real-world use cases. For our model, we’ll be using AdamW with the One Cycle Learning Rate Scheduler. Adam is a widely used optimizer that helps your model converge more quickly, therefore, saving compute time, but has been notorious for not generalizing as well as Stochastic Gradient Descent AKA SGD. AdamW was first introduced in Decoupled Weight Decay Regularization, and is considered a “fix” to Adam. The paper pointed out that the original Adam algorithm has a wrong implementation of weight decay, which AdamW attempts to fix. This fix helps with Adam ‘s generalization problem. The One Cycle Learning Rate Scheduler was first introduced in the paper Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates. This paper shows that you can train neural networks an order of magnitude faster, while keeping their generalizable abilities, using a simple trick. You start with a low learning rate, which warms up to a large maximum learning rate, then decays linearly to the same point of where you originally started. Because the maximum learning rate is magnitudes higher than the lowest, you also gain some regularization benefits which helps your model generalize better if you have a smaller set of data. With PyTorch, these two methods are already part of the package. optimizer = optim.AdamW(model.parameters(), hparams['learning_rate'])scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=hparams['learning_rate'], steps_per_epoch=int(len(train_loader)), epochs=hparams['epochs'], anneal_strategy='linear') Our model will be trained to predict the probability distribution of all characters in the alphabet for each frame (ie, timestep) in the spectrogram we feed into the model. Traditional speech recognition models would require you to align the transcript text to the audio before training, and the model would be trained to predict specific labels at specific frames. The innovation of the CTC loss function is that it allows us to skip this step. Our model will learn to align the transcript itself during training. The key to this is the “blank” label introduced by CTC, which gives the model the ability to say that a certain audio frame did not produce a character. You can see a more detailed explanation of CTC and how it works from this excellent post. The CTC loss function is also built into PyTorch. criterion = nn.CTCLoss(blank=28).to(device) When Evaluating your speech recognition model, the industry standard is using the Word Error Rate (WER) as the metric. The Word Error Rate does exactly what it says — it takes the transcription your model outputs, and the true transcription, and measures the error between them. You can see how that’s implemented here. Another useful metric is called the Character Error Rate (CER). The CER measures the error of the characters between the model’s output and the true labels. These metrics are helpful to measure how well your model performs. For this tutorial, we’ll use a “greedy” decoding method to process our model’s output into characters that can be combined to create the transcript. A “greedy” decoder takes in the model output, which is a softmax probability matrix of characters, and for each time step (spectrogram frame), it chooses the label with the highest probability. If the label is a blank label, we remove it from the final transcript. def GreedyDecoder(output, labels, label_lengths, blank_label=28, collapse_repeated=True): arg_maxes = torch.argmax(output, dim=2) decodes = [] targets = [] for i, args in enumerate(arg_maxes): decode = [] targets.append(text_transform.int_to_text(labels[i][:label_lengths[i]].tolist())) for j, index in enumerate(args): if index != blank_label: if collapse_repeated and j != 0 and index == args[j -1]: continue decode.append(index.item()) decodes.append(text_transform.int_to_text(decode)) return decodes, targets Comet.ml provides a platform that allows deep learning researchers to track, compare, explain, and optimize their experiments and models. Comet.ml has improved our productivity at AssemblyAI and we highly recommend using this platform for teams doing any sort of data science experiments. Comet.ml is super easy to set up. And works with just a few lines of code. # initialize experiment objectexperiment = Experiment(api_key=comet_api_key, project_name=project_name)experiment.set_name(exp_name)# track metricsexperiment.log_metric('loss', loss.item()) Comet.ml provides you with a very productive dashboard where you can view and track your model’s progress. You can use Comet to track metrics, code, hyper parameters, your model’s graphs, among many other things! A really handy feature that Comet provides is the ability to compare your experiment among many other experiments. Comet has a rich feature set that we won’t cover all here, but we highly recommended using it for a productivity and sanity boost. Here is the rest of our training script. class IterMeter(object): """keeps track of total iterations""" def __init__(self): self.val = 0def step(self): self.val += 1def get(self): return self.valdef train(model, device, train_loader, criterion, optimizer, scheduler, epoch, iter_meter, experiment): model.train() data_len = len(train_loader.dataset) with experiment.train(): for batch_idx, _data in enumerate(train_loader): spectrograms, labels, input_lengths, label_lengths = _data spectrograms, labels = spectrograms.to(device), labels.to(device)optimizer.zero_grad()output = model(spectrograms) # (batch, time, n_class) output = F.log_softmax(output, dim=2) output = output.transpose(0, 1) # (time, batch, n_class)loss = criterion(output, labels, input_lengths, label_lengths) loss.backward()experiment.log_metric('loss', loss.item(), step=iter_meter.get()) experiment.log_metric('learning_rate', scheduler.get_lr(), step=iter_meter.get())optimizer.step() scheduler.step() iter_meter.step() if batch_idx % 100 == 0 or batch_idx == data_len: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(spectrograms), data_len, 100. * batch_idx / len(train_loader), loss.item()))def test(model, device, test_loader, criterion, epoch, iter_meter, experiment): print('\nevaluating...') model.eval() test_loss = 0 test_cer, test_wer = [], [] with experiment.test(): with torch.no_grad(): for I, _data in enumerate(test_loader): spectrograms, labels, input_lengths, label_lengths = _data spectrograms, labels = spectrograms.to(device), labels.to(device)output = model(spectrograms) # (batch, time, n_class) output = F.log_softmax(output, dim=2) output = output.transpose(0, 1) # (time, batch, n_class)loss = criterion(output, labels, input_lengths, label_lengths) test_loss += loss.item() / len(test_loader)decoded_preds, decoded_targets = GreedyDecoder(output.transpose(0, 1), labels, label_lengths) for j in range(len(decoded_preds)): test_cer.append(cer(decoded_targets[j], decoded_preds[j])) test_wer.append(wer(decoded_targets[j], decoded_preds[j]))avg_cer = sum(test_cer)/len(test_cer) avg_wer = sum(test_wer)/len(test_wer) experiment.log_metric('test_loss', test_loss, step=iter_meter.get()) experiment.log_metric('cer', avg_cer, step=iter_meter.get()) experiment.log_metric('wer', avg_wer, step=iter_meter.get())print('Test set: Average loss: {:.4f}, Average CER: {:4f} Average WER: {:.4f}\n'.format(test_loss, avg_cer, avg_wer))def main(learning_rate=5e-4, batch_size=20, epochs=10, train_url="train-clean-100", test_url="test-clean", experiment=Experiment(api_key='dummy_key', disabled=True)):hparams = { "n_cnn_layers": 3, "n_rnn_layers": 5, "rnn_dim": 512, "n_class": 29, "n_feats": 128, "stride": 2, "dropout": 0.1, "learning_rate": learning_rate, "batch_size": batch_size, "epochs": epochs }experiment.log_parameters(hparams)use_cuda = torch.cuda.is_available() torch.manual_seed(7) device = torch.device("cuda" if use_cuda else "cpu")if not os.path.isdir("./data"): os.makedirs("./data")train_dataset = torchaudio.datasets.LIBRISPEECH("./data", url=train_url, download=True) test_dataset = torchaudio.datasets.LIBRISPEECH("./data", url=test_url, download=True)kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {} train_loader = data.DataLoader(dataset=train_dataset, batch_size=hparams['batch_size'], shuffle=True, collate_fn=lambda x: data_processing(x, 'train'), **kwargs) test_loader = data.DataLoader(dataset=test_dataset, batch_size=hparams['batch_size'], shuffle=False, collate_fn=lambda x: data_processing(x, 'valid'), **kwargs)model = SpeechRecognitionModel( hparams['n_cnn_layers'], hparams['n_rnn_layers'], hparams['rnn_dim'], hparams['n_class'], hparams['n_feats'], hparams['stride'], hparams['dropout'] ).to(device)print(model) print('Num Model Parameters', sum([param.nelement() for param in model.parameters()]))optimizer = optim.AdamW(model.parameters(), hparams['learning_rate']) criterion = nn.CTCLoss(blank=28).to(device) scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=hparams['learning_rate'], steps_per_epoch=int(len(train_loader)), epochs=hparams['epochs'], anneal_strategy='linear')iter_meter = IterMeter() for epoch in range(1, epochs + 1): train(model, device, train_loader, criterion, optimizer, scheduler, epoch, iter_meter, experiment) test(model, device, test_loader, criterion, epoch, iter_meter, experiment) The train function trains the model on a full epoch of data. The test function evaluates the model on test data after every epoch. It gets the test_loss as well as the cer and wer of the model. You can start running the training script right now with GPU support in the Google Colaboratory. Speech Recognition Requires a ton of data and a ton of compute resources. The example laid out is trained on a subset of LibriSpeech (100 hours of audio) and a single GPU. To get state of the art results you’ll need to do distributed training on thousands of hours of data, on tens of GPU’s spread out across many machines. Another way to get a big accuracy improvement is to decode the CTC probability matrix using a Language Model and the CTC beam search algorithm. CTC type models are very dependent on this decoding process to get good results. Luckily there is a handy open source library that allows you to do that. This tutorial was made to be more accessible so it’s a relatively small model (23 million Parameters) compared to something like BERT (340 million Parameters). It seems to be the larger you can get your network, the better it performs, although there are diminishing returns. A larger model equating to better performance is not always the case though, as proven by OpenAI’s research Deep Double Descent. This model has 3 residual CNN layers and 5 Bidirectional GRU layers which should allow you to train a reasonable batch size on a single GPU with at least 11GB of memory. You can tweak some of the hyper parameters in the main function to reduce or increase the model size for your use case and compute availability. Deep learning is a fast-moving field. It seems like you can’t go a week without some new technique getting state of the art results. Here are a few of things worth exploring int the world of speech recognition. Transformers have taken the Natural Language Processing world by storm! First Introduced in the paper Attention Is All You Need, transformers have been taking and modified to beat pretty much all existing NLP task dethroning RNN’s type architectures. The Transformer’s ability to see the full context of sequence data is transferable to speech as well. If you follow deep learning closely you’ve probably heard of BERT, GPT, and GPT2. These Transformer models have first pertained on a language modeling task with unlabeled text data, and fine-tuned on a wide array of NLP task and get state of the art results! During pre-training, the model learns something fundamental on the statistics of language and uses that power to excel at other tasks. We believe this technique has great promises on speech data as well. Our model defined above output characters. Some benefits to that are the model doesn’t have to worry about out of vocabulary words when running inference on speech. So for the word c h a t each character has is its own label. The downside to using characters are inefficiency and the model being prone to more errors because you’re predicting one character at a time. Using the whole word as labels have been explored, to some degree of success. Using this method, the entire word chat would be the label. But using whole words, you would have to keep an index of all possible vocabularies to make a prediction, which is memory inefficient with the possibility of running into out of vocabulary words during prediction. The sweet spot would be using word piece or sub-word units as labels. Instead of characters for the individual label, you can chop up the words into sub-word units, and use those as labels, i.e. ch at. This solves the out of vocabulary issue, and is much more efficient, as it needs fewer steps to decode then using characters, and without the need to have an index of all possible words. Word pieces have been used successfully with many NLP models, like BERT and would work natural with speech recognition problems as well.
[ { "code": null, "e": 384, "s": 172, "text": "This post was written by Michael Nguyen, Machine Learning Research Engineer at AssemblyAI, and Niko Laskaris at Comet.ml. AssemblyAI uses Comet to log, visualize, and understand their model development pipeline." }, { "code": null, "e": 990, "s": 384, "text": "Deep Learning has changed the game in speech recognition with the introduction of end-to-end models. These models take in audio, and directly output transcriptions. Two of the most popular end-to-end models today are Deep Speech by Baidu, and Listen Attend Spell (LAS) by Google. Both Deep Speech and LAS, are recurrent neural network (RNN) based architectures with different approaches to modeling speech recognition. Deep Speech uses the Connectionist Temporal Classification (CTC) loss function to predict the speech transcript. LAS uses a sequence to sequence network architecture for its predictions." }, { "code": null, "e": 1456, "s": 990, "text": "These models simplified speech recognition pipelines by taking advantage of the capacity of deep learning system to learn from large datasets. With enough data, you should, in theory, be able to build a super robust speech recognition model that can account for all the nuance in speech without having to spend a ton of time and effort hand engineering acoustic features or dealing with complex pipelines in more old-school GMM-HMM model architectures, for example." }, { "code": null, "e": 1666, "s": 1456, "text": "Deep learning is a fast-moving field, and Deep Speech and LAS style architectures are already quickly becoming outdated. You can read about where the industry is moving in the Latest Advancement Section below." }, { "code": null, "e": 2173, "s": 1666, "text": "Let’s walk through how one would build their own end-to-end speech recognition model in PyTorch. The model we’ll build is inspired by Deep Speech 2 (Baidu’s second revision of their now-famous model) with some personal improvements to the architecture. The output of the model will be a probability matrix of characters, and we’ll use that probability matrix to decode the most likely characters spoken from the audio. You can find the full code and also run the it with GPU support on Google Colaboratory." }, { "code": null, "e": 2307, "s": 2173, "text": "Data is one of the most important aspects of speech recognition. We’ll take raw audio waves and transform them into Mel Spectrograms." }, { "code": null, "e": 2497, "s": 2307, "text": "You can read more on the details about how that transformation looks from this excellent post here. For this post, you can just think of a Mel Spectrogram as essentially a picture of sound." }, { "code": null, "e": 2886, "s": 2497, "text": "For handling the audio data, we are going to use an extremely useful utility called torchaudio which is a library built by the PyTorch team specifically for audio data. We’ll be training on a subset of LibriSpeech, which is a corpus of read English speech data derived from audiobooks, comprising 100 hours of transcribed audio data. You can easily download this dataset using torchaudio:" }, { "code": null, "e": 3082, "s": 2886, "text": "import torchaudio train_dataset = torchaudio.datasets.LIBRISPEECH(\"./\", url=\"train-clean-100\", download=True) test_dataset = torchaudio.datasets.LIBRISPEECH(\"./\", url=\"test-clean\", download=True)" }, { "code": null, "e": 3276, "s": 3082, "text": "Each sample of the dataset contains the waveform, sample rate of audio, the utterance/label, and more metadata on the sample. You can view what each sample looks like from the source code here." }, { "code": null, "e": 3658, "s": 3276, "text": "Data augmentation is a technique used to artificially increase the diversity of your dataset in order to increase your dataset size. This strategy is especially helpful when data is scarce or if your model is overfitting. For speech recognition, you can do the standard augmentation techniques, like changing the pitch, speed, injecting noise, and adding reverb to your audio data." }, { "code": null, "e": 4055, "s": 3658, "text": "We found Spectrogram Augmentation (SpecAugment), to be a much simpler and more effective approach. SpecAugment, was first introduced in the paper SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition, in which the authors found that simply cutting out random blocks of consecutive time and frequency dimensions improved the models generalization abilities significantly!" }, { "code": null, "e": 4197, "s": 4055, "text": "In PyTorch, you can use the torchaudio function FrequencyMasking to mask out the frequency dimension, and TimeMasking for the time dimension." }, { "code": null, "e": 4273, "s": 4197, "text": "torchaudio.transforms.FrequencyMasking()torchaudio.transforms.TimeMasking()" }, { "code": null, "e": 4429, "s": 4273, "text": "Now that we have the data, we’ll need to transform the audio into Mel Spectrograms, and map the character labels for each audio sample into integer labels:" }, { "code": null, "e": 6873, "s": 4429, "text": "class TextTransform: \"\"\"Maps characters to integers and vice versa\"\"\" def __init__(self): char_map_str = \"\"\" ' 0 <SPACE> 1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i 10 j 11 k 12 l 13 m 14 n 15 o 16 p 17 q 18 r 19 s 20 t 21 u 22 v 23 w 24 x 25 y 26 z 27 \"\"\" self.char_map = {} self.index_map = {} for line in char_map_str.strip().split('\\n'): ch, index = line.split() self.char_map[ch] = int(index) self.index_map[int(index)] = ch self.index_map[1] = ' 'def text_to_int(self, text): \"\"\" Use a character map and convert text to an integer sequence \"\"\" int_sequence = [] for c in text: if c == ' ': ch = self.char_map[''] else: ch = self.char_map[c] int_sequence.append(ch) return int_sequencedef int_to_text(self, labels): \"\"\" Use a character map and convert integer labels to an text sequence \"\"\" string = [] for i in labels: string.append(self.index_map[i]) return ''.join(string).replace('', ' ')train_audio_transforms = nn.Sequential( torchaudio.transforms.MelSpectrogram(sample_rate=16000, n_mels=128), torchaudio.transforms.FrequencyMasking(freq_mask_param=15), torchaudio.transforms.TimeMasking(time_mask_param=35))valid_audio_transforms = torchaudio.transforms.MelSpectrogram()text_transform = TextTransform()def data_processing(data, data_type=\"train\"): spectrograms = [] labels = [] input_lengths = [] label_lengths = [] for (waveform, _, utterance, _, _, _) in data: if data_type == 'train': spec = train_audio_transforms(waveform).squeeze(0).transpose(0, 1) else: spec = valid_audio_transforms(waveform).squeeze(0).transpose(0, 1) spectrograms.append(spec) label = torch.Tensor(text_transform.text_to_int(utterance.lower())) labels.append(label) input_lengths.append(spec.shape[0]//2) label_lengths.append(len(label))spectrograms = nn.utils.rnn.pad_sequence(spectrograms, batch_first=True).unsqueeze(1).transpose(2, 3) labels = nn.utils.rnn.pad_sequence(labels, batch_first=True)return spectrograms, labels, input_lengths, label_lengths" }, { "code": null, "e": 7290, "s": 6873, "text": "Our model will be similar to the Deep Speech 2 architecture. The model will have two main neural network modules — N layers of Residual Convolutional Neural Networks (ResCNN) to learn the relevant audio features, and a set of Bidirectional Recurrent Neural Networks (BiRNN) to leverage the learned ResCNN audio features. The model is topped off with a fully connected layer used to classify characters per time step." }, { "code": null, "e": 8104, "s": 7290, "text": "Convolutional Neural Networks (CNN) are great at extracting abstract features, and we’ll apply the same feature extraction power to audio spectrograms. Instead of just vanilla CNN layers, we choose to use Residual CNN layers. Residual connections (AKA skip connections) were first introduced in the paper Deep Residual Learning for Image Recognition, where the author found that you can build really deep networks with good accuracy gains if you add these connections to your CNN’s. Adding these Residual connections also helps the model learn faster and generalize better. The paper Visualizing the Loss Landscape of Neural Nets shows that networks with residual connections have a “flatter” loss surface, making it easier for models to navigate the loss landscape and find a lower and more generalizable minima." }, { "code": null, "e": 8705, "s": 8104, "text": "Recurrent Neural Networks (RNN) are naturally great at sequence modeling problems. RNN’s processes the audio features step by step, making a prediction for each frame while using context from previous frames. We use BiRNN’s because we want the context of not only the frame before each step, but the frames after it as well. This can help the model make better predictions, as each frame in the audio will have more information before making a prediction. We use Gated Recurrent Unit (GRU’s) variant of RNN’s as it needs less computational resources than LSTM’s, and works just as well in some cases." }, { "code": null, "e": 8892, "s": 8705, "text": "The model outputs a probability matrix for characters which we’ll use to feed into our decoder to extract what the model believes are the highest probability characters that were spoken." }, { "code": null, "e": 12347, "s": 8892, "text": "class CNNLayerNorm(nn.Module): \"\"\"Layer normalization built for cnns input\"\"\" def __init__(self, n_feats): super(CNNLayerNorm, self).__init__() self.layer_norm = nn.LayerNorm(n_feats)def forward(self, x): # x (batch, channel, feature, time) x = x.transpose(2, 3).contiguous() # (batch, channel, time, feature) x = self.layer_norm(x) return x.transpose(2, 3).contiguous() # (batch, channel, feature, time)class ResidualCNN(nn.Module): \"\"\"Residual CNN inspired by https://arxiv.org/pdf/1603.05027.pdf except with layer norm instead of batch norm \"\"\" def __init__(self, in_channels, out_channels, kernel, stride, dropout, n_feats): super(ResidualCNN, self).__init__()self.cnn1 = nn.Conv2d(in_channels, out_channels, kernel, stride, padding=kernel//2) self.cnn2 = nn.Conv2d(out_channels, out_channels, kernel, stride, padding=kernel//2) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.layer_norm1 = CNNLayerNorm(n_feats) self.layer_norm2 = CNNLayerNorm(n_feats)def forward(self, x): residual = x # (batch, channel, feature, time) x = self.layer_norm1(x) x = F.gelu(x) x = self.dropout1(x) x = self.cnn1(x) x = self.layer_norm2(x) x = F.gelu(x) x = self.dropout2(x) x = self.cnn2(x) x += residual return x # (batch, channel, feature, time)class BidirectionalGRU(nn.Module):def __init__(self, rnn_dim, hidden_size, dropout, batch_first): super(BidirectionalGRU, self).__init__()self.BiGRU = nn.GRU( input_size=rnn_dim, hidden_size=hidden_size, num_layers=1, batch_first=batch_first, bidirectional=True) self.layer_norm = nn.LayerNorm(rnn_dim) self.dropout = nn.Dropout(dropout)def forward(self, x): x = self.layer_norm(x) x = F.gelu(x) x, _ = self.BiGRU(x) x = self.dropout(x) return xclass SpeechRecognitionModel(nn.Module): \"\"\"Speech Recognition Model Inspired by DeepSpeech 2\"\"\"def __init__(self, n_cnn_layers, n_rnn_layers, rnn_dim, n_class, n_feats, stride=2, dropout=0.1): super(SpeechRecognitionModel, self).__init__() n_feats = n_feats//2 self.cnn = nn.Conv2d(1, 32, 3, stride=stride, padding=3//2) # cnn for extracting heirachal features# n residual cnn layers with filter size of 32 self.rescnn_layers = nn.Sequential(*[ ResidualCNN(32, 32, kernel=3, stride=1, dropout=dropout, n_feats=n_feats) for _ in range(n_cnn_layers) ]) self.fully_connected = nn.Linear(n_feats*32, rnn_dim) self.birnn_layers = nn.Sequential(*[ BidirectionalGRU(rnn_dim=rnn_dim if i==0 else rnn_dim*2, hidden_size=rnn_dim, dropout=dropout, batch_first=i==0) for i in range(n_rnn_layers) ]) self.classifier = nn.Sequential( nn.Linear(rnn_dim*2, rnn_dim), # birnn returns rnn_dim*2 nn.GELU(), nn.Dropout(dropout), nn.Linear(rnn_dim, n_class) )def forward(self, x): x = self.cnn(x) x = self.rescnn_layers(x) sizes = x.size() x = x.view(sizes[0], sizes[1] * sizes[2], sizes[3]) # (batch, feature, time) x = x.transpose(1, 2) # (batch, time, feature) x = self.fully_connected(x) x = self.birnn_layers(x) x = self.classifier(x) return x" }, { "code": null, "e": 12886, "s": 12347, "text": "The optimizer and learning rate schedule plays a very important role in getting our model to converge to the best point. Picking the right optimizer and scheduler can also save you compute time, and help your model generalize better to real-world use cases. For our model, we’ll be using AdamW with the One Cycle Learning Rate Scheduler. Adam is a widely used optimizer that helps your model converge more quickly, therefore, saving compute time, but has been notorious for not generalizing as well as Stochastic Gradient Descent AKA SGD." }, { "code": null, "e": 13170, "s": 12886, "text": "AdamW was first introduced in Decoupled Weight Decay Regularization, and is considered a “fix” to Adam. The paper pointed out that the original Adam algorithm has a wrong implementation of weight decay, which AdamW attempts to fix. This fix helps with Adam ‘s generalization problem." }, { "code": null, "e": 13633, "s": 13170, "text": "The One Cycle Learning Rate Scheduler was first introduced in the paper Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates. This paper shows that you can train neural networks an order of magnitude faster, while keeping their generalizable abilities, using a simple trick. You start with a low learning rate, which warms up to a large maximum learning rate, then decays linearly to the same point of where you originally started." }, { "code": null, "e": 13824, "s": 13633, "text": "Because the maximum learning rate is magnitudes higher than the lowest, you also gain some regularization benefits which helps your model generalize better if you have a smaller set of data." }, { "code": null, "e": 13889, "s": 13824, "text": "With PyTorch, these two methods are already part of the package." }, { "code": null, "e": 14136, "s": 13889, "text": "optimizer = optim.AdamW(model.parameters(), hparams['learning_rate'])scheduler = optim.lr_scheduler.OneCycleLR(optimizer,\tmax_lr=hparams['learning_rate'],\tsteps_per_epoch=int(len(train_loader)),\tepochs=hparams['epochs'],\tanneal_strategy='linear')" }, { "code": null, "e": 14309, "s": 14136, "text": "Our model will be trained to predict the probability distribution of all characters in the alphabet for each frame (ie, timestep) in the spectrogram we feed into the model." }, { "code": null, "e": 14502, "s": 14309, "text": "Traditional speech recognition models would require you to align the transcript text to the audio before training, and the model would be trained to predict specific labels at specific frames." }, { "code": null, "e": 14894, "s": 14502, "text": "The innovation of the CTC loss function is that it allows us to skip this step. Our model will learn to align the transcript itself during training. The key to this is the “blank” label introduced by CTC, which gives the model the ability to say that a certain audio frame did not produce a character. You can see a more detailed explanation of CTC and how it works from this excellent post." }, { "code": null, "e": 14944, "s": 14894, "text": "The CTC loss function is also built into PyTorch." }, { "code": null, "e": 14988, "s": 14944, "text": "criterion = nn.CTCLoss(blank=28).to(device)" }, { "code": null, "e": 15532, "s": 14988, "text": "When Evaluating your speech recognition model, the industry standard is using the Word Error Rate (WER) as the metric. The Word Error Rate does exactly what it says — it takes the transcription your model outputs, and the true transcription, and measures the error between them. You can see how that’s implemented here. Another useful metric is called the Character Error Rate (CER). The CER measures the error of the characters between the model’s output and the true labels. These metrics are helpful to measure how well your model performs." }, { "code": null, "e": 15946, "s": 15532, "text": "For this tutorial, we’ll use a “greedy” decoding method to process our model’s output into characters that can be combined to create the transcript. A “greedy” decoder takes in the model output, which is a softmax probability matrix of characters, and for each time step (spectrogram frame), it chooses the label with the highest probability. If the label is a blank label, we remove it from the final transcript." }, { "code": null, "e": 16563, "s": 15946, "text": "def GreedyDecoder(output, labels, label_lengths, blank_label=28, collapse_repeated=True): arg_maxes = torch.argmax(output, dim=2) decodes = [] targets = [] for i, args in enumerate(arg_maxes): decode = [] targets.append(text_transform.int_to_text(labels[i][:label_lengths[i]].tolist())) for j, index in enumerate(args): if index != blank_label: if collapse_repeated and j != 0 and index == args[j -1]: continue decode.append(index.item()) decodes.append(text_transform.int_to_text(decode)) return decodes, targets" }, { "code": null, "e": 16927, "s": 16563, "text": "Comet.ml provides a platform that allows deep learning researchers to track, compare, explain, and optimize their experiments and models. Comet.ml has improved our productivity at AssemblyAI and we highly recommend using this platform for teams doing any sort of data science experiments. Comet.ml is super easy to set up. And works with just a few lines of code." }, { "code": null, "e": 17117, "s": 16927, "text": "# initialize experiment objectexperiment = Experiment(api_key=comet_api_key, project_name=project_name)experiment.set_name(exp_name)# track metricsexperiment.log_metric('loss', loss.item())" }, { "code": null, "e": 17224, "s": 17117, "text": "Comet.ml provides you with a very productive dashboard where you can view and track your model’s progress." }, { "code": null, "e": 17445, "s": 17224, "text": "You can use Comet to track metrics, code, hyper parameters, your model’s graphs, among many other things! A really handy feature that Comet provides is the ability to compare your experiment among many other experiments." }, { "code": null, "e": 17576, "s": 17445, "text": "Comet has a rich feature set that we won’t cover all here, but we highly recommended using it for a productivity and sanity boost." }, { "code": null, "e": 17617, "s": 17576, "text": "Here is the rest of our training script." }, { "code": null, "e": 22887, "s": 17617, "text": "class IterMeter(object): \"\"\"keeps track of total iterations\"\"\" def __init__(self): self.val = 0def step(self): self.val += 1def get(self): return self.valdef train(model, device, train_loader, criterion, optimizer, scheduler, epoch, iter_meter, experiment): model.train() data_len = len(train_loader.dataset) with experiment.train(): for batch_idx, _data in enumerate(train_loader): spectrograms, labels, input_lengths, label_lengths = _data spectrograms, labels = spectrograms.to(device), labels.to(device)optimizer.zero_grad()output = model(spectrograms) # (batch, time, n_class) output = F.log_softmax(output, dim=2) output = output.transpose(0, 1) # (time, batch, n_class)loss = criterion(output, labels, input_lengths, label_lengths) loss.backward()experiment.log_metric('loss', loss.item(), step=iter_meter.get()) experiment.log_metric('learning_rate', scheduler.get_lr(), step=iter_meter.get())optimizer.step() scheduler.step() iter_meter.step() if batch_idx % 100 == 0 or batch_idx == data_len: print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format( epoch, batch_idx * len(spectrograms), data_len, 100. * batch_idx / len(train_loader), loss.item()))def test(model, device, test_loader, criterion, epoch, iter_meter, experiment): print('\\nevaluating...') model.eval() test_loss = 0 test_cer, test_wer = [], [] with experiment.test(): with torch.no_grad(): for I, _data in enumerate(test_loader): spectrograms, labels, input_lengths, label_lengths = _data spectrograms, labels = spectrograms.to(device), labels.to(device)output = model(spectrograms) # (batch, time, n_class) output = F.log_softmax(output, dim=2) output = output.transpose(0, 1) # (time, batch, n_class)loss = criterion(output, labels, input_lengths, label_lengths) test_loss += loss.item() / len(test_loader)decoded_preds, decoded_targets = GreedyDecoder(output.transpose(0, 1), labels, label_lengths) for j in range(len(decoded_preds)): test_cer.append(cer(decoded_targets[j], decoded_preds[j])) test_wer.append(wer(decoded_targets[j], decoded_preds[j]))avg_cer = sum(test_cer)/len(test_cer) avg_wer = sum(test_wer)/len(test_wer) experiment.log_metric('test_loss', test_loss, step=iter_meter.get()) experiment.log_metric('cer', avg_cer, step=iter_meter.get()) experiment.log_metric('wer', avg_wer, step=iter_meter.get())print('Test set: Average loss: {:.4f}, Average CER: {:4f} Average WER: {:.4f}\\n'.format(test_loss, avg_cer, avg_wer))def main(learning_rate=5e-4, batch_size=20, epochs=10, train_url=\"train-clean-100\", test_url=\"test-clean\", experiment=Experiment(api_key='dummy_key', disabled=True)):hparams = { \"n_cnn_layers\": 3, \"n_rnn_layers\": 5, \"rnn_dim\": 512, \"n_class\": 29, \"n_feats\": 128, \"stride\": 2, \"dropout\": 0.1, \"learning_rate\": learning_rate, \"batch_size\": batch_size, \"epochs\": epochs }experiment.log_parameters(hparams)use_cuda = torch.cuda.is_available() torch.manual_seed(7) device = torch.device(\"cuda\" if use_cuda else \"cpu\")if not os.path.isdir(\"./data\"): os.makedirs(\"./data\")train_dataset = torchaudio.datasets.LIBRISPEECH(\"./data\", url=train_url, download=True) test_dataset = torchaudio.datasets.LIBRISPEECH(\"./data\", url=test_url, download=True)kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {} train_loader = data.DataLoader(dataset=train_dataset, batch_size=hparams['batch_size'], shuffle=True, collate_fn=lambda x: data_processing(x, 'train'), **kwargs) test_loader = data.DataLoader(dataset=test_dataset, batch_size=hparams['batch_size'], shuffle=False, collate_fn=lambda x: data_processing(x, 'valid'), **kwargs)model = SpeechRecognitionModel( hparams['n_cnn_layers'], hparams['n_rnn_layers'], hparams['rnn_dim'], hparams['n_class'], hparams['n_feats'], hparams['stride'], hparams['dropout'] ).to(device)print(model) print('Num Model Parameters', sum([param.nelement() for param in model.parameters()]))optimizer = optim.AdamW(model.parameters(), hparams['learning_rate']) criterion = nn.CTCLoss(blank=28).to(device) scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=hparams['learning_rate'], steps_per_epoch=int(len(train_loader)), epochs=hparams['epochs'], anneal_strategy='linear')iter_meter = IterMeter() for epoch in range(1, epochs + 1): train(model, device, train_loader, criterion, optimizer, scheduler, epoch, iter_meter, experiment) test(model, device, test_loader, criterion, epoch, iter_meter, experiment)" }, { "code": null, "e": 23178, "s": 22887, "text": "The train function trains the model on a full epoch of data. The test function evaluates the model on test data after every epoch. It gets the test_loss as well as the cer and wer of the model. You can start running the training script right now with GPU support in the Google Colaboratory." }, { "code": null, "e": 23502, "s": 23178, "text": "Speech Recognition Requires a ton of data and a ton of compute resources. The example laid out is trained on a subset of LibriSpeech (100 hours of audio) and a single GPU. To get state of the art results you’ll need to do distributed training on thousands of hours of data, on tens of GPU’s spread out across many machines." }, { "code": null, "e": 23800, "s": 23502, "text": "Another way to get a big accuracy improvement is to decode the CTC probability matrix using a Language Model and the CTC beam search algorithm. CTC type models are very dependent on this decoding process to get good results. Luckily there is a handy open source library that allows you to do that." }, { "code": null, "e": 24205, "s": 23800, "text": "This tutorial was made to be more accessible so it’s a relatively small model (23 million Parameters) compared to something like BERT (340 million Parameters). It seems to be the larger you can get your network, the better it performs, although there are diminishing returns. A larger model equating to better performance is not always the case though, as proven by OpenAI’s research Deep Double Descent." }, { "code": null, "e": 24520, "s": 24205, "text": "This model has 3 residual CNN layers and 5 Bidirectional GRU layers which should allow you to train a reasonable batch size on a single GPU with at least 11GB of memory. You can tweak some of the hyper parameters in the main function to reduce or increase the model size for your use case and compute availability." }, { "code": null, "e": 24731, "s": 24520, "text": "Deep learning is a fast-moving field. It seems like you can’t go a week without some new technique getting state of the art results. Here are a few of things worth exploring int the world of speech recognition." }, { "code": null, "e": 25084, "s": 24731, "text": "Transformers have taken the Natural Language Processing world by storm! First Introduced in the paper Attention Is All You Need, transformers have been taking and modified to beat pretty much all existing NLP task dethroning RNN’s type architectures. The Transformer’s ability to see the full context of sequence data is transferable to speech as well." }, { "code": null, "e": 25547, "s": 25084, "text": "If you follow deep learning closely you’ve probably heard of BERT, GPT, and GPT2. These Transformer models have first pertained on a language modeling task with unlabeled text data, and fine-tuned on a wide array of NLP task and get state of the art results! During pre-training, the model learns something fundamental on the statistics of language and uses that power to excel at other tasks. We believe this technique has great promises on speech data as well." } ]
How to search for element in a List in Java?
Let us first create a String array: String arr[] = { "One", "Two", "Three", "Four", "Five" }; Now convert the above array to List: ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr)); Sort the collection: Collections.sort(arrList); Now, find the elements “Four” in the list. We will get the index at which the specified element is found: int index = Collections.binarySearch(arrList, "Four"); import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Demo { public static void main(String args[]) { String arr[] = { "One", "Two", "Three", "Four", "Five" }; ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr)); Collections.sort(arrList); System.out.println(arrList); int index = Collections.binarySearch(arrList, "Four"); System.out.println("The element exists at index = " + index); } } [Five, Four, One, Three, Two] The element exists at index = 1
[ { "code": null, "e": 1098, "s": 1062, "text": "Let us first create a String array:" }, { "code": null, "e": 1156, "s": 1098, "text": "String arr[] = { \"One\", \"Two\", \"Three\", \"Four\", \"Five\" };" }, { "code": null, "e": 1193, "s": 1156, "text": "Now convert the above array to List:" }, { "code": null, "e": 1264, "s": 1193, "text": "ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));" }, { "code": null, "e": 1285, "s": 1264, "text": "Sort the collection:" }, { "code": null, "e": 1312, "s": 1285, "text": "Collections.sort(arrList);" }, { "code": null, "e": 1418, "s": 1312, "text": "Now, find the elements “Four” in the list. We will get the index at which the specified element is found:" }, { "code": null, "e": 1473, "s": 1418, "text": "int index = Collections.binarySearch(arrList, \"Four\");" }, { "code": null, "e": 1965, "s": 1473, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\npublic class Demo {\n public static void main(String args[]) {\n String arr[] = { \"One\", \"Two\", \"Three\", \"Four\", \"Five\" };\n ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));\n Collections.sort(arrList);\n System.out.println(arrList);\n int index = Collections.binarySearch(arrList, \"Four\");\n System.out.println(\"The element exists at index = \" + index);\n }\n}" }, { "code": null, "e": 2027, "s": 1965, "text": "[Five, Four, One, Three, Two]\nThe element exists at index = 1" } ]
JavaScript Array.isArray()
The Array.isArray() method of JavaScript is used to determine whether an object is an array or not. The syntax is as follows − Array.isArray(ob) Above, the ob parameter is the object to be tested. Let us now implement the Array.isArray() method in JavaScript − Live Demo <!DOCTYPE html> <html> <body> <h2>Ranking Points</h2> <p>Is this an array? Click the below button to get the answer...</p> <button onclick="display()">Result</button> <p id="test"></p> <script> var pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000]; var res = pointsArr.entries(); for (val of res) { document.getElementById("test").innerHTML += val + "<br>"; } function display() { var res = document.getElementById("test"); res.innerHTML = Array.isArray(pointsArr); } </script> </body> </html> Click the “Result” button above − Live Demo <!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p>Is this is an array?</p> <p id="test"></p> <script> var arr = ["Accessories", "Electronics", "Books", "Pet Supplies"]; var res = document.getElementById("test"); res.innerHTML = Array.isArray(arr); </script> </body> </html>
[ { "code": null, "e": 1162, "s": 1062, "text": "The Array.isArray() method of JavaScript is used to determine whether an object is an array or not." }, { "code": null, "e": 1189, "s": 1162, "text": "The syntax is as follows −" }, { "code": null, "e": 1207, "s": 1189, "text": "Array.isArray(ob)" }, { "code": null, "e": 1259, "s": 1207, "text": "Above, the ob parameter is the object to be tested." }, { "code": null, "e": 1323, "s": 1259, "text": "Let us now implement the Array.isArray() method in JavaScript −" }, { "code": null, "e": 1334, "s": 1323, "text": " Live Demo" }, { "code": null, "e": 1914, "s": 1334, "text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Ranking Points</h2>\n <p>Is this an array? Click the below button to get the answer...</p>\n <button onclick=\"display()\">Result</button>\n <p id=\"test\"></p>\n <script>\n var pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000];\n var res = pointsArr.entries();\n for (val of res) {\n document.getElementById(\"test\").innerHTML += val + \"<br>\";\n }\n function display() {\n var res = document.getElementById(\"test\");\n res.innerHTML = Array.isArray(pointsArr);\n }\n </script>\n</body>\n</html>" }, { "code": null, "e": 1948, "s": 1914, "text": "Click the “Result” button above −" }, { "code": null, "e": 1959, "s": 1948, "text": " Live Demo" }, { "code": null, "e": 2271, "s": 1959, "text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Demo Heading</h2>\n <p>Is this is an array?</p>\n <p id=\"test\"></p>\n <script>\n var arr = [\"Accessories\", \"Electronics\", \"Books\", \"Pet Supplies\"];\n var res = document.getElementById(\"test\");\n res.innerHTML = Array.isArray(arr);\n </script>\n</body>\n</html>" } ]
How to hide legend with Plotly Express and Plotly in Python? - GeeksforGeeks
19 Dec, 2021 In this article, we will learn How to hide legend with Plotly Express and Plotly. Here we will discuss two different methods for hiding legend in plotly and plotly express, using two different examples for each to make it more clear. Syntax: For legend: fig.update_traces(showlegend=False) fig.update(layout_showlegend=False) Example 1: In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), bypassing the show legend parameter as False. Python3 # importing packagesimport plotly.express as px # using the gapminder datasetdf = px.data.tips()fig = px.scatter(df, x="total_bill", y="tip", color="sex", symbol="smoker", facet_col="time", labels={"sex": "Gender", "smoker": "Smokes"}) # hiding legend in pyplot express.fig.update_traces(showlegend=False) fig.show() Output: Example 2: In this example, we are hiding legend in Plotly with the help of method fig.update(layout_showlegend=False), by passing the showlegend parameter as False. Python3 import plotly.graph_objects as go # using the Figure datasetfig = go.Figure() fig.add_trace(go.Line(name="first", x=["a", "b"], y=[1,3]))fig.add_trace(go.Line(name="second", x=["a", "b"], y=[2,1]))fig.add_trace(go.Line(name="third", x=["a", "b"], y=[1,2]))fig.add_trace(go.Line(name="fourth", x=["a", "b"], y=[2,3])) # hiding legend in pyplot express.fig.update(layout_showlegend=False) fig.show() Output: Example 3: In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), by passing the layout_showlegend parameter as False. Python3 import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y="sepal_width", line_dash='species', color='species') # hiding legend in pyplot express.fig.update_traces(showlegend=False) # showing the plotfig.show() Output: Picked Python Plotly express-class Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25789, "s": 25555, "text": "In this article, we will learn How to hide legend with Plotly Express and Plotly. Here we will discuss two different methods for hiding legend in plotly and plotly express, using two different examples for each to make it more clear." }, { "code": null, "e": 25809, "s": 25789, "text": "Syntax: For legend:" }, { "code": null, "e": 25845, "s": 25809, "text": "fig.update_traces(showlegend=False)" }, { "code": null, "e": 25881, "s": 25845, "text": "fig.update(layout_showlegend=False)" }, { "code": null, "e": 25892, "s": 25881, "text": "Example 1:" }, { "code": null, "e": 26055, "s": 25892, "text": "In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), bypassing the show legend parameter as False." }, { "code": null, "e": 26063, "s": 26055, "text": "Python3" }, { "code": "# importing packagesimport plotly.express as px # using the gapminder datasetdf = px.data.tips()fig = px.scatter(df, x=\"total_bill\", y=\"tip\", color=\"sex\", symbol=\"smoker\", facet_col=\"time\", labels={\"sex\": \"Gender\", \"smoker\": \"Smokes\"}) # hiding legend in pyplot express.fig.update_traces(showlegend=False) fig.show()", "e": 26416, "s": 26063, "text": null }, { "code": null, "e": 26424, "s": 26416, "text": "Output:" }, { "code": null, "e": 26435, "s": 26424, "text": "Example 2:" }, { "code": null, "e": 26590, "s": 26435, "text": "In this example, we are hiding legend in Plotly with the help of method fig.update(layout_showlegend=False), by passing the showlegend parameter as False." }, { "code": null, "e": 26598, "s": 26590, "text": "Python3" }, { "code": "import plotly.graph_objects as go # using the Figure datasetfig = go.Figure() fig.add_trace(go.Line(name=\"first\", x=[\"a\", \"b\"], y=[1,3]))fig.add_trace(go.Line(name=\"second\", x=[\"a\", \"b\"], y=[2,1]))fig.add_trace(go.Line(name=\"third\", x=[\"a\", \"b\"], y=[1,2]))fig.add_trace(go.Line(name=\"fourth\", x=[\"a\", \"b\"], y=[2,3])) # hiding legend in pyplot express.fig.update(layout_showlegend=False) fig.show()", "e": 27002, "s": 26598, "text": null }, { "code": null, "e": 27010, "s": 27002, "text": "Output:" }, { "code": null, "e": 27021, "s": 27010, "text": "Example 3:" }, { "code": null, "e": 27191, "s": 27021, "text": "In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), by passing the layout_showlegend parameter as False." }, { "code": null, "e": 27199, "s": 27191, "text": "Python3" }, { "code": "import plotly.express as px # using the iris datasetdf = px.data.iris() # plotting the line chartfig = px.line(df, y=\"sepal_width\", line_dash='species', color='species') # hiding legend in pyplot express.fig.update_traces(showlegend=False) # showing the plotfig.show()", "e": 27483, "s": 27199, "text": null }, { "code": null, "e": 27491, "s": 27483, "text": "Output:" }, { "code": null, "e": 27498, "s": 27491, "text": "Picked" }, { "code": null, "e": 27526, "s": 27498, "text": "Python Plotly express-class" }, { "code": null, "e": 27540, "s": 27526, "text": "Python-Plotly" }, { "code": null, "e": 27547, "s": 27540, "text": "Python" }, { "code": null, "e": 27645, "s": 27547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27645, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27719, "s": 27677, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27761, "s": 27719, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27817, "s": 27761, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27844, "s": 27817, "text": "Python Classes and Objects" }, { "code": null, "e": 27875, "s": 27844, "text": "Python | os.path.join() method" }, { "code": null, "e": 27914, "s": 27875, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27943, "s": 27914, "text": "Create a directory in Python" }, { "code": null, "e": 27965, "s": 27943, "text": "Defaultdict in Python" } ]
Check if given number is perfect square - GeeksforGeeks
12 Feb, 2022 Given a number, check if it is a perfect square or not. Examples : Input : 2500 Output : Yes Explanation: 2500 is a perfect square. 50 * 50 = 2500 Input : 2555 Output : No Approach: Take the floor()ed square root of the number.Multiply the square root twice.Use boolean equal operator to verify if the product of square root is equal to the number given. Take the floor()ed square root of the number. Multiply the square root twice. Use boolean equal operator to verify if the product of square root is equal to the number given. C++ Java Python3 C# PHP Javascript // CPP program to find if x is a// perfect square.#include <bits/stdc++.h>using namespace std; bool isPerfectSquare(long double x){ // Find floating point value of // square root of x. if (x >= 0) { long long sr = sqrt(x); // if product of square root //is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false;} int main(){ long long x = 2502; if (isPerfectSquare(x)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find if x is a// perfect square.class GFG { static boolean isPerfectSquare(int x) { if (x >= 0) { // Find floating point value of // square root of x. int sr = (int)Math.sqrt(x); // if product of square root // is equal, then // return T/F return ((sr * sr) == x); } return false; } // Driver code public static void main(String[] args) { int x = 2502; if (isPerfectSquare(x)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal. # Python program to find if x is a# perfect square. import math def isPerfectSquare(x): #if x >= 0, if(x >= 0): sr = int(math.sqrt(x)) # sqrt function returns floating value so we have to convert it into integer #return boolean T/F return ((sr*sr) == x) return false # Driver code x = 2502if (isPerfectSquare(x)): print("Yes")else: print("No") # This code is contributed# by Anant Agarwal. // C# program to find if x is a// perfect square.using System;class GFG { static bool isPerfectSquare(double x) { // Find floating point value of // square root of x. if (x >= 0) { double sr = Math.Sqrt(x); // if product of square root // is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false; } // Driver code public static void Main() { double x = 2502; if (isPerfectSquare(x)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP program to find if x is// a perfect square. function isPerfectSquare($x){ // Find floating point value // of square root of x. $sr = sqrt($x); // If square root is an integer return (($sr - floor($sr)) == 0);} // Driver code$x = 2502;if (isPerfectSquare($x)) echo("Yes");else echo("No"); // This code is contributed by Ajit.?> <script> // JavaScript program to find if x is a// perfect square. function isPerfectSquare(x) { if (x >= 0) { // Find floating point value of // square root of x. let sr = Math.sqrt(x); // if product of square root // is equal, then // return T/F return ((sr * sr) == x); } return false; } // Driver code let x = 2500; if (isPerfectSquare(x)) document.write("Yes"); else document.write("No"); // This code is contributed by souravghosh0416.</script> No To know more about the inbuilt sqrt function, refer this Stackoverflow and this StackExchange threads. Another Approach : Use the floor and ceil function .If they are equal that implies the number is a perfect square. Use the floor and ceil function . If they are equal that implies the number is a perfect square. C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>#include <math.h>using namespace std; void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) { cout << "perfect square"; } else { cout << "not a perfect square"; }} // Driver Codeint main(){ int n = 49; checkperfectsquare(n); return 0;} // Java program for the above approachimport java.io.*; class GFG{ static void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (Math.ceil((double)Math.sqrt(n)) == Math.floor((double)Math.sqrt(n))) { System.out.print("perfect square"); } else { System.out.print("not a perfect square"); }} // Driver Codepublic static void main(String[] args){ int n = 49; checkperfectsquare(n);}} // This code is contributed by subhammahato348 # Python3 program for the above approachimport math def checkperfectsquare(x): # If ceil and floor are equal # the number is a perfect # square if (math.ceil(math.sqrt(n)) == math.floor(math.sqrt(n))): print("perfect square") else: print("not a perfect square") # Driver coden = 49 checkperfectsquare(n) # This code is contributed by jana_sayantan // C# program for the above approachusing System; class GFG{ static void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (Math.Ceiling((double)Math.Sqrt(n)) == Math.Floor((double)Math.Sqrt(n))) { Console.Write("perfect square"); } else { Console.Write("not a perfect square"); }} // Driver Codepublic static void Main(){ int n = 49; checkperfectsquare(n);}} // This code is contributed by subhammahato348 <script> // Javascript program for the above approachfunction checkperfectsquare(n){ // If ceil and floor are equal // the number is a perfect // square if (Math.ceil(Math.sqrt(n)) == Math.floor(Math.sqrt(n))) { document.write("perfect square"); } else { document.write("not a perfect square"); }} // Driver Codelet n = 49; checkperfectsquare(n); // This code is contributed by rishavmahato348 </script> perfect square jit_t logicracker aditipandeyap1 vermaaayush68 souravghosh0416 rishavmahato348 subhammahato348 premansh2001 khushiagarwal226 jana_sayantan kishorenaidu712 r4jdeepbiswas maths-perfect-square C++ Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Shallow Copy and Deep Copy in C++ delete keyword in C++ Passing a function as a parameter in C++ cin in C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26610, "s": 26582, "text": "\n12 Feb, 2022" }, { "code": null, "e": 26667, "s": 26610, "text": "Given a number, check if it is a perfect square or not. " }, { "code": null, "e": 26679, "s": 26667, "text": "Examples : " }, { "code": null, "e": 26786, "s": 26679, "text": "Input : 2500\nOutput : Yes\nExplanation:\n2500 is a perfect square.\n50 * 50 = 2500\n\nInput : 2555\nOutput : No" }, { "code": null, "e": 26796, "s": 26786, "text": "Approach:" }, { "code": null, "e": 26969, "s": 26796, "text": "Take the floor()ed square root of the number.Multiply the square root twice.Use boolean equal operator to verify if the product of square root is equal to the number given." }, { "code": null, "e": 27015, "s": 26969, "text": "Take the floor()ed square root of the number." }, { "code": null, "e": 27047, "s": 27015, "text": "Multiply the square root twice." }, { "code": null, "e": 27144, "s": 27047, "text": "Use boolean equal operator to verify if the product of square root is equal to the number given." }, { "code": null, "e": 27148, "s": 27144, "text": "C++" }, { "code": null, "e": 27153, "s": 27148, "text": "Java" }, { "code": null, "e": 27161, "s": 27153, "text": "Python3" }, { "code": null, "e": 27164, "s": 27161, "text": "C#" }, { "code": null, "e": 27168, "s": 27164, "text": "PHP" }, { "code": null, "e": 27179, "s": 27168, "text": "Javascript" }, { "code": "// CPP program to find if x is a// perfect square.#include <bits/stdc++.h>using namespace std; bool isPerfectSquare(long double x){ // Find floating point value of // square root of x. if (x >= 0) { long long sr = sqrt(x); // if product of square root //is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false;} int main(){ long long x = 2502; if (isPerfectSquare(x)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27720, "s": 27179, "text": null }, { "code": "// Java program to find if x is a// perfect square.class GFG { static boolean isPerfectSquare(int x) { if (x >= 0) { // Find floating point value of // square root of x. int sr = (int)Math.sqrt(x); // if product of square root // is equal, then // return T/F return ((sr * sr) == x); } return false; } // Driver code public static void main(String[] args) { int x = 2502; if (isPerfectSquare(x)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.", "e": 28407, "s": 27720, "text": null }, { "code": "# Python program to find if x is a# perfect square. import math def isPerfectSquare(x): #if x >= 0, if(x >= 0): sr = int(math.sqrt(x)) # sqrt function returns floating value so we have to convert it into integer #return boolean T/F return ((sr*sr) == x) return false # Driver code x = 2502if (isPerfectSquare(x)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Anant Agarwal.", "e": 28843, "s": 28407, "text": null }, { "code": "// C# program to find if x is a// perfect square.using System;class GFG { static bool isPerfectSquare(double x) { // Find floating point value of // square root of x. if (x >= 0) { double sr = Math.Sqrt(x); // if product of square root // is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false; } // Driver code public static void Main() { double x = 2502; if (isPerfectSquare(x)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 29537, "s": 28843, "text": null }, { "code": "<?php// PHP program to find if x is// a perfect square. function isPerfectSquare($x){ // Find floating point value // of square root of x. $sr = sqrt($x); // If square root is an integer return (($sr - floor($sr)) == 0);} // Driver code$x = 2502;if (isPerfectSquare($x)) echo(\"Yes\");else echo(\"No\"); // This code is contributed by Ajit.?>", "e": 29902, "s": 29537, "text": null }, { "code": "<script> // JavaScript program to find if x is a// perfect square. function isPerfectSquare(x) { if (x >= 0) { // Find floating point value of // square root of x. let sr = Math.sqrt(x); // if product of square root // is equal, then // return T/F return ((sr * sr) == x); } return false; } // Driver code let x = 2500; if (isPerfectSquare(x)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by souravghosh0416.</script>", "e": 30530, "s": 29902, "text": null }, { "code": null, "e": 30533, "s": 30530, "text": "No" }, { "code": null, "e": 30636, "s": 30533, "text": "To know more about the inbuilt sqrt function, refer this Stackoverflow and this StackExchange threads." }, { "code": null, "e": 30655, "s": 30636, "text": "Another Approach :" }, { "code": null, "e": 30751, "s": 30655, "text": "Use the floor and ceil function .If they are equal that implies the number is a perfect square." }, { "code": null, "e": 30785, "s": 30751, "text": "Use the floor and ceil function ." }, { "code": null, "e": 30848, "s": 30785, "text": "If they are equal that implies the number is a perfect square." }, { "code": null, "e": 30852, "s": 30848, "text": "C++" }, { "code": null, "e": 30857, "s": 30852, "text": "Java" }, { "code": null, "e": 30865, "s": 30857, "text": "Python3" }, { "code": null, "e": 30868, "s": 30865, "text": "C#" }, { "code": null, "e": 30879, "s": 30868, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>#include <math.h>using namespace std; void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (ceil((double)sqrt(n)) == floor((double)sqrt(n))) { cout << \"perfect square\"; } else { cout << \"not a perfect square\"; }} // Driver Codeint main(){ int n = 49; checkperfectsquare(n); return 0;}", "e": 31320, "s": 30879, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ static void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (Math.ceil((double)Math.sqrt(n)) == Math.floor((double)Math.sqrt(n))) { System.out.print(\"perfect square\"); } else { System.out.print(\"not a perfect square\"); }} // Driver Codepublic static void main(String[] args){ int n = 49; checkperfectsquare(n);}} // This code is contributed by subhammahato348", "e": 31861, "s": 31320, "text": null }, { "code": "# Python3 program for the above approachimport math def checkperfectsquare(x): # If ceil and floor are equal # the number is a perfect # square if (math.ceil(math.sqrt(n)) == math.floor(math.sqrt(n))): print(\"perfect square\") else: print(\"not a perfect square\") # Driver coden = 49 checkperfectsquare(n) # This code is contributed by jana_sayantan", "e": 32254, "s": 31861, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static void checkperfectsquare(int n){ // If ceil and floor are equal // the number is a perfect // square if (Math.Ceiling((double)Math.Sqrt(n)) == Math.Floor((double)Math.Sqrt(n))) { Console.Write(\"perfect square\"); } else { Console.Write(\"not a perfect square\"); }} // Driver Codepublic static void Main(){ int n = 49; checkperfectsquare(n);}} // This code is contributed by subhammahato348", "e": 32769, "s": 32254, "text": null }, { "code": "<script> // Javascript program for the above approachfunction checkperfectsquare(n){ // If ceil and floor are equal // the number is a perfect // square if (Math.ceil(Math.sqrt(n)) == Math.floor(Math.sqrt(n))) { document.write(\"perfect square\"); } else { document.write(\"not a perfect square\"); }} // Driver Codelet n = 49; checkperfectsquare(n); // This code is contributed by rishavmahato348 </script>", "e": 33226, "s": 32769, "text": null }, { "code": null, "e": 33241, "s": 33226, "text": "perfect square" }, { "code": null, "e": 33247, "s": 33241, "text": "jit_t" }, { "code": null, "e": 33259, "s": 33247, "text": "logicracker" }, { "code": null, "e": 33274, "s": 33259, "text": "aditipandeyap1" }, { "code": null, "e": 33288, "s": 33274, "text": "vermaaayush68" }, { "code": null, "e": 33304, "s": 33288, "text": "souravghosh0416" }, { "code": null, "e": 33320, "s": 33304, "text": "rishavmahato348" }, { "code": null, "e": 33336, "s": 33320, "text": "subhammahato348" }, { "code": null, "e": 33349, "s": 33336, "text": "premansh2001" }, { "code": null, "e": 33366, "s": 33349, "text": "khushiagarwal226" }, { "code": null, "e": 33380, "s": 33366, "text": "jana_sayantan" }, { "code": null, "e": 33396, "s": 33380, "text": "kishorenaidu712" }, { "code": null, "e": 33410, "s": 33396, "text": "r4jdeepbiswas" }, { "code": null, "e": 33431, "s": 33410, "text": "maths-perfect-square" }, { "code": null, "e": 33444, "s": 33431, "text": "C++ Programs" }, { "code": null, "e": 33457, "s": 33444, "text": "Mathematical" }, { "code": null, "e": 33470, "s": 33457, "text": "Mathematical" }, { "code": null, "e": 33568, "s": 33470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33594, "s": 33568, "text": "C++ Program for QuickSort" }, { "code": null, "e": 33628, "s": 33594, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 33650, "s": 33628, "text": "delete keyword in C++" }, { "code": null, "e": 33691, "s": 33650, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33702, "s": 33691, "text": "cin in C++" }, { "code": null, "e": 33732, "s": 33702, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33792, "s": 33732, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33807, "s": 33792, "text": "C++ Data Types" }, { "code": null, "e": 33850, "s": 33807, "text": "Set in C++ Standard Template Library (STL)" } ]
Data pretty printer (pprint) in Python
Python has the ability to properly format the content of a print method using a special method called pretty print or pprint. For example when we read a content of an url which is in the form of json, the content will be printed as single line which is hard to read or comprehend. But if we apply pretty print, python gives it a ice structure as per the json tags. In the below program we are printing the json content of a web page using the traditional print method. The entire result comes as a single line. import requests json_url_link = "https://pypi.org/pypi/sampleproject/json" result = requests.get(json_url_link ) print(result.json()) Running the above code gives us the following result − {'info': {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', . . . Next we take the same content as above but apply the pprint now. As you can see the output format is very organized. import requests from pprint import pprint json_url_link = "https://pypi.org/pypi/sampleproject/json" result = requests.get(json_url_link ) pprint(result.json()) Running the above code gives us the following result − {'info': {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', 'bugtrack_url': None, 'classifiers': ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7',
[ { "code": null, "e": 1427, "s": 1062, "text": "Python has the ability to properly format the content of a print method using a special method called pretty print or pprint. For example when we read a content of an url which is in the form of json, the content will be printed as single line which is hard to read or comprehend. But if we apply pretty print, python gives it a ice structure as per the json tags." }, { "code": null, "e": 1573, "s": 1427, "text": "In the below program we are printing the json content of a web page using the traditional print method. The entire result comes as a single line." }, { "code": null, "e": 1707, "s": 1573, "text": "import requests\njson_url_link = \"https://pypi.org/pypi/sampleproject/json\"\nresult = requests.get(json_url_link )\nprint(result.json())" }, { "code": null, "e": 1762, "s": 1707, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1867, "s": 1762, "text": "{'info': {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', . . ." }, { "code": null, "e": 1984, "s": 1867, "text": "Next we take the same content as above but apply the pprint now. As you can see the output format is very organized." }, { "code": null, "e": 2145, "s": 1984, "text": "import requests\nfrom pprint import pprint\njson_url_link = \"https://pypi.org/pypi/sampleproject/json\"\nresult = requests.get(json_url_link )\npprint(result.json())" }, { "code": null, "e": 2200, "s": 2145, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2652, "s": 2200, "text": "{'info': {'author': 'The Python Packaging Authority',\n 'author_email': 'pypa-dev@googlegroups.com',\n 'bugtrack_url': None,\n 'classifiers': ['Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7'," } ]
Creating Choropleth Map Using GeoPandas — Irish Wind Energy Dataset | by Saeed Misaghian | Towards Data Science
In my previous article [1] I discussed Irish wind energy penetration within the electricity network . In that article, I reported figures representing the change in the number of wind turbines in each country over the past few years. Below, I will go through the steps involved in creating your own choropleth map for visualizing any data of your choice! For illustration purposes, the code below is for generating the figure I reported in my previous article. However, these steps apply to any data! Following the steps detailed below, we will generate the choropleth map shown below. This map color codes the different Irish counties based on the wind turbine installed capacity. The number of wind turbines installed in each county is illustrated by dots where each dot is one wind turbine. All you need to create this map is some hands on Python (Pandas, Matplotlib) and I will help you with GeoPandas. We will breakdown generating the choropleth map into the followng steps: Data curation: Data curation: Because I’m based in Dublin and working on renewable energies; I will be plotting the wind turbine installation in terms of number of turbines and capacity, you can just follow the process for your data to create your own. The energy data was curated from EirGrid website [2]. The data is in PDF format. I converted it into CSV file, did a little bit of preprocessing to it and uploaded it to my GitHub. The curated data is perfect for our illustration purposes. We also need to have access to the map in question. I used the map of the Republic of Ireland, which I downloaded from the following website which I also uploaded into my GitHub. 2. Let’s start coding: I know it might be your first time working with GeoPands, so at first you need to install it. This can be done by running the following line of code: pip install geopandas If you got an error, don’t panic, there are other ways to install it. Have a look at this. To load the CSV file in question, execute the following lines of code: import pandas as pdpath = 'Give it the data path' df = pd.read_csv(path+'Tdata.csv')df.head() # to see how data look likes A shown, we have the the installed capacity and number of turbines for each county in Ireland in the loaded dataset. Now, we need to load the map in question, which is in this case the map of Ireland. import geopandas as gpdROI_map= gpd.read_file(path+'IRL_adm1.shp') #reading the map ROI_map.NAME_1 #you can see names of counties here Now, we have a Panadas dataframe representing our data (df) and a GeoPandas dataframe representing Ireland map (ROI_map). What we need to do is to merge these two data sets based on the county names: ROI_map=ROI_map.set_index('NAME_1')df=df.set_index('County')df2= ROI_map.join(df)# we need to replace NaN rows with 0 since there are some counties #without any wind turbines df2['Installed Capacity (MW)']=df2['Installed Capacity (MW)'].fillna(value=0)df2['No of Turbines']=df2['No of Turbines'].fillna(value=0)df2['name1'] = df2.indexdf2.head() # it is the new data frame that we created merging map and wind data sets 2. Ready to plot? To plot the data in question, we use the MatPlotlib library in Python. I color coded each county based on the installed capacity. I chose green because I’m talking about green energies (cmap=’YlGn’). One point I like to touch on here is that since we are coloring the map based on the installed capacity, we need a color bar showing how the range of installed capacity is changing with color, so you need to define the minimum (vmin) and maximum (vmax) of installed capacity for the color bar too. WAIT! We are talking about island of Ireland, so I like the face color of my plot to be light blue (facecolor=’lightsteelblue’), you can remove it if you want it to be white. import matplotlib.pyplot as pltvmin, vmax = 0, 500 #Range of variable you use as map color (here #range of Installed Capacity (MW)fig, ax = plt.subplots(figsize=(6,8),facecolor='lightsteelblue')fig=df2.plot(column='Installed Capacity (MW)', cmap='YlGn', linewidth=0.8, ax=ax, edgecolor='#140656',facecolor='lightslategray',vmin=vmin, vmax=vmax,legend=True, norm=plt.Normalize(vmin=vmin, vmax=vmax))ax.axis('off') Add a legend to the color bar: ax.annotate('Installed Capacity (MW)',xy=(0.9, .65),rotation=270, xycoords='figure fraction', horizontalalignment='left', verticalalignment='top', fontsize=12, color='black') Here is your plot so far: 3. Can we add county names? YES! You can assign anything you want by specifying the longitude and latitude. You might be interested in adding county names to your plot, so let’s take the longitude and latitude of each county and ask Python to add names on this basis. #Getting the lan and lat here from geometry datadf2['coords']=df2['geometry'].apply(lambda x: x.representative_point().coords[:])df2['coords']=[coords[0] for coords in df2['coords']]#Add names of county herefor idx, row in df2.iterrows(): plt.annotate(s=row['name1'], xy=row['coords'], horizontalalignment='center', color='black',fontsize=10, fontweight='light') There are some overlapping of names, but you can avoid it by adjusting the layout or changing the size of figure. 4. What about number of wind turbines? Of course! It is quite similar to part 3, yet there is a small difference, instead of adding names, add number of wind turbines! BUT, be careful, I liked to distribute the circles across the county to clearly show the cumulative of wind turbines, since otherwise, all circles would overlap at the same spot and we wouldn’t tell how many are there!, so I just produced some random numbers for each county and each turbine; hence; you would have equal number of circles and wind turbines in each county. from random import gauss # Add turbine numbers herefor idx, row in df2.iterrows(): if row['No of Turbines']!=0: s=row['No of Turbines'] ss=int(s) for i in list(range(ss)): z=row['No of Turbines']/1000+gauss(0, 0.1) DFF=plt.scatter(x=z+row['coords'][0],y=gauss(0, 0.03)+row['coords'][1],c='#ec1313',alpha=0.5) Finally we have: 5. Stop! We always need legend for our data! Add legend to the map by the following code: #Add legend to red circles i.e. wind turbinesplt.legend([DFF, DFF], ["Wind turbines"],loc='upper left') Here we go: 6. Can I save my map? You can save your map by the following code: import os path2='your path here!'filepath = os.path.join(path2,'mymap.jpg')chart = fig.get_figure()chart.savefig(filepath, dpi=300) 6. BYE! I Hope you enjoyed this article and I wish it could help you with your study or work. You can access the code and data on my GitHub. It is worth to note that I have been inspired by these two articles [3,4] on Towards Data Science. I want to acknowledge UCD energy institute and ESIPP group for supporting me. Plus, I recommend you have a look at my colleagues’ interesting works in this institute. [1]: Green like Ireland: Choropleth map of Irish wind energy, Towards Data science; Feb. 23, 2021 https://towardsdatascience.com/green-like-ireland-choropleth-map-of-irish-wind-energy-26603106fe3e?source=social.tw [2]: TSO Connected Renewables — Annual Installed Capacities, EirGrid, Feb. 2021. http://www.eirgridgroup.com/site-files/library/EirGrid/TSO-Connected-Renewable-Generation.pdf [3]: A Complete Guide to creating Choropleth Maps in Python, Towards Data science; Oct. 4, 2020 https://towardsdatascience.com/a-complete-guide-to-creating-choropleth-maps-in-python-728ee2949db4 [4]: Let’s make a map! Using Geopandas, Pandas and Matplotlib to make a Choropleth map; Jun 25, 2018. https://towardsdatascience.com/lets-make-a-map-using-geopandas-pandas-and-matplotlib-to-make-a-chloropleth-map-dddc31c1983d
[ { "code": null, "e": 527, "s": 172, "text": "In my previous article [1] I discussed Irish wind energy penetration within the electricity network . In that article, I reported figures representing the change in the number of wind turbines in each country over the past few years. Below, I will go through the steps involved in creating your own choropleth map for visualizing any data of your choice!" }, { "code": null, "e": 673, "s": 527, "text": "For illustration purposes, the code below is for generating the figure I reported in my previous article. However, these steps apply to any data!" }, { "code": null, "e": 966, "s": 673, "text": "Following the steps detailed below, we will generate the choropleth map shown below. This map color codes the different Irish counties based on the wind turbine installed capacity. The number of wind turbines installed in each county is illustrated by dots where each dot is one wind turbine." }, { "code": null, "e": 1079, "s": 966, "text": "All you need to create this map is some hands on Python (Pandas, Matplotlib) and I will help you with GeoPandas." }, { "code": null, "e": 1152, "s": 1079, "text": "We will breakdown generating the choropleth map into the followng steps:" }, { "code": null, "e": 1167, "s": 1152, "text": "Data curation:" }, { "code": null, "e": 1182, "s": 1167, "text": "Data curation:" }, { "code": null, "e": 1405, "s": 1182, "text": "Because I’m based in Dublin and working on renewable energies; I will be plotting the wind turbine installation in terms of number of turbines and capacity, you can just follow the process for your data to create your own." }, { "code": null, "e": 1645, "s": 1405, "text": "The energy data was curated from EirGrid website [2]. The data is in PDF format. I converted it into CSV file, did a little bit of preprocessing to it and uploaded it to my GitHub. The curated data is perfect for our illustration purposes." }, { "code": null, "e": 1824, "s": 1645, "text": "We also need to have access to the map in question. I used the map of the Republic of Ireland, which I downloaded from the following website which I also uploaded into my GitHub." }, { "code": null, "e": 1847, "s": 1824, "text": "2. Let’s start coding:" }, { "code": null, "e": 1997, "s": 1847, "text": "I know it might be your first time working with GeoPands, so at first you need to install it. This can be done by running the following line of code:" }, { "code": null, "e": 2019, "s": 1997, "text": "pip install geopandas" }, { "code": null, "e": 2110, "s": 2019, "text": "If you got an error, don’t panic, there are other ways to install it. Have a look at this." }, { "code": null, "e": 2181, "s": 2110, "text": "To load the CSV file in question, execute the following lines of code:" }, { "code": null, "e": 2305, "s": 2181, "text": "import pandas as pdpath = 'Give it the data path' df = pd.read_csv(path+'Tdata.csv')df.head() # to see how data look likes" }, { "code": null, "e": 2506, "s": 2305, "text": "A shown, we have the the installed capacity and number of turbines for each county in Ireland in the loaded dataset. Now, we need to load the map in question, which is in this case the map of Ireland." }, { "code": null, "e": 2642, "s": 2506, "text": "import geopandas as gpdROI_map= gpd.read_file(path+'IRL_adm1.shp') #reading the map ROI_map.NAME_1 #you can see names of counties here" }, { "code": null, "e": 2842, "s": 2642, "text": "Now, we have a Panadas dataframe representing our data (df) and a GeoPandas dataframe representing Ireland map (ROI_map). What we need to do is to merge these two data sets based on the county names:" }, { "code": null, "e": 3262, "s": 2842, "text": "ROI_map=ROI_map.set_index('NAME_1')df=df.set_index('County')df2= ROI_map.join(df)# we need to replace NaN rows with 0 since there are some counties #without any wind turbines df2['Installed Capacity (MW)']=df2['Installed Capacity (MW)'].fillna(value=0)df2['No of Turbines']=df2['No of Turbines'].fillna(value=0)df2['name1'] = df2.indexdf2.head() # it is the new data frame that we created merging map and wind data sets" }, { "code": null, "e": 3280, "s": 3262, "text": "2. Ready to plot?" }, { "code": null, "e": 3953, "s": 3280, "text": "To plot the data in question, we use the MatPlotlib library in Python. I color coded each county based on the installed capacity. I chose green because I’m talking about green energies (cmap=’YlGn’). One point I like to touch on here is that since we are coloring the map based on the installed capacity, we need a color bar showing how the range of installed capacity is changing with color, so you need to define the minimum (vmin) and maximum (vmax) of installed capacity for the color bar too. WAIT! We are talking about island of Ireland, so I like the face color of my plot to be light blue (facecolor=’lightsteelblue’), you can remove it if you want it to be white." }, { "code": null, "e": 4366, "s": 3953, "text": "import matplotlib.pyplot as pltvmin, vmax = 0, 500 #Range of variable you use as map color (here #range of Installed Capacity (MW)fig, ax = plt.subplots(figsize=(6,8),facecolor='lightsteelblue')fig=df2.plot(column='Installed Capacity (MW)', cmap='YlGn', linewidth=0.8, ax=ax, edgecolor='#140656',facecolor='lightslategray',vmin=vmin, vmax=vmax,legend=True, norm=plt.Normalize(vmin=vmin, vmax=vmax))ax.axis('off')" }, { "code": null, "e": 4397, "s": 4366, "text": "Add a legend to the color bar:" }, { "code": null, "e": 4572, "s": 4397, "text": "ax.annotate('Installed Capacity (MW)',xy=(0.9, .65),rotation=270, xycoords='figure fraction', horizontalalignment='left', verticalalignment='top', fontsize=12, color='black')" }, { "code": null, "e": 4598, "s": 4572, "text": "Here is your plot so far:" }, { "code": null, "e": 4626, "s": 4598, "text": "3. Can we add county names?" }, { "code": null, "e": 4866, "s": 4626, "text": "YES! You can assign anything you want by specifying the longitude and latitude. You might be interested in adding county names to your plot, so let’s take the longitude and latitude of each county and ask Python to add names on this basis." }, { "code": null, "e": 5248, "s": 4866, "text": "#Getting the lan and lat here from geometry datadf2['coords']=df2['geometry'].apply(lambda x: x.representative_point().coords[:])df2['coords']=[coords[0] for coords in df2['coords']]#Add names of county herefor idx, row in df2.iterrows(): plt.annotate(s=row['name1'], xy=row['coords'], horizontalalignment='center', color='black',fontsize=10, fontweight='light')" }, { "code": null, "e": 5362, "s": 5248, "text": "There are some overlapping of names, but you can avoid it by adjusting the layout or changing the size of figure." }, { "code": null, "e": 5401, "s": 5362, "text": "4. What about number of wind turbines?" }, { "code": null, "e": 5903, "s": 5401, "text": "Of course! It is quite similar to part 3, yet there is a small difference, instead of adding names, add number of wind turbines! BUT, be careful, I liked to distribute the circles across the county to clearly show the cumulative of wind turbines, since otherwise, all circles would overlap at the same spot and we wouldn’t tell how many are there!, so I just produced some random numbers for each county and each turbine; hence; you would have equal number of circles and wind turbines in each county." }, { "code": null, "e": 6258, "s": 5903, "text": "from random import gauss # Add turbine numbers herefor idx, row in df2.iterrows(): if row['No of Turbines']!=0: s=row['No of Turbines'] ss=int(s) for i in list(range(ss)): z=row['No of Turbines']/1000+gauss(0, 0.1) DFF=plt.scatter(x=z+row['coords'][0],y=gauss(0, 0.03)+row['coords'][1],c='#ec1313',alpha=0.5)" }, { "code": null, "e": 6275, "s": 6258, "text": "Finally we have:" }, { "code": null, "e": 6320, "s": 6275, "text": "5. Stop! We always need legend for our data!" }, { "code": null, "e": 6365, "s": 6320, "text": "Add legend to the map by the following code:" }, { "code": null, "e": 6469, "s": 6365, "text": "#Add legend to red circles i.e. wind turbinesplt.legend([DFF, DFF], [\"Wind turbines\"],loc='upper left')" }, { "code": null, "e": 6481, "s": 6469, "text": "Here we go:" }, { "code": null, "e": 6503, "s": 6481, "text": "6. Can I save my map?" }, { "code": null, "e": 6548, "s": 6503, "text": "You can save your map by the following code:" }, { "code": null, "e": 6680, "s": 6548, "text": "import os path2='your path here!'filepath = os.path.join(path2,'mymap.jpg')chart = fig.get_figure()chart.savefig(filepath, dpi=300)" }, { "code": null, "e": 6688, "s": 6680, "text": "6. BYE!" }, { "code": null, "e": 6774, "s": 6688, "text": "I Hope you enjoyed this article and I wish it could help you with your study or work." }, { "code": null, "e": 6821, "s": 6774, "text": "You can access the code and data on my GitHub." }, { "code": null, "e": 6920, "s": 6821, "text": "It is worth to note that I have been inspired by these two articles [3,4] on Towards Data Science." }, { "code": null, "e": 7087, "s": 6920, "text": "I want to acknowledge UCD energy institute and ESIPP group for supporting me. Plus, I recommend you have a look at my colleagues’ interesting works in this institute." }, { "code": null, "e": 7301, "s": 7087, "text": "[1]: Green like Ireland: Choropleth map of Irish wind energy, Towards Data science; Feb. 23, 2021 https://towardsdatascience.com/green-like-ireland-choropleth-map-of-irish-wind-energy-26603106fe3e?source=social.tw" }, { "code": null, "e": 7476, "s": 7301, "text": "[2]: TSO Connected Renewables — Annual Installed Capacities, EirGrid, Feb. 2021. http://www.eirgridgroup.com/site-files/library/EirGrid/TSO-Connected-Renewable-Generation.pdf" }, { "code": null, "e": 7671, "s": 7476, "text": "[3]: A Complete Guide to creating Choropleth Maps in Python, Towards Data science; Oct. 4, 2020 https://towardsdatascience.com/a-complete-guide-to-creating-choropleth-maps-in-python-728ee2949db4" } ]
Find current weather of any city using OpenWeathermap API in Python - GeeksforGeeks
09 Aug, 2021 The OpenWeatherMap is a service that provides weather data, including current weather data, forecasts, and historical data to the developers of web services and mobile applications. It provides an API with JSON, XML, and HTML endpoints and a limited free usage tier. Making more than 60 calls per minute requires a paid subscription starting at USD 40 per month. Access to historical data requires a subscription starting at 150 USD per month. Users can request current weather information, extended forecasts, and graphical maps (showing cloud cover, wind speed, pressure, and precipitation). To use this current weather data API, one must need the API key, which can be get from here. Note: User need to create an account on openweathermap.org then only can use the APIs. requests json Below is the implementation : Python3 # Python program to find current# weather details of any city# using openweathermap api # import required modulesimport requests, json # Enter your API key hereapi_key = "Your_API_Key" # base_url variable to store urlbase_url = "http://api.openweathermap.org/data/2.5/weather?" # Give city namecity_name = input("Enter city name : ") # complete_url variable to store# complete url addresscomplete_url = base_url + "appid=" + api_key + "&q=" + city_name # get method of requests module# return response objectresponse = requests.get(complete_url) # json method of response object# convert json format data into# python format datax = response.json() # Now x contains list of nested dictionaries# Check the value of "cod" key is equal to# "404", means city is found otherwise,# city is not foundif x["cod"] != "404": # store the value of "main" # key in variable y y = x["main"] # store the value corresponding # to the "temp" key of y current_temperature = y["temp"] # store the value corresponding # to the "pressure" key of y current_pressure = y["pressure"] # store the value corresponding # to the "humidity" key of y current_humidity = y["humidity"] # store the value of "weather" # key in variable z z = x["weather"] # store the value corresponding # to the "description" key at # the 0th index of z weather_description = z[0]["description"] # print following values print(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) = " + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidity) + "\n description = " + str(weather_description)) else: print(" City Not Found ") Output : Enter city name : Delhi Temperature (in kelvin unit) = 312.15 atmospheric pressure (in hPa unit) = 996 humidity (in percentage) = 40 description = haze Here in the second approach, we will use some of the following modules and functions as listed below: 1. BeautifulSoup: It is a library in python used to extract data from HTML and XML files i.e for web scraping purposes. It generates a parse tree from the page source code, which can be used to extract data in a more readable and hierarchical manner. For installing a beautiful soup library in the system use the code below in the terminal:- -->> pip install beautifulsoup 2. Requests: Here we will use Python’s requests module to make HTTP requests. For installing use the code below in the terminal. -->> pip install requests 3. Here we are using headers because the headers contain protocol-specific information that is placed before the raw message i.e retrieved from the website. 4. After that, we will use the get() function and pass the google search in it along with the name of the city to retrieve the data from google. Then we will use beautifulsoup and parse the HTML data that is required from the website. 5. Then we will use the select() function to retrieve the particular information like time, info, location, store them in some variable, and, store them further. After all of this, we will finally print the data i.e stored in the variables. Python3 from bs4 import BeautifulSoupimport requestsheaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} def weather(city): city = city.replace(" ", "+") res = requests.get( f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8', headers=headers) print("Searching...\n") soup = BeautifulSoup(res.text, 'html.parser') location = soup.select('#wob_loc')[0].getText().strip() time = soup.select('#wob_dts')[0].getText().strip() info = soup.select('#wob_dc')[0].getText().strip() weather = soup.select('#wob_tm')[0].getText().strip() print(location) print(time) print(info) print(weather+"°C") city = input("Enter the Name of City -> ")city = city+" weather"weather(city)print("Have a Nice Day:)") # This code is contributed by adityatri Sample Input: Mahoba Sample Output: Enter the Name of City -> Mahoba Searching... Mahoba, Uttar Pradesh Monday, 12:00 am Cloudy 27°C Have a Nice Day:) surinderdawra388 adityatri python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Defaultdict in Python Python program to convert a list to string Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25923, "s": 25895, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26105, "s": 25923, "text": "The OpenWeatherMap is a service that provides weather data, including current weather data, forecasts, and historical data to the developers of web services and mobile applications." }, { "code": null, "e": 26517, "s": 26105, "text": "It provides an API with JSON, XML, and HTML endpoints and a limited free usage tier. Making more than 60 calls per minute requires a paid subscription starting at USD 40 per month. Access to historical data requires a subscription starting at 150 USD per month. Users can request current weather information, extended forecasts, and graphical maps (showing cloud cover, wind speed, pressure, and precipitation)." }, { "code": null, "e": 26610, "s": 26517, "text": "To use this current weather data API, one must need the API key, which can be get from here." }, { "code": null, "e": 26698, "s": 26610, "text": "Note: User need to create an account on openweathermap.org then only can use the APIs. " }, { "code": null, "e": 26712, "s": 26698, "text": "requests\njson" }, { "code": null, "e": 26743, "s": 26712, "text": "Below is the implementation : " }, { "code": null, "e": 26751, "s": 26743, "text": "Python3" }, { "code": "# Python program to find current# weather details of any city# using openweathermap api # import required modulesimport requests, json # Enter your API key hereapi_key = \"Your_API_Key\" # base_url variable to store urlbase_url = \"http://api.openweathermap.org/data/2.5/weather?\" # Give city namecity_name = input(\"Enter city name : \") # complete_url variable to store# complete url addresscomplete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name # get method of requests module# return response objectresponse = requests.get(complete_url) # json method of response object# convert json format data into# python format datax = response.json() # Now x contains list of nested dictionaries# Check the value of \"cod\" key is equal to# \"404\", means city is found otherwise,# city is not foundif x[\"cod\"] != \"404\": # store the value of \"main\" # key in variable y y = x[\"main\"] # store the value corresponding # to the \"temp\" key of y current_temperature = y[\"temp\"] # store the value corresponding # to the \"pressure\" key of y current_pressure = y[\"pressure\"] # store the value corresponding # to the \"humidity\" key of y current_humidity = y[\"humidity\"] # store the value of \"weather\" # key in variable z z = x[\"weather\"] # store the value corresponding # to the \"description\" key at # the 0th index of z weather_description = z[0][\"description\"] # print following values print(\" Temperature (in kelvin unit) = \" + str(current_temperature) + \"\\n atmospheric pressure (in hPa unit) = \" + str(current_pressure) + \"\\n humidity (in percentage) = \" + str(current_humidity) + \"\\n description = \" + str(weather_description)) else: print(\" City Not Found \")", "e": 28577, "s": 26751, "text": null }, { "code": null, "e": 28588, "s": 28577, "text": "Output : " }, { "code": null, "e": 28745, "s": 28588, "text": " Enter city name : Delhi\n Temperature (in kelvin unit) = 312.15\n atmospheric pressure (in hPa unit) = 996\n humidity (in percentage) = 40\n description = haze" }, { "code": null, "e": 28847, "s": 28745, "text": "Here in the second approach, we will use some of the following modules and functions as listed below:" }, { "code": null, "e": 29189, "s": 28847, "text": "1. BeautifulSoup: It is a library in python used to extract data from HTML and XML files i.e for web scraping purposes. It generates a parse tree from the page source code, which can be used to extract data in a more readable and hierarchical manner. For installing a beautiful soup library in the system use the code below in the terminal:-" }, { "code": null, "e": 29220, "s": 29189, "text": "-->> pip install beautifulsoup" }, { "code": null, "e": 29349, "s": 29220, "text": "2. Requests: Here we will use Python’s requests module to make HTTP requests. For installing use the code below in the terminal." }, { "code": null, "e": 29375, "s": 29349, "text": "-->> pip install requests" }, { "code": null, "e": 29532, "s": 29375, "text": "3. Here we are using headers because the headers contain protocol-specific information that is placed before the raw message i.e retrieved from the website." }, { "code": null, "e": 29677, "s": 29532, "text": "4. After that, we will use the get() function and pass the google search in it along with the name of the city to retrieve the data from google." }, { "code": null, "e": 29768, "s": 29677, "text": "Then we will use beautifulsoup and parse the HTML data that is required from the website. " }, { "code": null, "e": 29930, "s": 29768, "text": "5. Then we will use the select() function to retrieve the particular information like time, info, location, store them in some variable, and, store them further." }, { "code": null, "e": 30009, "s": 29930, "text": "After all of this, we will finally print the data i.e stored in the variables." }, { "code": null, "e": 30017, "s": 30009, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupimport requestsheaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} def weather(city): city = city.replace(\" \", \"+\") res = requests.get( f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8', headers=headers) print(\"Searching...\\n\") soup = BeautifulSoup(res.text, 'html.parser') location = soup.select('#wob_loc')[0].getText().strip() time = soup.select('#wob_dts')[0].getText().strip() info = soup.select('#wob_dc')[0].getText().strip() weather = soup.select('#wob_tm')[0].getText().strip() print(location) print(time) print(info) print(weather+\"°C\") city = input(\"Enter the Name of City -> \")city = city+\" weather\"weather(city)print(\"Have a Nice Day:)\") # This code is contributed by adityatri", "e": 30948, "s": 30017, "text": null }, { "code": null, "e": 30962, "s": 30948, "text": "Sample Input:" }, { "code": null, "e": 30969, "s": 30962, "text": "Mahoba" }, { "code": null, "e": 30984, "s": 30969, "text": "Sample Output:" }, { "code": null, "e": 31101, "s": 30984, "text": "Enter the Name of City -> Mahoba\nSearching...\n\nMahoba, Uttar Pradesh\nMonday, 12:00 am\nCloudy\n27°C\nHave a Nice Day:)" }, { "code": null, "e": 31118, "s": 31101, "text": "surinderdawra388" }, { "code": null, "e": 31128, "s": 31118, "text": "adityatri" }, { "code": null, "e": 31143, "s": 31128, "text": "python-utility" }, { "code": null, "e": 31150, "s": 31143, "text": "Python" }, { "code": null, "e": 31166, "s": 31150, "text": "Python Programs" }, { "code": null, "e": 31264, "s": 31166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31282, "s": 31264, "text": "Python Dictionary" }, { "code": null, "e": 31317, "s": 31282, "text": "Read a file line by line in Python" }, { "code": null, "e": 31349, "s": 31317, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31371, "s": 31349, "text": "Enumerate() in Python" }, { "code": null, "e": 31413, "s": 31371, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31435, "s": 31413, "text": "Defaultdict in Python" }, { "code": null, "e": 31478, "s": 31435, "text": "Python program to convert a list to string" }, { "code": null, "e": 31517, "s": 31478, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 31563, "s": 31517, "text": "Python | Split string into list of characters" } ]
Difference between Compile Time Errors and Runtime Errors in C Program
Error or exception is something that refers to the interruption of code execution due to which the expected outcome could not be attained to the end-user.On the basis of the event when an error is generated or identified we can classify them as Compile time error and runtime error. The following are the important differences between Compile Time Errors and Runtime Errors. CompileDemo.c #include<stdio.h> public class CompileDemo{ void main(){ int x = 100; int y = 155; // semicolon missed printf("%d", (x, y)) } } error: expected ';' before '}' token RuntimeDemo.c include<stdio.h> public class RuntimeDemo{ void main(){ int n = 9; div = 0; div = n/0; printf("resut = %d", div); } } warning: division by zero [-Wdiv-by-zero] div = n/0;
[ { "code": null, "e": 1345, "s": 1062, "text": "Error or exception is something that refers to the interruption of code execution due to which the expected outcome could not be attained to the end-user.On the basis of the event when an error is generated or identified we can classify them as Compile time error and runtime error." }, { "code": null, "e": 1437, "s": 1345, "text": "The following are the important differences between Compile Time Errors and Runtime Errors." }, { "code": null, "e": 1451, "s": 1437, "text": "CompileDemo.c" }, { "code": null, "e": 1609, "s": 1451, "text": "#include<stdio.h>\npublic class CompileDemo{\n void main(){\n int x = 100;\n int y = 155;\n // semicolon missed\n printf(\"%d\", (x, y))\n }\n}" }, { "code": null, "e": 1646, "s": 1609, "text": "error: expected ';' before '}' token" }, { "code": null, "e": 1660, "s": 1646, "text": "RuntimeDemo.c" }, { "code": null, "e": 1808, "s": 1660, "text": "include<stdio.h>\npublic class RuntimeDemo{\n void main(){\n int n = 9;\n div = 0;\n div = n/0;\n printf(\"resut = %d\", div);\n }\n}" }, { "code": null, "e": 1861, "s": 1808, "text": "warning: division by zero [-Wdiv-by-zero]\ndiv = n/0;" } ]
How to inverse a matrix using NumPy - GeeksforGeeks
18 Aug, 2020 The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula, if det(A) != 0 A-1 = adj(A)/det(A) else "Inverse doesn't exist" where, A-1: The inverse of matrix A x: The unknown variable column B: The solution matrix Python provides a very easy method to calculate the inverse of a matrix. The function numpy.linalg.inv() which is available in the python NumPy module is used to compute the inverse of a matrix. Syntax: numpy.linalg.inv(a) Parameters: a: Matrix to be inverted Returns: Inverse of the matrix a. Example 1: Python # Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Taking a 3 * 3 matrixA = np.array([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A)) Output: [[ 0.17647059 -0.00326797 -0.02287582] [ 0.05882353 -0.13071895 0.08496732] [-0.11764706 0.1503268 0.05228758]] Example 2: Python # Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Taking a 4 * 4 matrixA = np.array([[6, 1, 1, 3], [4, -2, 5, 1], [2, 8, 7, 6], [3, 1, 9, 7]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A)) Output: [[ 0.13368984 0.10695187 0.02139037 -0.09090909] [-0.00229183 0.02673797 0.14820474 -0.12987013] [-0.12987013 0.18181818 0.06493506 -0.02597403] [ 0.11000764 -0.28342246 -0.11382735 0.23376623]] Example 3: Python # Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Inverses of several matrices can# be computed at onceA = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A)) Output: [[[-2. 1. ] [ 1.5 -0.5 ]] [[-1.25 0.75] [ 0.75 -0.25]]] Picked Python-numpy Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 25178, "s": 25150, "text": "\n18 Aug, 2020" }, { "code": null, "e": 25686, "s": 25178, "text": "The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula," }, { "code": null, "e": 25760, "s": 25686, "text": "if det(A) != 0\n A-1 = adj(A)/det(A)\nelse\n \"Inverse doesn't exist\" " }, { "code": null, "e": 25767, "s": 25760, "text": "where," }, { "code": null, "e": 25796, "s": 25767, "text": "A-1: The inverse of matrix A" }, { "code": null, "e": 25827, "s": 25796, "text": "x: The unknown variable column" }, { "code": null, "e": 25850, "s": 25827, "text": "B: The solution matrix" }, { "code": null, "e": 26046, "s": 25850, "text": "Python provides a very easy method to calculate the inverse of a matrix. The function numpy.linalg.inv() which is available in the python NumPy module is used to compute the inverse of a matrix. " }, { "code": null, "e": 26054, "s": 26046, "text": "Syntax:" }, { "code": null, "e": 26074, "s": 26054, "text": "numpy.linalg.inv(a)" }, { "code": null, "e": 26086, "s": 26074, "text": "Parameters:" }, { "code": null, "e": 26111, "s": 26086, "text": "a: Matrix to be inverted" }, { "code": null, "e": 26121, "s": 26111, "text": "Returns: " }, { "code": null, "e": 26146, "s": 26121, "text": "Inverse of the matrix a." }, { "code": null, "e": 26157, "s": 26146, "text": "Example 1:" }, { "code": null, "e": 26164, "s": 26157, "text": "Python" }, { "code": "# Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Taking a 3 * 3 matrixA = np.array([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A))", "e": 26422, "s": 26164, "text": null }, { "code": null, "e": 26430, "s": 26422, "text": "Output:" }, { "code": null, "e": 26548, "s": 26430, "text": "[[ 0.17647059 -0.00326797 -0.02287582]\n [ 0.05882353 -0.13071895 0.08496732]\n [-0.11764706 0.1503268 0.05228758]]" }, { "code": null, "e": 26559, "s": 26548, "text": "Example 2:" }, { "code": null, "e": 26566, "s": 26559, "text": "Python" }, { "code": "# Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Taking a 4 * 4 matrixA = np.array([[6, 1, 1, 3], [4, -2, 5, 1], [2, 8, 7, 6], [3, 1, 9, 7]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A))", "e": 26860, "s": 26566, "text": null }, { "code": null, "e": 26868, "s": 26860, "text": "Output:" }, { "code": null, "e": 27074, "s": 26868, "text": "[[ 0.13368984 0.10695187 0.02139037 -0.09090909]\n [-0.00229183 0.02673797 0.14820474 -0.12987013]\n [-0.12987013 0.18181818 0.06493506 -0.02597403]\n [ 0.11000764 -0.28342246 -0.11382735 0.23376623]]\n" }, { "code": null, "e": 27085, "s": 27074, "text": "Example 3:" }, { "code": null, "e": 27092, "s": 27085, "text": "Python" }, { "code": "# Python program to inverse# a matrix using numpy # Import required packageimport numpy as np # Inverses of several matrices can# be computed at onceA = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]]) # Calculating the inverse of the matrixprint(np.linalg.inv(A))", "e": 27375, "s": 27092, "text": null }, { "code": null, "e": 27383, "s": 27375, "text": "Output:" }, { "code": null, "e": 27452, "s": 27383, "text": "[[[-2. 1. ]\n [ 1.5 -0.5 ]]\n\n [[-1.25 0.75]\n [ 0.75 -0.25]]]\n" }, { "code": null, "e": 27459, "s": 27452, "text": "Picked" }, { "code": null, "e": 27472, "s": 27459, "text": "Python-numpy" }, { "code": null, "e": 27479, "s": 27472, "text": "Python" }, { "code": null, "e": 27495, "s": 27479, "text": "Python Programs" }, { "code": null, "e": 27593, "s": 27495, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27611, "s": 27593, "text": "Python Dictionary" }, { "code": null, "e": 27646, "s": 27611, "text": "Read a file line by line in Python" }, { "code": null, "e": 27668, "s": 27646, "text": "Enumerate() in Python" }, { "code": null, "e": 27700, "s": 27668, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27730, "s": 27700, "text": "Iterate over a list in Python" }, { "code": null, "e": 27773, "s": 27730, "text": "Python program to convert a list to string" }, { "code": null, "e": 27795, "s": 27773, "text": "Defaultdict in Python" }, { "code": null, "e": 27841, "s": 27795, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27880, "s": 27841, "text": "Python | Get dictionary keys as a list" } ]
How to replace an element of an ArrayList in Java?
You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with. Live Demo import java.util.ArrayList; public class ArrayListSample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("JavaFx"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); System.out.println(list); list.set(2, "HBase"); System.out.println(list); } } [JavaFx, Java, WebGL, OpenCV] [JavaFx, Java, HBase, OpenCV]
[ { "code": null, "e": 1293, "s": 1062, "text": "You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with." }, { "code": null, "e": 1304, "s": 1293, "text": " Live Demo" }, { "code": null, "e": 1664, "s": 1304, "text": "import java.util.ArrayList;\n\npublic class ArrayListSample {\n public static void main(String[] args) {\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"JavaFx\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n System.out.println(list);\n list.set(2, \"HBase\");\n System.out.println(list);\n }\n}" }, { "code": null, "e": 1724, "s": 1664, "text": "[JavaFx, Java, WebGL, OpenCV]\n[JavaFx, Java, HBase, OpenCV]" } ]
Bootstrap - Wells
A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well. The following example shows a default well − <div class = "well">Hi, am in well !!</div> You can change the size of well using the optional classes such as, well-lg or well-lg. These classes are used in conjunction with .well class. These affect the padding, making the well larger or smaller depending on the class. <div class = "well well-lg">Hi, am in large well !!</div> <div class = "well well-sm">Hi, am in small well !!</div> 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": 3608, "s": 3331, "text": "A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well. The following example shows a default well −" }, { "code": null, "e": 3652, "s": 3608, "text": "<div class = \"well\">Hi, am in well !!</div>" }, { "code": null, "e": 3880, "s": 3652, "text": "You can change the size of well using the optional classes such as, well-lg or well-lg. These classes are used in conjunction with .well class. These affect the padding, making the well larger or smaller depending on the class." }, { "code": null, "e": 3996, "s": 3880, "text": "<div class = \"well well-lg\">Hi, am in large well !!</div>\n<div class = \"well well-sm\">Hi, am in small well !!</div>" }, { "code": null, "e": 4029, "s": 3996, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4043, "s": 4029, "text": " Anadi Sharma" }, { "code": null, "e": 4078, "s": 4043, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4095, "s": 4078, "text": " Frahaan Hussain" }, { "code": null, "e": 4132, "s": 4095, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4160, "s": 4132, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4193, "s": 4160, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4205, "s": 4193, "text": " Azaz Patel" }, { "code": null, "e": 4240, "s": 4205, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4257, "s": 4240, "text": " Muhammad Ismail" }, { "code": null, "e": 4290, "s": 4257, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 4310, "s": 4290, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4317, "s": 4310, "text": " Print" }, { "code": null, "e": 4328, "s": 4317, "text": " Add Notes" } ]
Find parent of given node in a Binary Tree with given postorder traversal - GeeksforGeeks
22 Jun, 2021 Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first natural numbers For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2 4 5 Examples: Input: N = 4, K = 5 Output: 6 Explanation: Parent of the node 5 is 6. As shown in the tree above.Input: N = 5, K = 3 Output: 7 Explanation: Parent of the node 3 is 7. As shown in the tree above. Naive Approach: A simple approach is to build the tree according to the following pattern and then traverse the whole tree to find the parent of a given node.Efficient Approach: The idea is to use a binary search to find the parent of the node. As we know the binary Tree of Height N has nodes. Therefore, the search space for the binary search will be 1 to Now each node has children value either or Therefore, parents of such nodes can be found easily.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbers #include <bits/stdc++.h>using namespace std; // Function to find the parent// of the given nodeint findParent(int height, int node){ int start = 1; int end = pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } }} // Driver Codeint main(){ int height = 4; int node = 6; int k = findParent(height, node); cout << k; return 0;} // Java implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbersimport java.util.*;class GFG{ // Function to find the parent// of the given nodestatic int findParent(int height, int node){ int start = 1; int end = (int)Math.pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1;} // Driver Codepublic static void main(String[] args){ int height = 4; int node = 6; int k = findParent(height, node); System.out.print(k);}} // This code is contributed by gauravrajput1 # Python implementation to find the# parent of the given node import math # Function to find the parent# of the given nodedef findParent(height, node): start = 1 end = pow(2, height) - 1 # Check whether the given node # is a root node.if it is then # return -1 because root # node has no parent if (end == node): return -1 # Loop till we found # the given node while(node >= 1): end = end - 1 # Find the middle node of the # tree because at every level # tree parent is divided # into two halves mid = start + (end - start)//2 # if the node is found # return the parent # always the child nodes of every # node is node / 2 or (node-1) if(mid == node or end == node): return (end + 1) # if the node to be found is greater # than the mid search for left # subtree else search in right subtree elif (node < mid): end = mid else: start = mid # Driver codeif __name__ == "__main__": height = 4 node = 6 # Function Call k = findParent(height, node) print(k) // C# implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbersusing System;class GFG{ // Function to find the parent// of the given nodestatic int findParent(int height, int node){ int start = 1; int end = (int)Math.Pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1;} // Driver Codepublic static void Main(String[] args){ int height = 4; int node = 6; int k = findParent(height, node); Console.Write(k);}} // This code is contributed by Princi Singh <script> // Javascript implementation to find the // parent of the given node K in // a binary tree whose post-order // traversal is N natural numbers // Function to find the parent // of the given node function findParent(height, node) { let start = 1; let end = Math.pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves let mid = start + parseInt((end - start) / 2, 10); // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1; } let height = 4; let node = 6; let k = findParent(height, node); document.write(k); // This code is contributed by divyeshrabadiya07.</script> 7 GauravRajput1 princi singh divyeshrabadiya07 Binary Tree PostOrder Traversal Searching Tree Searching Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. k largest(or smallest) elements in an array Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Most frequent element in an array Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25368, "s": 25340, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25549, "s": 25368, "text": "Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first " }, { "code": null, "e": 25568, "s": 25551, "text": "natural numbers " }, { "code": null, "e": 25655, "s": 25568, "text": "For N = 3, the Tree will be -\n\n 7\n / \\\n 3 6\n / \\ / \\\n1 2 4 5" }, { "code": null, "e": 25668, "s": 25657, "text": "Examples: " }, { "code": null, "e": 25866, "s": 25670, "text": "Input: N = 4, K = 5 Output: 6 Explanation: Parent of the node 5 is 6. As shown in the tree above.Input: N = 5, K = 3 Output: 7 Explanation: Parent of the node 3 is 7. As shown in the tree above. " }, { "code": null, "e": 26157, "s": 25868, "text": "Naive Approach: A simple approach is to build the tree according to the following pattern and then traverse the whole tree to find the parent of a given node.Efficient Approach: The idea is to use a binary search to find the parent of the node. As we know the binary Tree of Height N has " }, { "code": null, "e": 26230, "s": 26159, "text": "nodes. Therefore, the search space for the binary search will be 1 to " }, { "code": null, "e": 26273, "s": 26232, "text": "Now each node has children value either " }, { "code": null, "e": 26279, "s": 26275, "text": "or " }, { "code": null, "e": 26386, "s": 26281, "text": "Therefore, parents of such nodes can be found easily.Below is the implementation of the above approach: " }, { "code": null, "e": 26392, "s": 26388, "text": "C++" }, { "code": null, "e": 26397, "s": 26392, "text": "Java" }, { "code": null, "e": 26405, "s": 26397, "text": "Python3" }, { "code": null, "e": 26408, "s": 26405, "text": "C#" }, { "code": null, "e": 26419, "s": 26408, "text": "Javascript" }, { "code": "// C++ implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbers #include <bits/stdc++.h>using namespace std; // Function to find the parent// of the given nodeint findParent(int height, int node){ int start = 1; int end = pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } }} // Driver Codeint main(){ int height = 4; int node = 6; int k = findParent(height, node); cout << k; return 0;}", "e": 27830, "s": 26419, "text": null }, { "code": "// Java implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbersimport java.util.*;class GFG{ // Function to find the parent// of the given nodestatic int findParent(int height, int node){ int start = 1; int end = (int)Math.pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1;} // Driver Codepublic static void main(String[] args){ int height = 4; int node = 6; int k = findParent(height, node); System.out.print(k);}} // This code is contributed by gauravrajput1", "e": 29184, "s": 27830, "text": null }, { "code": "# Python implementation to find the# parent of the given node import math # Function to find the parent# of the given nodedef findParent(height, node): start = 1 end = pow(2, height) - 1 # Check whether the given node # is a root node.if it is then # return -1 because root # node has no parent if (end == node): return -1 # Loop till we found # the given node while(node >= 1): end = end - 1 # Find the middle node of the # tree because at every level # tree parent is divided # into two halves mid = start + (end - start)//2 # if the node is found # return the parent # always the child nodes of every # node is node / 2 or (node-1) if(mid == node or end == node): return (end + 1) # if the node to be found is greater # than the mid search for left # subtree else search in right subtree elif (node < mid): end = mid else: start = mid # Driver codeif __name__ == \"__main__\": height = 4 node = 6 # Function Call k = findParent(height, node) print(k)", "e": 30354, "s": 29184, "text": null }, { "code": "// C# implementation to find the// parent of the given node K in// a binary tree whose post-order// traversal is N natural numbersusing System;class GFG{ // Function to find the parent// of the given nodestatic int findParent(int height, int node){ int start = 1; int end = (int)Math.Pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves int mid = start + (end - start) / 2; // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1;} // Driver Codepublic static void Main(String[] args){ int height = 4; int node = 6; int k = findParent(height, node); Console.Write(k);}} // This code is contributed by Princi Singh", "e": 31696, "s": 30354, "text": null }, { "code": "<script> // Javascript implementation to find the // parent of the given node K in // a binary tree whose post-order // traversal is N natural numbers // Function to find the parent // of the given node function findParent(height, node) { let start = 1; let end = Math.pow(2, height) - 1; // Condition to check whether // the given node is a root node. // if it is then return -1 because // root node has no parent if (end == node) return -1; // Loop till we found // the given node while (node >= 1) { end = end - 1; // Finding the middle node of the // tree because at every level // tree parent is // divided into two halves let mid = start + parseInt((end - start) / 2, 10); // if the node is found return // the parent always the child // nodes of every node // is node*/2 or (node-1) if (mid == node || end == node) { return (end + 1); } // if the node to be found // is greater than the mid // search for left subtree else // search in right subtree else if (node < mid) { end = mid; } else { start = mid; } } return -1; } let height = 4; let node = 6; let k = findParent(height, node); document.write(k); // This code is contributed by divyeshrabadiya07.</script>", "e": 33184, "s": 31696, "text": null }, { "code": null, "e": 33186, "s": 33184, "text": "7" }, { "code": null, "e": 33202, "s": 33188, "text": "GauravRajput1" }, { "code": null, "e": 33215, "s": 33202, "text": "princi singh" }, { "code": null, "e": 33233, "s": 33215, "text": "divyeshrabadiya07" }, { "code": null, "e": 33245, "s": 33233, "text": "Binary Tree" }, { "code": null, "e": 33265, "s": 33245, "text": "PostOrder Traversal" }, { "code": null, "e": 33275, "s": 33265, "text": "Searching" }, { "code": null, "e": 33280, "s": 33275, "text": "Tree" }, { "code": null, "e": 33290, "s": 33280, "text": "Searching" }, { "code": null, "e": 33295, "s": 33290, "text": "Tree" }, { "code": null, "e": 33393, "s": 33295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33437, "s": 33393, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 33484, "s": 33437, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 33527, "s": 33484, "text": "Find the index of an array element in Java" }, { "code": null, "e": 33550, "s": 33527, "text": "Two Pointers Technique" }, { "code": null, "e": 33584, "s": 33550, "text": "Most frequent element in an array" }, { "code": null, "e": 33634, "s": 33584, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 33669, "s": 33634, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 33703, "s": 33669, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 33732, "s": 33703, "text": "AVL Tree | Set 1 (Insertion)" } ]
Nested collection filter with JavaScript
Suppose, we have an array of nested objects like this − const arr = [{ id: 1, legs:[{ carrierName:'Pegasus' }] }, { id: 2, legs:[{ carrierName: 'SunExpress' }, { carrierName: 'SunExpress' }] }, { id: 3, legs:[{ carrierName: 'Pegasus' }, { carrierName: 'SunExpress' }] }]; We are required to write a JavaScript function that takes one such array as the first argument and a search query string as the second argument. Our function should filter the array to contain only those objects whose "carrier name" property value is the same value specified by the second argument. If for the above array, the second argument is "Pegasus". Then the output should look like − const output = [{ id: 1, legs:[{ carrierName:'Pegasus' }] }, { id: 3, legs:[{ carrierName: 'Pegasus' }, { carrierName: 'SunExpress' }] }]; The code for this will be − const arr = [{ id: 1, legs:[{ carrierName:'Pegasus' }] }, { id: 2, legs:[{ carrierName: 'SunExpress' }, { carrierName: 'SunExpress' }] }, { id: 3, legs:[{ carrierName: 'Pegasus' }, { carrierName: 'SunExpress' }] }]; const keys = ['Pegasus']; const filterByKeys = (arr = [], keys = []) => { const res = arr.filter(function(item) { const thisObj = this; return item.legs.some(leg => { return thisObj[leg.carrierName]; }); }, keys.reduce((acc, val) => { acc[val] = true; return acc; }, Object.create(null))); return res; } console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4)); And the output in the console will be − [ { "id": 1, "legs": [ { "carrierName": "Pegasus" } ] }, { "id": 3, "legs": [ { "carrierName": "Pegasus" }, { "carrierName": "SunExpress" } ] } ]
[ { "code": null, "e": 1118, "s": 1062, "text": "Suppose, we have an array of nested objects like this −" }, { "code": null, "e": 1403, "s": 1118, "text": "const arr = [{\n id: 1,\n legs:[{\n carrierName:'Pegasus'\n }]\n},\n{\n id: 2,\n legs:[{\n carrierName: 'SunExpress'\n },\n {\n carrierName: 'SunExpress'\n }]\n},\n{\n id: 3,\n legs:[{\n carrierName: 'Pegasus'\n },\n {\n carrierName: 'SunExpress'\n }]\n}];" }, { "code": null, "e": 1548, "s": 1403, "text": "We are required to write a JavaScript function that takes one such array as the first argument and a search query string as the second argument." }, { "code": null, "e": 1703, "s": 1548, "text": "Our function should filter the array to contain only those objects whose \"carrier name\" property value is the same value specified by the second argument." }, { "code": null, "e": 1796, "s": 1703, "text": "If for the above array, the second argument is \"Pegasus\". Then the output should look like −" }, { "code": null, "e": 1977, "s": 1796, "text": "const output = [{\n id: 1,\n legs:[{\n carrierName:'Pegasus'\n }]\n},\n{\n id: 3,\n legs:[{\n carrierName: 'Pegasus'\n },\n {\n carrierName: 'SunExpress'\n }]\n}];" }, { "code": null, "e": 2005, "s": 1977, "text": "The code for this will be −" }, { "code": null, "e": 2713, "s": 2005, "text": "const arr = [{\n id: 1,\n legs:[{\n carrierName:'Pegasus'\n }]\n},\n{\n id: 2,\n legs:[{\n carrierName: 'SunExpress'\n },\n {\n carrierName: 'SunExpress'\n }]\n},\n{\n id: 3,\n legs:[{\n carrierName: 'Pegasus'\n },\n {\n carrierName: 'SunExpress'\n }]\n}];\nconst keys = ['Pegasus'];\nconst filterByKeys = (arr = [], keys = []) => {\n const res = arr.filter(function(item) {\n const thisObj = this;\n return item.legs.some(leg => {\n return thisObj[leg.carrierName];\n });\n }, keys.reduce((acc, val) => {\n acc[val] = true;\n return acc;\n }, Object.create(null)));\n return res;\n}\nconsole.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));" }, { "code": null, "e": 2753, "s": 2713, "text": "And the output in the console will be −" }, { "code": null, "e": 3037, "s": 2753, "text": "[\n {\n \"id\": 1,\n \"legs\": [\n {\n \"carrierName\": \"Pegasus\"\n }\n ]\n },\n {\n \"id\": 3,\n \"legs\": [\n {\n \"carrierName\": \"Pegasus\"\n },\n {\n \"carrierName\": \"SunExpress\"\n }\n ]\n }\n]" } ]
Assembly program to transfer the status of switches - GeeksforGeeks
30 Sep, 2019 Problem – Write an assembly language program in 8085 of interfacing between 8085 and 8255. 8 switches are connected at port A. Transfer the status of these switches into port B where LEDs are connected. Example – Input port is A and output port is B. Algorithm – Construct the control word registerInput the data from port ADisplay the result in port B Construct the control word register Input the data from port A Display the result in port B Program – Explanation – MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode D6=0 & D5=0 as Poet A is in m0 mode D4=1 as Port A is taking input D3=0 & D0=0 as Port C is not taking part D2=0 as mode of Port B is m0 D1=0as Port B is displaying the resultOUT 83 putting the value of A in 83H which is the port number of port control register.IN 80 taking input from 80H which is the port number of port A.OUT 81 displaying the result in 81H which is the port number of port B.RET return MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode D6=0 & D5=0 as Poet A is in m0 mode D4=1 as Port A is taking input D3=0 & D0=0 as Port C is not taking part D2=0 as mode of Port B is m0 D1=0as Port B is displaying the result D7=1 as it is in I/O mode D6=0 & D5=0 as Poet A is in m0 mode D4=1 as Port A is taking input D3=0 & D0=0 as Port C is not taking part D2=0 as mode of Port B is m0 D1=0as Port B is displaying the result OUT 83 putting the value of A in 83H which is the port number of port control register. IN 80 taking input from 80H which is the port number of port A. OUT 81 displaying the result in 81H which is the port number of port B. RET return Akanksha_Rai microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture Pin diagram of 8086 microprocessor Computer Organization | Different Instruction Cycles Difference between SRAM and DRAM General purpose registers in 8086 microprocessor I2C Communication Protocol Memory mapped I/O and Isolated I/O Shift Micro-Operations in Computer Architecture
[ { "code": null, "e": 24780, "s": 24752, "text": "\n30 Sep, 2019" }, { "code": null, "e": 24983, "s": 24780, "text": "Problem – Write an assembly language program in 8085 of interfacing between 8085 and 8255. 8 switches are connected at port A. Transfer the status of these switches into port B where LEDs are connected." }, { "code": null, "e": 24993, "s": 24983, "text": "Example –" }, { "code": null, "e": 25031, "s": 24993, "text": "Input port is A and output port is B." }, { "code": null, "e": 25043, "s": 25031, "text": "Algorithm –" }, { "code": null, "e": 25133, "s": 25043, "text": "Construct the control word registerInput the data from port ADisplay the result in port B" }, { "code": null, "e": 25169, "s": 25133, "text": "Construct the control word register" }, { "code": null, "e": 25196, "s": 25169, "text": "Input the data from port A" }, { "code": null, "e": 25225, "s": 25196, "text": "Display the result in port B" }, { "code": null, "e": 25235, "s": 25225, "text": "Program –" }, { "code": null, "e": 25249, "s": 25235, "text": "Explanation –" }, { "code": null, "e": 25739, "s": 25249, "text": "MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode\nD6=0 & D5=0 as Poet A is in m0 mode\nD4=1 as Port A is taking input\nD3=0 & D0=0 as Port C is not taking part\nD2=0 as mode of Port B is m0\nD1=0as Port B is displaying the resultOUT 83 putting the value of A in 83H which is the port number of port control register.IN 80 taking input from 80H which is the port number of port A.OUT 81 displaying the result in 81H which is the port number of port B.RET return" }, { "code": null, "e": 25998, "s": 25739, "text": "MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode\nD6=0 & D5=0 as Poet A is in m0 mode\nD4=1 as Port A is taking input\nD3=0 & D0=0 as Port C is not taking part\nD2=0 as mode of Port B is m0\nD1=0as Port B is displaying the result" }, { "code": null, "e": 26200, "s": 25998, "text": "D7=1 as it is in I/O mode\nD6=0 & D5=0 as Poet A is in m0 mode\nD4=1 as Port A is taking input\nD3=0 & D0=0 as Port C is not taking part\nD2=0 as mode of Port B is m0\nD1=0as Port B is displaying the result" }, { "code": null, "e": 26288, "s": 26200, "text": "OUT 83 putting the value of A in 83H which is the port number of port control register." }, { "code": null, "e": 26352, "s": 26288, "text": "IN 80 taking input from 80H which is the port number of port A." }, { "code": null, "e": 26424, "s": 26352, "text": "OUT 81 displaying the result in 81H which is the port number of port B." }, { "code": null, "e": 26435, "s": 26424, "text": "RET return" }, { "code": null, "e": 26448, "s": 26435, "text": "Akanksha_Rai" }, { "code": null, "e": 26463, "s": 26448, "text": "microprocessor" }, { "code": null, "e": 26482, "s": 26463, "text": "system-programming" }, { "code": null, "e": 26519, "s": 26482, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26534, "s": 26519, "text": "microprocessor" }, { "code": null, "e": 26632, "s": 26534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26668, "s": 26632, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 26759, "s": 26668, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 26821, "s": 26759, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 26856, "s": 26821, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 26909, "s": 26856, "text": "Computer Organization | Different Instruction Cycles" }, { "code": null, "e": 26942, "s": 26909, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 26991, "s": 26942, "text": "General purpose registers in 8086 microprocessor" }, { "code": null, "e": 27018, "s": 26991, "text": "I2C Communication Protocol" }, { "code": null, "e": 27053, "s": 27018, "text": "Memory mapped I/O and Isolated I/O" } ]
How to remove all objects except one or few in R?
We can use rm remove all or few objects. < x>-rnorm(100,0.5) < y>-1:100 < z>-rpois(100,5) < a>-rep(1:5,20) To remove all objects > rm(list=ls()) ls() character(0) To remove all except a > rm(list=setdiff(ls(), "a")) > ls() [1] "a" To remove all except x and a > rm(list=ls()[! ls() %in% c("x","a")]) ls() [1] "a" "x"
[ { "code": null, "e": 1103, "s": 1062, "text": "We can use rm remove all or few objects." }, { "code": null, "e": 1169, "s": 1103, "text": "< x>-rnorm(100,0.5)\n< y>-1:100\n< z>-rpois(100,5)\n< a>-rep(1:5,20)" }, { "code": null, "e": 1191, "s": 1169, "text": "To remove all objects" }, { "code": null, "e": 1225, "s": 1191, "text": "> rm(list=ls())\nls()\ncharacter(0)" }, { "code": null, "e": 1248, "s": 1225, "text": "To remove all except a" }, { "code": null, "e": 1293, "s": 1248, "text": "> rm(list=setdiff(ls(), \"a\"))\n> ls()\n[1] \"a\"" }, { "code": null, "e": 1322, "s": 1293, "text": "To remove all except x and a" }, { "code": null, "e": 1379, "s": 1322, "text": "> rm(list=ls()[! ls() %in% c(\"x\",\"a\")])\nls()\n[1] \"a\" \"x\"" } ]
Calculate the Floor and Ceiling values in R Programming - floor() and ceiling() Function - GeeksforGeeks
03 Jun, 2020 floor() function in R Language returns the largest integer that is smaller than or equal to value passed to it as argument(i.e : rounds downs to the nearest integer). Syntax: floor(x) Parameter:x: Value to be rounded off Example 1: # R program to calculate floor value # Using floor() method answer1 <- floor(1.2) answer2 <- floor(1.5) answer3 <- floor(2.6) answer4 <- floor(-2.6) print(answer1) print(answer2) print(answer3) print(answer4) Output: 1 1 2 -3 ceiling() function in R Language returns the smallest integer that is greater than or equal to the value passed to it as argument(i.e : rounds up to the nearest integer). Syntax: ceiling(x) Parameter:x: Value to be rounded off Example 1: # R program to calculate ceiling value # Using ceiling() method answer1 <- ceiling(1.2) answer2 <- ceiling(1.5) answer3 <- ceiling(2.6) answer4 <- ceiling(-2.6) print(answer1) print(answer2) print(answer3) print(answer4) Output: 2 2 3 -2 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 25496, "s": 25468, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25663, "s": 25496, "text": "floor() function in R Language returns the largest integer that is smaller than or equal to value passed to it as argument(i.e : rounds downs to the nearest integer)." }, { "code": null, "e": 25680, "s": 25663, "text": "Syntax: floor(x)" }, { "code": null, "e": 25717, "s": 25680, "text": "Parameter:x: Value to be rounded off" }, { "code": null, "e": 25728, "s": 25717, "text": "Example 1:" }, { "code": "# R program to calculate floor value # Using floor() method answer1 <- floor(1.2) answer2 <- floor(1.5) answer3 <- floor(2.6) answer4 <- floor(-2.6) print(answer1) print(answer2) print(answer3) print(answer4) ", "e": 25946, "s": 25728, "text": null }, { "code": null, "e": 25954, "s": 25946, "text": "Output:" }, { "code": null, "e": 25964, "s": 25954, "text": "1\n1\n2\n-3\n" }, { "code": null, "e": 26135, "s": 25964, "text": "ceiling() function in R Language returns the smallest integer that is greater than or equal to the value passed to it as argument(i.e : rounds up to the nearest integer)." }, { "code": null, "e": 26154, "s": 26135, "text": "Syntax: ceiling(x)" }, { "code": null, "e": 26191, "s": 26154, "text": "Parameter:x: Value to be rounded off" }, { "code": null, "e": 26202, "s": 26191, "text": "Example 1:" }, { "code": "# R program to calculate ceiling value # Using ceiling() method answer1 <- ceiling(1.2) answer2 <- ceiling(1.5) answer3 <- ceiling(2.6) answer4 <- ceiling(-2.6) print(answer1) print(answer2) print(answer3) print(answer4) ", "e": 26432, "s": 26202, "text": null }, { "code": null, "e": 26440, "s": 26432, "text": "Output:" }, { "code": null, "e": 26450, "s": 26440, "text": "2\n2\n3\n-2\n" }, { "code": null, "e": 26466, "s": 26450, "text": "R Math-Function" }, { "code": null, "e": 26477, "s": 26466, "text": "R Language" }, { "code": null, "e": 26575, "s": 26477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26633, "s": 26575, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26685, "s": 26633, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26717, "s": 26685, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26769, "s": 26717, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26813, "s": 26769, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26851, "s": 26813, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26886, "s": 26851, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26922, "s": 26886, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 26971, "s": 26922, "text": "Remove rows with NA in one column of R DataFrame" } ]
Bash Scripting - Else If Statement - GeeksforGeeks
19 Dec, 2021 In this article, we will discuss how to write a bash script for the Else If statement. Conditional statements: The statements that perform specific functions based on certain conditions are called conditional statements. In bash scripting, we have several conditional statements like IF, IF-ELSE, IF-ELSE-IF, etc. Every statement has its way of working and according to the need, we use them. This statement is used when there is a need to check only conditions. If the condition founds to be true then the statement was written inside the if block will get executed. Syntax: if (condition) then statement fi Code: if [ 15 -gt 10 ] then # If variable less than 10 echo "a is greater than 10" fi This program will check the condition, whether 15 is greater than 10 or not. If 15 is greater than 10, the statement written inside the IF block will get printed on the screen. Output: a is greater than 10 As seen in the If statement, If the condition is true, the IF statement block gets executed but if the condition is false nothing is returned or executed. If we want the program to perform certain action after the IF statement condition is false, we use the ELSE statement after the If statement. Syntax: if [condition ] then If statement else ELSE statement fi If the condition is true: the IF statement will get executed. If the condition is false: the ELSE statement will get executed. Code: if [ 5 -gt 10 ] then # If variable less than 10 echo "number is greater than 10" else echo "number is less than 10" fi Output: number is less than 10 ELIF is the keyword used for the ELSE IF statement in bash scripting. If in a loop if more than two conditions exist which can not be solved only by using IF-ELSE statement then ELIF is used. Multiple ELIF conditions can be defined inside one if-else loop. ELIF syntax: if [ condition1 ] then statement1 elif [ condition2 ] then statement2 elif [condition3 ] then statement3 else statement_n fi Code: #!/bin/bash # Initializing the variable a=20 if [ $a < 10 ] then # If variable less than 10 echo "a is less than 10" elif [ $a < 25 ] then # If variable less than 25 echo "a is less than 25" else # If variable is greater than 25 echo "a is greater than 25" fi Output: a is greater than 25 If one or more than one conditional statement is written inside another statement, this is called nested statements like IF statements inside another IF statement. Syntax (Nested IF): If [condition] then if [condition_2] then statement_1 fi fi Example: #!/bin/bash #Initializing the variable if [ 12 -gt 10 ] then if [ 12 -gt 15] then echo "number is greater than 15" else echo "number is less than 15" fi fi Output: number is less than 15 Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization echo command in Linux with Examples
[ { "code": null, "e": 24632, "s": 24604, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24719, "s": 24632, "text": "In this article, we will discuss how to write a bash script for the Else If statement." }, { "code": null, "e": 25025, "s": 24719, "text": "Conditional statements: The statements that perform specific functions based on certain conditions are called conditional statements. In bash scripting, we have several conditional statements like IF, IF-ELSE, IF-ELSE-IF, etc. Every statement has its way of working and according to the need, we use them." }, { "code": null, "e": 25200, "s": 25025, "text": "This statement is used when there is a need to check only conditions. If the condition founds to be true then the statement was written inside the if block will get executed." }, { "code": null, "e": 25208, "s": 25200, "text": "Syntax:" }, { "code": null, "e": 25242, "s": 25208, "text": "if (condition)\nthen\n statement\nfi" }, { "code": null, "e": 25248, "s": 25242, "text": "Code:" }, { "code": null, "e": 25337, "s": 25248, "text": "if [ 15 -gt 10 ]\nthen \n# If variable less than 10 \n echo \"a is greater than 10\"\n\nfi " }, { "code": null, "e": 25514, "s": 25337, "text": "This program will check the condition, whether 15 is greater than 10 or not. If 15 is greater than 10, the statement written inside the IF block will get printed on the screen." }, { "code": null, "e": 25522, "s": 25514, "text": "Output:" }, { "code": null, "e": 25543, "s": 25522, "text": "a is greater than 10" }, { "code": null, "e": 25840, "s": 25543, "text": "As seen in the If statement, If the condition is true, the IF statement block gets executed but if the condition is false nothing is returned or executed. If we want the program to perform certain action after the IF statement condition is false, we use the ELSE statement after the If statement." }, { "code": null, "e": 25848, "s": 25840, "text": "Syntax:" }, { "code": null, "e": 25916, "s": 25848, "text": "if [condition ]\nthen \n If statement\nelse\n ELSE statement\nfi " }, { "code": null, "e": 25978, "s": 25916, "text": "If the condition is true: the IF statement will get executed." }, { "code": null, "e": 26043, "s": 25978, "text": "If the condition is false: the ELSE statement will get executed." }, { "code": null, "e": 26049, "s": 26043, "text": "Code:" }, { "code": null, "e": 26179, "s": 26049, "text": "if [ 5 -gt 10 ]\nthen \n# If variable less than 10 \n echo \"number is greater than 10\"\nelse\n echo \"number is less than 10\"\nfi " }, { "code": null, "e": 26187, "s": 26179, "text": "Output:" }, { "code": null, "e": 26210, "s": 26187, "text": "number is less than 10" }, { "code": null, "e": 26467, "s": 26210, "text": "ELIF is the keyword used for the ELSE IF statement in bash scripting. If in a loop if more than two conditions exist which can not be solved only by using IF-ELSE statement then ELIF is used. Multiple ELIF conditions can be defined inside one if-else loop." }, { "code": null, "e": 26480, "s": 26467, "text": "ELIF syntax:" }, { "code": null, "e": 26634, "s": 26480, "text": "if [ condition1 ]\nthen\n statement1\n elif [ condition2 ]\nthen\n statement2\n elif [condition3 ]\nthen\n statement3\nelse\n statement_n\nfi" }, { "code": null, "e": 26640, "s": 26634, "text": "Code:" }, { "code": null, "e": 26960, "s": 26640, "text": "#!/bin/bash\n # Initializing the variable\n a=20\n if [ $a < 10 ] \nthen \n # If variable less than 10 \n echo \"a is less than 10\" \nelif [ $a < 25 ] \nthen \n # If variable less than 25 \n echo \"a is less than 25\" \nelse \n # If variable is greater than 25 \n echo \"a is greater than 25\" \nfi " }, { "code": null, "e": 26968, "s": 26960, "text": "Output:" }, { "code": null, "e": 26989, "s": 26968, "text": "a is greater than 25" }, { "code": null, "e": 27153, "s": 26989, "text": "If one or more than one conditional statement is written inside another statement, this is called nested statements like IF statements inside another IF statement." }, { "code": null, "e": 27173, "s": 27153, "text": "Syntax (Nested IF):" }, { "code": null, "e": 27272, "s": 27173, "text": "If [condition]\nthen \n if [condition_2]\n then \n statement_1\n \n fi\nfi" }, { "code": null, "e": 27281, "s": 27272, "text": "Example:" }, { "code": null, "e": 27466, "s": 27281, "text": "#!/bin/bash\n#Initializing the variable\n\nif [ 12 -gt 10 ]\nthen\n if [ 12 -gt 15]\n then\n echo \"number is greater than 15\"\n\n else\n echo \"number is less than 15\"\n fi\nfi " }, { "code": null, "e": 27474, "s": 27466, "text": "Output:" }, { "code": null, "e": 27497, "s": 27474, "text": "number is less than 15" }, { "code": null, "e": 27509, "s": 27497, "text": "Bash-Script" }, { "code": null, "e": 27516, "s": 27509, "text": "Picked" }, { "code": null, "e": 27527, "s": 27516, "text": "Linux-Unix" }, { "code": null, "e": 27625, "s": 27527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27660, "s": 27625, "text": "tar command in Linux with examples" }, { "code": null, "e": 27696, "s": 27660, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27729, "s": 27696, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 27767, "s": 27729, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27803, "s": 27767, "text": "diff command in Linux with examples" }, { "code": null, "e": 27838, "s": 27803, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27874, "s": 27838, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27911, "s": 27874, "text": "touch command in Linux with Examples" }, { "code": null, "e": 27955, "s": 27911, "text": "Mutex lock for Linux Thread Synchronization" } ]
How to pass a 2D array as a parameter in C?
A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows. Live Demo #include <stdio.h> const int R = 4; const int C = 3; void func(int a[R][C]) { int i, j; for (i = 0; i < R; i++) for (j = 0; j < C; j++) a[i][j] += 5; ; } int main() { int a[R][C]; int i, j; for (i = 0; i < R; i++) for (j = 0; j < C; j++) a[i][j] = i+j; printf("Initial 2-D array is:\n"); for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { printf("%d ", a[i][j]); } printf("\n"); } func(a); printf("Modified 2-D array is:\n"); for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { printf("%d ", a[i][j]); } printf("\n"); } return 0; } The output of the above program is as follows. Initial 2-D array is: 0 1 2 1 2 3 2 3 4 3 4 5 Modified 2-D array is: 5 6 7 6 7 8 7 8 9 8 9 10
[ { "code": null, "e": 1238, "s": 1062, "text": "A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows." }, { "code": null, "e": 1249, "s": 1238, "text": " Live Demo" }, { "code": null, "e": 1887, "s": 1249, "text": "#include <stdio.h>\nconst int R = 4;\nconst int C = 3;\nvoid func(int a[R][C]) {\n int i, j;\n for (i = 0; i < R; i++)\n for (j = 0; j < C; j++)\n a[i][j] += 5; ;\n}\nint main() {\n int a[R][C];\n int i, j;\n for (i = 0; i < R; i++)\n for (j = 0; j < C; j++)\n a[i][j] = i+j;\n printf(\"Initial 2-D array is:\\n\");\n for (i = 0; i < R; i++) {\n for (j = 0; j < C; j++) {\n printf(\"%d \", a[i][j]);\n }\n printf(\"\\n\");\n }\n func(a);\n printf(\"Modified 2-D array is:\\n\");\n for (i = 0; i < R; i++) {\n for (j = 0; j < C; j++) {\n printf(\"%d \", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}" }, { "code": null, "e": 1934, "s": 1887, "text": "The output of the above program is as follows." }, { "code": null, "e": 2028, "s": 1934, "text": "Initial 2-D array is:\n0 1 2\n1 2 3\n2 3 4\n3 4 5\nModified 2-D array is:\n5 6 7\n6 7 8\n7 8 9\n8 9 10" } ]
A Deep Learning Approach in Predicting the Next Word(s) | by Kamil Mysiak | Towards Data Science
In this tutorial, we will walk through the process of building a deep learning model used to predict the next word(s) following a seed phrase. For example, we’ll ask the computer to predict the next 10 words after we have typed “The candidates are”. Although cutting-edge models used in your smartphones to assist with sending text messages are vastly more complex, this article should give you a general idea of the methodology involved in this prediction (classification) task. Text Processing: tokenization, n_gram sequencing, engineering features and labels, and word embeddingsBuilding a Bidirectional LSTM modelUsing our model to predict words based on a seed phrase Text Processing: tokenization, n_gram sequencing, engineering features and labels, and word embeddings Building a Bidirectional LSTM model Using our model to predict words based on a seed phrase All development for this tutorial has been done using Google Colab for its data processing capabilities. You can certainly run this code on your local machine but unless you have a dedicated GPU the training times might be rather lengthy. For this tutorial, we’ll use snippets of users’ comments on New York Times articles LINK. As this is merely a tutorial and natural language data is extremely computationally expensive the limited scope of this dataset suits our needs very well. Let’s load the required libraries and since the training data resides on Google Drive we’ll mount gdrive to Colab. Finally, we’ll change our directory to where our training data resides. Be aware that linking your Google Drive with Colab will automatically create the “Colab Notebooks” directory in your Google Drive. Due to the space between “Colab” and “Notebooks” your path directory might be slightly different. For example, notice the backward-slash used to designate a space “/content/drive/MyDrive/Colab\Notebooks” import csvimport nltkimport stringimport pandas as pdimport numpy as npfrom google.colab import drivefrom keras import backend as Kimport tensorflow as tffrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectionalfrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.optimizers import Adamdrive.mount('/content/drive/')%cd '/content/drive/MyDrive/Colab Notebooks' Determining what data will be used to train our deep learning model is very important. You obviously wouldn’t want to train your model using Shakespeare’s writing when trying to build a modern-day text prediction model. Your model would learn the contextual nuances amount the words as written by Shakespeare which would not effectively translate to today’s modern English. Using a dataset which is most likely to reflect the type of sentences you wish to predict will yield the best results. That said, utilizing very large datasets of generalized text, think Wikipedia, can also produce accurate results. We’ll use Pandas to read in the CSV file and print out the first 5 rows. We’ll be using the highlighted “snippet” column which contains an excerpt of the comments left by the user. Our data has a strong political and global news connotation but for this tutorial, this will suffice. path = '/content/drive/MyDrive/Colab Notebooks/ArticlesMarch2018.csv'df = pd.read_csv(path)df.head() We need to apply a few processing steps to our data before building our model. First, let’s combine all the snippets into a series of strings. snippet = '\n'.join(df['snippet'])print(type(snippet))print(snippet) Next, we’ll transform any capitalized word into lowercase to reduce the size of our vocabulary. Otherwise, we would have duplicate words, the only difference being the capital letter (ie. America/america). Notice the lower() function has transformed our string into a list of strings. Our corpus contains 1,385 unique snippets. corpus = snippet.lower().split('\n')print(len(corpus))print(type(corpus))print(corpus[:2]) As computers cannot process raw text data, we need to tokenize our corpus to transform the text into numerical values. Keras’s Tokenizer class transforms text based on word frequency where the most common word will have a tokenized value of 1, the next most common word the value 2, and so on. The result is a dictionary containing key/value pairs of the unique word and its assigned token determined based on word frequency. We have 6,862 unique words in our vocabulary plus (1) for out of vocabulary words. Notice that Keras’s Tokenizer class automatically removes all punctuation from our corpus. Often, when dealing with NLP prediction tasks we remove what are called “stopwords” or terms which really don’t add much meaning to a sentence (ie. the, he, in, for, etc.). However, as we are trying to predict sentences which resemble human speech we’ll keep the stopwords. tokenizer = Tokenizer()tokenizer.fit_on_texts(corpus)word_index = tokenizer.word_indextotal_unique_words = len(tokenizer.word_index) + 1 print(total_unique_words)print(word_index) Although the code below is not necessary for our analysis, it is good practice to compare the actual text along with its tokenized version for accuracy. We can see our entire tokenized corpus by applying the code below. For example, the first snippet starts with “america has a productivity problem” which has been tokenized to [193, 14, 2, 2796, 699]. Examining the word_index dictionary above, we see that the letter “a” has been tokenized with the number 2 which corresponds with the tokenized first snippet. for line in corpus: seqs = tokenizer.texts_to_sequences([line])[0]print(seqs) Here comes a tricky portion of this tutorial. In typical supervised regression or classification problems our dataset would contain the x_values (ie. input features) and y_values (ie. labels) which allows the model to learn the unique patterns among our features in relation to our labels. Our dataset seems to be missing the y_values (ie. labels). Fear not, n_grams help assist us in splitting our data in order to derive our labels. An n_gram is a sequence of words (n) sizes long. For example, “Chicago Cubs are” is an n_gram of length 3 (ie. 3_gram). We are going to take this concept one step further and iterate over each tokenized snippet to create n_grams the size of n_gram+1. Sometimes this is called a “many-to-one” sequence map. For example, our first five tokenized words in the first snippet (ie. america has a productivity problem) are [193, 14, 2, 2796, 699]. By creating n_gram+1 sequences of n_grams we produce the list below. We use this approach for all snippets which eventually yields almost 27,000 n_grams. Let’s examine the code in a bit more detail. First, we create an empty list which will hold our n_gram sequences described above. Next, we iterate over our corpus of untokenized snippets and apply the “texts_to_sequences” method to each untokenized snippet. As we saw above, the “texts_to_sequences” method simply converts each snippet to its tokenized version. Next, we iterate over each token beginning with the second (index=1) thru all remaining tokens. At each iteration, we append the sequence of n_grams to input_sequences and expand the n_gram+1. input_sequences = []for line in corpus: token_list = tokenizer.texts_to_sequences([line])[0] for i in range(1, len(token_list)): n_gram_seqs = token_list[:i+1] input_sequences.append(n_gram_seqs)print(len(input_sequences))print(input_sequences) Notice that the n_grams are of different lengths and our model requires each input sequence of n_grams to be of the same length. Therefore, we need to “pad” each n_gram sequence with zeros to the length of the longest n_gram. Max_seq_length will identify the length of the longest n_gram sequence (ie. 41). Then the “pad_sequences” method will add zeros prior to our tokens (ie. padding=’pre) to the length of max_seq_lenth (ie. 41). max_seq_length = max([len(x) for x in input_sequences])input_seqs = np.array(pad_sequences(input_sequences, maxlen=max_seq_length, padding='pre'))print(max_seq_length)print(input_seqs[:5]) Now that we have padded created and padded our n_gram sequences we can extract our features and labels. Recall that each n_gram sequence is 41 values in length. The first 40 values will be our features and the 41st value will be our label. In theory, this is a multi-class classification problem as the model will learn the relationships among our words and then provide probabilities as to which word should be next in our sequence. The model can only provide probabilities for words it has seen (ie. total number of unique words: 6,863). Since this is a multi-classification problem, we’ll apply one-hot encoding for our labels as well. Below we have printed the first three features and labels (without one-hot encoding) to demonstrate our methodology. x_values, labels = input_seqs[:, :-1], input_seqs[:, -1]y_values = tf.keras.utils.to_categorical(labels, num_classes=total_unique_words)\print(x_values[:3])print(labels[:3]) Our one-hot encoded labels (ie. y_values) have a shape of 26,937 (ie. the number of sequenced n_grams) by 6,863 (ie. the number of unique words in the corpus). Each word in our corpus, except the first word, is both a feature and a label as the model will learn what words are more and less likely to follow other sequences of words. The name of the game in these types of NLP problems is “context”. How can we optimize our strategy (ie. data processing and model complexity) to enable our model to be better able to learn the relationships among words. In its current form, our data is providing forward context for our model to learn. In other words, we know what words are more or less likely are to follow other words due to our n_gram sequences. However, the tokens used to represent each word are nothing but frequency counts which provide the model limited information regarding the contextual information among the words. For example, words such as “good” and “great” are very similar in meaning yet their respected token values are (299, 673). print(tokenizer.word_index['good'])print(tokenizer.word_index['great']) Word embeddings enable us to represent words in a n_dimensional space where words such as “good” and “great” have similar representations in this n_dimensional space which the computer can understand. In the image below we can see word embeddings (7-dimensional) for words such as dog, puppy, cat, houses, man, woman, king, and queen. The dimensions are unknown to us (not interpretable) as the model learns these dimensions as it iterates over the data. That said, to aid the reader in an understanding of word embeddings models, let’s assume the dimensions are “living being, feline, human, gender, royalty, verb, plural”. We can see that “houses” have a -0.8 embedding on D1 (ie. living being) whereas all other words score relatively high on the “living being” dimension. By learning these embeddings the computer is better able to understand the contextual relationships among words and therefore should be better able to predict the next word(s) following a seed phrase. Keras has an “Embedding” layer that can build its own word embeddings based on our corpus but we will utilize a pre-trained word embeddings model from Stanford University named “GloVe” (Global Vectors for Word Representation). The GloVe embeddings come in several flavors but we’ll use the 100-dimensional version. You will need to download the pre-trained model from this link. This model was trained on a billion words with a vocabulary (ie. unique words) of 400 thousand words. First, let’s process the embeddings text file and produce a dictionary which contains the word/character as the key and a 100-dimensional array as the value. path = '/content/drive/MyDrive/Colab Notebooks/glove.6B.100d.txt'embeddings_index = {}with open(path) as f: for line in f: values = line.split() word = values[0] coeffs = np.array(values[1:], dtype='float32') embeddings_index[word] = coeffsdict(list(embeddings_index.items())[0:2]) Now let’s create a matrix which contains the GloVe word embeddings (ie. 100-dimensional arrays) only for the words in our vocabulary. First, we create a matrix of zeros with the shape of 6,863 (ie. total number of unique words in our corpus) by 100 (ie. glove contains 100 dimensions). Then we are going to iterate over the “word_index” dictionary which contains the unique words in your corpus as the keys and their corresponding tokens as the values. At each iteration through the word_index dictionary, we’ll fetch the corresponding GloVe embeddings (ie. 100-dimensional array) stored in “embeddings_index” and update the embeddings_matrix (ie. replace the zeros with the 100-dimensional array). embeddings_matrix = np.zeros((total_unique_words, 100))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embeddings_matrix[i] = embedding_vector; We’ll build a relatively shallow model consisting of an embedding layer, three LSTM layers, three dropout layers, and a fully connected Dense layer. The first layer being the Embedding layer will enable us to utilize the pre-trained GloVe word embeddings coefficients/weights. The embedding layer requires an input_dim of the total number of unique words (ie. size of vocabulary) in your corpus and an output_dim which specifies the number of word embedding dimensions we want. As we are using GloVe 100-dimensions our out_dim parameter will be 100. We’ll pass the embeddings_matrix into the weights argument in order to use the GloVe weights and set the trainable argument to “False”, otherwise, we’ll retrain the GloVe weights. Finally, we’ll set the input_length parameter to “max_seq_length -1”. Recall that helping your model to understand the context or the relationships among the words will ultimately yield a better-performing model. We have used n_gram sequences and word embeddings to assist our model in learning these relationships. We can now utilize a specific model architecture particularly suited to examine the relationships among sequences of words. In traditional neural networks, the input and predictions/outputs are completely independent of each other. On the other hand, we are trying to predict the next word in a sentence which means the network needs to “remember” the contextual information from previous words. A Recurrent Neural Network (RNN) model architecture incorporates previous data to make future predictions. In other words, RNNs have a built-in memory function which stores information from previous words and uses that information when predicting the next word. That said, simple RNNs have trouble “remembering” information learned earlier in the sequence. In other words, given a sentence of words, an RNN can incorporate the information among a few adjacent words but as the RNN continues to iterate over the sentence the relationships between the first and the latter words in the sentence begin to lose their meaning. This is particularly important when you have a very deep model contain dozens or hundreds of hidden layers. A Long Short-Term Memory (LSTM) model gets around this issue by learning the relationships among words and allowing the important relationships to propagate through the network. This way the information learned during the first few words in a sequence can influence the prediction further in the sequence/sentence, paragraph, chapter, etc. What’s more, we will utilize a Bidirectional LSTM which will learn the relationships among words reading the sentence from left-to-right and right-to-left. The input to our LSTM layers is always 3-dimensional (ie. batch_size, max_seq_length, num_features). The batch_size will be set to None which simply specifies the layer will take any size of a batch. Max_seq_length is 40 as all snippets have been tokenized and padded to 41 minus 1 as our label. Finally, we have 100 features because GloVe has 100 dimensions. We’ll add three dropout layers (drop 30%) to help with overfitting the model to training data. Deep learning is an exercise in futility as you can adjust parameters for the rest of time. Choosing the correct optimizer is just another parameter we can tweak. We ultimately settled on Adam as it outperformed SGD and RMSProp both in terms of outright model accuracy and efficiency as the loss decreased almost twice as fast compared to SGD and RMSProp. Since the output of this model can be 1 out of 6,863 (ie. total_unique_words) words, this is a multi-class classification problem which is why we are using categorical_crossentropy as our loss function. K.clear_session()model = tf.keras.Sequential([tf.keras.layers.Embedding(input_dim = total_unique_words, output_dim=100, weights=[embeddings_matrix], input_length=max_seq_length-1, trainable=False),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256, return_sequences=True)),tf.keras.layers.Dropout(0.2), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256)),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(128, activation='relu'),tf.keras.layers.Dense(total_unique_words , activation='softmax')])model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])tf.keras.utils.plot_model(model, show_shapes=True) Finally, we’ll fit/train our model using the x_values and y_values. Selecting the batch_size is yet another parameter we can tweak to. Since we have 26,937 n_grams to train our model it would be very inefficient to load all 26,937 n_grams at once. Let’s train our model for 120 epochs where 1 epoch requires all 26, 937 n_grams to run through the model once. Therefore, 26,937 (ie. 27,000) divided by 120 means each batch_size should be 225 n_grams. However, to best utilize our memory, we’ll use a batch_size of 256. We’ll also apply an 80/20 split for training and validation data. history = model.fit(x_values, y_values, epochs=120, validation_split=0.2, verbose=1, batch_size=256) Our model is definitely overfitting our training data as training accuracy continues to increase whereas validation accuracy has plateaued. Well-performing NLP models are very data-hungry. It is not unusual to see datasets with tens of millions of words whereas our corpus consisted of merely 6,863 words. We can add additional LSTM layers, more regularization techniques along with more data to improve the model but this tutorial is meant to you give, the reader, a general idea of how to structure and build word prediction models. With that said, let’s see how well our model predicts actual new snippets. Let’s examine how well our model can generalize to news snippets which it hasn’t seen before. We’ll seed the model with the first few words of each actual news snippet from the previous month and compare the model’s prediction. def prediction(seed_text, next_words): for _ in range(next_words): token_list = tokenizer.texts_to_sequences([seed_text])[0] token_list = pad_sequences([token_list], maxlen=max_seq_length-1, padding='pre') predicted = np.argmax(model.predict(token_list, verbose=1), axis=-1) ouput_word = "" for word, index in tokenizer.word_index.items(): if index == predicted: output_word = word break seed_text += ' '+output_word print(seed_text)seed_phrase = "I understand that they could meet"next_words = len("with us, patronize us and do nothing in the end".split())prediction(seed_text, next_words) The model generated text is certainly oriented around global news and politics. We see words such as “generation”, “government”, “borrow”, “regulation”, “policies” which fits the type of data the model learned. Unfortunately, it is not difficult to identify model generated text from human snippets. Furthermore, when we used a seed phrase with a very different context “I truly enjoy riding my motorcycle” the model had a particularly difficult time classifying a sentence that resembles an accurate English sentence. “I understand that they could meet with us, patronize us and do nothing in the end” “I understand that they could meet” “I understand that they could meet the defining challenge of your generation and why you borrow” “The agency plans to publish a new regulation Tuesday that would restrict the kinds of scientific studies the agency can use when it develops policies.” “The agency plans to publish a new regulation Tuesday that would restrict the” “The agency plans to publish a new regulation Tuesday that would restrict the government through september what happens happens happens they must be the third” “Gun owners who favor increased restrictions can be an overlooked group. Some have grown more vocal, marching and testifying in favor of limits. “Gun owners who favor increased restrictions” Gun owners who favor increased restrictions for experts are recently in a plan to introduce sweeping tariffs on steel and aluminum tariffs while “I truly enjoy riding my motorcycle” “I truly enjoy riding my motorcycle list yet everyone asks i hate this question” This is certainly an exciting time in the world of natural language processing. Models such as OpenAI’s “GPT-3” are continuing to push the advancement of our NLP capabilities. This tutorial served as a rather simple introduction to text classification and I hope it inspired your interest in this exciting area. Some insights into OpenAI’s GPT-3 capabilities LINK.
[ { "code": null, "e": 421, "s": 171, "text": "In this tutorial, we will walk through the process of building a deep learning model used to predict the next word(s) following a seed phrase. For example, we’ll ask the computer to predict the next 10 words after we have typed “The candidates are”." }, { "code": null, "e": 651, "s": 421, "text": "Although cutting-edge models used in your smartphones to assist with sending text messages are vastly more complex, this article should give you a general idea of the methodology involved in this prediction (classification) task." }, { "code": null, "e": 844, "s": 651, "text": "Text Processing: tokenization, n_gram sequencing, engineering features and labels, and word embeddingsBuilding a Bidirectional LSTM modelUsing our model to predict words based on a seed phrase" }, { "code": null, "e": 947, "s": 844, "text": "Text Processing: tokenization, n_gram sequencing, engineering features and labels, and word embeddings" }, { "code": null, "e": 983, "s": 947, "text": "Building a Bidirectional LSTM model" }, { "code": null, "e": 1039, "s": 983, "text": "Using our model to predict words based on a seed phrase" }, { "code": null, "e": 1278, "s": 1039, "text": "All development for this tutorial has been done using Google Colab for its data processing capabilities. You can certainly run this code on your local machine but unless you have a dedicated GPU the training times might be rather lengthy." }, { "code": null, "e": 1523, "s": 1278, "text": "For this tutorial, we’ll use snippets of users’ comments on New York Times articles LINK. As this is merely a tutorial and natural language data is extremely computationally expensive the limited scope of this dataset suits our needs very well." }, { "code": null, "e": 2045, "s": 1523, "text": "Let’s load the required libraries and since the training data resides on Google Drive we’ll mount gdrive to Colab. Finally, we’ll change our directory to where our training data resides. Be aware that linking your Google Drive with Colab will automatically create the “Colab Notebooks” directory in your Google Drive. Due to the space between “Colab” and “Notebooks” your path directory might be slightly different. For example, notice the backward-slash used to designate a space “/content/drive/MyDrive/Colab\\Notebooks”" }, { "code": null, "e": 2559, "s": 2045, "text": "import csvimport nltkimport stringimport pandas as pdimport numpy as npfrom google.colab import drivefrom keras import backend as Kimport tensorflow as tffrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectionalfrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.optimizers import Adamdrive.mount('/content/drive/')%cd '/content/drive/MyDrive/Colab Notebooks'" }, { "code": null, "e": 3166, "s": 2559, "text": "Determining what data will be used to train our deep learning model is very important. You obviously wouldn’t want to train your model using Shakespeare’s writing when trying to build a modern-day text prediction model. Your model would learn the contextual nuances amount the words as written by Shakespeare which would not effectively translate to today’s modern English. Using a dataset which is most likely to reflect the type of sentences you wish to predict will yield the best results. That said, utilizing very large datasets of generalized text, think Wikipedia, can also produce accurate results." }, { "code": null, "e": 3449, "s": 3166, "text": "We’ll use Pandas to read in the CSV file and print out the first 5 rows. We’ll be using the highlighted “snippet” column which contains an excerpt of the comments left by the user. Our data has a strong political and global news connotation but for this tutorial, this will suffice." }, { "code": null, "e": 3550, "s": 3449, "text": "path = '/content/drive/MyDrive/Colab Notebooks/ArticlesMarch2018.csv'df = pd.read_csv(path)df.head()" }, { "code": null, "e": 3693, "s": 3550, "text": "We need to apply a few processing steps to our data before building our model. First, let’s combine all the snippets into a series of strings." }, { "code": null, "e": 3762, "s": 3693, "text": "snippet = '\\n'.join(df['snippet'])print(type(snippet))print(snippet)" }, { "code": null, "e": 4047, "s": 3762, "text": "Next, we’ll transform any capitalized word into lowercase to reduce the size of our vocabulary. Otherwise, we would have duplicate words, the only difference being the capital letter (ie. America/america). Notice the lower() function has transformed our string into a list of strings." }, { "code": null, "e": 4090, "s": 4047, "text": "Our corpus contains 1,385 unique snippets." }, { "code": null, "e": 4181, "s": 4090, "text": "corpus = snippet.lower().split('\\n')print(len(corpus))print(type(corpus))print(corpus[:2])" }, { "code": null, "e": 4607, "s": 4181, "text": "As computers cannot process raw text data, we need to tokenize our corpus to transform the text into numerical values. Keras’s Tokenizer class transforms text based on word frequency where the most common word will have a tokenized value of 1, the next most common word the value 2, and so on. The result is a dictionary containing key/value pairs of the unique word and its assigned token determined based on word frequency." }, { "code": null, "e": 5055, "s": 4607, "text": "We have 6,862 unique words in our vocabulary plus (1) for out of vocabulary words. Notice that Keras’s Tokenizer class automatically removes all punctuation from our corpus. Often, when dealing with NLP prediction tasks we remove what are called “stopwords” or terms which really don’t add much meaning to a sentence (ie. the, he, in, for, etc.). However, as we are trying to predict sentences which resemble human speech we’ll keep the stopwords." }, { "code": null, "e": 5235, "s": 5055, "text": "tokenizer = Tokenizer()tokenizer.fit_on_texts(corpus)word_index = tokenizer.word_indextotal_unique_words = len(tokenizer.word_index) + 1 print(total_unique_words)print(word_index)" }, { "code": null, "e": 5388, "s": 5235, "text": "Although the code below is not necessary for our analysis, it is good practice to compare the actual text along with its tokenized version for accuracy." }, { "code": null, "e": 5747, "s": 5388, "text": "We can see our entire tokenized corpus by applying the code below. For example, the first snippet starts with “america has a productivity problem” which has been tokenized to [193, 14, 2, 2796, 699]. Examining the word_index dictionary above, we see that the letter “a” has been tokenized with the number 2 which corresponds with the tokenized first snippet." }, { "code": null, "e": 5827, "s": 5747, "text": "for line in corpus: seqs = tokenizer.texts_to_sequences([line])[0]print(seqs)" }, { "code": null, "e": 6382, "s": 5827, "text": "Here comes a tricky portion of this tutorial. In typical supervised regression or classification problems our dataset would contain the x_values (ie. input features) and y_values (ie. labels) which allows the model to learn the unique patterns among our features in relation to our labels. Our dataset seems to be missing the y_values (ie. labels). Fear not, n_grams help assist us in splitting our data in order to derive our labels. An n_gram is a sequence of words (n) sizes long. For example, “Chicago Cubs are” is an n_gram of length 3 (ie. 3_gram)." }, { "code": null, "e": 6772, "s": 6382, "text": "We are going to take this concept one step further and iterate over each tokenized snippet to create n_grams the size of n_gram+1. Sometimes this is called a “many-to-one” sequence map. For example, our first five tokenized words in the first snippet (ie. america has a productivity problem) are [193, 14, 2, 2796, 699]. By creating n_gram+1 sequences of n_grams we produce the list below." }, { "code": null, "e": 7412, "s": 6772, "text": "We use this approach for all snippets which eventually yields almost 27,000 n_grams. Let’s examine the code in a bit more detail. First, we create an empty list which will hold our n_gram sequences described above. Next, we iterate over our corpus of untokenized snippets and apply the “texts_to_sequences” method to each untokenized snippet. As we saw above, the “texts_to_sequences” method simply converts each snippet to its tokenized version. Next, we iterate over each token beginning with the second (index=1) thru all remaining tokens. At each iteration, we append the sequence of n_grams to input_sequences and expand the n_gram+1." }, { "code": null, "e": 7672, "s": 7412, "text": "input_sequences = []for line in corpus: token_list = tokenizer.texts_to_sequences([line])[0] for i in range(1, len(token_list)): n_gram_seqs = token_list[:i+1] input_sequences.append(n_gram_seqs)print(len(input_sequences))print(input_sequences)" }, { "code": null, "e": 8106, "s": 7672, "text": "Notice that the n_grams are of different lengths and our model requires each input sequence of n_grams to be of the same length. Therefore, we need to “pad” each n_gram sequence with zeros to the length of the longest n_gram. Max_seq_length will identify the length of the longest n_gram sequence (ie. 41). Then the “pad_sequences” method will add zeros prior to our tokens (ie. padding=’pre) to the length of max_seq_lenth (ie. 41)." }, { "code": null, "e": 8295, "s": 8106, "text": "max_seq_length = max([len(x) for x in input_sequences])input_seqs = np.array(pad_sequences(input_sequences, maxlen=max_seq_length, padding='pre'))print(max_seq_length)print(input_seqs[:5])" }, { "code": null, "e": 9051, "s": 8295, "text": "Now that we have padded created and padded our n_gram sequences we can extract our features and labels. Recall that each n_gram sequence is 41 values in length. The first 40 values will be our features and the 41st value will be our label. In theory, this is a multi-class classification problem as the model will learn the relationships among our words and then provide probabilities as to which word should be next in our sequence. The model can only provide probabilities for words it has seen (ie. total number of unique words: 6,863). Since this is a multi-classification problem, we’ll apply one-hot encoding for our labels as well. Below we have printed the first three features and labels (without one-hot encoding) to demonstrate our methodology." }, { "code": null, "e": 9225, "s": 9051, "text": "x_values, labels = input_seqs[:, :-1], input_seqs[:, -1]y_values = tf.keras.utils.to_categorical(labels, num_classes=total_unique_words)\\print(x_values[:3])print(labels[:3])" }, { "code": null, "e": 9559, "s": 9225, "text": "Our one-hot encoded labels (ie. y_values) have a shape of 26,937 (ie. the number of sequenced n_grams) by 6,863 (ie. the number of unique words in the corpus). Each word in our corpus, except the first word, is both a feature and a label as the model will learn what words are more and less likely to follow other sequences of words." }, { "code": null, "e": 10278, "s": 9559, "text": "The name of the game in these types of NLP problems is “context”. How can we optimize our strategy (ie. data processing and model complexity) to enable our model to be better able to learn the relationships among words. In its current form, our data is providing forward context for our model to learn. In other words, we know what words are more or less likely are to follow other words due to our n_gram sequences. However, the tokens used to represent each word are nothing but frequency counts which provide the model limited information regarding the contextual information among the words. For example, words such as “good” and “great” are very similar in meaning yet their respected token values are (299, 673)." }, { "code": null, "e": 10350, "s": 10278, "text": "print(tokenizer.word_index['good'])print(tokenizer.word_index['great'])" }, { "code": null, "e": 11327, "s": 10350, "text": "Word embeddings enable us to represent words in a n_dimensional space where words such as “good” and “great” have similar representations in this n_dimensional space which the computer can understand. In the image below we can see word embeddings (7-dimensional) for words such as dog, puppy, cat, houses, man, woman, king, and queen. The dimensions are unknown to us (not interpretable) as the model learns these dimensions as it iterates over the data. That said, to aid the reader in an understanding of word embeddings models, let’s assume the dimensions are “living being, feline, human, gender, royalty, verb, plural”. We can see that “houses” have a -0.8 embedding on D1 (ie. living being) whereas all other words score relatively high on the “living being” dimension. By learning these embeddings the computer is better able to understand the contextual relationships among words and therefore should be better able to predict the next word(s) following a seed phrase." }, { "code": null, "e": 11808, "s": 11327, "text": "Keras has an “Embedding” layer that can build its own word embeddings based on our corpus but we will utilize a pre-trained word embeddings model from Stanford University named “GloVe” (Global Vectors for Word Representation). The GloVe embeddings come in several flavors but we’ll use the 100-dimensional version. You will need to download the pre-trained model from this link. This model was trained on a billion words with a vocabulary (ie. unique words) of 400 thousand words." }, { "code": null, "e": 11966, "s": 11808, "text": "First, let’s process the embeddings text file and produce a dictionary which contains the word/character as the key and a 100-dimensional array as the value." }, { "code": null, "e": 12261, "s": 11966, "text": "path = '/content/drive/MyDrive/Colab Notebooks/glove.6B.100d.txt'embeddings_index = {}with open(path) as f: for line in f: values = line.split() word = values[0] coeffs = np.array(values[1:], dtype='float32') embeddings_index[word] = coeffsdict(list(embeddings_index.items())[0:2])" }, { "code": null, "e": 12960, "s": 12261, "text": "Now let’s create a matrix which contains the GloVe word embeddings (ie. 100-dimensional arrays) only for the words in our vocabulary. First, we create a matrix of zeros with the shape of 6,863 (ie. total number of unique words in our corpus) by 100 (ie. glove contains 100 dimensions). Then we are going to iterate over the “word_index” dictionary which contains the unique words in your corpus as the keys and their corresponding tokens as the values. At each iteration through the word_index dictionary, we’ll fetch the corresponding GloVe embeddings (ie. 100-dimensional array) stored in “embeddings_index” and update the embeddings_matrix (ie. replace the zeros with the 100-dimensional array)." }, { "code": null, "e": 13178, "s": 12960, "text": "embeddings_matrix = np.zeros((total_unique_words, 100))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embeddings_matrix[i] = embedding_vector;" }, { "code": null, "e": 13978, "s": 13178, "text": "We’ll build a relatively shallow model consisting of an embedding layer, three LSTM layers, three dropout layers, and a fully connected Dense layer. The first layer being the Embedding layer will enable us to utilize the pre-trained GloVe word embeddings coefficients/weights. The embedding layer requires an input_dim of the total number of unique words (ie. size of vocabulary) in your corpus and an output_dim which specifies the number of word embedding dimensions we want. As we are using GloVe 100-dimensions our out_dim parameter will be 100. We’ll pass the embeddings_matrix into the weights argument in order to use the GloVe weights and set the trainable argument to “False”, otherwise, we’ll retrain the GloVe weights. Finally, we’ll set the input_length parameter to “max_seq_length -1”." }, { "code": null, "e": 14620, "s": 13978, "text": "Recall that helping your model to understand the context or the relationships among the words will ultimately yield a better-performing model. We have used n_gram sequences and word embeddings to assist our model in learning these relationships. We can now utilize a specific model architecture particularly suited to examine the relationships among sequences of words. In traditional neural networks, the input and predictions/outputs are completely independent of each other. On the other hand, we are trying to predict the next word in a sentence which means the network needs to “remember” the contextual information from previous words." }, { "code": null, "e": 15350, "s": 14620, "text": "A Recurrent Neural Network (RNN) model architecture incorporates previous data to make future predictions. In other words, RNNs have a built-in memory function which stores information from previous words and uses that information when predicting the next word. That said, simple RNNs have trouble “remembering” information learned earlier in the sequence. In other words, given a sentence of words, an RNN can incorporate the information among a few adjacent words but as the RNN continues to iterate over the sentence the relationships between the first and the latter words in the sentence begin to lose their meaning. This is particularly important when you have a very deep model contain dozens or hundreds of hidden layers." }, { "code": null, "e": 15846, "s": 15350, "text": "A Long Short-Term Memory (LSTM) model gets around this issue by learning the relationships among words and allowing the important relationships to propagate through the network. This way the information learned during the first few words in a sequence can influence the prediction further in the sequence/sentence, paragraph, chapter, etc. What’s more, we will utilize a Bidirectional LSTM which will learn the relationships among words reading the sentence from left-to-right and right-to-left." }, { "code": null, "e": 16206, "s": 15846, "text": "The input to our LSTM layers is always 3-dimensional (ie. batch_size, max_seq_length, num_features). The batch_size will be set to None which simply specifies the layer will take any size of a batch. Max_seq_length is 40 as all snippets have been tokenized and padded to 41 minus 1 as our label. Finally, we have 100 features because GloVe has 100 dimensions." }, { "code": null, "e": 16301, "s": 16206, "text": "We’ll add three dropout layers (drop 30%) to help with overfitting the model to training data." }, { "code": null, "e": 16657, "s": 16301, "text": "Deep learning is an exercise in futility as you can adjust parameters for the rest of time. Choosing the correct optimizer is just another parameter we can tweak. We ultimately settled on Adam as it outperformed SGD and RMSProp both in terms of outright model accuracy and efficiency as the loss decreased almost twice as fast compared to SGD and RMSProp." }, { "code": null, "e": 16860, "s": 16657, "text": "Since the output of this model can be 1 out of 6,863 (ie. total_unique_words) words, this is a multi-class classification problem which is why we are using categorical_crossentropy as our loss function." }, { "code": null, "e": 17521, "s": 16860, "text": "K.clear_session()model = tf.keras.Sequential([tf.keras.layers.Embedding(input_dim = total_unique_words, output_dim=100, weights=[embeddings_matrix], input_length=max_seq_length-1, trainable=False),tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256, return_sequences=True)),tf.keras.layers.Dropout(0.2), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256)),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(128, activation='relu'),tf.keras.layers.Dense(total_unique_words , activation='softmax')])model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])tf.keras.utils.plot_model(model, show_shapes=True)" }, { "code": null, "e": 18105, "s": 17521, "text": "Finally, we’ll fit/train our model using the x_values and y_values. Selecting the batch_size is yet another parameter we can tweak to. Since we have 26,937 n_grams to train our model it would be very inefficient to load all 26,937 n_grams at once. Let’s train our model for 120 epochs where 1 epoch requires all 26, 937 n_grams to run through the model once. Therefore, 26,937 (ie. 27,000) divided by 120 means each batch_size should be 225 n_grams. However, to best utilize our memory, we’ll use a batch_size of 256. We’ll also apply an 80/20 split for training and validation data." }, { "code": null, "e": 18206, "s": 18105, "text": "history = model.fit(x_values, y_values, epochs=120, validation_split=0.2, verbose=1, batch_size=256)" }, { "code": null, "e": 18816, "s": 18206, "text": "Our model is definitely overfitting our training data as training accuracy continues to increase whereas validation accuracy has plateaued. Well-performing NLP models are very data-hungry. It is not unusual to see datasets with tens of millions of words whereas our corpus consisted of merely 6,863 words. We can add additional LSTM layers, more regularization techniques along with more data to improve the model but this tutorial is meant to you give, the reader, a general idea of how to structure and build word prediction models. With that said, let’s see how well our model predicts actual new snippets." }, { "code": null, "e": 19044, "s": 18816, "text": "Let’s examine how well our model can generalize to news snippets which it hasn’t seen before. We’ll seed the model with the first few words of each actual news snippet from the previous month and compare the model’s prediction." }, { "code": null, "e": 19657, "s": 19044, "text": "def prediction(seed_text, next_words): for _ in range(next_words): token_list = tokenizer.texts_to_sequences([seed_text])[0] token_list = pad_sequences([token_list], maxlen=max_seq_length-1, padding='pre') predicted = np.argmax(model.predict(token_list, verbose=1), axis=-1) ouput_word = \"\" for word, index in tokenizer.word_index.items(): if index == predicted: output_word = word break seed_text += ' '+output_word print(seed_text)seed_phrase = \"I understand that they could meet\"next_words = len(\"with us, patronize us and do nothing in the end\".split())prediction(seed_text, next_words)" }, { "code": null, "e": 20176, "s": 19657, "text": "The model generated text is certainly oriented around global news and politics. We see words such as “generation”, “government”, “borrow”, “regulation”, “policies” which fits the type of data the model learned. Unfortunately, it is not difficult to identify model generated text from human snippets. Furthermore, when we used a seed phrase with a very different context “I truly enjoy riding my motorcycle” the model had a particularly difficult time classifying a sentence that resembles an accurate English sentence." }, { "code": null, "e": 20260, "s": 20176, "text": "“I understand that they could meet with us, patronize us and do nothing in the end”" }, { "code": null, "e": 20296, "s": 20260, "text": "“I understand that they could meet”" }, { "code": null, "e": 20393, "s": 20296, "text": "“I understand that they could meet the defining challenge of your generation and why you borrow”" }, { "code": null, "e": 20546, "s": 20393, "text": "“The agency plans to publish a new regulation Tuesday that would restrict the kinds of scientific studies the agency can use when it develops policies.”" }, { "code": null, "e": 20625, "s": 20546, "text": "“The agency plans to publish a new regulation Tuesday that would restrict the”" }, { "code": null, "e": 20785, "s": 20625, "text": "“The agency plans to publish a new regulation Tuesday that would restrict the government through september what happens happens happens they must be the third”" }, { "code": null, "e": 20930, "s": 20785, "text": "“Gun owners who favor increased restrictions can be an overlooked group. Some have grown more vocal, marching and testifying in favor of limits." }, { "code": null, "e": 20976, "s": 20930, "text": "“Gun owners who favor increased restrictions”" }, { "code": null, "e": 21121, "s": 20976, "text": "Gun owners who favor increased restrictions for experts are recently in a plan to introduce sweeping tariffs on steel and aluminum tariffs while" }, { "code": null, "e": 21158, "s": 21121, "text": "“I truly enjoy riding my motorcycle”" }, { "code": null, "e": 21239, "s": 21158, "text": "“I truly enjoy riding my motorcycle list yet everyone asks i hate this question”" }, { "code": null, "e": 21551, "s": 21239, "text": "This is certainly an exciting time in the world of natural language processing. Models such as OpenAI’s “GPT-3” are continuing to push the advancement of our NLP capabilities. This tutorial served as a rather simple introduction to text classification and I hope it inspired your interest in this exciting area." } ]
How to check if two given line segments intersect? - GeeksforGeeks
21 Oct, 2021 Given two line segments (p1, q1) and (p2, q2), find if the given line segments intersect with each other.Before we discuss solution, let us define notion of orientation. Orientation of an ordered triplet of points in the plane can be –counterclockwise –clockwise –collinear The following diagram shows different possible orientations of (a, b, c) How is Orientation useful here? Two segments (p1,q1) and (p2,q2) intersect if and only if one of the following two conditions is verified 1. General Case: – (p1, q1, p2) and (p1, q1, q2) have different orientations and – (p2, q2, p1) and (p2, q2, q1) have different orientations. Examples: 2. Special Case – (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and – the x-projections of (p1, q1) and (p2, q2) intersect – the y-projections of (p1, q1) and (p2, q2) intersect Examples: Following is the implementation based on above idea. C++ Java Python3 C# Javascript // A C++ program to check if two given line segments intersect#include <iostream>using namespace std; struct Point{ int x; int y;}; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'bool onSegment(Point p, Point q, Point r){ if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.bool doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver program to test above functionsint main(){ struct Point p1 = {1, 1}, q1 = {10, 1}; struct Point p2 = {1, 2}, q2 = {10, 2}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {10, 0}, q1 = {0, 10}; p2 = {0, 0}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; p1 = {-5, -5}, q1 = {0, 0}; p2 = {1, 1}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n"; return 0;} // Java program to check if two given line segments intersectclass GFG{ static class Point{ int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'static boolean onSegment(Point p, Point q, Point r){ if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisestatic int orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.static boolean doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codepublic static void main(String[] args){ Point p1 = new Point(1, 1); Point q1 = new Point(10, 1); Point p2 = new Point(1, 2); Point q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) System.out.println("Yes"); else System.out.println("No"); p1 = new Point(10, 1); q1 = new Point(0, 10); p2 = new Point(0, 0); q2 = new Point(10, 10); if(doIntersect(p1, q1, p2, q2)) System.out.println("Yes"); else System.out.println("No"); p1 = new Point(-5, -5); q1 = new Point(0, 0); p2 = new Point(1, 1); q2 = new Point(10, 10);; if(doIntersect(p1, q1, p2, q2)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Princi Singh # A Python3 program to find if 2 given line segments intersect or not class Point: def __init__(self, x, y): self.x = x self.y = y # Given three collinear points p, q, r, the function checks if# point q lies on line segment 'pr'def onSegment(p, q, r): if ( (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))): return True return False def orientation(p, q, r): # to find the orientation of an ordered triplet (p,q,r) # function returns the following values: # 0 : Collinear points # 1 : Clockwise points # 2 : Counterclockwise # See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/ # for details of below formula. val = (float(q.y - p.y) * (r.x - q.x)) - (float(q.x - p.x) * (r.y - q.y)) if (val > 0): # Clockwise orientation return 1 elif (val < 0): # Counterclockwise orientation return 2 else: # Collinear orientation return 0 # The main function that returns true if# the line segment 'p1q1' and 'p2q2' intersect.def doIntersect(p1,q1,p2,q2): # Find the 4 orientations required for # the general and special cases o1 = orientation(p1, q1, p2) o2 = orientation(p1, q1, q2) o3 = orientation(p2, q2, p1) o4 = orientation(p2, q2, q1) # General case if ((o1 != o2) and (o3 != o4)): return True # Special Cases # p1 , q1 and p2 are collinear and p2 lies on segment p1q1 if ((o1 == 0) and onSegment(p1, p2, q1)): return True # p1 , q1 and q2 are collinear and q2 lies on segment p1q1 if ((o2 == 0) and onSegment(p1, q2, q1)): return True # p2 , q2 and p1 are collinear and p1 lies on segment p2q2 if ((o3 == 0) and onSegment(p2, p1, q2)): return True # p2 , q2 and q1 are collinear and q1 lies on segment p2q2 if ((o4 == 0) and onSegment(p2, q1, q2)): return True # If none of the cases return False # Driver program to test above functions:p1 = Point(1, 1)q1 = Point(10, 1)p2 = Point(1, 2)q2 = Point(10, 2) if doIntersect(p1, q1, p2, q2): print("Yes")else: print("No") p1 = Point(10, 0)q1 = Point(0, 10)p2 = Point(0, 0)q2 = Point(10,10) if doIntersect(p1, q1, p2, q2): print("Yes")else: print("No") p1 = Point(-5,-5)q1 = Point(0, 0)p2 = Point(1, 1)q2 = Point(10, 10) if doIntersect(p1, q1, p2, q2): print("Yes")else: print("No") # This code is contributed by Ansh Riyal // C# program to check if two given line segments intersectusing System;using System.Collections.Generic; class GFG{ public class Point{ public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'static Boolean onSegment(Point p, Point q, Point r){ if (q.x <= Math.Max(p.x, r.x) && q.x >= Math.Min(p.x, r.x) && q.y <= Math.Max(p.y, r.y) && q.y >= Math.Min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisestatic int orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.static Boolean doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codepublic static void Main(String[] args){ Point p1 = new Point(1, 1); Point q1 = new Point(10, 1); Point p2 = new Point(1, 2); Point q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); p1 = new Point(10, 1); q1 = new Point(0, 10); p2 = new Point(0, 0); q2 = new Point(10, 10); if(doIntersect(p1, q1, p2, q2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); p1 = new Point(-5, -5); q1 = new Point(0, 0); p2 = new Point(1, 1); q2 = new Point(10, 10);; if(doIntersect(p1, q1, p2, q2)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} /* This code contributed by PrinciRaj1992 */ <script>// Javascript program to check if two given line segments intersect class Point{ constructor(x, y) { this.x = x; this.y = y; }} // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'function onSegment(p, q, r){ if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisefunction orientation(p, q, r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.function doIntersect(p1, q1, p2, q2){ // Find the four orientations needed for general and // special cases let o1 = orientation(p1, q1, p2); let o2 = orientation(p1, q1, q2); let o3 = orientation(p2, q2, p1); let o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codelet p1 = new Point(1, 1);let q1 = new Point(10, 1);let p2 = new Point(1, 2);let q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) document.write("Yes<br>");else document.write("No<br>"); p1 = new Point(10, 1); q1 = new Point(0, 10);p2 = new Point(0, 0); q2 = new Point(10, 10);if(doIntersect(p1, q1, p2, q2)) document.write("Yes<br>");else document.write("No<br>"); p1 = new Point(-5, -5); q1 = new Point(0, 0);p2 = new Point(1, 1); q2 = new Point(10, 10);;if(doIntersect(p1, q1, p2, q2)) document.write("Yes<br>");else document.write("No<br>"); // This code is contributed by avanitrachhadiya2155</script> Output: No Yes No Time Complexity: O(1) YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=wCR48FqkI4w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Sources: http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. RivestPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above princi singh princiraj1992 anshrco18 avanitrachhadiya2155 sumitgumber28 varshagumber28 subhammahato348 Adobe Geometric-Lines Snapdeal Zomato Geometric Mathematical Snapdeal Adobe Zomato Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for distance between two points on earth Find if two rectangles overlap Check whether triangle is valid or not if sides are given Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Circle and Lattice Points C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 34203, "s": 34175, "text": "\n21 Oct, 2021" }, { "code": null, "e": 34478, "s": 34203, "text": "Given two line segments (p1, q1) and (p2, q2), find if the given line segments intersect with each other.Before we discuss solution, let us define notion of orientation. Orientation of an ordered triplet of points in the plane can be –counterclockwise –clockwise –collinear " }, { "code": null, "e": 34552, "s": 34478, "text": "The following diagram shows different possible orientations of (a, b, c) " }, { "code": null, "e": 34690, "s": 34552, "text": "How is Orientation useful here? Two segments (p1,q1) and (p2,q2) intersect if and only if one of the following two conditions is verified" }, { "code": null, "e": 34832, "s": 34690, "text": "1. General Case: – (p1, q1, p2) and (p1, q1, q2) have different orientations and – (p2, q2, p1) and (p2, q2, q1) have different orientations." }, { "code": null, "e": 34844, "s": 34832, "text": "Examples: " }, { "code": null, "e": 35053, "s": 34844, "text": "2. Special Case – (p1, q1, p2), (p1, q1, q2), (p2, q2, p1), and (p2, q2, q1) are all collinear and – the x-projections of (p1, q1) and (p2, q2) intersect – the y-projections of (p1, q1) and (p2, q2) intersect" }, { "code": null, "e": 35065, "s": 35053, "text": "Examples: " }, { "code": null, "e": 35120, "s": 35065, "text": "Following is the implementation based on above idea. " }, { "code": null, "e": 35124, "s": 35120, "text": "C++" }, { "code": null, "e": 35129, "s": 35124, "text": "Java" }, { "code": null, "e": 35137, "s": 35129, "text": "Python3" }, { "code": null, "e": 35140, "s": 35137, "text": "C#" }, { "code": null, "e": 35151, "s": 35140, "text": "Javascript" }, { "code": "// A C++ program to check if two given line segments intersect#include <iostream>using namespace std; struct Point{ int x; int y;}; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'bool onSegment(Point p, Point q, Point r){ if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.bool doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver program to test above functionsint main(){ struct Point p1 = {1, 1}, q1 = {10, 1}; struct Point p2 = {1, 2}, q2 = {10, 2}; doIntersect(p1, q1, p2, q2)? cout << \"Yes\\n\": cout << \"No\\n\"; p1 = {10, 0}, q1 = {0, 10}; p2 = {0, 0}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << \"Yes\\n\": cout << \"No\\n\"; p1 = {-5, -5}, q1 = {0, 0}; p2 = {1, 1}, q2 = {10, 10}; doIntersect(p1, q1, p2, q2)? cout << \"Yes\\n\": cout << \"No\\n\"; return 0;}", "e": 37539, "s": 35151, "text": null }, { "code": "// Java program to check if two given line segments intersectclass GFG{ static class Point{ int x; int y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'static boolean onSegment(Point p, Point q, Point r){ if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisestatic int orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.static boolean doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codepublic static void main(String[] args){ Point p1 = new Point(1, 1); Point q1 = new Point(10, 1); Point p2 = new Point(1, 2); Point q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); p1 = new Point(10, 1); q1 = new Point(0, 10); p2 = new Point(0, 0); q2 = new Point(10, 10); if(doIntersect(p1, q1, p2, q2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); p1 = new Point(-5, -5); q1 = new Point(0, 0); p2 = new Point(1, 1); q2 = new Point(10, 10);; if(doIntersect(p1, q1, p2, q2)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Princi Singh", "e": 40331, "s": 37539, "text": null }, { "code": "# A Python3 program to find if 2 given line segments intersect or not class Point: def __init__(self, x, y): self.x = x self.y = y # Given three collinear points p, q, r, the function checks if# point q lies on line segment 'pr'def onSegment(p, q, r): if ( (q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))): return True return False def orientation(p, q, r): # to find the orientation of an ordered triplet (p,q,r) # function returns the following values: # 0 : Collinear points # 1 : Clockwise points # 2 : Counterclockwise # See https://www.geeksforgeeks.org/orientation-3-ordered-points/amp/ # for details of below formula. val = (float(q.y - p.y) * (r.x - q.x)) - (float(q.x - p.x) * (r.y - q.y)) if (val > 0): # Clockwise orientation return 1 elif (val < 0): # Counterclockwise orientation return 2 else: # Collinear orientation return 0 # The main function that returns true if# the line segment 'p1q1' and 'p2q2' intersect.def doIntersect(p1,q1,p2,q2): # Find the 4 orientations required for # the general and special cases o1 = orientation(p1, q1, p2) o2 = orientation(p1, q1, q2) o3 = orientation(p2, q2, p1) o4 = orientation(p2, q2, q1) # General case if ((o1 != o2) and (o3 != o4)): return True # Special Cases # p1 , q1 and p2 are collinear and p2 lies on segment p1q1 if ((o1 == 0) and onSegment(p1, p2, q1)): return True # p1 , q1 and q2 are collinear and q2 lies on segment p1q1 if ((o2 == 0) and onSegment(p1, q2, q1)): return True # p2 , q2 and p1 are collinear and p1 lies on segment p2q2 if ((o3 == 0) and onSegment(p2, p1, q2)): return True # p2 , q2 and q1 are collinear and q1 lies on segment p2q2 if ((o4 == 0) and onSegment(p2, q1, q2)): return True # If none of the cases return False # Driver program to test above functions:p1 = Point(1, 1)q1 = Point(10, 1)p2 = Point(1, 2)q2 = Point(10, 2) if doIntersect(p1, q1, p2, q2): print(\"Yes\")else: print(\"No\") p1 = Point(10, 0)q1 = Point(0, 10)p2 = Point(0, 0)q2 = Point(10,10) if doIntersect(p1, q1, p2, q2): print(\"Yes\")else: print(\"No\") p1 = Point(-5,-5)q1 = Point(0, 0)p2 = Point(1, 1)q2 = Point(10, 10) if doIntersect(p1, q1, p2, q2): print(\"Yes\")else: print(\"No\") # This code is contributed by Ansh Riyal", "e": 42845, "s": 40331, "text": null }, { "code": "// C# program to check if two given line segments intersectusing System;using System.Collections.Generic; class GFG{ public class Point{ public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'static Boolean onSegment(Point p, Point q, Point r){ if (q.x <= Math.Max(p.x, r.x) && q.x >= Math.Min(p.x, r.x) && q.y <= Math.Max(p.y, r.y) && q.y >= Math.Min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisestatic int orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.static Boolean doIntersect(Point p1, Point q1, Point p2, Point q2){ // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codepublic static void Main(String[] args){ Point p1 = new Point(1, 1); Point q1 = new Point(10, 1); Point p2 = new Point(1, 2); Point q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); p1 = new Point(10, 1); q1 = new Point(0, 10); p2 = new Point(0, 0); q2 = new Point(10, 10); if(doIntersect(p1, q1, p2, q2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); p1 = new Point(-5, -5); q1 = new Point(0, 0); p2 = new Point(1, 1); q2 = new Point(10, 10);; if(doIntersect(p1, q1, p2, q2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} /* This code contributed by PrinciRaj1992 */", "e": 45671, "s": 42845, "text": null }, { "code": "<script>// Javascript program to check if two given line segments intersect class Point{ constructor(x, y) { this.x = x; this.y = y; }} // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'function onSegment(p, q, r){ if (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwisefunction orientation(p, q, r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.function doIntersect(p1, q1, p2, q2){ // Find the four orientations needed for general and // special cases let o1 = orientation(p1, q1, p2); let o2 = orientation(p1, q1, q2); let o3 = orientation(p2, q2, p1); let o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Driver codelet p1 = new Point(1, 1);let q1 = new Point(10, 1);let p2 = new Point(1, 2);let q2 = new Point(10, 2); if(doIntersect(p1, q1, p2, q2)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); p1 = new Point(10, 1); q1 = new Point(0, 10);p2 = new Point(0, 0); q2 = new Point(10, 10);if(doIntersect(p1, q1, p2, q2)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); p1 = new Point(-5, -5); q1 = new Point(0, 0);p2 = new Point(1, 1); q2 = new Point(10, 10);;if(doIntersect(p1, q1, p2, q2)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 48238, "s": 45671, "text": null }, { "code": null, "e": 48247, "s": 48238, "text": "Output: " }, { "code": null, "e": 48257, "s": 48247, "text": "No\nYes\nNo" }, { "code": null, "e": 48279, "s": 48257, "text": "Time Complexity: O(1)" }, { "code": null, "e": 48571, "s": 48279, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=wCR48FqkI4w\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 48878, "s": 48571, "text": "Sources: http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. RivestPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 48891, "s": 48878, "text": "princi singh" }, { "code": null, "e": 48905, "s": 48891, "text": "princiraj1992" }, { "code": null, "e": 48915, "s": 48905, "text": "anshrco18" }, { "code": null, "e": 48936, "s": 48915, "text": "avanitrachhadiya2155" }, { "code": null, "e": 48950, "s": 48936, "text": "sumitgumber28" }, { "code": null, "e": 48965, "s": 48950, "text": "varshagumber28" }, { "code": null, "e": 48981, "s": 48965, "text": "subhammahato348" }, { "code": null, "e": 48987, "s": 48981, "text": "Adobe" }, { "code": null, "e": 49003, "s": 48987, "text": "Geometric-Lines" }, { "code": null, "e": 49012, "s": 49003, "text": "Snapdeal" }, { "code": null, "e": 49019, "s": 49012, "text": "Zomato" }, { "code": null, "e": 49029, "s": 49019, "text": "Geometric" }, { "code": null, "e": 49042, "s": 49029, "text": "Mathematical" }, { "code": null, "e": 49051, "s": 49042, "text": "Snapdeal" }, { "code": null, "e": 49057, "s": 49051, "text": "Adobe" }, { "code": null, "e": 49064, "s": 49057, "text": "Zomato" }, { "code": null, "e": 49077, "s": 49064, "text": "Mathematical" }, { "code": null, "e": 49087, "s": 49077, "text": "Geometric" }, { "code": null, "e": 49185, "s": 49087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49194, "s": 49185, "text": "Comments" }, { "code": null, "e": 49207, "s": 49194, "text": "Old Comments" }, { "code": null, "e": 49256, "s": 49207, "text": "Program for distance between two points on earth" }, { "code": null, "e": 49287, "s": 49256, "text": "Find if two rectangles overlap" }, { "code": null, "e": 49345, "s": 49287, "text": "Check whether triangle is valid or not if sides are given" }, { "code": null, "e": 49396, "s": 49345, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 49422, "s": 49396, "text": "Circle and Lattice Points" }, { "code": null, "e": 49437, "s": 49422, "text": "C++ Data Types" }, { "code": null, "e": 49480, "s": 49437, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 49504, "s": 49480, "text": "Merge two sorted arrays" } ]
Neural Net from scratch (using Numpy) | by Sanjay.M | Towards Data Science
This post is about building a shallow NeuralNetowrk(nn) from scratch (with just 1 hidden layer) for a classification problem using numpy library in Python and also compare the performance against the LogisticRegression (using scikit learn). Building a nn from scratch helps in understanding how nn works in the back-end and it is essential for building effective models. Without delay lets dive into building our simple shallow nn model from scratch. Complete code is available here. For this task I am generating a dataset using the scikit learn dataset generator make_gaussian_quantiles function (Generate isotropic Gaussian and label samples by quantile). Generated input dataset will have have two features (‘X1’ and ‘X2’ and output ‘Y’ will have 2 classes (red: 0, blue:1), with total of 200 examples. def load_extra_datasets(): N = 200 gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles (mean=None, cov=0.7, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None) return gaussian_quantilesgaussian_quantiles= load_extra_datasets()X, Y = gaussian_quantilesX, Y = X.T, Y.reshape(1, Y.shape[0])# Visualize the dataplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); The dataset generated has two classes, plotted as red and blue points. Our goal is to build a Machine Learning classifier that predicts the correct class given the X- and Y- coordinates. As we can see in the graph, data is not linearly separable, so we can’t draw a straight line that separates the two classes. This means that linear classifiers such as Logistic Regression, won’t be able to fit these kind of data properly. In these cases nn comes to our rescue. In nn feature engineering is not required, as hidden layers will automatically learn feature patterns to classifies the data accurately. First lets train a LR classifier using the inputs x- and y-values and the output will be the predicted class (0 or 1). We will use the Regression class from scikit-learn clf = sklearn.linear_model.LogisticRegressionCV()clf.fit(X.T, Y.T)# Plot the decision boundary for logistic regressionplot_decision_boundary(lambda x: clf.predict(x), X, Y)plt.title("Logistic Regression")# Print accuracyLR_predictions = clf.predict(X.T)print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) + '% ' + "(percentage of correctly labelled datapoints)") As we can see from the above LR could able to classify just 53% of the data points correctly, as these data points are not linearly separable. Lets now build a simple nn with 1 hidden layer with 4 neurons. Input layer will have 2 nodes as our data has two features (X1 and X2) and output layer will have one node , based on the probability threshold we will classify the output as either red or blue (0 or 1). We need to do the below steps to build our nn model. Define Network structure ( # of input units, # of hidden units, etc). Initialise the model’s parameters Perform the below steps in loop until we get minimum cost/optimal parameters. Implement forward propagationCompute lossImplement backward propagation to get the gradientsUpdate parameters Implement forward propagation Compute loss Implement backward propagation to get the gradients Update parameters Then merge all the above steps into one function we call `nn_model()`. Once we built `nn_model()` and learnt the right parameters,we can make predictions on new data. Define Network Structure: As mentioned earlier, for input layer number of nodes will be 2, and for hidden layer i set it to 4. By choosing more nodes in this layer, we can make model learn complex functions. But it comes at a cost of heavy computation to make predictions and learn the network parameters. More number of hidden layers and nodes could also lead to over-fitting of our data. Define Network Structure: As mentioned earlier, for input layer number of nodes will be 2, and for hidden layer i set it to 4. By choosing more nodes in this layer, we can make model learn complex functions. But it comes at a cost of heavy computation to make predictions and learn the network parameters. More number of hidden layers and nodes could also lead to over-fitting of our data. #X and Y are the input and output variables n_x = X.shape[0] # size of input layer` n_h = 4 n_y = Y.shape[0] # size of output layer 2. Initialize the model’s parameters: W1 (weight matrix for hidden layer) and W2(wight matrix for output layer) parameters are initialized randomly using the numpy random function. Multiplied by 0.01 as we do not want the initial weights to be large, because it will lead to slower learning. b1 and b2 are initialized to zeros. W1 — weight matrix of shape (n_h, n_x) for hidden layer b1 — bias vector of shape (n_h, 1) W2 — weight matrix of shape (n_y, n_h) for output layer b2 — bias vector of shape (n_y, 1) W1 = np.random.randn(n_h,n_x) * 0.01 b1 = np.zeros(shape=(n_h, 1)) W2 = np.random.randn(n_y,n_h) * 0.01 b2 = np.zeros(shape=(n_y, 1)) 3. Forward Propagation: During forward propagation the input feature matrix is fed to the every neuron in the hidden layer. Which will be multiplied by the respective initial set of weights(W1) and bias(b1) will be added to form Z1 matrix (linear transformations of the given inputs). Then we apply the non-linearity to Z1 by feeding it through an activation function (to apply non-linearity). We chose ‘tanh’ as our activation function as it fits to many scenarios. The output of this activation function/hidden layer will be A1 (which is a matrix of size (4,1) contains the activations from the 4 neurons i.e a1, a2, a3 a4). For the next layer which is the final output layer in our case, we multiply the inputs from the previous layer (A1) with the initial weights of output layer(W2), add bias(b2) to form Z2. Then apply the sigmoid activation function on Z2 to produce out final output A2 (which is our predictions). We used sigmoid for our final layer as we want our output to be between 0 and 1. Based on the probability threshold we can decide weather the output is red or blue. This is how nn makes predictions during forward propagation, which is just a sequence of matrix multiplications and application of activation function(s). # Implement Forward Propagation to calculate A2 (probabilities) Z1 = np.dot(W1,X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2,A1) + b2 A2 = sigmoid(Z2) # Final output prediction 4. Compute Loss: Now that we have our predictions, next step would be to check how much our predictions differ from the actual values, i.e loss/error. Here we do not use mean square error (MSE) to compute our loss as our prediction function is non-linear(sigmoid). Squaring the prediction will results in non-convex function with many local minimums. In such case gradient descent many not find the optimal global minimum. Hence we use the binary Cross_Entropy loss (log-likelihood method for error estimate), this cost function is convex in nature, so reaching the global minimum point (minimum loss point) will be easier. Below is the cost function formula and the code. m : Number of training examples # Compute the cross-entropy costlogprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2)cost = - np.sum(logprobs) / m 5. BackPropagation/Gradient Descent (GD): Back propagation is used to calculate the gradients(slope/derivatives) of the loss function with respect to the model parameters(w1,b1,w2,b2). To minimize our cost we use the GD algorithm, which uses the computed gradients to update the parameters so that the our cost keeps reducing over iterations, i.e it help move towards global minimum. Below are the gradient/slope computing formulae for each of the model parameters. ‘m’ is number of training examples. dZ2 = A2 - Y dW2 = (1 / m) * np.dot(dZ2, A1.T) db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1 / m) * np.dot(dZ1, X.T) db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True) 6. Update the parameters: Once we have computed our gradients, we multiply them with a factor called learning-rate (converging rate) and subtract from the initial parameters to get the updated parameters(weights and biases). Learning rate should be minimal so that we will not miss the global minimum point. Multiply the gradients by learning rate Subtract from weights W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 Now we have performed one round of forward propagation and backward propagation for all the training examples, i.e we completed 1 epoch. We need to repeat these steps over multiple epochs till our cost is minimum(model reaches global minimum point)or the learning stops (no updates to the parameters). Below is the function ‘nn_model’ which performs all the above operations repeatedly over a given number of epochs(num_iterations) and prints the cost after every 1000 epochs. The output of this function will be the final set of optimised parameters(weights/baiases). 7. Predictions: Below is the function which makes prediction using the learned parameters, by doing just a forward propagation. We are setting a threshold as 0.5, if the output of the final layer (A2) is > 0.5 then we are classifying it as 1:blue else 0:red. Now lets train our final model by running the function nn_model over 5000 epochs and see the results. As we can see from the results, our nn model has learnt the patterns well. Which is able to learn non-linear decision boundaries which separates the classes. And our cost started from 0.69 and reached to 0.089 after 4000 epochs. Final accuracy came to 93% which is much higher compare to what we achieved from Logistic regression which is just 53%. Tuning the Hidden Layer size: Next step would be to decide the optimal number of neurons for the hidden layer to see if our model can do better without over-fitting. For this lets train the model with different number of nodes (1,2,3,4,5,20,50) and see the results. Below are the findings from this test. The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models over-fit the data. We can see that at n_h = 50 the model seems over-fitting (100% accuracy). The best hidden layer size seems to be around n_h = 4. Indeed, a value around here seems to fits the data well without also incurring noticeble over-fitting. Thanks a lot for reading till end, please comment for any suggestions/changes. And please do 👏 if you like the post... 😉
[ { "code": null, "e": 413, "s": 172, "text": "This post is about building a shallow NeuralNetowrk(nn) from scratch (with just 1 hidden layer) for a classification problem using numpy library in Python and also compare the performance against the LogisticRegression (using scikit learn)." }, { "code": null, "e": 623, "s": 413, "text": "Building a nn from scratch helps in understanding how nn works in the back-end and it is essential for building effective models. Without delay lets dive into building our simple shallow nn model from scratch." }, { "code": null, "e": 656, "s": 623, "text": "Complete code is available here." }, { "code": null, "e": 979, "s": 656, "text": "For this task I am generating a dataset using the scikit learn dataset generator make_gaussian_quantiles function (Generate isotropic Gaussian and label samples by quantile). Generated input dataset will have have two features (‘X1’ and ‘X2’ and output ‘Y’ will have 2 classes (red: 0, blue:1), with total of 200 examples." }, { "code": null, "e": 1398, "s": 979, "text": "def load_extra_datasets(): N = 200 gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles (mean=None, cov=0.7, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None) return gaussian_quantilesgaussian_quantiles= load_extra_datasets()X, Y = gaussian_quantilesX, Y = X.T, Y.reshape(1, Y.shape[0])# Visualize the dataplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);" }, { "code": null, "e": 2000, "s": 1398, "text": "The dataset generated has two classes, plotted as red and blue points. Our goal is to build a Machine Learning classifier that predicts the correct class given the X- and Y- coordinates. As we can see in the graph, data is not linearly separable, so we can’t draw a straight line that separates the two classes. This means that linear classifiers such as Logistic Regression, won’t be able to fit these kind of data properly. In these cases nn comes to our rescue. In nn feature engineering is not required, as hidden layers will automatically learn feature patterns to classifies the data accurately." }, { "code": null, "e": 2170, "s": 2000, "text": "First lets train a LR classifier using the inputs x- and y-values and the output will be the predicted class (0 or 1). We will use the Regression class from scikit-learn" }, { "code": null, "e": 2618, "s": 2170, "text": "clf = sklearn.linear_model.LogisticRegressionCV()clf.fit(X.T, Y.T)# Plot the decision boundary for logistic regressionplot_decision_boundary(lambda x: clf.predict(x), X, Y)plt.title(\"Logistic Regression\")# Print accuracyLR_predictions = clf.predict(X.T)print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) + '% ' + \"(percentage of correctly labelled datapoints)\")" }, { "code": null, "e": 2761, "s": 2618, "text": "As we can see from the above LR could able to classify just 53% of the data points correctly, as these data points are not linearly separable." }, { "code": null, "e": 3028, "s": 2761, "text": "Lets now build a simple nn with 1 hidden layer with 4 neurons. Input layer will have 2 nodes as our data has two features (X1 and X2) and output layer will have one node , based on the probability threshold we will classify the output as either red or blue (0 or 1)." }, { "code": null, "e": 3081, "s": 3028, "text": "We need to do the below steps to build our nn model." }, { "code": null, "e": 3151, "s": 3081, "text": "Define Network structure ( # of input units, # of hidden units, etc)." }, { "code": null, "e": 3185, "s": 3151, "text": "Initialise the model’s parameters" }, { "code": null, "e": 3263, "s": 3185, "text": "Perform the below steps in loop until we get minimum cost/optimal parameters." }, { "code": null, "e": 3373, "s": 3263, "text": "Implement forward propagationCompute lossImplement backward propagation to get the gradientsUpdate parameters" }, { "code": null, "e": 3403, "s": 3373, "text": "Implement forward propagation" }, { "code": null, "e": 3416, "s": 3403, "text": "Compute loss" }, { "code": null, "e": 3468, "s": 3416, "text": "Implement backward propagation to get the gradients" }, { "code": null, "e": 3486, "s": 3468, "text": "Update parameters" }, { "code": null, "e": 3654, "s": 3486, "text": "Then merge all the above steps into one function we call `nn_model()`. Once we built `nn_model()` and learnt the right parameters,we can make predictions on new data." }, { "code": null, "e": 4044, "s": 3654, "text": "Define Network Structure: As mentioned earlier, for input layer number of nodes will be 2, and for hidden layer i set it to 4. By choosing more nodes in this layer, we can make model learn complex functions. But it comes at a cost of heavy computation to make predictions and learn the network parameters. More number of hidden layers and nodes could also lead to over-fitting of our data." }, { "code": null, "e": 4434, "s": 4044, "text": "Define Network Structure: As mentioned earlier, for input layer number of nodes will be 2, and for hidden layer i set it to 4. By choosing more nodes in this layer, we can make model learn complex functions. But it comes at a cost of heavy computation to make predictions and learn the network parameters. More number of hidden layers and nodes could also lead to over-fitting of our data." }, { "code": null, "e": 4575, "s": 4434, "text": "#X and Y are the input and output variables n_x = X.shape[0] # size of input layer` n_h = 4 n_y = Y.shape[0] # size of output layer" }, { "code": null, "e": 4903, "s": 4575, "text": "2. Initialize the model’s parameters: W1 (weight matrix for hidden layer) and W2(wight matrix for output layer) parameters are initialized randomly using the numpy random function. Multiplied by 0.01 as we do not want the initial weights to be large, because it will lead to slower learning. b1 and b2 are initialized to zeros." }, { "code": null, "e": 5085, "s": 4903, "text": "W1 — weight matrix of shape (n_h, n_x) for hidden layer b1 — bias vector of shape (n_h, 1) W2 — weight matrix of shape (n_y, n_h) for output layer b2 — bias vector of shape (n_y, 1)" }, { "code": null, "e": 5232, "s": 5085, "text": " W1 = np.random.randn(n_h,n_x) * 0.01 b1 = np.zeros(shape=(n_h, 1)) W2 = np.random.randn(n_y,n_h) * 0.01 b2 = np.zeros(shape=(n_y, 1))" }, { "code": null, "e": 5859, "s": 5232, "text": "3. Forward Propagation: During forward propagation the input feature matrix is fed to the every neuron in the hidden layer. Which will be multiplied by the respective initial set of weights(W1) and bias(b1) will be added to form Z1 matrix (linear transformations of the given inputs). Then we apply the non-linearity to Z1 by feeding it through an activation function (to apply non-linearity). We chose ‘tanh’ as our activation function as it fits to many scenarios. The output of this activation function/hidden layer will be A1 (which is a matrix of size (4,1) contains the activations from the 4 neurons i.e a1, a2, a3 a4)." }, { "code": null, "e": 6474, "s": 5859, "text": "For the next layer which is the final output layer in our case, we multiply the inputs from the previous layer (A1) with the initial weights of output layer(W2), add bias(b2) to form Z2. Then apply the sigmoid activation function on Z2 to produce out final output A2 (which is our predictions). We used sigmoid for our final layer as we want our output to be between 0 and 1. Based on the probability threshold we can decide weather the output is red or blue. This is how nn makes predictions during forward propagation, which is just a sequence of matrix multiplications and application of activation function(s)." }, { "code": null, "e": 6657, "s": 6474, "text": "# Implement Forward Propagation to calculate A2 (probabilities) Z1 = np.dot(W1,X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2,A1) + b2 A2 = sigmoid(Z2) # Final output prediction" }, { "code": null, "e": 7330, "s": 6657, "text": "4. Compute Loss: Now that we have our predictions, next step would be to check how much our predictions differ from the actual values, i.e loss/error. Here we do not use mean square error (MSE) to compute our loss as our prediction function is non-linear(sigmoid). Squaring the prediction will results in non-convex function with many local minimums. In such case gradient descent many not find the optimal global minimum. Hence we use the binary Cross_Entropy loss (log-likelihood method for error estimate), this cost function is convex in nature, so reaching the global minimum point (minimum loss point) will be easier. Below is the cost function formula and the code." }, { "code": null, "e": 7362, "s": 7330, "text": "m : Number of training examples" }, { "code": null, "e": 7499, "s": 7362, "text": "# Compute the cross-entropy costlogprobs = np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2)cost = - np.sum(logprobs) / m" }, { "code": null, "e": 7883, "s": 7499, "text": "5. BackPropagation/Gradient Descent (GD): Back propagation is used to calculate the gradients(slope/derivatives) of the loss function with respect to the model parameters(w1,b1,w2,b2). To minimize our cost we use the GD algorithm, which uses the computed gradients to update the parameters so that the our cost keeps reducing over iterations, i.e it help move towards global minimum." }, { "code": null, "e": 8001, "s": 7883, "text": "Below are the gradient/slope computing formulae for each of the model parameters. ‘m’ is number of training examples." }, { "code": null, "e": 8260, "s": 8001, "text": " dZ2 = A2 - Y dW2 = (1 / m) * np.dot(dZ2, A1.T) db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True) dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2)) dW1 = (1 / m) * np.dot(dZ1, X.T) db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True)" }, { "code": null, "e": 8568, "s": 8260, "text": "6. Update the parameters: Once we have computed our gradients, we multiply them with a factor called learning-rate (converging rate) and subtract from the initial parameters to get the updated parameters(weights and biases). Learning rate should be minimal so that we will not miss the global minimum point." }, { "code": null, "e": 8608, "s": 8568, "text": "Multiply the gradients by learning rate" }, { "code": null, "e": 8630, "s": 8608, "text": "Subtract from weights" }, { "code": null, "e": 8763, "s": 8630, "text": " W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2" }, { "code": null, "e": 9065, "s": 8763, "text": "Now we have performed one round of forward propagation and backward propagation for all the training examples, i.e we completed 1 epoch. We need to repeat these steps over multiple epochs till our cost is minimum(model reaches global minimum point)or the learning stops (no updates to the parameters)." }, { "code": null, "e": 9332, "s": 9065, "text": "Below is the function ‘nn_model’ which performs all the above operations repeatedly over a given number of epochs(num_iterations) and prints the cost after every 1000 epochs. The output of this function will be the final set of optimised parameters(weights/baiases)." }, { "code": null, "e": 9591, "s": 9332, "text": "7. Predictions: Below is the function which makes prediction using the learned parameters, by doing just a forward propagation. We are setting a threshold as 0.5, if the output of the final layer (A2) is > 0.5 then we are classifying it as 1:blue else 0:red." }, { "code": null, "e": 9693, "s": 9591, "text": "Now lets train our final model by running the function nn_model over 5000 epochs and see the results." }, { "code": null, "e": 10042, "s": 9693, "text": "As we can see from the results, our nn model has learnt the patterns well. Which is able to learn non-linear decision boundaries which separates the classes. And our cost started from 0.69 and reached to 0.089 after 4000 epochs. Final accuracy came to 93% which is much higher compare to what we achieved from Logistic regression which is just 53%." }, { "code": null, "e": 10308, "s": 10042, "text": "Tuning the Hidden Layer size: Next step would be to decide the optimal number of neurons for the hidden layer to see if our model can do better without over-fitting. For this lets train the model with different number of nodes (1,2,3,4,5,20,50) and see the results." }, { "code": null, "e": 10347, "s": 10308, "text": "Below are the findings from this test." }, { "code": null, "e": 10560, "s": 10347, "text": "The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models over-fit the data. We can see that at n_h = 50 the model seems over-fitting (100% accuracy)." }, { "code": null, "e": 10718, "s": 10560, "text": "The best hidden layer size seems to be around n_h = 4. Indeed, a value around here seems to fits the data well without also incurring noticeble over-fitting." } ]
Check if two Nodes are Cousins | Practice | GeeksforGeeks
Given the binary Tree of and two-node values. Check whether the two-node values are cousins of each other or not. Example 1: Input: 1 / \ 2 3 a = 2, b = 3 Output: 0 Example 2: Input: 1 / \ 2 3 / \ 5 4 a = 5, b = 4 Output: 1 Explanation: Here, nodes 5 and 4 are at the same level and have different parent nodes. Hence, they both are cousins Your Task: You don't need to read input or print anything. Your task is to complete the function isCousins() that takes the root node of the tree (having all nodes distinct), and two integers 'a' and 'b' as inputs. It returns true if the nodes with given values 'a' and 'b' are Cousins of each other and returns false otherwise. Two nodes value are cousins of each other if they are at the same level and have different parents. (The driver code will print 1 if the returned values is true,otherwise 0.) Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1<=Number of Nodes<=1000 Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 somyadebsarkar3633 weeks ago pair<int,int> solve(Node* root,int n,int level){ if(root==NULL){ return make_pair(0,0); } if(root->data==n){ return make_pair(n,level); } pair<int,int> left=solve(root->left,n,level+1); pair<int,int> right=solve(root->right,n,level+1); if(left.first ==n){ return make_pair(root->data,left.second); } else if(right.first==n){ return make_pair(root->data,right.second); } else if(left.first!=0){ return left; } else if(right.first!=0){ return right; } return make_pair(0,0); } bool isCousins(Node *root, int a, int b){ //add code here. pair<int,int> fir=solve(root,a,0); pair<int,int> sec=solve(root,b,0); if(fir.first!=sec.first && fir.second==sec.second){ return true; } return false;} 0 amanpandey30071 month ago bool isCousins(Node *root, int a, int b){ queue<Node*>q; q.push(root); int f1=0,f2=0; while(!q.empty()) { int k=q.size(); while(k--) { Node*t=q.front(); q.pop(); if(t->left and t->right) { if(t->left->data==a and t->right->data==b) return false; if(t->left->data==b and t->right->data==a) return false; } if(t->data==a) f1=1; if(t->data==b) f2=1; if(t->left) q.push(t->left); if(t->right) q.push(t->right); } if( f1 and f2) return true; if(f1 || f2) return false; } return false;} +1 satyamagarwal2491 month ago def isCousin(root, a, b): l[0], l[1],p[0],p[1] = None,None,None,None if root is None: return False util(root,a,b,0) if l[0] is not None and l[0] == l[1] and p[0] != p[1]: return True return False def util(root,a,b,level): if root is None: return if root.left and root.left.data == a: l[0] = level p[0] = root.data elif root.left and root.left.data == b: l[1] = level p[1] = root.data if root.right and root.right.data == a: l[0] = level p[0] = root.data elif root.right and root.right.data == b: l[1] = level p[1] = root.data util(root.left,a,b,level+1) util(root.right,a,b,level+1) l=[None] * 2 # level p=[None] * 2 # parent 0 tarun2002ts0211 month ago my logic - bfs code bool isCousins(Node *root, int a, int b){ //add code here. if(root->data==a||root->data==b||a==b) return false; int la=0,lb=0,lev=0; Node*pra=NULL,*prb=NULL; queue<Node*>q; q.push(root); while(!q.empty()) { int s=q.size();lev++; while(s--) { Node* temp1=q.front();q.pop(); if(temp1->left) { q.push(temp1->left); if(temp1->left->data==a) {la=lev;pra=temp1;} else if(temp1->left->data==b) {lb=lev;prb=temp1;} } if(temp1->right) { q.push(temp1->right); if(temp1->right->data==a) {la=lev;pra=temp1;} else if(temp1->right->data==b) {lb=lev;prb=temp1;} } } } if(la==lb && pra!=prb) return true; return false;} 0 kaditya73221 month ago class Solution { // Returns true if the nodes with values 'a' and 'b' are cousins. Else returns false public boolean isCousins(Node root, int A, int B) { if(A == B) return false; if (root == null) return false; Queue<Node> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); boolean isAexist = false; boolean isBexist = false; for (int i = 0; i < size; i++) { Node cur = queue.poll(); if (cur.data == A) isAexist = true; if (cur.data == B) isBexist = true; if (cur.left != null && cur.right != null) { if (cur.left.data == A && cur.right.data == B) { return false; } if (cur.left.data == B && cur.right.data == A) { return false; } } if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } if (isAexist && isBexist) return true; } return false; } } 0 amukherjee98am3 months ago bool isCousins(Node *root, int a, int b) { //add code here. bool found=false; bool sp=false; if(!root) return false; queue<Node*> q; q.push(root); while(!q.empty()) { int n=q.size(); while(n--) { Node* temp=q.front(); q.pop(); if(temp->left) { q.push(temp->left); if(temp->left->data==a || temp->left->data==b) { if(found && !sp) return true; found=true; //found in the same level sp=true; //If its the left child then there is a chance that right one matches with the other value. So same parent is true } } if(temp->right) { q.push(temp->right); if(temp->right->data==a || temp->right->data==b) { if(found && !sp) return true; found=true; } if(temp->right->data!=a && temp->right->data!=b) { sp=false; //making the same parent false } } sp=false; } if(found) return false; //If one element is found but the other one is not in a level then they can't be cousin } } 0 17vineet3 months ago bool isCousins(Node *root, int a, int b) { Node* parent1;Node* parent2 ; int level1,level2 ; int level = 0 ; queue<Node*> q ; q.push(root) ; while(1) { int size = q.size() ; if(size==0) break ; while(size>0) { Node* node = q.front() ; q.pop() ; if(node->left) { if(node->left->data==a) { parent1 = node ; level1 = level ; } else if(node->left->data==b) { parent2 = node ; level2 = level ; } q.push(node->left) ; } if(node->right) { if(node->right->data==a) { parent1 = node ; level1 = level ; } else if(node->right->data==b) { parent2 = node ; level2 = level ; } q.push(node->right) ; } size-- ; } level++ ; } if(level1 == level2) if(parent1 == parent2) return false ; else return true ; return false ; } +1 hrithikraina20013 months ago C++ easy level order traversal solution bool isCousins(Node *root, int a, int b) { queue<Node* >q; if(root==NULL) { return 0; } q.push(root); while(!q.empty()) { int n= q.size(); bool aexist=false; bool bexist=false; for(int i=0;i<n;i++) { Node *temp= q.front(); q.pop(); if(temp->data==a) { aexist=true; } if(temp->data==b) { bexist=true; } if(temp->left && temp->right) { if(temp->left->data==a && temp->right->data==b) { return false; } if(temp->left->data==b && temp->right->data==a) { return false; } } if(temp->left){ q.push(temp->left); } if(temp->right) { q.push(temp->right); } } if(aexist && bexist) { return 1; } } return 0; //add code here. } Explaination: 1. We are using level order traversing here. So there is no need to keep check of levels of both the cousin elements. 2. Make aexist and bexist as false before traversing a particular level. If it's present, we make it true inside the program. 3. If left and right child of node is there, and left is a and right is b or left is b and right is a, then we have to return false as both have same parent. 4. at the end of the particular level traversal , we check if a and b exists there and if yes, then return 1. 0 chessnoobdj4 months ago Easy c++ void helper(Node *root, int x, int y, vector<pair<int,int>> &res, int depth){ if(!root) return; if(root->left && root->right){ if(root->left->data==x && root->right->data==y) return; if(root->left->data==y && root->right->data==x) return; } if(root->data==x || root->data==y){ res.push_back(make_pair(root->data, depth)); return; } helper(root->left, x, y, res, depth-1); helper(root->right, x, y, res, depth-1); } bool isCousins(Node *root, int x, int y) { int depth = 0; vector <pair <int,int> > res; helper(root, x, y, res, depth); //for(auto i:res) //cout << i.first << " " << i.second << "\n"; if(res.size() == 2 && res[0].second == res[1].second) return true; return false; } 0 moulyapradeep5 months ago Goldmansachs 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": 352, "s": 238, "text": "Given the binary Tree of and two-node values. Check whether the two-node values are cousins of each other or not." }, { "code": null, "e": 363, "s": 352, "text": "Example 1:" }, { "code": null, "e": 424, "s": 363, "text": "Input:\n 1\n / \\\n 2 3\na = 2, b = 3\nOutput: 0\n\n" }, { "code": null, "e": 435, "s": 424, "text": "Example 2:" }, { "code": null, "e": 644, "s": 435, "text": "Input:\n 1\n / \\ \n 2 3\n / \\\n 5 4 \na = 5, b = 4\nOutput: 1\nExplanation: Here, nodes 5 and 4 are\nat the same level and have different\nparent nodes. Hence, they both are cousins " }, { "code": null, "e": 1150, "s": 644, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isCousins() that takes the root node of the tree (having all nodes distinct), and two integers 'a' and 'b' as inputs. It returns true if the nodes with given values 'a' and 'b' are Cousins of each other and returns false otherwise. \nTwo nodes value are cousins of each other if they are at the same level and have different parents. (The driver code will print 1 if the returned values is true,otherwise 0.)" }, { "code": null, "e": 1231, "s": 1150, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 1269, "s": 1231, "text": "Constraints:\n1<=Number of Nodes<=1000" }, { "code": null, "e": 1580, "s": 1269, "text": "\nNote: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1582, "s": 1580, "text": "0" }, { "code": null, "e": 1611, "s": 1582, "text": "somyadebsarkar3633 weeks ago" }, { "code": null, "e": 2162, "s": 1611, "text": "pair<int,int> solve(Node* root,int n,int level){ if(root==NULL){ return make_pair(0,0); } if(root->data==n){ return make_pair(n,level); } pair<int,int> left=solve(root->left,n,level+1); pair<int,int> right=solve(root->right,n,level+1); if(left.first ==n){ return make_pair(root->data,left.second); } else if(right.first==n){ return make_pair(root->data,right.second); } else if(left.first!=0){ return left; } else if(right.first!=0){ return right; } return make_pair(0,0); }" }, { "code": null, "e": 2384, "s": 2162, "text": "bool isCousins(Node *root, int a, int b){ //add code here. pair<int,int> fir=solve(root,a,0); pair<int,int> sec=solve(root,b,0); if(fir.first!=sec.first && fir.second==sec.second){ return true; } return false;}" }, { "code": null, "e": 2386, "s": 2384, "text": "0" }, { "code": null, "e": 2412, "s": 2386, "text": "amanpandey30071 month ago" }, { "code": null, "e": 3191, "s": 2412, "text": "bool isCousins(Node *root, int a, int b){ queue<Node*>q; q.push(root); int f1=0,f2=0; while(!q.empty()) { int k=q.size(); while(k--) { Node*t=q.front(); q.pop(); if(t->left and t->right) { if(t->left->data==a and t->right->data==b) return false; if(t->left->data==b and t->right->data==a) return false; } if(t->data==a) f1=1; if(t->data==b) f2=1; if(t->left) q.push(t->left); if(t->right) q.push(t->right); } if( f1 and f2) return true; if(f1 || f2) return false; } return false;}" }, { "code": null, "e": 3194, "s": 3191, "text": "+1" }, { "code": null, "e": 3222, "s": 3194, "text": "satyamagarwal2491 month ago" }, { "code": null, "e": 4003, "s": 3222, "text": "def isCousin(root, a, b):\n l[0], l[1],p[0],p[1] = None,None,None,None\n \n if root is None:\n return False\n util(root,a,b,0)\n if l[0] is not None and l[0] == l[1] and p[0] != p[1]:\n return True\n return False\n \n\ndef util(root,a,b,level):\n if root is None:\n return\n if root.left and root.left.data == a:\n l[0] = level\n p[0] = root.data\n elif root.left and root.left.data == b:\n l[1] = level\n p[1] = root.data\n if root.right and root.right.data == a:\n l[0] = level\n p[0] = root.data\n elif root.right and root.right.data == b:\n l[1] = level\n p[1] = root.data\n util(root.left,a,b,level+1) \n util(root.right,a,b,level+1) \n\nl=[None] * 2 # level\np=[None] * 2 # parent\n" }, { "code": null, "e": 4005, "s": 4003, "text": "0" }, { "code": null, "e": 4031, "s": 4005, "text": "tarun2002ts0211 month ago" }, { "code": null, "e": 4051, "s": 4031, "text": "my logic - bfs code" }, { "code": null, "e": 4894, "s": 4053, "text": "bool isCousins(Node *root, int a, int b){ //add code here. if(root->data==a||root->data==b||a==b) return false; int la=0,lb=0,lev=0; Node*pra=NULL,*prb=NULL; queue<Node*>q; q.push(root); while(!q.empty()) { int s=q.size();lev++; while(s--) { Node* temp1=q.front();q.pop(); if(temp1->left) { q.push(temp1->left); if(temp1->left->data==a) {la=lev;pra=temp1;} else if(temp1->left->data==b) {lb=lev;prb=temp1;} } if(temp1->right) { q.push(temp1->right); if(temp1->right->data==a) {la=lev;pra=temp1;} else if(temp1->right->data==b) {lb=lev;prb=temp1;} } } } if(la==lb && pra!=prb) return true; return false;}" }, { "code": null, "e": 4896, "s": 4894, "text": "0" }, { "code": null, "e": 4919, "s": 4896, "text": "kaditya73221 month ago" }, { "code": null, "e": 5897, "s": 4919, "text": "\nclass Solution {\n \n // Returns true if the nodes with values 'a' and 'b' are cousins. Else returns false\n public boolean isCousins(Node root, int A, int B) {\n \n if(A == B) return false;\n \n if (root == null) return false;\nQueue<Node> queue = new LinkedList<>();\nqueue.offer(root);\nwhile (!queue.isEmpty()) {\n int size = queue.size();\n boolean isAexist = false; \n boolean isBexist = false; \n for (int i = 0; i < size; i++) {\n Node cur = queue.poll();\n if (cur.data == A) isAexist = true;\n if (cur.data == B) isBexist = true;\n if (cur.left != null && cur.right != null) { \n if (cur.left.data == A && cur.right.data == B) { \n return false;\n }\n if (cur.left.data == B && cur.right.data == A) { \n return false;\n }\n }\n if (cur.left != null) {\n queue.offer(cur.left);\n }\n if (cur.right != null) {\n queue.offer(cur.right);\n }\n }\n if (isAexist && isBexist) return true;\n}\nreturn false;\n \n \n }\n}" }, { "code": null, "e": 5899, "s": 5897, "text": "0" }, { "code": null, "e": 5926, "s": 5899, "text": "amukherjee98am3 months ago" }, { "code": null, "e": 7346, "s": 5926, "text": "bool isCousins(Node *root, int a, int b)\n{\n //add code here.\n bool found=false;\n bool sp=false;\n if(!root)\n return false;\n queue<Node*> q;\n q.push(root);\n while(!q.empty())\n {\n int n=q.size();\n while(n--)\n {\n Node* temp=q.front();\n q.pop();\n if(temp->left)\n {\n q.push(temp->left);\n if(temp->left->data==a || temp->left->data==b)\n {\n if(found && !sp)\n return true;\n found=true; //found in the same level\n sp=true; //If its the left child then there is a chance that right one matches with the other value. So same parent is true\n }\n }\n if(temp->right)\n {\n q.push(temp->right);\n if(temp->right->data==a || temp->right->data==b)\n {\n if(found && !sp)\n return true;\n found=true;\n }\n if(temp->right->data!=a && temp->right->data!=b)\n {\n sp=false; //making the same parent false\n }\n }\n sp=false;\n }\n if(found)\n return false; //If one element is found but the other one is not in a level then they can't be cousin\n }\n \n}" }, { "code": null, "e": 7348, "s": 7346, "text": "0" }, { "code": null, "e": 7369, "s": 7348, "text": "17vineet3 months ago" }, { "code": null, "e": 8708, "s": 7369, "text": "bool isCousins(Node *root, int a, int b)\n{\n Node* parent1;Node* parent2 ;\n int level1,level2 ;\n int level = 0 ;\n queue<Node*> q ;\n q.push(root) ;\n while(1)\n {\n int size = q.size() ;\n if(size==0)\n break ;\n while(size>0)\n {\n Node* node = q.front() ;\n q.pop() ;\n if(node->left)\n {\n if(node->left->data==a)\n {\n parent1 = node ;\n level1 = level ;\n }\n else if(node->left->data==b)\n {\n parent2 = node ;\n level2 = level ;\n }\n q.push(node->left) ;\n }\n if(node->right)\n {\n if(node->right->data==a)\n {\n parent1 = node ;\n level1 = level ;\n }\n else if(node->right->data==b)\n {\n parent2 = node ;\n level2 = level ;\n }\n q.push(node->right) ;\n }\n size-- ;\n }\n level++ ;\n }\n if(level1 == level2)\n if(parent1 == parent2)\n return false ;\n else\n return true ;\n return false ;\n}" }, { "code": null, "e": 8711, "s": 8708, "text": "+1" }, { "code": null, "e": 8740, "s": 8711, "text": "hrithikraina20013 months ago" }, { "code": null, "e": 8780, "s": 8740, "text": "C++ easy level order traversal solution" }, { "code": null, "e": 9946, "s": 8780, "text": "bool isCousins(Node *root, int a, int b)\n{\n queue<Node* >q;\n \n if(root==NULL)\n {\n return 0;\n }\n q.push(root);\n \n while(!q.empty())\n {\n int n= q.size();\n bool aexist=false;\n bool bexist=false;\n for(int i=0;i<n;i++)\n {\n Node *temp= q.front();\n q.pop();\n if(temp->data==a)\n {\n aexist=true;\n }\n if(temp->data==b)\n {\n bexist=true;\n }\n if(temp->left && temp->right)\n {\n if(temp->left->data==a && temp->right->data==b)\n {\n return false;\n }\n if(temp->left->data==b && temp->right->data==a)\n {\n return false;\n }\n }\n \n \n if(temp->left){\n q.push(temp->left);\n }\n if(temp->right)\n {\n q.push(temp->right);\n }\n }\n if(aexist && bexist)\n {\n return 1;\n }\n \n \n }\n return 0;\n //add code here.\n}" }, { "code": null, "e": 10473, "s": 9946, "text": "Explaination: \n1. We are using level order traversing here. So there is no need to keep check of levels of both the cousin elements.\n2. Make aexist and bexist as false before traversing a particular level. If it's present, we make it true inside the program.\n3. If left and right child of node is there, and left is a and right is b or left is b and right is a, then we have to return false as both have same parent.\n4. at the end of the particular level traversal , we check if a and b exists there and if yes, then return 1." }, { "code": null, "e": 10475, "s": 10473, "text": "0" }, { "code": null, "e": 10499, "s": 10475, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 10508, "s": 10499, "text": "Easy c++" }, { "code": null, "e": 11415, "s": 10508, "text": "void helper(Node *root, int x, int y, vector<pair<int,int>> &res, int depth){\n if(!root)\n return;\n if(root->left && root->right){\n if(root->left->data==x && root->right->data==y)\n return;\n if(root->left->data==y && root->right->data==x)\n return;\n }\n if(root->data==x || root->data==y){\n res.push_back(make_pair(root->data, depth));\n return;\n }\n helper(root->left, x, y, res, depth-1);\n helper(root->right, x, y, res, depth-1);\n }\n \nbool isCousins(Node *root, int x, int y)\n{\n int depth = 0;\n vector <pair <int,int> > res;\n helper(root, x, y, res, depth);\n //for(auto i:res)\n //cout << i.first << \" \" << i.second << \"\\n\";\n if(res.size() == 2 && res[0].second == res[1].second)\n return true;\n return false;\n}" }, { "code": null, "e": 11417, "s": 11415, "text": "0" }, { "code": null, "e": 11443, "s": 11417, "text": "moulyapradeep5 months ago" }, { "code": null, "e": 11456, "s": 11443, "text": "Goldmansachs" }, { "code": null, "e": 11602, "s": 11456, "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": 11638, "s": 11602, "text": " Login to access your submissions. " }, { "code": null, "e": 11648, "s": 11638, "text": "\nProblem\n" }, { "code": null, "e": 11658, "s": 11648, "text": "\nContest\n" }, { "code": null, "e": 11721, "s": 11658, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11869, "s": 11721, "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": 12077, "s": 11869, "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": 12183, "s": 12077, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Prototype - escapeHTML() Method
This method converts HTML special characters to their entity equivalents. string.escapeHTML(); Returns a string. <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function showResult() { var str = '<div class = "article">This is an article</div>'; alert( str.escapeHTML() ); } </script> </head> <body> <p>Click the button to see the result.</p> <br /> <br /> <input type = "button" value = "Result" onclick = "showResult();"/> </body> </html> Click the button to see the result. 127 Lectures 11.5 hours Aleksandar Cucukovic Print Add Notes Bookmark this page
[ { "code": null, "e": 2135, "s": 2061, "text": "This method converts HTML special characters to their entity equivalents." }, { "code": null, "e": 2157, "s": 2135, "text": "string.escapeHTML();\n" }, { "code": null, "e": 2175, "s": 2157, "text": "Returns a string." }, { "code": null, "e": 2698, "s": 2175, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function showResult() {\n var str = '<div class = \"article\">This is an article</div>';\n alert( str.escapeHTML() );\n }\n </script>\n </head>\n\n <body>\n <p>Click the button to see the result.</p>\n <br />\n <br />\n <input type = \"button\" value = \"Result\" onclick = \"showResult();\"/>\n </body>\n</html>" }, { "code": null, "e": 2734, "s": 2698, "text": "Click the button to see the result." }, { "code": null, "e": 2771, "s": 2734, "text": "\n 127 Lectures \n 11.5 hours \n" }, { "code": null, "e": 2793, "s": 2771, "text": " Aleksandar Cucukovic" }, { "code": null, "e": 2800, "s": 2793, "text": " Print" }, { "code": null, "e": 2811, "s": 2800, "text": " Add Notes" } ]
Create a Horizontal Navigation Bar with CSS
To create a horizontal navigation bar, set the <li> elements as inline. You can try to run the following code to create horizontal navigation bar Live Demo <!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; } .active { background-color: #4CAF50; color: white; } li { border-bottom: 1px solid #555; display: inline; } </style> </head> <body> <ul> <li><a href = "#home">Home</a></li> <li><a href = "#company" class = "active">Company</a></li> <li><a href = "#product">Product</a></li> <li><a href = "#services">Services</a></li> <li><a href = "#contact">Contact</a></li> </ul> </body> </html>
[ { "code": null, "e": 1134, "s": 1062, "text": "To create a horizontal navigation bar, set the <li> elements as inline." }, { "code": null, "e": 1208, "s": 1134, "text": "You can try to run the following code to create horizontal navigation bar" }, { "code": null, "e": 1218, "s": 1208, "text": "Live Demo" }, { "code": null, "e": 1910, "s": 1218, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 0;\n padding: 0;\n }\n .active {\n background-color: #4CAF50;\n color: white;\n }\n li {\n border-bottom: 1px solid #555;\n display: inline;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href = \"#home\">Home</a></li>\n <li><a href = \"#company\" class = \"active\">Company</a></li>\n <li><a href = \"#product\">Product</a></li>\n <li><a href = \"#services\">Services</a></li>\n <li><a href = \"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>" } ]
ASP.NET WP - Delete Database Data
In this chapter, we will be covering how to delete an existing database record. This topic is similar to the previous chapter except that − instead of updating the record, we will delete it. Both deleting and updating processes are almost the same, except that deleting is simpler. This example will also contain two web pages. On the first page, the users will select a record which they want to delete. On the first page, the users will select a record which they want to delete. On the second page, the record to be deleted is then displayed so that the user can confirm that he/she wants to delete that record. On the second page, the record to be deleted is then displayed so that the user can confirm that he/she wants to delete that record. Let’s have a look into a simple example in which we will delete an existing database record. First of all, we need to create a new CSHTML page. Enter ListCustomersForDelete.cshtml in the Name field and click OK. Now replace the following code in the ListCustomersForDelete.cshtml file. @{ var db = Database.Open("WebPagesCustomers"); var selectQueryString = "SELECT * FROM Customers ORDER BY FirstName"; } <!DOCTYPE html> <html> <head> <title>Delete a Customer</title> <style> table, th, td { border: solid 1px #bbbbbb; border-collapse: collapse; padding: 2px; } </style> </head> <body> <h1>Delete a Customer</h1> <table> <thead> <tr> <th> </th> <th>First Name</th> <th>Last Name</th> <th>Address</th> </tr> </thead> <tbody> @foreach(var row in db.Query(selectQueryString)){ <tr> <td><a href = "@Href("~/DeleteCustomer", row.Id)">Delete</a></td> <td>@row.FirstName</td> <td>@row.LastName</td> <td>@row.Address</td> </tr> } </tbody> </table> </body> </html> As you can see, the above page is similar to the EditCustomers.cshtml page, the only difference is that instead of displaying an Edit link for each customer. Use the following code to add the Delete link. Once this is done, it will display a Delete link that will help in deleting the selected record. <td><a href = "@Href("~/DeleteCustomer", row.Id)">Delete</a></td> We should start with creating a CHTML file as shown in the following screenshot. Enter DeleteCustomer.cshtml in the name field and click OK. Now replace DeleteCustomer.cshtml file with the following code. @{ var db = Database.Open("WebPagesCustomers"); var CustomerId = UrlData[0]; if (CustomerId.IsEmpty()) { Response.Redirect("~/ListCustomersForDelete"); } var customer = db.QuerySingle("SELECT * FROM CUSTOMERS WHERE ID = @0", CustomerId); if( IsPost && !CustomerId.IsEmpty()) { var deleteQueryString = "DELETE FROM Customers WHERE Id=@0"; db.Execute(deleteQueryString, CustomerId); Response.Redirect("~/ListCustomersForDelete"); } } <!DOCTYPE html> <html> <head> <title>Delete Customer</title> </head> <body> <h1>Delete Customer - Confirmation</h1> <form method = "post" action = "" name = "form"> <p>Are you sure you want to delete the following Customer?</p> <p>FirstName: @customer.FirstName <br /> LastName: @customer.LastName <br /> Address: @customer.Address</p> <p><input type = "submit" value = "Delete" /></p> </form> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/ListCustomersForDelete and you will see the following web page. As you can see all the customers from the database and also the Delete link for each customer. Let’s select the Delete link for Kerry Hill and you will see the following page. All the information is displayed for that customer. When you click on the Delete button then this customer will be deleted from the database. Let’s click the Delete button and you will see that it is deleted from the database as shown in the following screenshot. Now the database only has two records. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2613, "s": 2285, "text": "In this chapter, we will be covering how to delete an existing database record. This topic is similar to the previous chapter except that − instead of updating the record, we will delete it. Both deleting and updating processes are almost the same, except that deleting is simpler. This example will also contain two web pages." }, { "code": null, "e": 2690, "s": 2613, "text": "On the first page, the users will select a record which they want to delete." }, { "code": null, "e": 2767, "s": 2690, "text": "On the first page, the users will select a record which they want to delete." }, { "code": null, "e": 2900, "s": 2767, "text": "On the second page, the record to be deleted is then displayed so that the user can confirm that he/she wants to delete that record." }, { "code": null, "e": 3033, "s": 2900, "text": "On the second page, the record to be deleted is then displayed so that the user can confirm that he/she wants to delete that record." }, { "code": null, "e": 3177, "s": 3033, "text": "Let’s have a look into a simple example in which we will delete an existing database record. First of all, we need to create a new CSHTML page." }, { "code": null, "e": 3245, "s": 3177, "text": "Enter ListCustomersForDelete.cshtml in the Name field and click OK." }, { "code": null, "e": 3319, "s": 3245, "text": "Now replace the following code in the ListCustomersForDelete.cshtml file." }, { "code": null, "e": 4374, "s": 3319, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var selectQueryString = \"SELECT * FROM Customers ORDER BY FirstName\";\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Delete a Customer</title>\n <style>\n table, th, td {\n border: solid 1px #bbbbbb;\n border-collapse: collapse;\n padding: 2px;\n }\n </style>\n \n </head>\n <body>\n <h1>Delete a Customer</h1>\n \n <table>\n <thead>\n <tr>\n <th> </th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Address</th>\n </tr>\n </thead>\n \n <tbody>\n @foreach(var row in db.Query(selectQueryString)){\n <tr>\n <td><a href = \"@Href(\"~/DeleteCustomer\", row.Id)\">Delete</a></td>\n <td>@row.FirstName</td>\n <td>@row.LastName</td>\n <td>@row.Address</td>\n </tr>\n }\n </tbody>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 4676, "s": 4374, "text": "As you can see, the above page is similar to the EditCustomers.cshtml page, the only difference is that instead of displaying an Edit link for each customer. Use the following code to add the Delete link. Once this is done, it will display a Delete link that will help in deleting the selected record." }, { "code": null, "e": 4743, "s": 4676, "text": "<td><a href = \"@Href(\"~/DeleteCustomer\", row.Id)\">Delete</a></td>\n" }, { "code": null, "e": 4824, "s": 4743, "text": "We should start with creating a CHTML file as shown in the following screenshot." }, { "code": null, "e": 4948, "s": 4824, "text": "Enter DeleteCustomer.cshtml in the name field and click OK. Now replace DeleteCustomer.cshtml file with the following code." }, { "code": null, "e": 5944, "s": 4948, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var CustomerId = UrlData[0];\n \n if (CustomerId.IsEmpty()) {\n Response.Redirect(\"~/ListCustomersForDelete\");\n }\n var customer = db.QuerySingle(\"SELECT * FROM CUSTOMERS WHERE ID = @0\", CustomerId);\n \n if( IsPost && !CustomerId.IsEmpty()) {\n var deleteQueryString = \"DELETE FROM Customers WHERE Id=@0\";\n db.Execute(deleteQueryString, CustomerId);\n Response.Redirect(\"~/ListCustomersForDelete\");\n }\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Delete Customer</title>\n </head>\n \n <body>\n <h1>Delete Customer - Confirmation</h1>\n \n <form method = \"post\" action = \"\" name = \"form\">\n <p>Are you sure you want to delete the following Customer?</p>\n <p>FirstName: @customer.FirstName <br />\n LastName: @customer.LastName <br />\n Address: @customer.Address</p>\n <p><input type = \"submit\" value = \"Delete\" /></p>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 6093, "s": 5944, "text": "Now let’s run the application and specify the following url − http://localhost:36905/ListCustomersForDelete and you will see the following web page." }, { "code": null, "e": 6269, "s": 6093, "text": "As you can see all the customers from the database and also the Delete link for each customer. Let’s select the Delete link for Kerry Hill and you will see the following page." }, { "code": null, "e": 6411, "s": 6269, "text": "All the information is displayed for that customer. When you click on the Delete button then this customer will be deleted from the database." }, { "code": null, "e": 6533, "s": 6411, "text": "Let’s click the Delete button and you will see that it is deleted from the database as shown in the following screenshot." }, { "code": null, "e": 6572, "s": 6533, "text": "Now the database only has two records." }, { "code": null, "e": 6607, "s": 6572, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6621, "s": 6607, "text": " Anadi Sharma" }, { "code": null, "e": 6656, "s": 6621, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6679, "s": 6656, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6713, "s": 6679, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 6733, "s": 6713, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6768, "s": 6733, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6785, "s": 6768, "text": " University Code" }, { "code": null, "e": 6820, "s": 6785, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6837, "s": 6820, "text": " University Code" }, { "code": null, "e": 6871, "s": 6837, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 6886, "s": 6871, "text": " Bhrugen Patel" }, { "code": null, "e": 6893, "s": 6886, "text": " Print" }, { "code": null, "e": 6904, "s": 6893, "text": " Add Notes" } ]
PyQt5 - QFormLayout Class
QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. Mainly three overloads of addRow() method addLayout() are commonly used. addRow(QLabel, QWidget) Adds a row containing label and input field addRow(QLabel, QLayout) Adds a child layout in the second column addRow(QWidget) Adds a widget spanning both columns This code adds a LineEdit field to input name in the first row. Then it adds a vertical box layout for two address fields in the second column of the next row. Next, a horizontal box layout object containing two Radio button fields is added in the second column of the third row. The fourth row shows two buttons ‘Submit’ and ‘Cancel’. import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * def window(): app = QApplication(sys.argv) win = QWidget() l1 = QLabel("Name") nm = QLineEdit() l2 = QLabel("Address") add1 = QLineEdit() add2 = QLineEdit() fbox = QFormLayout() fbox.addRow(l1,nm) vbox = QVBoxLayout() vbox.addWidget(add1) vbox.addWidget(add2) fbox.addRow(l2,vbox) hbox = QHBoxLayout() r1 = QRadioButton("Male") r2 = QRadioButton("Female") hbox.addWidget(r1) hbox.addWidget(r2) hbox.addStretch() fbox.addRow(QLabel("sex"),hbox) fbox.addRow(QPushButton("Submit"),QPushButton("Cancel")) win.setLayout(fbox) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) if __name__ == '__main__': window() The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2260, "s": 1963, "text": "QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. Mainly three overloads of addRow() method addLayout() are commonly used." }, { "code": null, "e": 2284, "s": 2260, "text": "addRow(QLabel, QWidget)" }, { "code": null, "e": 2328, "s": 2284, "text": "Adds a row containing label and input field" }, { "code": null, "e": 2352, "s": 2328, "text": "addRow(QLabel, QLayout)" }, { "code": null, "e": 2393, "s": 2352, "text": "Adds a child layout in the second column" }, { "code": null, "e": 2409, "s": 2393, "text": "addRow(QWidget)" }, { "code": null, "e": 2445, "s": 2409, "text": "Adds a widget spanning both columns" }, { "code": null, "e": 2781, "s": 2445, "text": "This code adds a LineEdit field to input name in the first row. Then it adds a vertical box layout for two address fields in the second column of the next row. Next, a horizontal box layout object containing two Radio button fields is added in the second column of the third row. The fourth row shows two buttons ‘Submit’ and ‘Cancel’." }, { "code": null, "e": 3584, "s": 2781, "text": "import sys \nfrom PyQt5.QtCore import * \nfrom PyQt5.QtGui import * \nfrom PyQt5.QtWidgets import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n\n l1 = QLabel(\"Name\")\n nm = QLineEdit()\n\n l2 = QLabel(\"Address\")\n add1 = QLineEdit()\n add2 = QLineEdit()\n fbox = QFormLayout()\n fbox.addRow(l1,nm)\n vbox = QVBoxLayout()\n\n vbox.addWidget(add1)\n vbox.addWidget(add2)\n fbox.addRow(l2,vbox)\n hbox = QHBoxLayout()\n\n r1 = QRadioButton(\"Male\")\n r2 = QRadioButton(\"Female\")\n hbox.addWidget(r1)\n hbox.addWidget(r2)\n hbox.addStretch()\n fbox.addRow(QLabel(\"sex\"),hbox)\n fbox.addRow(QPushButton(\"Submit\"),QPushButton(\"Cancel\"))\n\n win.setLayout(fbox)\n \n win.setWindowTitle(\"PyQt\")\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 3631, "s": 3584, "text": "The above code produces the following output −" }, { "code": null, "e": 3668, "s": 3631, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3678, "s": 3668, "text": " ALAA EID" }, { "code": null, "e": 3685, "s": 3678, "text": " Print" }, { "code": null, "e": 3696, "s": 3685, "text": " Add Notes" } ]
ConvertDecimal to equivalent 32-bit unsigned integer in C#
To convert the value of the specified Decimal to the equivalent 32-bit unsigned integer, the code is as follows − Live Demo using System; public class Demo { public static void Main() { Decimal val = 0.001m; Console.WriteLine("Decimal value = "+val); uint res = Decimal.ToUInt32(val); Console.WriteLine("32-bit unsigned integer = "+res); } } This will produce the following output − Decimal value = 0.001 32-bit unsigned integer = 0 Let us see another example − Live Demo using System; public class Demo { public static void Main() { Decimal val = 67.487m; Console.WriteLine("Decimal value = "+val); uint res = Decimal.ToUInt32(val); Console.WriteLine("32-bit unsigned integer = "+res); } } This will produce the following output − Decimal value = 67.487 32-bit unsigned integer = 67
[ { "code": null, "e": 1176, "s": 1062, "text": "To convert the value of the specified Decimal to the equivalent 32-bit unsigned integer, the code is as follows −" }, { "code": null, "e": 1187, "s": 1176, "text": " Live Demo" }, { "code": null, "e": 1435, "s": 1187, "text": "using System;\npublic class Demo {\n public static void Main() {\n Decimal val = 0.001m;\n Console.WriteLine(\"Decimal value = \"+val);\n uint res = Decimal.ToUInt32(val);\n Console.WriteLine(\"32-bit unsigned integer = \"+res);\n }\n}" }, { "code": null, "e": 1476, "s": 1435, "text": "This will produce the following output −" }, { "code": null, "e": 1526, "s": 1476, "text": "Decimal value = 0.001\n32-bit unsigned integer = 0" }, { "code": null, "e": 1555, "s": 1526, "text": "Let us see another example −" }, { "code": null, "e": 1566, "s": 1555, "text": " Live Demo" }, { "code": null, "e": 1815, "s": 1566, "text": "using System;\npublic class Demo {\n public static void Main() {\n Decimal val = 67.487m;\n Console.WriteLine(\"Decimal value = \"+val);\n uint res = Decimal.ToUInt32(val);\n Console.WriteLine(\"32-bit unsigned integer = \"+res);\n }\n}" }, { "code": null, "e": 1856, "s": 1815, "text": "This will produce the following output −" }, { "code": null, "e": 1908, "s": 1856, "text": "Decimal value = 67.487\n32-bit unsigned integer = 67" } ]
Import module in Python
In this article, we will learn about all the methods by which we can import modules in Python 3.x. Or earlier. The import statement is used to include all the dependencies/modules needed to execute the code. import < module name > import math print(math.log10(100)) 2.0 from <module name> import <function name> from math import pi print(math.pi) 3.14159265358979 from math import * from math import * print(math.log10(100)) 2.0 import <module name> as <alias name> import math as m print(m.log10(100)) 2.0 In this article, we learned about importing external modules and libraries in Python 3.x. Or earlier.
[ { "code": null, "e": 1270, "s": 1062, "text": "In this article, we will learn about all the methods by which we can import modules in Python 3.x. Or earlier. The import statement is used to include all the dependencies/modules needed to execute the code." }, { "code": null, "e": 1293, "s": 1270, "text": "import < module name >" }, { "code": null, "e": 1328, "s": 1293, "text": "import math\nprint(math.log10(100))" }, { "code": null, "e": 1332, "s": 1328, "text": "2.0" }, { "code": null, "e": 1374, "s": 1332, "text": "from <module name> import <function name>" }, { "code": null, "e": 1409, "s": 1374, "text": "from math import pi\nprint(math.pi)" }, { "code": null, "e": 1426, "s": 1409, "text": "3.14159265358979" }, { "code": null, "e": 1445, "s": 1426, "text": "from math import *" }, { "code": null, "e": 1487, "s": 1445, "text": "from math import *\nprint(math.log10(100))" }, { "code": null, "e": 1491, "s": 1487, "text": "2.0" }, { "code": null, "e": 1528, "s": 1491, "text": "import <module name> as <alias name>" }, { "code": null, "e": 1567, "s": 1528, "text": "import math as m\nprint(m.log10(100))\n\n" }, { "code": null, "e": 1571, "s": 1567, "text": "2.0" }, { "code": null, "e": 1673, "s": 1571, "text": "In this article, we learned about importing external modules and libraries in Python 3.x. Or earlier." } ]
How to pass an image from one activity another activity in Android?
This example demonstrates how to do I pass an image from one Activity 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="16dp" tools:context=".MainActivity"> <Button android:id="@+id/btnSend" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:onClick="SendImage" android:text="Send Image" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/btnSend" android:layout_marginTop="10dp" android:src="@drawable/image" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void SendImage(View view) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("resId", R.drawable.image); startActivity(intent); } } Step 4 − Create an empty activity and add the following code: Activity_second.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=".SecondActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:text="Second Activity" android:textSize="24sp" android:textStyle="bold"/> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/textView" android:layout_marginTop="5dp" android:id="@+id/imageView2"/> </RelativeLayout> SecondActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; public class SecondActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); imageView = findViewById(R.id.imageView2); Bundle bundle = getIntent().getExtras(); if (bundle != null) { int resId = bundle.getInt("resId"); imageView.setImageResource(resId); } } } Step 5 − 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=".SecondActivity"></activity> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how to do I pass an image from one Activity in android." }, { "code": null, "e": 1273, "s": 1144, "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": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2145, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns: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=\"16dp\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnSend\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"40dp\"\n android:onClick=\"SendImage\"\n android:text=\"Send Image\" />\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/btnSend\"\n android:layout_marginTop=\"10dp\"\n android:src=\"@drawable/image\" />\n</RelativeLayout>" }, { "code": null, "e": 2202, "s": 2145, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2749, "s": 2202, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void SendImage(View view) {\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n intent.putExtra(\"resId\", R.drawable.image);\n startActivity(intent);\n }\n}" }, { "code": null, "e": 2811, "s": 2749, "text": "Step 4 − Create an empty activity and add the following code:" }, { "code": null, "e": 2833, "s": 2811, "text": "Activity_second.xml −" }, { "code": null, "e": 3684, "s": 2833, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\nxmlns: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=\".SecondActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"40dp\"\n android:text=\"Second Activity\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"/>\n <ImageView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/textView\"\n android:layout_marginTop=\"5dp\"\n android:id=\"@+id/imageView2\"/>\n</RelativeLayout>" }, { "code": null, "e": 3704, "s": 3684, "text": "SecondActivity.java" }, { "code": null, "e": 4279, "s": 3704, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\npublic class SecondActivity extends AppCompatActivity {\n ImageView imageView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n imageView = findViewById(R.id.imageView2);\n Bundle bundle = getIntent().getExtras();\n if (bundle != null) {\n int resId = bundle.getInt(\"resId\");\n imageView.setImageResource(resId);\n }\n }\n}" }, { "code": null, "e": 4334, "s": 4279, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5063, "s": 4334, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" 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=\".SecondActivity\"></activity>\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": 5414, "s": 5063, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5455, "s": 5414, "text": "Click here to download the project code." } ]
Array Copy in Java
Array in java can be copied to another array using the following ways. Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements. Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements. Create a new array of the same length and copy each element. Create a new array of the same length and copy each element. Use the clone method of the array. Clone methods create a new array of the same size. Use the clone method of the array. Clone methods create a new array of the same size. Use System.arraycopy() method. arraycopy can be used to copy a subset of an array. Use System.arraycopy() method. arraycopy can be used to copy a subset of an array. Create a java class named Tester. Tester.java Live Demo public class Tester { public static void main(String args[]) { //Scenario 1: Copy array using assignment int[] a = {1, 2, 3}; int[] b = a; //test side effect b[0]++; System.out.println("Scenario 1: "); System.out.print("Array a: "); printArray(a); System.out.print("Array b: "); printArray(b); //Scenario 2: Copy array by iterating int[] c = {1, 2, 3}; int[] d = new int[c.length]; for (int i = 0; i < d.length; i++) { d[i] = c[i]; } //test side effect d[0]++; System.out.println("Scenario 2: "); System.out.print("Array c: "); printArray(c); System.out.print("Array d: "); printArray(d); //Scenario 3: Copy array using clone int[] e = {1, 2, 3}; int[] f = e.clone(); //test side effect f[0]++; System.out.println("Scenario 3: "); System.out.print("Array e: "); printArray(e); System.out.print("Array f: "); printArray(f); //Scenario 4: Copy array using arraycopy int[] g = {1, 2, 3}; int[] h = new int[g.length]; System.arraycopy(g, 0, h, 0, h.length); //test side effect h[0]++; System.out.println("Scenario 4: "); System.out.print("Array g: "); printArray(g); System.out.print("Array h: "); printArray(h); } public static void printArray(int[] a) { System.out.print("[ "); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println("]"); } } Compile and Run the file to verify the result. Scenario 1: Array a: [ 2 2 3 ] Array b: [ 2 2 3 ] Scenario 2: Array c: [ 1 2 3 ] Array d: [ 2 2 3 ] Scenario 3: Array e: [ 1 2 3 ] Array f: [ 2 2 3 ] Scenario 4: Array g: [ 1 2 3 ] Array h: [ 2 2 3 ]
[ { "code": null, "e": 1133, "s": 1062, "text": "Array in java can be copied to another array using the following ways." }, { "code": null, "e": 1342, "s": 1133, "text": "Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements." }, { "code": null, "e": 1551, "s": 1342, "text": "Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements." }, { "code": null, "e": 1612, "s": 1551, "text": "Create a new array of the same length and copy each element." }, { "code": null, "e": 1673, "s": 1612, "text": "Create a new array of the same length and copy each element." }, { "code": null, "e": 1759, "s": 1673, "text": "Use the clone method of the array. Clone methods create a new array of the same size." }, { "code": null, "e": 1845, "s": 1759, "text": "Use the clone method of the array. Clone methods create a new array of the same size." }, { "code": null, "e": 1928, "s": 1845, "text": "Use System.arraycopy() method. arraycopy can be used to copy a subset of an array." }, { "code": null, "e": 2011, "s": 1928, "text": "Use System.arraycopy() method. arraycopy can be used to copy a subset of an array." }, { "code": null, "e": 2045, "s": 2011, "text": "Create a java class named Tester." }, { "code": null, "e": 2057, "s": 2045, "text": "Tester.java" }, { "code": null, "e": 2067, "s": 2057, "text": "Live Demo" }, { "code": null, "e": 3693, "s": 2067, "text": "public class Tester {\n public static void main(String args[]) { \n //Scenario 1: Copy array using assignment\n int[] a = {1, 2, 3}; \n int[] b = a;\n\n //test side effect\n b[0]++;\n\n System.out.println(\"Scenario 1: \");\n System.out.print(\"Array a: \");\n printArray(a);\n System.out.print(\"Array b: \");\n printArray(b);\n\n //Scenario 2: Copy array by iterating\n int[] c = {1, 2, 3}; int[] d = new int[c.length];\n for (int i = 0; i < d.length; i++) {\n d[i] = c[i];\n }\n\n //test side effect\n d[0]++;\n\n System.out.println(\"Scenario 2: \");\n System.out.print(\"Array c: \");\n printArray(c);\n System.out.print(\"Array d: \");\n printArray(d);\n\n //Scenario 3: Copy array using clone\n int[] e = {1, 2, 3}; \n int[] f = e.clone();\n\n //test side effect\n f[0]++;\n\n System.out.println(\"Scenario 3: \");\n System.out.print(\"Array e: \");\n printArray(e);\n System.out.print(\"Array f: \");\n printArray(f);\n\n //Scenario 4: Copy array using arraycopy\n int[] g = {1, 2, 3}; \n int[] h = new int[g.length];\n System.arraycopy(g, 0, h, 0, h.length);\n\n //test side effect\n h[0]++;\n\n System.out.println(\"Scenario 4: \");\n System.out.print(\"Array g: \");\n printArray(g);\n System.out.print(\"Array h: \");\n printArray(h); \n }\n\n public static void printArray(int[] a) {\n System.out.print(\"[ \");\n for (int i = 0; i < a.length; i++) {\n System.out.print(a[i] + \" \");\n }\n System.out.println(\"]\");\n }\n}" }, { "code": null, "e": 3740, "s": 3693, "text": "Compile and Run the file to verify the result." }, { "code": null, "e": 3948, "s": 3740, "text": "Scenario 1: \nArray a: [ 2 2 3 ]\nArray b: [ 2 2 3 ]\nScenario 2: \nArray c: [ 1 2 3 ]\nArray d: [ 2 2 3 ]\nScenario 3: \nArray e: [ 1 2 3 ]\nArray f: [ 2 2 3 ]\nScenario 4: \nArray g: [ 1 2 3 ]\nArray h: [ 2 2 3 ]" } ]
Apache Presto - contains(x,element)
presto:default> select contains(array[1,2],5) as array_contains; array_contains ---------------- false 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2072, "s": 2006, "text": "presto:default> select contains(array[1,2],5) as array_contains; " }, { "code": null, "e": 2119, "s": 2072, "text": " array_contains \n---------------- \n false \n" }, { "code": null, "e": 2154, "s": 2119, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2173, "s": 2154, "text": " Arnab Chakraborty" }, { "code": null, "e": 2208, "s": 2173, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2229, "s": 2208, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 2262, "s": 2229, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2275, "s": 2262, "text": " Nilay Mehta" }, { "code": null, "e": 2310, "s": 2275, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2328, "s": 2310, "text": " Bigdata Engineer" }, { "code": null, "e": 2361, "s": 2328, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2379, "s": 2361, "text": " Bigdata Engineer" }, { "code": null, "e": 2412, "s": 2379, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 2430, "s": 2412, "text": " Bigdata Engineer" }, { "code": null, "e": 2437, "s": 2430, "text": " Print" }, { "code": null, "e": 2448, "s": 2437, "text": " Add Notes" } ]
Read and Write to an excel file using Python openpyxl module
Python provides openpyxl module for operating with Excel files. How to create Excel files, how to write, read etc. can be implemented by this module. For installing openpyxl module, we can write this command in command prompt pip install openpyxl import openpyxl my_wb = openpyxl.Workbook() my_sheet = my_wb.active my_sheet_title = my_sheet.title print("My sheet title: " + my_sheet_title) My sheet title:Sheet import openpyxl my_wb = openpyxl.Workbook() my_sheet = my_wb.active my_sheet.title = "My New Sheet" print("sheet name is : " + sheet.title) sheet name is : My New Sheet import openpyxl my_wb = openpyxl.Workbook() my_sheet = my_wb.active c1 = my_sheet.cell(row = 1, column = 1) c1.value = "Aadrika" c2 = my_sheet.cell(row= 1 , column = 2) c2.value = "Adwaita" c3 = my_sheet['A2'] c3.value = "Satyajit" # B2 = column = 2 & row = 2. c4 = my_sheet['B2'] c4.value = "Bivas" my_wb.save("C:\Users\TP\Desktop\Book1.xlsx") import openpyxl my_wb = openpyxl.Workbook() my_sheet = my_wb.active my_wb.create_sheet(index = 1 , title = "new sheet") my_wb.save("C:\Users\TP\Desktop\Book1.xlsx") import openpyxl my_path = "C:\Users\TP\Desktop\Book1.xlsx" my_wb_obj = openpyxl.load_workbook(my_path) my_sheet_obj = my_wb_obj.active print(my_sheet_obj.max_row) 2 import openpyxl # Give the location of the file My_path = "C:\Users\TP\Desktop\Book1.xlsx" wb_obj = openpyxl.load_workbook(my_path) my_sheet_obj = my_wb_obj.active my_cell_obj = my_sheet_obj.cell(row = 1, column = 1) print(my_cell_obj.value) Aadrika import openpyxl # Give the location of the file My_path = "C:\Users\TP\Desktop\Book1.xlsx" My_wb_obj = openpyxl.load_workbook(path) my_sheet_obj = my_wb_obj.active print(sheet_obj.max_column) 2 import openpyxl # Give the location of the file my_path = "C:\Users\TP\Desktop\Book1.xlsx" # workbook object is created my_wb_obj = openpyxl.load_workbook(my_path) my_sheet_obj = my_wb_obj.active my_max_col = my_sheet_obj.max_column for i in range(1, my_max_col + 1): my_cell_obj = my_sheet_obj.cell(row = 1, column = i) print(my_cell_obj.value) Aadrika Adwaita import openpyxl # Give the location of the file my_path = "C:\Users\TP\Desktop\Book1.xlsx" my_wb_obj = openpyxl.load_workbook(my_path) my_sheet_obj = my_wb_obj.active my_row = my_sheet_obj.max_row for i in range(1, my_row + 1): cell_obj = my_sheet_obj.cell(row = i, column = 1) print(cell_obj.value) Aadrika Satyajit import openpyxl # Give the location of the file my_path = "C:\Users\TP\Desktop\Book1.xlsx" my_wb_obj = openpyxl.load_workbook(my_path) my_sheet_obj = my_wb_obj.active my_max_col = my_sheet_obj.max_column for i in range(1, my_max_col + 1): cell_obj = my_sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = " ") Satyajit Bivas
[ { "code": null, "e": 1126, "s": 1062, "text": "Python provides openpyxl module for operating with Excel files." }, { "code": null, "e": 1212, "s": 1126, "text": "How to create Excel files, how to write, read etc. can be implemented by this module." }, { "code": null, "e": 1288, "s": 1212, "text": "For installing openpyxl module, we can write this command in command prompt" }, { "code": null, "e": 1310, "s": 1288, "text": "pip install openpyxl\n" }, { "code": null, "e": 1453, "s": 1310, "text": "import openpyxl\nmy_wb = openpyxl.Workbook()\nmy_sheet = my_wb.active\nmy_sheet_title = my_sheet.title\nprint(\"My sheet title: \" + my_sheet_title)" }, { "code": null, "e": 1475, "s": 1453, "text": "My sheet title:Sheet\n" }, { "code": null, "e": 1615, "s": 1475, "text": "import openpyxl\nmy_wb = openpyxl.Workbook()\nmy_sheet = my_wb.active\nmy_sheet.title = \"My New Sheet\"\nprint(\"sheet name is : \" + sheet.title)" }, { "code": null, "e": 1645, "s": 1615, "text": "sheet name is : My New Sheet\n" }, { "code": null, "e": 1990, "s": 1645, "text": "import openpyxl\nmy_wb = openpyxl.Workbook()\nmy_sheet = my_wb.active\nc1 = my_sheet.cell(row = 1, column = 1)\nc1.value = \"Aadrika\"\nc2 = my_sheet.cell(row= 1 , column = 2)\nc2.value = \"Adwaita\"\nc3 = my_sheet['A2']\nc3.value = \"Satyajit\"\n# B2 = column = 2 & row = 2.\nc4 = my_sheet['B2']\nc4.value = \"Bivas\"\nmy_wb.save(\"C:\\Users\\TP\\Desktop\\Book1.xlsx\")" }, { "code": null, "e": 2155, "s": 1990, "text": "import openpyxl\nmy_wb = openpyxl.Workbook()\nmy_sheet = my_wb.active\nmy_wb.create_sheet(index = 1 , title = \"new sheet\")\nmy_wb.save(\"C:\\Users\\TP\\Desktop\\Book1.xlsx\")" }, { "code": null, "e": 2318, "s": 2155, "text": "import openpyxl\nmy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\nmy_wb_obj = openpyxl.load_workbook(my_path)\nmy_sheet_obj = my_wb_obj.active\nprint(my_sheet_obj.max_row)" }, { "code": null, "e": 2321, "s": 2318, "text": "2\n" }, { "code": null, "e": 2563, "s": 2321, "text": "import openpyxl\n# Give the location of the file\nMy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\nwb_obj = openpyxl.load_workbook(my_path)\nmy_sheet_obj = my_wb_obj.active\nmy_cell_obj = my_sheet_obj.cell(row = 1, column = 1)\nprint(my_cell_obj.value)" }, { "code": null, "e": 2572, "s": 2563, "text": "Aadrika\n" }, { "code": null, "e": 2764, "s": 2572, "text": "import openpyxl\n# Give the location of the file\nMy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\nMy_wb_obj = openpyxl.load_workbook(path)\nmy_sheet_obj = my_wb_obj.active\nprint(sheet_obj.max_column)" }, { "code": null, "e": 2767, "s": 2764, "text": "2\n" }, { "code": null, "e": 3120, "s": 2767, "text": "import openpyxl\n# Give the location of the file\nmy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\n# workbook object is created\nmy_wb_obj = openpyxl.load_workbook(my_path)\nmy_sheet_obj = my_wb_obj.active\nmy_max_col = my_sheet_obj.max_column\nfor i in range(1, my_max_col + 1):\n my_cell_obj = my_sheet_obj.cell(row = 1, column = i)\n print(my_cell_obj.value) " }, { "code": null, "e": 3137, "s": 3120, "text": "Aadrika Adwaita\n" }, { "code": null, "e": 3443, "s": 3137, "text": "import openpyxl\n# Give the location of the file\nmy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\nmy_wb_obj = openpyxl.load_workbook(my_path)\nmy_sheet_obj = my_wb_obj.active\nmy_row = my_sheet_obj.max_row\nfor i in range(1, my_row + 1):\n cell_obj = my_sheet_obj.cell(row = i, column = 1)\n print(cell_obj.value)" }, { "code": null, "e": 3461, "s": 3443, "text": "Aadrika\nSatyajit\n" }, { "code": null, "e": 3789, "s": 3461, "text": "import openpyxl\n# Give the location of the file\nmy_path = \"C:\\Users\\TP\\Desktop\\Book1.xlsx\"\nmy_wb_obj = openpyxl.load_workbook(my_path)\nmy_sheet_obj = my_wb_obj.active\nmy_max_col = my_sheet_obj.max_column\nfor i in range(1, my_max_col + 1):\n cell_obj = my_sheet_obj.cell(row = 2, column = i)\n print(cell_obj.value, end = \" \")" }, { "code": null, "e": 3805, "s": 3789, "text": "Satyajit Bivas\n" } ]
Text Summarization Using Deep Neural Networks | by Shivam Duseja | Towards Data Science
The amount of textual data being produced every day is increasing rapidly both in terms of complexity as well as volume. Social Media, News articles, emails, text messages (the list goes on..), generate massive information and it becomes cumbersome to go through lengthy text materials (and boring too!). Thankfully with the advancements in Deep Learning, we can build models to shorten long pieces of text and produce a crisp and coherent summary to save time and understand the key points effectively. We can broadly classify text summarization into two types: 1. Extractive Summarization: This technique involves the extraction of important words/phrases from the input sentence. The underlying idea is to create a summary by selecting the most important words from the input sentence 2. Abstractive Summarization: This technique involves the generation of entirely new phrases that capture the meaning of the input sentence. The underlying idea is to put a strong emphasis on the form — aiming to generate a grammatical summary thereby requiring advanced language modeling techniques. In this article, we will use PyTorch to build a sequence 2 sequence (encoder-decoder) model with simple dot product attention using GRU and evaluate their attention scores. We will further look into metrics like — BLEU, ROUGE for evaluating our model. Dataset used :We will work on the wikihow dataset that contains around 200,000 long sequence pairs of articles and their headlines. This dataset is one of the large-scale datasets available for summarization with the length of articles varying considerably. These articles are quite diverse in their writing style which makes the summarization problem more challenging and interesting. For more information on the dataset: https://arxiv.org/abs/1810.09305 Pre-processing and cleaning is an important step because building a model on unclean and messy data will in turn produce messy results. We will apply the below cleaning techniques before feeding our data to the model: Converting all text to lower case for further processingParsing HTML tagsRemoving text between () and []Contraction Mapping — Replacing shortened version of words (for e.g. can’t is replaced with cannot and so on)Removing apostropheRemoving punctuations and special charactersRemoving stop words using nltk libraryRetaining only long words, i.e. words with length > 3 Converting all text to lower case for further processing Parsing HTML tags Removing text between () and [] Contraction Mapping — Replacing shortened version of words (for e.g. can’t is replaced with cannot and so on) Removing apostrophe Removing punctuations and special characters Removing stop words using nltk library Retaining only long words, i.e. words with length > 3 We will first define the contractions in the form of a dictionary: ## Find the complete list of contractions on my Github Repocontraction_mapping = {"ain't": "is not", "aren't": "are not"}stop_words = set(stopwords.words('english'))def text_cleaner(text,num): str = text.lower() str = BeautifulSoup(str, "lxml").text str = re.sub("[\(\[].*?[\)\]]", "", str) str = ' '.join([contraction_mapping[t] if t in contraction_mapping else t for t in str.split(" ")]) str = re.sub(r"'s\b","",str) str = re.sub("[^a-zA-Z]", " ", str) if(num==0): tokens = [w for w in str.split() if not w in stop_words] else: tokens=str.split() long_words=[] for i in tokens: if len(i)>3: #removing short words long_words.append(i) return (" ".join(long_words)).strip()#calling the above functionclean_text = []clean_summary = []for t in df['text']: clean_text.append(text_cleaner(t,0))for t in df['headline']: clean_summary.append(text_cleaner(t,0)) Before feeding the training data to our deep model, we will represent each word as a one-hot vector. We will then need a unique index per word to use it as the input and output of the network. In order to do so, we will create a helper class Lang which has word-> index and index-> word mappings along with the count of each word. To read data in our model, we have created pairs of our input and output in the form of a list (Pairs-> [Input, Output]) We will be using a seq2seq(encoder-decoder architecture) model with a simple dot product attention. The underlying idea of choosing this architecture is that we have a many-to-many problem at hand(n number of words as input and m number of words as output). The figure below shows the detailed architecture diagram for this model. There are four major components in this architecture: Encoder: The encoder layer of the seq2seq model extracts information from the input text and encodes it into a single vector, that is a context vector. Basically, for each input word, the encoder generates a hidden state and a vector , using this hidden state for the next input word. We have used GRU(Gated Recurrent Unit) for the encoder layer in order to capture long term dependencies - mitigating the vanishing/exploding gradient problem encountered while working with vanilla RNNs.The GRU cell reads one word at a time and using the update and reset gate, computes the hidden state content and cell state. I found the below two links useful for getting more information on the working of GRU:Empirical Evaluation of Gated Recurrent Neural Networks on Sequence ModelingGated Recurrent Units (GRU) Decoder: The decoder layer of a seq2seq model uses the last hidden state of the encoder i.e. the context vector and generates the output words. The decoding process starts once the sentence has been encoded and the decoder is given a hidden state and an input token at each step/time. At the initial time stamp/state the first hidden state is the context vector and the input vector is SOS(start-of-string). The decoding process ends when EOS(end-of-sentence) is reached. The SOS and EOS tokens are explicitly added at the start and end of each sentence respectively. Attention Mechanism: Using the encoder-decoder architecture, the encoded context vector is passed on to the decoder to generate an output sentence. Now what if the input sentence is long and a single context vector cannot capture all the important information. This is where attention comes into picture!!! The main intuition of using attention is to allow the model to focus/pay attention on the most important part of the input text. As a blessing in disguise, it also helps to overcome the vanishing gradient problem.There are different types of attention — additive, multiplicative, however, we will use the basic dot product attention for our model. 1. Attention scores are first calculated by computing the dot product of the encoder(h) and decoder(s) hidden state2. These attention scores are converted to a distribution(α) by passing them through the Softmax layer.3. Then the weighted sum of the hidden states (z) is computed.4. This z is then concatenated with s and fed through the softmax layer to generate the words using ‘Greedy Algorithm’ (by computing argmax) In this architecture, instead of directly using the output of last encoder’s hidden state, we are also feeding the weighted combination of all the encoder hidden states. This helps the model to pay attention to important words across long sequences. Supporting Equations Teacher Forcing: In general, for recurrent neural networks, the output from a state is fed as an input to the next state. This process causes slow convergence thereby increasing the training time. What is Teacher ForcingTeacher forcing addresses this slow convergence problem by feeding the actual value/ground truth to the model. The basic intuition behind this technique is that instead of feeding the decoders predicted output as an input for the next state, the ground truth or the actual value is fed to the model. If the model predicts a wrong word it might lead to a condition wherein all the further words that are predicted are incorrect. Hence, teacher forcing feeds the actual value thereby correcting the model if it predicts/generates a wrong word. Teacher forcing is a fast and effective way to train RNNs, however, this approach may result in more fragile/unstable models when the generated sequences vary from what was seen during the training process.To deal with such an isssue, we will follow an approach that involves randomly choosing to use the ground truth output or the generated output from the previous time step as an input for current time step. Below code snippet shows the dynamic implementation of Teacher Forcing teacher_forcing_ratio = 0.5use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False if use_teacher_forcing: # Teacher forcing: Feed the target as the next input for di in range(target_length): decoder_output, decoder_hidden, decoder_attention = decoder( decoder_input, decoder_hidden, encoder_outputs) loss += criterion(decoder_output, target_tensor[di]) decoder_input = target_tensor[di] # Teacher forcing else: # W/O teacher forcing: use own predictions as the next input for di in range(target_length): decoder_output, decoder_hidden, decoder_attention = decoder( decoder_input, decoder_hidden, encoder_outputs) topv, topi = decoder_output.topk(1) decoder_input = topi.squeeze().detach() # detach from history as input loss += criterion(decoder_output, target_tensor[di]) if decoder_input.item() == EOS_token: break For our text summarization problem, there can be multiple correct answers and as we do not have a single correct output, we can evaluate our model using different parameters like — Recall, Precision, F-score. Below are some of the metrics that we will use: BLEU(Bilingual Evaluation Understudy): The cornerstone of this metric is precision having values between [0,1], wherein 1 represents a perfect match and 0 represents a complete mismatch. This metric is basically calculated by comparing the number of machine-generated words that are a part of the reference sentence with respect to the total number of words in the machine-generated output. Let’s understand this with the help of an example: Reference Sentence: The door is lockedMachine Output: the the theBLEU Score=1 The above machine output is an extreme condition, however, in order to overcome this problem, the BLEU score is calculated in a way that each word in the generated sentence will be clipped to the number of times, that word occurs in the reference sentence. This basically makes sure that if one word is generated more number of times than it is present in the reference sentence– it is not considered while evaluating the similarity.After applying the above rule, we get the modified BLEU Score as 1/3 Let’s take a look at another extreme example: Reference Sentence: The door is lockedMachine Output: theBLEU Score: 1 (even after applying the above rule) In such a scenario, where the length of the generated sentence is less than the reference sentence, a Brevity penalty(BP) is introduced, i.e. there is a penalty to the BLEU score, if the generated sentence is smaller than the reference sentence, however, when the generated sentence is longer than the reference sentence no penalty is introduced. Brevity Penalty is defined as- where, r is the effective reference corpus lengthc is the length of generated/candidate sentence This metric was first proposed by Kishore Papineni in 2002. Refer the below link for more details around this metric: BLEU: a Method for Automatic Evaluation of Machine Translation ROUGE (Recall-Oriented Understanding for Gisting Evaluation): ROUGE is basically a recall-oriented measure that works by comparing the number of machine-generated words that are a part of the reference sentence with respect to the total number of words in the reference sentence. This metric is more intuitive in the sense that every time we add a reference to the pool, we expand our space of alternating summaries. Hence, this metric should be preferred when we have multiple references. ROUGE implementation is pretty similar to BELU, however, there are other underlying implementations like LCS (Longest common subsequence) and skip-gram, etc. We can directly use the ROUGE-N implementation using the python library ROUGE. For more details, you can refer to the below paper: ROUGE: A Package for Automatic Evaluation of Summaries We have seen a precision-based metric(BLEU) and a recall oriented metric(ROUGE), however, if we want our evaluation on the basis of both recall and precision, we can use F-Score as an evaluation measure. Result: The implementation code can be found on my Github. The model ran on Google Colab Pro(T4 & P100 GPU - 25GB with high memory VMs) for ~6–7 hours and it seemed to work fine on shorter summaries (~50 words). However, the model can be optimized by further tuning the hyperparameters (learning rate, optimizer, loss function, hidden layers, momentum, iterations, etc.) Bi-directional/stacked GRU cells can be used for improving performanceImplementing different kinds of attention-mechanism — multiplicative attention, multi-head attention, etc.Output words can be selected using beam search instead of greedy-algorithm Bi-directional/stacked GRU cells can be used for improving performance Implementing different kinds of attention-mechanism — multiplicative attention, multi-head attention, etc. Output words can be selected using beam search instead of greedy-algorithm Attention is all you needhttps://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.htmlhttps://www.aclweb.org/anthology/W04-1013.pdf Attention is all you need
[ { "code": null, "e": 676, "s": 172, "text": "The amount of textual data being produced every day is increasing rapidly both in terms of complexity as well as volume. Social Media, News articles, emails, text messages (the list goes on..), generate massive information and it becomes cumbersome to go through lengthy text materials (and boring too!). Thankfully with the advancements in Deep Learning, we can build models to shorten long pieces of text and produce a crisp and coherent summary to save time and understand the key points effectively." }, { "code": null, "e": 735, "s": 676, "text": "We can broadly classify text summarization into two types:" }, { "code": null, "e": 960, "s": 735, "text": "1. Extractive Summarization: This technique involves the extraction of important words/phrases from the input sentence. The underlying idea is to create a summary by selecting the most important words from the input sentence" }, { "code": null, "e": 1261, "s": 960, "text": "2. Abstractive Summarization: This technique involves the generation of entirely new phrases that capture the meaning of the input sentence. The underlying idea is to put a strong emphasis on the form — aiming to generate a grammatical summary thereby requiring advanced language modeling techniques." }, { "code": null, "e": 1513, "s": 1261, "text": "In this article, we will use PyTorch to build a sequence 2 sequence (encoder-decoder) model with simple dot product attention using GRU and evaluate their attention scores. We will further look into metrics like — BLEU, ROUGE for evaluating our model." }, { "code": null, "e": 1899, "s": 1513, "text": "Dataset used :We will work on the wikihow dataset that contains around 200,000 long sequence pairs of articles and their headlines. This dataset is one of the large-scale datasets available for summarization with the length of articles varying considerably. These articles are quite diverse in their writing style which makes the summarization problem more challenging and interesting." }, { "code": null, "e": 1969, "s": 1899, "text": "For more information on the dataset: https://arxiv.org/abs/1810.09305" }, { "code": null, "e": 2187, "s": 1969, "text": "Pre-processing and cleaning is an important step because building a model on unclean and messy data will in turn produce messy results. We will apply the below cleaning techniques before feeding our data to the model:" }, { "code": null, "e": 2555, "s": 2187, "text": "Converting all text to lower case for further processingParsing HTML tagsRemoving text between () and []Contraction Mapping — Replacing shortened version of words (for e.g. can’t is replaced with cannot and so on)Removing apostropheRemoving punctuations and special charactersRemoving stop words using nltk libraryRetaining only long words, i.e. words with length > 3" }, { "code": null, "e": 2612, "s": 2555, "text": "Converting all text to lower case for further processing" }, { "code": null, "e": 2630, "s": 2612, "text": "Parsing HTML tags" }, { "code": null, "e": 2662, "s": 2630, "text": "Removing text between () and []" }, { "code": null, "e": 2772, "s": 2662, "text": "Contraction Mapping — Replacing shortened version of words (for e.g. can’t is replaced with cannot and so on)" }, { "code": null, "e": 2792, "s": 2772, "text": "Removing apostrophe" }, { "code": null, "e": 2837, "s": 2792, "text": "Removing punctuations and special characters" }, { "code": null, "e": 2876, "s": 2837, "text": "Removing stop words using nltk library" }, { "code": null, "e": 2930, "s": 2876, "text": "Retaining only long words, i.e. words with length > 3" }, { "code": null, "e": 2997, "s": 2930, "text": "We will first define the contractions in the form of a dictionary:" }, { "code": null, "e": 3914, "s": 2997, "text": "## Find the complete list of contractions on my Github Repocontraction_mapping = {\"ain't\": \"is not\", \"aren't\": \"are not\"}stop_words = set(stopwords.words('english'))def text_cleaner(text,num): str = text.lower() str = BeautifulSoup(str, \"lxml\").text str = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", str) str = ' '.join([contraction_mapping[t] if t in contraction_mapping else t for t in str.split(\" \")]) str = re.sub(r\"'s\\b\",\"\",str) str = re.sub(\"[^a-zA-Z]\", \" \", str) if(num==0): tokens = [w for w in str.split() if not w in stop_words] else: tokens=str.split() long_words=[] for i in tokens: if len(i)>3: #removing short words long_words.append(i) return (\" \".join(long_words)).strip()#calling the above functionclean_text = []clean_summary = []for t in df['text']: clean_text.append(text_cleaner(t,0))for t in df['headline']: clean_summary.append(text_cleaner(t,0))" }, { "code": null, "e": 4107, "s": 3914, "text": "Before feeding the training data to our deep model, we will represent each word as a one-hot vector. We will then need a unique index per word to use it as the input and output of the network." }, { "code": null, "e": 4366, "s": 4107, "text": "In order to do so, we will create a helper class Lang which has word-> index and index-> word mappings along with the count of each word. To read data in our model, we have created pairs of our input and output in the form of a list (Pairs-> [Input, Output])" }, { "code": null, "e": 4697, "s": 4366, "text": "We will be using a seq2seq(encoder-decoder architecture) model with a simple dot product attention. The underlying idea of choosing this architecture is that we have a many-to-many problem at hand(n number of words as input and m number of words as output). The figure below shows the detailed architecture diagram for this model." }, { "code": null, "e": 4751, "s": 4697, "text": "There are four major components in this architecture:" }, { "code": null, "e": 5036, "s": 4751, "text": "Encoder: The encoder layer of the seq2seq model extracts information from the input text and encodes it into a single vector, that is a context vector. Basically, for each input word, the encoder generates a hidden state and a vector , using this hidden state for the next input word." }, { "code": null, "e": 5363, "s": 5036, "text": "We have used GRU(Gated Recurrent Unit) for the encoder layer in order to capture long term dependencies - mitigating the vanishing/exploding gradient problem encountered while working with vanilla RNNs.The GRU cell reads one word at a time and using the update and reset gate, computes the hidden state content and cell state." }, { "code": null, "e": 5553, "s": 5363, "text": "I found the below two links useful for getting more information on the working of GRU:Empirical Evaluation of Gated Recurrent Neural Networks on Sequence ModelingGated Recurrent Units (GRU)" }, { "code": null, "e": 6121, "s": 5553, "text": "Decoder: The decoder layer of a seq2seq model uses the last hidden state of the encoder i.e. the context vector and generates the output words. The decoding process starts once the sentence has been encoded and the decoder is given a hidden state and an input token at each step/time. At the initial time stamp/state the first hidden state is the context vector and the input vector is SOS(start-of-string). The decoding process ends when EOS(end-of-sentence) is reached. The SOS and EOS tokens are explicitly added at the start and end of each sentence respectively." }, { "code": null, "e": 6428, "s": 6121, "text": "Attention Mechanism: Using the encoder-decoder architecture, the encoded context vector is passed on to the decoder to generate an output sentence. Now what if the input sentence is long and a single context vector cannot capture all the important information. This is where attention comes into picture!!!" }, { "code": null, "e": 6776, "s": 6428, "text": "The main intuition of using attention is to allow the model to focus/pay attention on the most important part of the input text. As a blessing in disguise, it also helps to overcome the vanishing gradient problem.There are different types of attention — additive, multiplicative, however, we will use the basic dot product attention for our model." }, { "code": null, "e": 7197, "s": 6776, "text": "1. Attention scores are first calculated by computing the dot product of the encoder(h) and decoder(s) hidden state2. These attention scores are converted to a distribution(α) by passing them through the Softmax layer.3. Then the weighted sum of the hidden states (z) is computed.4. This z is then concatenated with s and fed through the softmax layer to generate the words using ‘Greedy Algorithm’ (by computing argmax)" }, { "code": null, "e": 7447, "s": 7197, "text": "In this architecture, instead of directly using the output of last encoder’s hidden state, we are also feeding the weighted combination of all the encoder hidden states. This helps the model to pay attention to important words across long sequences." }, { "code": null, "e": 7468, "s": 7447, "text": "Supporting Equations" }, { "code": null, "e": 7665, "s": 7468, "text": "Teacher Forcing: In general, for recurrent neural networks, the output from a state is fed as an input to the next state. This process causes slow convergence thereby increasing the training time." }, { "code": null, "e": 8230, "s": 7665, "text": "What is Teacher ForcingTeacher forcing addresses this slow convergence problem by feeding the actual value/ground truth to the model. The basic intuition behind this technique is that instead of feeding the decoders predicted output as an input for the next state, the ground truth or the actual value is fed to the model. If the model predicts a wrong word it might lead to a condition wherein all the further words that are predicted are incorrect. Hence, teacher forcing feeds the actual value thereby correcting the model if it predicts/generates a wrong word." }, { "code": null, "e": 8642, "s": 8230, "text": "Teacher forcing is a fast and effective way to train RNNs, however, this approach may result in more fragile/unstable models when the generated sequences vary from what was seen during the training process.To deal with such an isssue, we will follow an approach that involves randomly choosing to use the ground truth output or the generated output from the previous time step as an input for current time step." }, { "code": null, "e": 8713, "s": 8642, "text": "Below code snippet shows the dynamic implementation of Teacher Forcing" }, { "code": null, "e": 9725, "s": 8713, "text": "teacher_forcing_ratio = 0.5use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False if use_teacher_forcing: # Teacher forcing: Feed the target as the next input for di in range(target_length): decoder_output, decoder_hidden, decoder_attention = decoder( decoder_input, decoder_hidden, encoder_outputs) loss += criterion(decoder_output, target_tensor[di]) decoder_input = target_tensor[di] # Teacher forcing else: # W/O teacher forcing: use own predictions as the next input for di in range(target_length): decoder_output, decoder_hidden, decoder_attention = decoder( decoder_input, decoder_hidden, encoder_outputs) topv, topi = decoder_output.topk(1) decoder_input = topi.squeeze().detach() # detach from history as input loss += criterion(decoder_output, target_tensor[di]) if decoder_input.item() == EOS_token: break" }, { "code": null, "e": 9982, "s": 9725, "text": "For our text summarization problem, there can be multiple correct answers and as we do not have a single correct output, we can evaluate our model using different parameters like — Recall, Precision, F-score. Below are some of the metrics that we will use:" }, { "code": null, "e": 10424, "s": 9982, "text": "BLEU(Bilingual Evaluation Understudy): The cornerstone of this metric is precision having values between [0,1], wherein 1 represents a perfect match and 0 represents a complete mismatch. This metric is basically calculated by comparing the number of machine-generated words that are a part of the reference sentence with respect to the total number of words in the machine-generated output. Let’s understand this with the help of an example:" }, { "code": null, "e": 10502, "s": 10424, "text": "Reference Sentence: The door is lockedMachine Output: the the theBLEU Score=1" }, { "code": null, "e": 11004, "s": 10502, "text": "The above machine output is an extreme condition, however, in order to overcome this problem, the BLEU score is calculated in a way that each word in the generated sentence will be clipped to the number of times, that word occurs in the reference sentence. This basically makes sure that if one word is generated more number of times than it is present in the reference sentence– it is not considered while evaluating the similarity.After applying the above rule, we get the modified BLEU Score as 1/3" }, { "code": null, "e": 11050, "s": 11004, "text": "Let’s take a look at another extreme example:" }, { "code": null, "e": 11158, "s": 11050, "text": "Reference Sentence: The door is lockedMachine Output: theBLEU Score: 1 (even after applying the above rule)" }, { "code": null, "e": 11505, "s": 11158, "text": "In such a scenario, where the length of the generated sentence is less than the reference sentence, a Brevity penalty(BP) is introduced, i.e. there is a penalty to the BLEU score, if the generated sentence is smaller than the reference sentence, however, when the generated sentence is longer than the reference sentence no penalty is introduced." }, { "code": null, "e": 11536, "s": 11505, "text": "Brevity Penalty is defined as-" }, { "code": null, "e": 11633, "s": 11536, "text": "where, r is the effective reference corpus lengthc is the length of generated/candidate sentence" }, { "code": null, "e": 11814, "s": 11633, "text": "This metric was first proposed by Kishore Papineni in 2002. Refer the below link for more details around this metric: BLEU: a Method for Automatic Evaluation of Machine Translation" }, { "code": null, "e": 11876, "s": 11814, "text": "ROUGE (Recall-Oriented Understanding for Gisting Evaluation):" }, { "code": null, "e": 12094, "s": 11876, "text": "ROUGE is basically a recall-oriented measure that works by comparing the number of machine-generated words that are a part of the reference sentence with respect to the total number of words in the reference sentence." }, { "code": null, "e": 12304, "s": 12094, "text": "This metric is more intuitive in the sense that every time we add a reference to the pool, we expand our space of alternating summaries. Hence, this metric should be preferred when we have multiple references." }, { "code": null, "e": 12541, "s": 12304, "text": "ROUGE implementation is pretty similar to BELU, however, there are other underlying implementations like LCS (Longest common subsequence) and skip-gram, etc. We can directly use the ROUGE-N implementation using the python library ROUGE." }, { "code": null, "e": 12648, "s": 12541, "text": "For more details, you can refer to the below paper: ROUGE: A Package for Automatic Evaluation of Summaries" }, { "code": null, "e": 12852, "s": 12648, "text": "We have seen a precision-based metric(BLEU) and a recall oriented metric(ROUGE), however, if we want our evaluation on the basis of both recall and precision, we can use F-Score as an evaluation measure." }, { "code": null, "e": 12911, "s": 12852, "text": "Result: The implementation code can be found on my Github." }, { "code": null, "e": 13223, "s": 12911, "text": "The model ran on Google Colab Pro(T4 & P100 GPU - 25GB with high memory VMs) for ~6–7 hours and it seemed to work fine on shorter summaries (~50 words). However, the model can be optimized by further tuning the hyperparameters (learning rate, optimizer, loss function, hidden layers, momentum, iterations, etc.)" }, { "code": null, "e": 13474, "s": 13223, "text": "Bi-directional/stacked GRU cells can be used for improving performanceImplementing different kinds of attention-mechanism — multiplicative attention, multi-head attention, etc.Output words can be selected using beam search instead of greedy-algorithm" }, { "code": null, "e": 13545, "s": 13474, "text": "Bi-directional/stacked GRU cells can be used for improving performance" }, { "code": null, "e": 13652, "s": 13545, "text": "Implementing different kinds of attention-mechanism — multiplicative attention, multi-head attention, etc." }, { "code": null, "e": 13727, "s": 13652, "text": "Output words can be selected using beam search instead of greedy-algorithm" }, { "code": null, "e": 13874, "s": 13727, "text": "Attention is all you needhttps://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.htmlhttps://www.aclweb.org/anthology/W04-1013.pdf" } ]
AWK - Time Functions
AWK has the following built-in time functions − This function returns the current time of the day as the number of seconds since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems). [jerry]$ awk 'BEGIN { print "Number of seconds since the Epoch = " systime() }' On executing this code, you get the following result − Number of seconds since the Epoch = 1418574432 This function converts datespec string into a timestamp of the same form as returned by systime(). The datespec is a string of the form YYYY MM DD HH MM SS. [jerry]$ awk 'BEGIN { print "Number of seconds since the Epoch = " mktime("2014 12 14 30 20 10") }' On executing this code, you get the following result − Number of seconds since the Epoch = 1418604610 This function formats timestamps according to the specification in format. [jerry]$ awk 'BEGIN { print strftime("Time = %m/%d/%Y %H:%M:%S", systime()) }' On executing this code, you get the following result − Time = 12/14/2014 22:08:42 The following time formats are supported by AWK − %a The locale’s abbreviated weekday name. %A The locale’s full weekday name. %b The locale’s abbreviated month name. %B The locale’s full month name. %c The locale’s appropriate date and time representation. (This is %A %B %d %T %Y in the C locale.) %C The century part of the current year. This is the year divided by 100 and truncated to the next lower integer. %d The day of the month as a decimal number (01–31). %D Equivalent to specifying %m/%d/%y. %e The day of the month, padded with a space if it is only one digit. %F Equivalent to specifying %Y-%m-%d. This is the ISO 8601 date format. %g The year modulo 100 of the ISO 8601 week number, as a decimal number (00–99). For example, January 1, 1993 is in week 53 of 1992. Thus, the year of its ISO 8601 week number is 1992, even though its year is 1993. Similarly, December 31, 1973 is in week 1 of 1974. Thus, the year of its ISO week number is 1974, even though its year is 1973. %G The full year of the ISO week number, as a decimal number. %h Equivalent to %b. %H The hour (24-hour clock) as a decimal number (00–23). %I The hour (12-hour clock) as a decimal number (01–12). %j The day of the year as a decimal number (001–366). %m The month as a decimal number (01–12). %M The minute as a decimal number (00–59). %n A newline character (ASCII LF). %p The locale’s equivalent of the AM/PM designations associated with a 12-hour clock. %r The locale’s 12-hour clock time. (This is %I:%M:%S %p in the C locale.) %R Equivalent to specifying %H:%M. %S The second as a decimal number (00–60). %t A TAB character. %T Equivalent to specifying %H:%M:%S. %u The weekday as a decimal number (1–7). Monday is day one. %U The week number of the year (the first Sunday as the first day of week one) as a decimal number (00–53). %V The week number of the year (the first Monday as the first day of week one) as a decimal number (01–53). %w The weekday as a decimal number (0–6). Sunday is day zero. %W The week number of the year (the first Monday as the first day of week one) as a decimal number (00–53). %x The locale’s appropriate date representation. (This is %A %B %d %Y in the C locale.). %X The locale’s appropriate time representation. (This is %T in the C locale.). %y The year modulo 100 as a decimal number (00–99). %Y The full year as a decimal number (e.g. 2011). %z The time-zone offset in a +HHMM format (e.g., the format necessary to produce RFC 822/RFC 1036 date headers). %Z The time zone name or abbreviation; no characters if no time zone is determinable. Print Add Notes Bookmark this page
[ { "code": null, "e": 1905, "s": 1857, "text": "AWK has the following built-in time functions −" }, { "code": null, "e": 2040, "s": 1905, "text": "This function returns the current time of the day as the number of seconds since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems)." }, { "code": null, "e": 2123, "s": 2040, "text": "[jerry]$ awk 'BEGIN {\n print \"Number of seconds since the Epoch = \" systime()\n}'" }, { "code": null, "e": 2178, "s": 2123, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2226, "s": 2178, "text": "Number of seconds since the Epoch = 1418574432\n" }, { "code": null, "e": 2383, "s": 2226, "text": "This function converts datespec string into a timestamp of the same form as returned by systime(). The datespec is a string of the form YYYY MM DD HH MM SS." }, { "code": null, "e": 2486, "s": 2383, "text": "[jerry]$ awk 'BEGIN {\n print \"Number of seconds since the Epoch = \" mktime(\"2014 12 14 30 20 10\")\n}'" }, { "code": null, "e": 2541, "s": 2486, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2589, "s": 2541, "text": "Number of seconds since the Epoch = 1418604610\n" }, { "code": null, "e": 2664, "s": 2589, "text": "This function formats timestamps according to the specification in format." }, { "code": null, "e": 2746, "s": 2664, "text": "[jerry]$ awk 'BEGIN {\n print strftime(\"Time = %m/%d/%Y %H:%M:%S\", systime())\n}'" }, { "code": null, "e": 2801, "s": 2746, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2829, "s": 2801, "text": "Time = 12/14/2014 22:08:42\n" }, { "code": null, "e": 2879, "s": 2829, "text": "The following time formats are supported by AWK −" }, { "code": null, "e": 2882, "s": 2879, "text": "%a" }, { "code": null, "e": 2921, "s": 2882, "text": "The locale’s abbreviated weekday name." }, { "code": null, "e": 2924, "s": 2921, "text": "%A" }, { "code": null, "e": 2956, "s": 2924, "text": "The locale’s full weekday name." }, { "code": null, "e": 2959, "s": 2956, "text": "%b" }, { "code": null, "e": 2996, "s": 2959, "text": "The locale’s abbreviated month name." }, { "code": null, "e": 2999, "s": 2996, "text": "%B" }, { "code": null, "e": 3029, "s": 2999, "text": "The locale’s full month name." }, { "code": null, "e": 3032, "s": 3029, "text": "%c" }, { "code": null, "e": 3129, "s": 3032, "text": "The locale’s appropriate date and time representation. (This is %A %B %d %T %Y in the C locale.)" }, { "code": null, "e": 3132, "s": 3129, "text": "%C" }, { "code": null, "e": 3243, "s": 3132, "text": "The century part of the current year. This is the year divided by 100 and truncated to the next lower integer." }, { "code": null, "e": 3246, "s": 3243, "text": "%d" }, { "code": null, "e": 3296, "s": 3246, "text": "The day of the month as a decimal number (01–31)." }, { "code": null, "e": 3299, "s": 3296, "text": "%D" }, { "code": null, "e": 3334, "s": 3299, "text": "Equivalent to specifying %m/%d/%y." }, { "code": null, "e": 3337, "s": 3334, "text": "%e" }, { "code": null, "e": 3404, "s": 3337, "text": "The day of the month, padded with a space if it is only one digit." }, { "code": null, "e": 3407, "s": 3404, "text": "%F" }, { "code": null, "e": 3476, "s": 3407, "text": "Equivalent to specifying %Y-%m-%d. This is the ISO 8601 date format." }, { "code": null, "e": 3479, "s": 3476, "text": "%g" }, { "code": null, "e": 3819, "s": 3479, "text": "The year modulo 100 of the ISO 8601 week number, as a decimal number (00–99). For example, January 1, 1993 is in week 53 of 1992. Thus, the year of its ISO 8601 week number is 1992, even though its year is 1993. Similarly, December 31, 1973 is in week 1 of 1974. Thus, the year of its ISO week number is 1974, even though its year is 1973." }, { "code": null, "e": 3822, "s": 3819, "text": "%G" }, { "code": null, "e": 3881, "s": 3822, "text": "The full year of the ISO week number, as a decimal number." }, { "code": null, "e": 3884, "s": 3881, "text": "%h" }, { "code": null, "e": 3902, "s": 3884, "text": "Equivalent to %b." }, { "code": null, "e": 3905, "s": 3902, "text": "%H" }, { "code": null, "e": 3959, "s": 3905, "text": "The hour (24-hour clock) as a decimal number (00–23)." }, { "code": null, "e": 3962, "s": 3959, "text": "%I" }, { "code": null, "e": 4016, "s": 3962, "text": "The hour (12-hour clock) as a decimal number (01–12)." }, { "code": null, "e": 4019, "s": 4016, "text": "%j" }, { "code": null, "e": 4070, "s": 4019, "text": "The day of the year as a decimal number (001–366)." }, { "code": null, "e": 4073, "s": 4070, "text": "%m" }, { "code": null, "e": 4112, "s": 4073, "text": "The month as a decimal number (01–12)." }, { "code": null, "e": 4115, "s": 4112, "text": "%M" }, { "code": null, "e": 4155, "s": 4115, "text": "The minute as a decimal number (00–59)." }, { "code": null, "e": 4158, "s": 4155, "text": "%n" }, { "code": null, "e": 4190, "s": 4158, "text": "A newline character (ASCII LF)." }, { "code": null, "e": 4193, "s": 4190, "text": "%p" }, { "code": null, "e": 4276, "s": 4193, "text": "The locale’s equivalent of the AM/PM designations associated with a 12-hour clock." }, { "code": null, "e": 4279, "s": 4276, "text": "%r" }, { "code": null, "e": 4351, "s": 4279, "text": "The locale’s 12-hour clock time. (This is %I:%M:%S %p in the C locale.)" }, { "code": null, "e": 4354, "s": 4351, "text": "%R" }, { "code": null, "e": 4386, "s": 4354, "text": "Equivalent to specifying %H:%M." }, { "code": null, "e": 4389, "s": 4386, "text": "%S" }, { "code": null, "e": 4429, "s": 4389, "text": "The second as a decimal number (00–60)." }, { "code": null, "e": 4432, "s": 4429, "text": "%t" }, { "code": null, "e": 4449, "s": 4432, "text": "A TAB character." }, { "code": null, "e": 4452, "s": 4449, "text": "%T" }, { "code": null, "e": 4487, "s": 4452, "text": "Equivalent to specifying %H:%M:%S." }, { "code": null, "e": 4490, "s": 4487, "text": "%u" }, { "code": null, "e": 4548, "s": 4490, "text": "The weekday as a decimal number (1–7). Monday is day one." }, { "code": null, "e": 4551, "s": 4548, "text": "%U" }, { "code": null, "e": 4656, "s": 4551, "text": "The week number of the year (the first Sunday as the first day of week one) as a decimal number (00–53)." }, { "code": null, "e": 4659, "s": 4656, "text": "%V" }, { "code": null, "e": 4764, "s": 4659, "text": "The week number of the year (the first Monday as the first day of week one) as a decimal number (01–53)." }, { "code": null, "e": 4767, "s": 4764, "text": "%w" }, { "code": null, "e": 4826, "s": 4767, "text": "The weekday as a decimal number (0–6). Sunday is day zero." }, { "code": null, "e": 4829, "s": 4826, "text": "%W" }, { "code": null, "e": 4934, "s": 4829, "text": "The week number of the year (the first Monday as the first day of week one) as a decimal number (00–53)." }, { "code": null, "e": 4937, "s": 4934, "text": "%x" }, { "code": null, "e": 5023, "s": 4937, "text": "The locale’s appropriate date representation. (This is %A %B %d %Y in the C locale.)." }, { "code": null, "e": 5026, "s": 5023, "text": "%X" }, { "code": null, "e": 5103, "s": 5026, "text": "The locale’s appropriate time representation. (This is %T in the C locale.)." }, { "code": null, "e": 5106, "s": 5103, "text": "%y" }, { "code": null, "e": 5155, "s": 5106, "text": "The year modulo 100 as a decimal number (00–99)." }, { "code": null, "e": 5158, "s": 5155, "text": "%Y" }, { "code": null, "e": 5205, "s": 5158, "text": "The full year as a decimal number (e.g. 2011)." }, { "code": null, "e": 5208, "s": 5205, "text": "%z" }, { "code": null, "e": 5318, "s": 5208, "text": "The time-zone offset in a +HHMM format (e.g., the format necessary to produce RFC 822/RFC 1036 date headers)." }, { "code": null, "e": 5321, "s": 5318, "text": "%Z" }, { "code": null, "e": 5404, "s": 5321, "text": "The time zone name or abbreviation; no characters if no time zone is determinable." }, { "code": null, "e": 5411, "s": 5404, "text": " Print" }, { "code": null, "e": 5422, "s": 5411, "text": " Add Notes" } ]
AWT Graphics2D Class
The Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. Following is the declaration for java.awt.Graphics2D class: public abstract class Graphics2D extends Graphics Graphics2D() Constructs a new Graphics2D object. abstract void addRenderingHints(Map<?,?> hints) Sets the values of an arbitrary number of preferences for the rendering algorithms. abstract void clip(Shape s) Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection. abstract void draw(Shape s) Strokes the outline of a Shape using the settings of the current Graphics2D context. void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. abstract void drawGlyphVector(GlyphVector g, float x, float y) Renders the text of the specified GlyphVector using the Graphics2D context's rendering attributes. abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) Renders a BufferedImage that is filtered with a BufferedImageOp. abstract boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) Renders an image, applying a transform from image space into user space before drawing. abstract void drawRenderableImage(RenderableImage img, AffineTransform xform) Renders a RenderableImage, applying a transform from image space into user space before drawing. abstract void drawRenderedImage(RenderedImage img, AffineTransform xform) Renders a RenderedImage, applying a transform from image space into user space before drawing. abstract void drawString(AttributedCharacterIterator iterator, float x, float y) Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class. abstract void drawString(AttributedCharacterIterator iterator, int x, int y) Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class. abstract void drawString(String str, float x, float y) Renders the text specified by the specified String, using the current text attribute state in the Graphics2D context abstract void drawString(String str, int x, int y) Renders the text of the specified String, using the current text attribute state in the Graphics2D context. abstract void fill(Shape s) Fills the interior of a Shape using the settings of the Graphics2D context. void fill3DRect(int x, int y, int width, int height, boolean raised) Paints a 3-D highlighted rectangle filled with the current color. abstract Color getBackground() Returns the background color used for clearing a region. abstract Composite getComposite() Returns the current Composite in the Graphics2D context. abstract GraphicsConfiguration getDeviceConfiguration() Returns the device configuration associated with this Graphics2D. abstract FontRenderContext getFontRenderContext() Get the rendering context of the Font within this Graphics2D context. abstract Paint getPaint() Returns the current Paint of the Graphics2D context. abstract Object getRenderingHint(RenderingHints.Key hintKey) Returns the value of a single preference for the rendering algorithms. abstract RenderingHints getRenderingHints() Gets the preferences for the rendering algorithms. abstract Stroke getStroke() Returns the current Stroke in the Graphics2D context. abstract AffineTransform getTransform() Returns a copy of the current Transform in the Graphics2D context. abstract boolean hit(Rectangle rect, Shape s, boolean onStroke) Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space. abstract void rotate(double theta) Concatenates the current Graphics2D Transform with a rotation transform. abstract void rotate(double theta, double x, double y) Concatenates the current Graphics2D Transform with a translated rotation transform. abstract void scale(double sx, double sy) Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling. abstract void setBackground(Color color) Sets the background color for the Graphics2D context. abstract void setComposite(Composite comp) Sets the Composite for the Graphics2D context. abstract void setPaint(Paint paint) Sets the Paint attribute for the Graphics2D context. abstract void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) Sets the value of a single preference for the rendering algorithms. abstract void setRenderingHints(Map<?,?> hints) Replaces the values of all preferences for the rendering algorithms with the specified hints. abstract void setStroke(Stroke s) Sets the Stroke for the Graphics2D context. abstract void setTransform(AffineTransform Tx) Overwrites the Transform in the Graphics2D context. abstract void shear(double shx, double shy) Concatenates the current Graphics2D Transform with a shearing transform. abstract void transform(AffineTransform Tx) Composes an AffineTransform object with the Transform in this Graphics2D according to the rulelast-specified-first-applied. abstract void translate(double tx, double ty) Concatenates the current Graphics2D Transform with a translation transform. abstract void translate(int x, int y) Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system. This class inherits methods from the following classes: 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.*; import java.awt.geom.*; public class AWTGraphicsDemo extends Frame { public AWTGraphicsDemo(){ super("Java AWT Examples"); prepareGUI(); } public static void main(String[] args){ AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); awtGraphicsDemo.setVisible(true); } private void prepareGUI(){ setSize(400,400); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 24); g2.setFont(font); g2.drawString("Welcome to TutorialsPoint", 50, 70); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1911, "s": 1747, "text": "The Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout." }, { "code": null, "e": 1971, "s": 1911, "text": "Following is the declaration for java.awt.Graphics2D class:" }, { "code": null, "e": 2024, "s": 1971, "text": "public abstract class Graphics2D\n extends Graphics" }, { "code": null, "e": 2037, "s": 2024, "text": "Graphics2D()" }, { "code": null, "e": 2074, "s": 2037, "text": " Constructs a new Graphics2D object." }, { "code": null, "e": 2123, "s": 2074, "text": "abstract void addRenderingHints(Map<?,?> hints) " }, { "code": null, "e": 2207, "s": 2123, "text": "Sets the values of an arbitrary number of preferences for the rendering algorithms." }, { "code": null, "e": 2236, "s": 2207, "text": "abstract void clip(Shape s) " }, { "code": null, "e": 2354, "s": 2236, "text": "Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection." }, { "code": null, "e": 2383, "s": 2354, "text": "abstract void draw(Shape s) " }, { "code": null, "e": 2468, "s": 2383, "text": "Strokes the outline of a Shape using the settings of the current Graphics2D context." }, { "code": null, "e": 2538, "s": 2468, "text": "void draw3DRect(int x, int y, int width, int height, boolean raised) " }, { "code": null, "e": 2598, "s": 2538, "text": "Draws a 3-D highlighted outline of the specified rectangle." }, { "code": null, "e": 2661, "s": 2598, "text": "abstract void drawGlyphVector(GlyphVector g, float x, float y)" }, { "code": null, "e": 2760, "s": 2661, "text": "Renders the text of the specified GlyphVector using the Graphics2D context's rendering attributes." }, { "code": null, "e": 2838, "s": 2760, "text": "abstract void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) " }, { "code": null, "e": 2903, "s": 2838, "text": "Renders a BufferedImage that is filtered with a BufferedImageOp." }, { "code": null, "e": 2985, "s": 2903, "text": "abstract boolean\tdrawImage(Image img, AffineTransform xform, ImageObserver obs) " }, { "code": null, "e": 3073, "s": 2985, "text": "Renders an image, applying a transform from image space into user space before drawing." }, { "code": null, "e": 3152, "s": 3073, "text": "abstract void drawRenderableImage(RenderableImage img, AffineTransform xform) " }, { "code": null, "e": 3249, "s": 3152, "text": "Renders a RenderableImage, applying a transform from image space into user space before drawing." }, { "code": null, "e": 3324, "s": 3249, "text": "abstract void drawRenderedImage(RenderedImage img, AffineTransform xform) " }, { "code": null, "e": 3419, "s": 3324, "text": "Renders a RenderedImage, applying a transform from image space into user space before drawing." }, { "code": null, "e": 3501, "s": 3419, "text": "abstract void drawString(AttributedCharacterIterator iterator, float x, float y) " }, { "code": null, "e": 3633, "s": 3501, "text": "Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class." }, { "code": null, "e": 3711, "s": 3633, "text": "abstract void drawString(AttributedCharacterIterator iterator, int x, int y) " }, { "code": null, "e": 3843, "s": 3711, "text": "Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class." }, { "code": null, "e": 3899, "s": 3843, "text": "abstract void drawString(String str, float x, float y) " }, { "code": null, "e": 4016, "s": 3899, "text": "Renders the text specified by the specified String, using the current text attribute state in the Graphics2D context" }, { "code": null, "e": 4068, "s": 4016, "text": "abstract void drawString(String str, int x, int y) " }, { "code": null, "e": 4176, "s": 4068, "text": "Renders the text of the specified String, using the current text attribute state in the Graphics2D context." }, { "code": null, "e": 4205, "s": 4176, "text": "abstract void fill(Shape s) " }, { "code": null, "e": 4281, "s": 4205, "text": "Fills the interior of a Shape using the settings of the Graphics2D context." }, { "code": null, "e": 4351, "s": 4281, "text": "void fill3DRect(int x, int y, int width, int height, boolean raised) " }, { "code": null, "e": 4417, "s": 4351, "text": "Paints a 3-D highlighted rectangle filled with the current color." }, { "code": null, "e": 4449, "s": 4417, "text": "abstract Color getBackground() " }, { "code": null, "e": 4506, "s": 4449, "text": "Returns the background color used for clearing a region." }, { "code": null, "e": 4541, "s": 4506, "text": "abstract Composite getComposite() " }, { "code": null, "e": 4598, "s": 4541, "text": "Returns the current Composite in the Graphics2D context." }, { "code": null, "e": 4654, "s": 4598, "text": "abstract GraphicsConfiguration getDeviceConfiguration()" }, { "code": null, "e": 4720, "s": 4654, "text": "Returns the device configuration associated with this Graphics2D." }, { "code": null, "e": 4771, "s": 4720, "text": "abstract FontRenderContext getFontRenderContext() " }, { "code": null, "e": 4841, "s": 4771, "text": "Get the rendering context of the Font within this Graphics2D context." }, { "code": null, "e": 4868, "s": 4841, "text": "abstract Paint\tgetPaint() " }, { "code": null, "e": 4921, "s": 4868, "text": "Returns the current Paint of the Graphics2D context." }, { "code": null, "e": 4982, "s": 4921, "text": "abstract Object getRenderingHint(RenderingHints.Key hintKey)" }, { "code": null, "e": 5053, "s": 4982, "text": "Returns the value of a single preference for the rendering algorithms." }, { "code": null, "e": 5098, "s": 5053, "text": "abstract RenderingHints getRenderingHints() " }, { "code": null, "e": 5149, "s": 5098, "text": "Gets the preferences for the rendering algorithms." }, { "code": null, "e": 5178, "s": 5149, "text": "abstract Stroke getStroke() " }, { "code": null, "e": 5232, "s": 5178, "text": "Returns the current Stroke in the Graphics2D context." }, { "code": null, "e": 5273, "s": 5232, "text": "abstract AffineTransform getTransform() " }, { "code": null, "e": 5340, "s": 5273, "text": "Returns a copy of the current Transform in the Graphics2D context." }, { "code": null, "e": 5405, "s": 5340, "text": "abstract boolean hit(Rectangle rect, Shape s, boolean onStroke) " }, { "code": null, "e": 5509, "s": 5405, "text": "Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space." }, { "code": null, "e": 5544, "s": 5509, "text": "abstract void rotate(double theta)" }, { "code": null, "e": 5617, "s": 5544, "text": "Concatenates the current Graphics2D Transform with a rotation transform." }, { "code": null, "e": 5673, "s": 5617, "text": "abstract void rotate(double theta, double x, double y) " }, { "code": null, "e": 5757, "s": 5673, "text": "Concatenates the current Graphics2D Transform with a translated rotation transform." }, { "code": null, "e": 5800, "s": 5757, "text": "abstract void scale(double sx, double sy) " }, { "code": null, "e": 5985, "s": 5800, "text": "Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling." }, { "code": null, "e": 6027, "s": 5985, "text": "abstract void setBackground(Color color) " }, { "code": null, "e": 6081, "s": 6027, "text": "Sets the background color for the Graphics2D context." }, { "code": null, "e": 6125, "s": 6081, "text": "abstract void setComposite(Composite comp) " }, { "code": null, "e": 6172, "s": 6125, "text": "Sets the Composite for the Graphics2D context." }, { "code": null, "e": 6209, "s": 6172, "text": "abstract void setPaint(Paint paint) " }, { "code": null, "e": 6262, "s": 6209, "text": "Sets the Paint attribute for the Graphics2D context." }, { "code": null, "e": 6340, "s": 6262, "text": "abstract void setRenderingHint(RenderingHints.Key hintKey, Object hintValue) " }, { "code": null, "e": 6408, "s": 6340, "text": "Sets the value of a single preference for the rendering algorithms." }, { "code": null, "e": 6457, "s": 6408, "text": "abstract void setRenderingHints(Map<?,?> hints) " }, { "code": null, "e": 6551, "s": 6457, "text": "Replaces the values of all preferences for the rendering algorithms with the specified hints." }, { "code": null, "e": 6586, "s": 6551, "text": "abstract void setStroke(Stroke s) " }, { "code": null, "e": 6630, "s": 6586, "text": "Sets the Stroke for the Graphics2D context." }, { "code": null, "e": 6677, "s": 6630, "text": "abstract void setTransform(AffineTransform Tx)" }, { "code": null, "e": 6729, "s": 6677, "text": "Overwrites the Transform in the Graphics2D context." }, { "code": null, "e": 6774, "s": 6729, "text": "abstract void shear(double shx, double shy) " }, { "code": null, "e": 6847, "s": 6774, "text": "Concatenates the current Graphics2D Transform with a shearing transform." }, { "code": null, "e": 6892, "s": 6847, "text": "abstract void transform(AffineTransform Tx) " }, { "code": null, "e": 7016, "s": 6892, "text": "Composes an AffineTransform object with the Transform in this Graphics2D according to the rulelast-specified-first-applied." }, { "code": null, "e": 7063, "s": 7016, "text": "abstract void translate(double tx, double ty) " }, { "code": null, "e": 7139, "s": 7063, "text": "Concatenates the current Graphics2D Transform with a translation transform." }, { "code": null, "e": 7178, "s": 7139, "text": "abstract void translate(int x, int y) " }, { "code": null, "e": 7280, "s": 7178, "text": "Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system." }, { "code": null, "e": 7336, "s": 7280, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 7353, "s": 7336, "text": "java.lang.Object" }, { "code": null, "e": 7370, "s": 7353, "text": "java.lang.Object" }, { "code": null, "e": 7484, "s": 7370, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 8444, "s": 7484, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D)g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n Font font = new Font(\"Serif\", Font.PLAIN, 24);\n g2.setFont(font);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 70); \n }\n}" }, { "code": null, "e": 8535, "s": 8444, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 8592, "s": 8535, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTGraphicsDemo.java" }, { "code": null, "e": 8689, "s": 8592, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 8740, "s": 8689, "text": "D:\\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo" }, { "code": null, "e": 8768, "s": 8740, "text": "Verify the following output" }, { "code": null, "e": 8801, "s": 8768, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8809, "s": 8801, "text": " EduOLC" }, { "code": null, "e": 8816, "s": 8809, "text": " Print" }, { "code": null, "e": 8827, "s": 8816, "text": " Add Notes" } ]
Create database in Cassandra - GeeksforGeeks
28 Apr, 2020 In this article, we are going to discuss how to create the database in Cassandra. so, for better understanding you can read “Introduction to Cassandra” article before creating a database in Cassandra. Step-1: login into cqlshyou can log in into the cqlsh using Cassandra default credential. Now, here before creating a database you first need login into cqlsh. you can check the cluster information after login into cqlsh.let’s have a look. cqlsh 127.0.0.1 -u cassandra -p cassandra Step-2: Creating a databaseCreating a keyspace in Cassandra is the same as creating a database in SQL. CQL query for creating a keyspace as following. Syntax: CREATE KEYSPACE [IF NOT EXISTS] keyspace_name WITH REPLICATION = {replication_map} [AND DURABLE_WRITES = true|false] ; Here’s an example that shows how to create a keyspace named App_data: you must read replication strategy in Cassandra for better understanding. Replication Strategy : NetworkTopologyStrategy cqlsh> CREATE KEYSPACE IF NOT EXISTS App_data WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3, 'datacenter2': 2 }; Now, here you must check If there are no errors, the database is created, or not then You can run the describe keyspaces command to ascertain that the database did indeed create the keyspace. To check the all keyspaces which are already created then you can run the following CQL query given below. cqlsh> describe keyspaces; To check the App_data keyspaces is created or not then you can run the following CQL query given below. cqlsh> describe App_data; Output: cassandra@cqlsh> describe keyspaces; university system backup_copy system_traces system_schema system_auth app_data system_distributed operation In Cassandra, IF NOT EXISTS part is optional but it is always good practice using such statements because it helps avoid an error should the keyspace cycling already exist. Step-3: Describing the keyspaceIn Cassandra, A keyspace is a defining container for replication. Now, You can see the new keyspace App_data in the list of keyspaces shown by the database. Now, to check the details about App_data keyspace, you can execute the describe App_data command. describe App_data; Output: cassandra@cqlsh> describe App_data; CREATE KEYSPACE app_data WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': '3', 'datacenter2': '2'} AND durable_writes = true; NoSQL DBMS Write From Home DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database Introduction of B-Tree Difference between Clustered and Non-clustered index CTE in SQL Introduction of ER Model Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24196, "s": 24168, "text": "\n28 Apr, 2020" }, { "code": null, "e": 24397, "s": 24196, "text": "In this article, we are going to discuss how to create the database in Cassandra. so, for better understanding you can read “Introduction to Cassandra” article before creating a database in Cassandra." }, { "code": null, "e": 24637, "s": 24397, "text": "Step-1: login into cqlshyou can log in into the cqlsh using Cassandra default credential. Now, here before creating a database you first need login into cqlsh. you can check the cluster information after login into cqlsh.let’s have a look." }, { "code": null, "e": 24680, "s": 24637, "text": "cqlsh 127.0.0.1 -u cassandra -p cassandra " }, { "code": null, "e": 24831, "s": 24680, "text": "Step-2: Creating a databaseCreating a keyspace in Cassandra is the same as creating a database in SQL. CQL query for creating a keyspace as following." }, { "code": null, "e": 24985, "s": 24831, "text": "Syntax: \n\nCREATE KEYSPACE [IF NOT EXISTS] keyspace_name \n WITH REPLICATION = {replication_map}\n [AND DURABLE_WRITES = true|false] ; " }, { "code": null, "e": 25055, "s": 24985, "text": "Here’s an example that shows how to create a keyspace named App_data:" }, { "code": null, "e": 25129, "s": 25055, "text": "you must read replication strategy in Cassandra for better understanding." }, { "code": null, "e": 25334, "s": 25129, "text": "Replication Strategy : NetworkTopologyStrategy\ncqlsh> CREATE KEYSPACE IF NOT EXISTS App_data\n WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy',\n 'datacenter1' : 3, 'datacenter2': 2 }; " }, { "code": null, "e": 25526, "s": 25334, "text": "Now, here you must check If there are no errors, the database is created, or not then You can run the describe keyspaces command to ascertain that the database did indeed create the keyspace." }, { "code": null, "e": 25633, "s": 25526, "text": "To check the all keyspaces which are already created then you can run the following CQL query given below." }, { "code": null, "e": 25661, "s": 25633, "text": "cqlsh> describe keyspaces; " }, { "code": null, "e": 25765, "s": 25661, "text": "To check the App_data keyspaces is created or not then you can run the following CQL query given below." }, { "code": null, "e": 25792, "s": 25765, "text": "cqlsh> describe App_data; " }, { "code": null, "e": 25800, "s": 25792, "text": "Output:" }, { "code": null, "e": 25960, "s": 25800, "text": "cassandra@cqlsh> describe keyspaces;\n\nuniversity system backup_copy system_traces system_schema\nsystem_auth app_data system_distributed operation " }, { "code": null, "e": 26133, "s": 25960, "text": "In Cassandra, IF NOT EXISTS part is optional but it is always good practice using such statements because it helps avoid an error should the keyspace cycling already exist." }, { "code": null, "e": 26321, "s": 26133, "text": "Step-3: Describing the keyspaceIn Cassandra, A keyspace is a defining container for replication. Now, You can see the new keyspace App_data in the list of keyspaces shown by the database." }, { "code": null, "e": 26419, "s": 26321, "text": "Now, to check the details about App_data keyspace, you can execute the describe App_data command." }, { "code": null, "e": 26439, "s": 26419, "text": "describe App_data; " }, { "code": null, "e": 26447, "s": 26439, "text": "Output:" }, { "code": null, "e": 26652, "s": 26447, "text": "cassandra@cqlsh> describe App_data;\n\nCREATE KEYSPACE app_data WITH \nreplication = {'class': 'NetworkTopologyStrategy', \n 'datacenter1': '3', 'datacenter2': '2'} \nAND durable_writes = true; " }, { "code": null, "e": 26658, "s": 26652, "text": "NoSQL" }, { "code": null, "e": 26663, "s": 26658, "text": "DBMS" }, { "code": null, "e": 26679, "s": 26663, "text": "Write From Home" }, { "code": null, "e": 26684, "s": 26679, "text": "DBMS" }, { "code": null, "e": 26782, "s": 26684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26813, "s": 26782, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26836, "s": 26813, "text": "Introduction of B-Tree" }, { "code": null, "e": 26889, "s": 26836, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26900, "s": 26889, "text": "CTE in SQL" }, { "code": null, "e": 26925, "s": 26900, "text": "Introduction of ER Model" }, { "code": null, "e": 26961, "s": 26925, "text": "Convert integer to string in Python" }, { "code": null, "e": 26997, "s": 26961, "text": "Convert string to integer in Python" }, { "code": null, "e": 27013, "s": 26997, "text": "Python infinity" }, { "code": null, "e": 27074, "s": 27013, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to Load the Content of a Google Document in Python | by Angelica Lo Duca | Towards Data Science
It may happen that you have a document stored as a Google Doc in Google Drive and you want to load its content dynamically into a Python pandas DataFrame for further processing. First of all, you need to access the Google Cloud Platform and create a new project, say MyProject. Then you must select the created project in the main dashboard and select explore and enable APIs. You can search for Google Docs API and you can click on Enable API. Once enabled, you should create new credentials. You can select Google Doc API and check the User Data, as shown in the image below. You can follow the wizard and complete the creation of credentials. In the section 4 OAuth Client ID, you can choose Desktop app as Application type. Now you can download the created secret and rename it into credentials.json. Put this file in the same directory where you will write your Python code. Now you can download and copy the code of the official Google Doc API documentation, which permits you to download the content of a Google Doc document. Make sure that you have the rights to read the Google Doc!!! Once you’ve extracted the text, you can save it into a local file and then convert into a DataFrame for further analysis. You will store each line of the text as a new row in the DataFrame. Let’s suppose that you have stored the text of the Google Doc into a variable called text. doc_content = body.get('content')text = read_strucutural_elements(doc_content) Now, you can save it into a local file: with open("my_doc.txt", "w") as text_file: text_file.write(text) and then you can reload the file and convert it to a DataFrame: import pandas as pdwith open('my_doc.txt', 'r') as f: text = [line for line in f.readlines()]df = pd.DataFrame(text,columns=['text']) Eventually, you are ready to work with your data! Enjoy it! In this tutorial, I have illustrated how to load a text from a Google Doc document through the official Google Doc API and convert it into a Python pandas DataFrame. The procedure is simple, but it requires some important steps, including the configuration of the credentials used to access the Google Doc API. If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube, and Github.
[ { "code": null, "e": 349, "s": 171, "text": "It may happen that you have a document stored as a Google Doc in Google Drive and you want to load its content dynamically into a Python pandas DataFrame for further processing." }, { "code": null, "e": 665, "s": 349, "text": "First of all, you need to access the Google Cloud Platform and create a new project, say MyProject. Then you must select the created project in the main dashboard and select explore and enable APIs. You can search for Google Docs API and you can click on Enable API. Once enabled, you should create new credentials." }, { "code": null, "e": 749, "s": 665, "text": "You can select Google Doc API and check the User Data, as shown in the image below." }, { "code": null, "e": 899, "s": 749, "text": "You can follow the wizard and complete the creation of credentials. In the section 4 OAuth Client ID, you can choose Desktop app as Application type." }, { "code": null, "e": 1051, "s": 899, "text": "Now you can download the created secret and rename it into credentials.json. Put this file in the same directory where you will write your Python code." }, { "code": null, "e": 1265, "s": 1051, "text": "Now you can download and copy the code of the official Google Doc API documentation, which permits you to download the content of a Google Doc document. Make sure that you have the rights to read the Google Doc!!!" }, { "code": null, "e": 1546, "s": 1265, "text": "Once you’ve extracted the text, you can save it into a local file and then convert into a DataFrame for further analysis. You will store each line of the text as a new row in the DataFrame. Let’s suppose that you have stored the text of the Google Doc into a variable called text." }, { "code": null, "e": 1625, "s": 1546, "text": "doc_content = body.get('content')text = read_strucutural_elements(doc_content)" }, { "code": null, "e": 1665, "s": 1625, "text": "Now, you can save it into a local file:" }, { "code": null, "e": 1733, "s": 1665, "text": "with open(\"my_doc.txt\", \"w\") as text_file: text_file.write(text)" }, { "code": null, "e": 1797, "s": 1733, "text": "and then you can reload the file and convert it to a DataFrame:" }, { "code": null, "e": 1934, "s": 1797, "text": "import pandas as pdwith open('my_doc.txt', 'r') as f: text = [line for line in f.readlines()]df = pd.DataFrame(text,columns=['text'])" }, { "code": null, "e": 1994, "s": 1934, "text": "Eventually, you are ready to work with your data! Enjoy it!" }, { "code": null, "e": 2160, "s": 1994, "text": "In this tutorial, I have illustrated how to load a text from a Google Doc document through the official Google Doc API and convert it into a Python pandas DataFrame." }, { "code": null, "e": 2305, "s": 2160, "text": "The procedure is simple, but it requires some important steps, including the configuration of the credentials used to access the Google Doc API." } ]
Time Series Forecasting with Graph Convolutional Neural Network | by Marco Cerliani | Towards Data Science
Time Series forecasting tasks can be carried out following different approaches. The most classical is based on statistical and autoregressive methods. More tricky are the algorithms based on boosting and ensemble where we have to produce a good amount of useful handmade features with rolling periods. On the other side, we can find neural network models that enable more freedom in their development, providing customizable adoption of sequential modeling and much more. Recurrent and convolutional structure achieve great success in time series forecasting. Interesting approaches in the field are given by the adoption of Transformers and Attention architectures, originally native in the NLP. Uncommon seems to be the usage of graph structures, where we have a network composed of different nodes that are related by some kind of linkage to each other. What we try to do is to use a graphical representation of our time series to produce future forecasts. In this post, we carry out a sales forecasting task where we make use of graph convolutional neural networks exploiting the nested structure of our data, composed of different sales series of various items in different stores. The dataset is collected from a past competition on Kaggle. The Store Item Demand Forecasting Challenge provides 4 whole years of sales data in a daily format for different items sold in various stores. We have 10 stores and 50 products, for a total of 500 series. Each product is sold in every store. Our scope is to provide accurate future forecasts daily for all the items. The data at our disposal is minimal: only sales amount and numerical encoding of items and stores. This is still enough for us to underline a basic hierarchical structure. All we need to do is to group the series at item levels, in this way we end with 50 groups (items) each composed by 10 series (items sold in each store); an example of a group is depicted in the figure above. In classical graph networks, all the relevant information is stored in an object called the adjacent matrix. This is a numerical representation of all the linkages present in the data. The adjacent matrix in our context can be retrieved by the correlation matrix calculated on sale sequences of a given item in all stores. The sequence repartition is fundamental in our approach because we decide to process the data in pieces like for recurrent architecture, which will be also part of our model. Our model receives, as input, sequences of sales from all stores and adjacent matrixes obtained from the same sequences. The sequences are passed through LSTM layers, while the correlation matrixes are processed by GraphConvolution layers. They are implemented in Spektral, a cool library for graph deep learning build on Tensorflow. It has various kinds of graph layers available. We use the most basic one, the GraphConvolution. It operates a series of convolution operations between learnable weights, external node features (provided together with the adjacent matrix), and our correlation matrixes. Unlikely, at the moment Spektral doesn’t support Window so I have to extract manually the class of my interest and create my Python executable. Our network looks like below: def get_model(): opt = Adam(lr=0.001) inp_seq = Input((sequence_length, 10)) inp_lap = Input((10, 10)) inp_feat = Input((10, X_train_feat.shape[-1])) x = GraphConv(32, activation='relu')([inp_feat, inp_lap]) x = GraphConv(16, activation='relu')([x, inp_lap]) x = Flatten()(x) xx = LSTM(128, activation='relu',return_sequences=True)(inp_seq) xx = LSTM(32, activation='relu')(xx) x = Concatenate()([x,xx]) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(128, activation='relu')(x) x = Dense(32, activation='relu')(x) x = Dropout(0.3)(x) out = Dense(1)(x) model = Model([inp_seq, inp_lap, inp_feat], out) model.compile(optimizer=opt, loss='mse', metrics=[tf.keras.metrics.RootMeanSquaredError()]) return model As introduced before, the data are processed as always like when developing a recurrent network. The sequences are a collection of sales, for a fixed temporal period, in all stores for the item taken into consideration. The further step in our case is to calculate, on the same pieces of sequences, also the correlation matrix of sales between stores which represents our adjacent matrix. Together with them are provided some hand made features (like mean, standard deviation, skewness, kurtosis, regression coefficient), calculated by us on stores for each sequence, which stands for our node features in the network. Given a sample covariance or correlation matrix, we can estimate an adjacency matrix applying a Laplacian normalization which enables the usage of an efficient layer-wise propagation rule, based on the first-order approximation of spectral convolutions (as described here and implemented in Spektral). The train is computed with the first two years of data while the remaining two are respectively used for validation and testing. I trained a model for each store so we ended with a total of 10 different neural networks. The predictions of stores are retrieved at the end of the training procedure by the relative models. The errors are calculated as RMSE on test data and reported below. In the same way, it’s easy to extract the predictions for items in desired stores directing manipulating our nested data structure. In this post, I’ve adopted graph neural networks in an uncommon scenario like time series forecasting. In our deep learning model, graph dependency combines itself with the recurrent part trying to provide more accurate forecasts. This approach seems to suits well to our problem because we could underline a basic hierarchical structure in our data, which we numerical encoded with correlation matrixes. CHECK MY GITHUB REPO Keep in touch: Linkedin REFERENCES Spektral: Graph Neural Networks with Keras and Tensorflow Semi-Supervised Classification with Graph Convolutional Networks: Thomas N. Kipf, Max Welling
[ { "code": null, "e": 645, "s": 172, "text": "Time Series forecasting tasks can be carried out following different approaches. The most classical is based on statistical and autoregressive methods. More tricky are the algorithms based on boosting and ensemble where we have to produce a good amount of useful handmade features with rolling periods. On the other side, we can find neural network models that enable more freedom in their development, providing customizable adoption of sequential modeling and much more." }, { "code": null, "e": 1133, "s": 645, "text": "Recurrent and convolutional structure achieve great success in time series forecasting. Interesting approaches in the field are given by the adoption of Transformers and Attention architectures, originally native in the NLP. Uncommon seems to be the usage of graph structures, where we have a network composed of different nodes that are related by some kind of linkage to each other. What we try to do is to use a graphical representation of our time series to produce future forecasts." }, { "code": null, "e": 1360, "s": 1133, "text": "In this post, we carry out a sales forecasting task where we make use of graph convolutional neural networks exploiting the nested structure of our data, composed of different sales series of various items in different stores." }, { "code": null, "e": 1737, "s": 1360, "text": "The dataset is collected from a past competition on Kaggle. The Store Item Demand Forecasting Challenge provides 4 whole years of sales data in a daily format for different items sold in various stores. We have 10 stores and 50 products, for a total of 500 series. Each product is sold in every store. Our scope is to provide accurate future forecasts daily for all the items." }, { "code": null, "e": 2118, "s": 1737, "text": "The data at our disposal is minimal: only sales amount and numerical encoding of items and stores. This is still enough for us to underline a basic hierarchical structure. All we need to do is to group the series at item levels, in this way we end with 50 groups (items) each composed by 10 series (items sold in each store); an example of a group is depicted in the figure above." }, { "code": null, "e": 2441, "s": 2118, "text": "In classical graph networks, all the relevant information is stored in an object called the adjacent matrix. This is a numerical representation of all the linkages present in the data. The adjacent matrix in our context can be retrieved by the correlation matrix calculated on sale sequences of a given item in all stores." }, { "code": null, "e": 2616, "s": 2441, "text": "The sequence repartition is fundamental in our approach because we decide to process the data in pieces like for recurrent architecture, which will be also part of our model." }, { "code": null, "e": 3364, "s": 2616, "text": "Our model receives, as input, sequences of sales from all stores and adjacent matrixes obtained from the same sequences. The sequences are passed through LSTM layers, while the correlation matrixes are processed by GraphConvolution layers. They are implemented in Spektral, a cool library for graph deep learning build on Tensorflow. It has various kinds of graph layers available. We use the most basic one, the GraphConvolution. It operates a series of convolution operations between learnable weights, external node features (provided together with the adjacent matrix), and our correlation matrixes. Unlikely, at the moment Spektral doesn’t support Window so I have to extract manually the class of my interest and create my Python executable." }, { "code": null, "e": 3394, "s": 3364, "text": "Our network looks like below:" }, { "code": null, "e": 4186, "s": 3394, "text": "def get_model(): opt = Adam(lr=0.001) inp_seq = Input((sequence_length, 10)) inp_lap = Input((10, 10)) inp_feat = Input((10, X_train_feat.shape[-1])) x = GraphConv(32, activation='relu')([inp_feat, inp_lap]) x = GraphConv(16, activation='relu')([x, inp_lap]) x = Flatten()(x) xx = LSTM(128, activation='relu',return_sequences=True)(inp_seq) xx = LSTM(32, activation='relu')(xx) x = Concatenate()([x,xx]) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(128, activation='relu')(x) x = Dense(32, activation='relu')(x) x = Dropout(0.3)(x) out = Dense(1)(x) model = Model([inp_seq, inp_lap, inp_feat], out) model.compile(optimizer=opt, loss='mse', metrics=[tf.keras.metrics.RootMeanSquaredError()]) return model" }, { "code": null, "e": 4406, "s": 4186, "text": "As introduced before, the data are processed as always like when developing a recurrent network. The sequences are a collection of sales, for a fixed temporal period, in all stores for the item taken into consideration." }, { "code": null, "e": 4805, "s": 4406, "text": "The further step in our case is to calculate, on the same pieces of sequences, also the correlation matrix of sales between stores which represents our adjacent matrix. Together with them are provided some hand made features (like mean, standard deviation, skewness, kurtosis, regression coefficient), calculated by us on stores for each sequence, which stands for our node features in the network." }, { "code": null, "e": 5107, "s": 4805, "text": "Given a sample covariance or correlation matrix, we can estimate an adjacency matrix applying a Laplacian normalization which enables the usage of an efficient layer-wise propagation rule, based on the first-order approximation of spectral convolutions (as described here and implemented in Spektral)." }, { "code": null, "e": 5327, "s": 5107, "text": "The train is computed with the first two years of data while the remaining two are respectively used for validation and testing. I trained a model for each store so we ended with a total of 10 different neural networks." }, { "code": null, "e": 5495, "s": 5327, "text": "The predictions of stores are retrieved at the end of the training procedure by the relative models. The errors are calculated as RMSE on test data and reported below." }, { "code": null, "e": 5627, "s": 5495, "text": "In the same way, it’s easy to extract the predictions for items in desired stores directing manipulating our nested data structure." }, { "code": null, "e": 6032, "s": 5627, "text": "In this post, I’ve adopted graph neural networks in an uncommon scenario like time series forecasting. In our deep learning model, graph dependency combines itself with the recurrent part trying to provide more accurate forecasts. This approach seems to suits well to our problem because we could underline a basic hierarchical structure in our data, which we numerical encoded with correlation matrixes." }, { "code": null, "e": 6053, "s": 6032, "text": "CHECK MY GITHUB REPO" }, { "code": null, "e": 6077, "s": 6053, "text": "Keep in touch: Linkedin" }, { "code": null, "e": 6088, "s": 6077, "text": "REFERENCES" }, { "code": null, "e": 6146, "s": 6088, "text": "Spektral: Graph Neural Networks with Keras and Tensorflow" } ]
C program to implement Adjacency Matrix of a given Graph - GeeksforGeeks
21 May, 2020 Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples: Input: N = 5, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } }Output:0 1 0 0 11 0 1 0 00 1 0 0 00 0 0 0 11 0 0 1 0 Input: N = 3, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 2, 2 } }Output:0 1 11 1 11 1 0 Approach: The idea is to use a square Matrix of size NxN to create Adjacency Matrix. Below are the steps: Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero.For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is a edge between X and Y.Display the Adjacency Matrix after the above operation for all the pairs in arr[][]. Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero. For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is a edge between X and Y. Display the Adjacency Matrix after the above operation for all the pairs in arr[][]. Below is the implementation of the above approach: // C program for the above approach#include <stdio.h> // N vertices and M Edgesint N, M; // Function to create Adjacency Matrixvoid createAdjMatrix(int Adj[][N + 1], int arr[][2]){ // Initialise all value to this // Adjacency list to zero for (int i = 0; i < N + 1; i++) { for (int j = 0; j < N + 1; j++) { Adj[i][j] = 0; } } // Traverse the array of Edges for (int i = 0; i < M; i++) { // Find X and Y of Edges int x = arr[i][0]; int y = arr[i][1]; // Update value to 1 Adj[x][y] = 1; Adj[y][x] = 1; }} // Function to print the created// Adjacency Matrixvoid printAdjMatrix(int Adj[][N + 1]){ // Traverse the Adj[][] for (int i = 1; i < N + 1; i++) { for (int j = 1; j < N + 1; j++) { // Print the value at Adj[i][j] printf("%d ", Adj[i][j]); } printf("\n"); }} // Driver Codeint main(){ // Number of vertices N = 5; // Given Edges int arr[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } }; // Number of Edges M = sizeof(arr) / sizeof(arr[0]); // For Adjacency Matrix int Adj[N + 1][N + 1]; // Function call to create // Adjacency Matrix createAdjMatrix(Adj, arr); // Print Adjacency Matrix printAdjMatrix(Adj); return 0;} 0 1 0 0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 Time Complexity: O(N2), where N is the number of vertices in a graph. C Programs Data Structures Graph Matrix Data Structures Matrix Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Regular expressions in C C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Producer Consumer Problem in C Handling multiple clients on server with multithreading using Socket Programming in C/C++ Difference between Stack and Queue Data Structures Difference between Singly linked list and Doubly linked list Multilevel Linked List Types of Linked List FIFO vs LIFO approach in Programming
[ { "code": null, "e": 24641, "s": 24613, "text": "\n21 May, 2020" }, { "code": null, "e": 24905, "s": 24641, "text": "Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph." }, { "code": null, "e": 24915, "s": 24905, "text": "Examples:" }, { "code": null, "e": 25041, "s": 24915, "text": "Input: N = 5, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } }Output:0 1 0 0 11 0 1 0 00 1 0 0 00 0 0 0 11 0 0 1 0" }, { "code": null, "e": 25137, "s": 25041, "text": "Input: N = 3, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 2, 2 } }Output:0 1 11 1 11 1 0" }, { "code": null, "e": 25243, "s": 25137, "text": "Approach: The idea is to use a square Matrix of size NxN to create Adjacency Matrix. Below are the steps:" }, { "code": null, "e": 25555, "s": 25243, "text": "Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero.For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is a edge between X and Y.Display the Adjacency Matrix after the above operation for all the pairs in arr[][]." }, { "code": null, "e": 25653, "s": 25555, "text": "Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero." }, { "code": null, "e": 25784, "s": 25653, "text": "For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is a edge between X and Y." }, { "code": null, "e": 25869, "s": 25784, "text": "Display the Adjacency Matrix after the above operation for all the pairs in arr[][]." }, { "code": null, "e": 25920, "s": 25869, "text": "Below is the implementation of the above approach:" }, { "code": "// C program for the above approach#include <stdio.h> // N vertices and M Edgesint N, M; // Function to create Adjacency Matrixvoid createAdjMatrix(int Adj[][N + 1], int arr[][2]){ // Initialise all value to this // Adjacency list to zero for (int i = 0; i < N + 1; i++) { for (int j = 0; j < N + 1; j++) { Adj[i][j] = 0; } } // Traverse the array of Edges for (int i = 0; i < M; i++) { // Find X and Y of Edges int x = arr[i][0]; int y = arr[i][1]; // Update value to 1 Adj[x][y] = 1; Adj[y][x] = 1; }} // Function to print the created// Adjacency Matrixvoid printAdjMatrix(int Adj[][N + 1]){ // Traverse the Adj[][] for (int i = 1; i < N + 1; i++) { for (int j = 1; j < N + 1; j++) { // Print the value at Adj[i][j] printf(\"%d \", Adj[i][j]); } printf(\"\\n\"); }} // Driver Codeint main(){ // Number of vertices N = 5; // Given Edges int arr[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } }; // Number of Edges M = sizeof(arr) / sizeof(arr[0]); // For Adjacency Matrix int Adj[N + 1][N + 1]; // Function call to create // Adjacency Matrix createAdjMatrix(Adj, arr); // Print Adjacency Matrix printAdjMatrix(Adj); return 0;}", "e": 27297, "s": 25920, "text": null }, { "code": null, "e": 27352, "s": 27297, "text": "0 1 0 0 1 \n1 0 1 0 0 \n0 1 0 0 0 \n0 0 0 0 1 \n1 0 0 1 0\n" }, { "code": null, "e": 27422, "s": 27352, "text": "Time Complexity: O(N2), where N is the number of vertices in a graph." }, { "code": null, "e": 27433, "s": 27422, "text": "C Programs" }, { "code": null, "e": 27449, "s": 27433, "text": "Data Structures" }, { "code": null, "e": 27455, "s": 27449, "text": "Graph" }, { "code": null, "e": 27462, "s": 27455, "text": "Matrix" }, { "code": null, "e": 27478, "s": 27462, "text": "Data Structures" }, { "code": null, "e": 27485, "s": 27478, "text": "Matrix" }, { "code": null, "e": 27491, "s": 27485, "text": "Graph" }, { "code": null, "e": 27589, "s": 27491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27598, "s": 27589, "text": "Comments" }, { "code": null, "e": 27611, "s": 27598, "text": "Old Comments" }, { "code": null, "e": 27652, "s": 27611, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27677, "s": 27652, "text": "Regular expressions in C" }, { "code": null, "e": 27748, "s": 27677, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 27779, "s": 27748, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27869, "s": 27779, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 27920, "s": 27869, "text": "Difference between Stack and Queue Data Structures" }, { "code": null, "e": 27981, "s": 27920, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 28004, "s": 27981, "text": "Multilevel Linked List" }, { "code": null, "e": 28025, "s": 28004, "text": "Types of Linked List" } ]
Image Data Analysis Using Python: | by Yassine Hamdaoui | Towards Data Science
Introduction: A Little Bit About Pixel Observe Basic Properties of Image Greyscale Use Logical Operator To Process Pixel Values Masking Image Processing Computers store images as a mosaic of tiny squares. This is like the ancient art form of tile mosaic, or the melting bead kits kids play with today. Now, if these square tiles are too big, it’s then hard to make smooth edges and curves. The more and smaller tiles we use, the smoother or as we say less pixelated, the image will be. These sometimes get referred to as resolution of the images. Vector graphics are a somewhat different method of storing images that aims to avoid pixel related issues. But even vector images, in the end, are displayed as a mosaic of pixels. The word pixel means a picture element. A simple way to describe each pixel is using a combination of three colors, namely Red, Green, Blue. This is what we call an RGB image. Every photograph, in digital form, is made up of pixels. They are the smallest unit of information that makes up a picture. Usually round or square, they are typically arranged in a 2-dimensional grid. Now, if all three values are at full intensity, that means they’re 255. It then shows as white, and if all three colors are muted, or has the value of 0, the color shows as black. The combination of these three will, in turn, give us a specific shade of the pixel color. Since each number is an 8-bit number, the values range from 0–255. The combination of these three colors tends to the highest value among them. Since each value can have 256 different intensity or brightness value, it makes 16.8 million total shades. Now let’s load an image and observe its various properties in general. import imageio import matplotlib.pyplot as plt %matplotlib inline pic = imageio.imread(‘images/me.jpg’) plt.figure(figsize = (5,5)) plt.imshow(pic) print('Type of the image : ' , type(pic)) print('Shape of the image : {}'.format(pic.shape)) print('Image Hight {}'.format(pic.shape[0])) print('Image Width {}'.format(pic.shape[1])) print('Dimension of Image {}'.format(pic.ndim)) output : Type of the image : <class 'imageio.core.util.Array'> Shape of the image : (728, 720, 3) Image Hight 728 Image Width 720 Dimension of Image 3 The shape of the ndarray shows that it is a three-layered matrix. The first two numbers here are length and width, and the third number (i.e. 3) is for three layers: Red, Green, Blue. So, if we calculate the size of an RGB image, the total size will be counted as height x width x 3 print('Image size {}'.format(pic.size)) print('Maximum RGB value in this image {}'.format(pic.max())) print('Minimum RGB value in this image {}'.format(pic.min())) output : Image size 1572480 Maximum RGB value in this image 255 Minimum RGB value in this image 0# A specific pixel located at Row : 100 ; Column : 50 # Each channel's value of it, gradually R , G , B print('Value of only R channel {}'.format(pic[ 100, 50, 0])) print('Value of only G channel {}'.format(pic[ 100, 50, 1])) print('Value of only B channel {}'.format(pic[ 100, 50, 2])) output : Value of only R channel 168Value of only G channel 189Value of only B channel 182 Okay, now let’s take a quick view of each channel in the whole image. plt.title('R channel') plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 0])plt.show() plt.title('G channel')plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 1]) plt.show() plt.title('B channel') plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 2]) plt.show() Now, we can also able to change the number of RGB values. As an example, let’s set the Red, Green, Blue layer for following Rows values to full intensity. R channel: Row — 100 to 110 G channel: Row — 200 to 210 B channel: Row — 300 to 310 We’ll load the image once so that we can visualize each change simultaneously. pic[50:150 , : , 0] = 255 # full intensity to those pixel's R channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show() pic[200:300 , : , 1] = 255 # full intensity to those pixel's G channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show() pic[350:450 , : , 2] = 255 # full intensity to those pixel's B channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show() To make it more clear let’s change the column section too and this time we’ll change the RGB channel simultaneously. # set value 200 of all channels to those pixels which turns them to white pic[ 50:450 , 400:600 , [0,1,2] ] = 200 plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show() Now, we know that each pixel of the image is represented by three integers. Splitting the image into separate color components is just a matter of pulling out the correct slice of the image array. import numpy as np pic = imageio.imread('images/me.jpg') fig, ax = plt.subplots(nrows = 1, ncols=3, figsize=(15,5)) for c, ax in zip(range(3), ax): # create zero matrix split_img = np.zeros(pic.shape, dtype="uint8") # 'dtype' by default: 'numpy.float64' # assing each channel split_img[ :, :, c] = pic[ :, :, c] # display each channel ax.imshow(split_img) Black and white images are stored in 2-Dimensional arrays. There’re two types of black and white images: - Binary: Pixel is either black or white:0 or 255- Greyscale: Ranges of shades of grey:0 ~ 255 Now, Greyscaling is a process by which an image is converted from a full color to shades of grey. In image processing tools, for example: in OpenCV, many functions use greyscale images before processing, and this is done because it simplifies the image, acting almost as noise reduction and increasing processing time as there’s less information in the images. There are a couple of ways to do this in python to convert an image to grayscale, but a straightforward way of using matplotlib is to take the weighted mean of the RGB value of original image using this formula. pic = imageio.imread('images/me.jpg') gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) gray = gray(pic) plt.figure( figsize = (5,5)) plt.imshow(gray, cmap = plt.get_cmap(name = 'gray')) plt.show() We can create a bullion ndarray in the same size by using a logical operator. However, this won’t create any new arrays, but it simply returns True to its host variable. For example, let’s consider we want to filter out some low-value pixels or high-value or (any condition) in an RGB image, and yes, it would be great to convert RGB to grayscale, but for now, we won’t go for that rather than deal with a color image. Let’s first load an image and show it on screen. pic = imageio.imread('images/logic_op_pic.JPG') plt.figure(figsize=(5,5)) plt.imshow(pic) plt.show() let’s consider this dump image. Now, for any case, we want to filter out all the pixel values, which is below than, let’s assume, 20. For this, we’ll use a logical operator to do this task, which we’ll return as a value of True for all the index. low_pixel = pic < 20 # to ensure of it let's check if all values in low_pixel are True or not if low_pixel.any() == True: print(low_pixel.shape) output : (743, 911, 3) Now as we said, a host variable is not traditionally used, but I refer it because it behaves. It just holds the True value and nothing else. So, if we see the shape of both low_pixel and pic , we’ll find that both have the same shape. print(pic.shape)print(low_pixel.shape) output : (743, 911, 3)(743, 911, 3) We generated that low-value filter using a global comparison operator for all the values less than 200. However, we can use this low_pixel array as an index to set those low values to some specific values, which may be higher than or lower than the previous pixel value. # randomly choose a value import random# load the orginal imagepic = imageio.imread('images/logic_op_pic.JPG')# set value randomly range from 25 to 225 - these value also randomly choosenpic[low_pixel] = random.randint(25,225)# display the imageplt.figure( figsize = (5,5))plt.imshow(pic)plt.show() Image masking is an image processing technique that is used to remove the background from which photographs those have fuzzy edges, transparent or hair portions. Now, we’ll create a mask that is in shape of a circular disc. First, we’ll measure the distance from the center of the image to every border pixel values. And we take a convenient radius value, and then using logical operator, we’ll create a circular disc. It’s quite simple, let’s see the code. # Load the image pic = imageio.imread('images/logic_op_pic.JPG') # seperate the row and column values total_row , total_col , layers = pic.shape ''' Create vector. Ogrid is a compact method of creating a multidimensional ndarray operations in single lines. for ex: >>> ogrid[0:5,0:5] output: [array([[0], [1], [2], [3], [4]]), array([[0, 1, 2, 3, 4]])] ''' x , y = np.ogrid[:total_row , :total_col] # get the center values of the image cen_x , cen_y = total_row/2 , total_col/2 ''' Measure distance value from center to each border pixel. To make it easy, we can think it's like, we draw a line from center- to each edge pixel value --> s**2 = (Y-y)**2 + (X-x)**2 ''' distance_from_the_center = np.sqrt((x-cen_x)**2 + (y-cen_y)**2) # Select convenient radius value radius = (total_row/2) # Using logical operator '>' ''' logical operator to do this task which will return as a value of True for all the index according to the given condition ''' circular_pic = distance_from_the_center > radius ''' let assign value zero for all pixel value that outside the cirular disc. All the pixel value outside the circular disc, will be black now. ''' pic[circular_pic] = 0 plt.figure(figsize = (5,5)) plt.imshow(pic) plt.show() One of MOOC course on edX, we’ve introduced with some satellite images and its processing system. It’s very informative of course. However, let’s do a few analysis tasks on it There’s something interesting about this image. Like many other visualizations, the colors in each RGB layer mean something. For example, the intensity of the red will be an indication of altitude of the geographical data point in the pixel. The intensity of blue will indicate a measure of aspect, and the green will indicate slope. These colors will help communicate this information in a quicker and more effective way rather than showing numbers. Red pixel indicates: AltitudeBlue pixel indicates: AspectGreen pixel indicates: Slope There is, by just looking at this colorful image, a trained eye that can tell already what the altitude is, what the slope is, and what the aspect is. So, that’s the idea of loading some more meaning to these colors to indicate something more scientific. # Only Red Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')red_mask = pic[:, :, 0] < 180pic[red_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Only Green Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')green_mask = pic[:, :, 1] < 180pic[green_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Only Blue Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')blue_mask = pic[:, :, 2] < 180pic[blue_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Composite mask using logical_andpic = imageio.imread('images/sat_img.JPG')final_mask = np.logical_and(red_mask, green_mask, blue_mask)pic[final_mask] = 40plt.figure(figsize=(5,5))plt.imshow(pic) Remember that you can find the fully working code in my github repository here. Thanks for reading and I will be glad to discuss any questions or corrections you may have :) Find me on LinkedIn if you want to discuss Machine Learning or anything else.
[ { "code": null, "e": 210, "s": 171, "text": "Introduction: A Little Bit About Pixel" }, { "code": null, "e": 244, "s": 210, "text": "Observe Basic Properties of Image" }, { "code": null, "e": 254, "s": 244, "text": "Greyscale" }, { "code": null, "e": 299, "s": 254, "text": "Use Logical Operator To Process Pixel Values" }, { "code": null, "e": 307, "s": 299, "text": "Masking" }, { "code": null, "e": 324, "s": 307, "text": "Image Processing" }, { "code": null, "e": 718, "s": 324, "text": "Computers store images as a mosaic of tiny squares. This is like the ancient art form of tile mosaic, or the melting bead kits kids play with today. Now, if these square tiles are too big, it’s then hard to make smooth edges and curves. The more and smaller tiles we use, the smoother or as we say less pixelated, the image will be. These sometimes get referred to as resolution of the images." }, { "code": null, "e": 1074, "s": 718, "text": "Vector graphics are a somewhat different method of storing images that aims to avoid pixel related issues. But even vector images, in the end, are displayed as a mosaic of pixels. The word pixel means a picture element. A simple way to describe each pixel is using a combination of three colors, namely Red, Green, Blue. This is what we call an RGB image." }, { "code": null, "e": 1276, "s": 1074, "text": "Every photograph, in digital form, is made up of pixels. They are the smallest unit of information that makes up a picture. Usually round or square, they are typically arranged in a 2-dimensional grid." }, { "code": null, "e": 1614, "s": 1276, "text": "Now, if all three values are at full intensity, that means they’re 255. It then shows as white, and if all three colors are muted, or has the value of 0, the color shows as black. The combination of these three will, in turn, give us a specific shade of the pixel color. Since each number is an 8-bit number, the values range from 0–255." }, { "code": null, "e": 1798, "s": 1614, "text": "The combination of these three colors tends to the highest value among them. Since each value can have 256 different intensity or brightness value, it makes 16.8 million total shades." }, { "code": null, "e": 1869, "s": 1798, "text": "Now let’s load an image and observe its various properties in general." }, { "code": null, "e": 2018, "s": 1869, "text": " import imageio import matplotlib.pyplot as plt %matplotlib inline pic = imageio.imread(‘images/me.jpg’) plt.figure(figsize = (5,5)) plt.imshow(pic)" }, { "code": null, "e": 2249, "s": 2018, "text": "print('Type of the image : ' , type(pic)) print('Shape of the image : {}'.format(pic.shape)) print('Image Hight {}'.format(pic.shape[0])) print('Image Width {}'.format(pic.shape[1])) print('Dimension of Image {}'.format(pic.ndim))" }, { "code": null, "e": 2258, "s": 2249, "text": "output :" }, { "code": null, "e": 2401, "s": 2258, "text": "Type of the image : <class 'imageio.core.util.Array'> Shape of the image : (728, 720, 3) Image Hight 728 Image Width 720 Dimension of Image 3" }, { "code": null, "e": 2684, "s": 2401, "text": "The shape of the ndarray shows that it is a three-layered matrix. The first two numbers here are length and width, and the third number (i.e. 3) is for three layers: Red, Green, Blue. So, if we calculate the size of an RGB image, the total size will be counted as height x width x 3" }, { "code": null, "e": 2848, "s": 2684, "text": "print('Image size {}'.format(pic.size)) print('Maximum RGB value in this image {}'.format(pic.max())) print('Minimum RGB value in this image {}'.format(pic.min()))" }, { "code": null, "e": 2857, "s": 2848, "text": "output :" }, { "code": null, "e": 3234, "s": 2857, "text": "Image size 1572480 Maximum RGB value in this image 255 Minimum RGB value in this image 0# A specific pixel located at Row : 100 ; Column : 50 # Each channel's value of it, gradually R , G , B print('Value of only R channel {}'.format(pic[ 100, 50, 0])) print('Value of only G channel {}'.format(pic[ 100, 50, 1])) print('Value of only B channel {}'.format(pic[ 100, 50, 2]))" }, { "code": null, "e": 3243, "s": 3234, "text": "output :" }, { "code": null, "e": 3325, "s": 3243, "text": "Value of only R channel 168Value of only G channel 189Value of only B channel 182" }, { "code": null, "e": 3395, "s": 3325, "text": "Okay, now let’s take a quick view of each channel in the whole image." }, { "code": null, "e": 3545, "s": 3395, "text": "plt.title('R channel') plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 0])plt.show()" }, { "code": null, "e": 3695, "s": 3545, "text": "plt.title('G channel')plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 1]) plt.show()" }, { "code": null, "e": 3846, "s": 3695, "text": "plt.title('B channel') plt.ylabel('Height {}'.format(pic.shape[0])) plt.xlabel('Width {}'.format(pic.shape[1])) plt.imshow(pic[ : , : , 2]) plt.show()" }, { "code": null, "e": 4001, "s": 3846, "text": "Now, we can also able to change the number of RGB values. As an example, let’s set the Red, Green, Blue layer for following Rows values to full intensity." }, { "code": null, "e": 4029, "s": 4001, "text": "R channel: Row — 100 to 110" }, { "code": null, "e": 4057, "s": 4029, "text": "G channel: Row — 200 to 210" }, { "code": null, "e": 4085, "s": 4057, "text": "B channel: Row — 300 to 310" }, { "code": null, "e": 4164, "s": 4085, "text": "We’ll load the image once so that we can visualize each change simultaneously." }, { "code": null, "e": 4290, "s": 4164, "text": "pic[50:150 , : , 0] = 255 # full intensity to those pixel's R channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 4417, "s": 4290, "text": "pic[200:300 , : , 1] = 255 # full intensity to those pixel's G channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 4544, "s": 4417, "text": "pic[350:450 , : , 2] = 255 # full intensity to those pixel's B channel plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 4661, "s": 4544, "text": "To make it more clear let’s change the column section too and this time we’ll change the RGB channel simultaneously." }, { "code": null, "e": 4832, "s": 4661, "text": "# set value 200 of all channels to those pixels which turns them to white pic[ 50:450 , 400:600 , [0,1,2] ] = 200 plt.figure( figsize = (5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 5029, "s": 4832, "text": "Now, we know that each pixel of the image is represented by three integers. Splitting the image into separate color components is just a matter of pulling out the correct slice of the image array." }, { "code": null, "e": 5432, "s": 5029, "text": "import numpy as np pic = imageio.imread('images/me.jpg') fig, ax = plt.subplots(nrows = 1, ncols=3, figsize=(15,5)) for c, ax in zip(range(3), ax): # create zero matrix split_img = np.zeros(pic.shape, dtype=\"uint8\") # 'dtype' by default: 'numpy.float64' # assing each channel split_img[ :, :, c] = pic[ :, :, c] # display each channel ax.imshow(split_img)" }, { "code": null, "e": 5537, "s": 5432, "text": "Black and white images are stored in 2-Dimensional arrays. There’re two types of black and white images:" }, { "code": null, "e": 5632, "s": 5537, "text": "- Binary: Pixel is either black or white:0 or 255- Greyscale: Ranges of shades of grey:0 ~ 255" }, { "code": null, "e": 5993, "s": 5632, "text": "Now, Greyscaling is a process by which an image is converted from a full color to shades of grey. In image processing tools, for example: in OpenCV, many functions use greyscale images before processing, and this is done because it simplifies the image, acting almost as noise reduction and increasing processing time as there’s less information in the images." }, { "code": null, "e": 6205, "s": 5993, "text": "There are a couple of ways to do this in python to convert an image to grayscale, but a straightforward way of using matplotlib is to take the weighted mean of the RGB value of original image using this formula." }, { "code": null, "e": 6423, "s": 6205, "text": "pic = imageio.imread('images/me.jpg') gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) gray = gray(pic) plt.figure( figsize = (5,5)) plt.imshow(gray, cmap = plt.get_cmap(name = 'gray')) plt.show()" }, { "code": null, "e": 6842, "s": 6423, "text": "We can create a bullion ndarray in the same size by using a logical operator. However, this won’t create any new arrays, but it simply returns True to its host variable. For example, let’s consider we want to filter out some low-value pixels or high-value or (any condition) in an RGB image, and yes, it would be great to convert RGB to grayscale, but for now, we won’t go for that rather than deal with a color image." }, { "code": null, "e": 6891, "s": 6842, "text": "Let’s first load an image and show it on screen." }, { "code": null, "e": 6992, "s": 6891, "text": "pic = imageio.imread('images/logic_op_pic.JPG') plt.figure(figsize=(5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 7239, "s": 6992, "text": "let’s consider this dump image. Now, for any case, we want to filter out all the pixel values, which is below than, let’s assume, 20. For this, we’ll use a logical operator to do this task, which we’ll return as a value of True for all the index." }, { "code": null, "e": 7393, "s": 7239, "text": "low_pixel = pic < 20 # to ensure of it let's check if all values in low_pixel are True or not if low_pixel.any() == True: print(low_pixel.shape)" }, { "code": null, "e": 7402, "s": 7393, "text": "output :" }, { "code": null, "e": 7416, "s": 7402, "text": "(743, 911, 3)" }, { "code": null, "e": 7651, "s": 7416, "text": "Now as we said, a host variable is not traditionally used, but I refer it because it behaves. It just holds the True value and nothing else. So, if we see the shape of both low_pixel and pic , we’ll find that both have the same shape." }, { "code": null, "e": 7690, "s": 7651, "text": "print(pic.shape)print(low_pixel.shape)" }, { "code": null, "e": 7699, "s": 7690, "text": "output :" }, { "code": null, "e": 7726, "s": 7699, "text": "(743, 911, 3)(743, 911, 3)" }, { "code": null, "e": 7997, "s": 7726, "text": "We generated that low-value filter using a global comparison operator for all the values less than 200. However, we can use this low_pixel array as an index to set those low values to some specific values, which may be higher than or lower than the previous pixel value." }, { "code": null, "e": 8296, "s": 7997, "text": "# randomly choose a value import random# load the orginal imagepic = imageio.imread('images/logic_op_pic.JPG')# set value randomly range from 25 to 225 - these value also randomly choosenpic[low_pixel] = random.randint(25,225)# display the imageplt.figure( figsize = (5,5))plt.imshow(pic)plt.show()" }, { "code": null, "e": 8458, "s": 8296, "text": "Image masking is an image processing technique that is used to remove the background from which photographs those have fuzzy edges, transparent or hair portions." }, { "code": null, "e": 8754, "s": 8458, "text": "Now, we’ll create a mask that is in shape of a circular disc. First, we’ll measure the distance from the center of the image to every border pixel values. And we take a convenient radius value, and then using logical operator, we’ll create a circular disc. It’s quite simple, let’s see the code." }, { "code": null, "e": 10090, "s": 8754, "text": "# Load the image pic = imageio.imread('images/logic_op_pic.JPG') # seperate the row and column values total_row , total_col , layers = pic.shape ''' Create vector. Ogrid is a compact method of creating a multidimensional ndarray operations in single lines. for ex: >>> ogrid[0:5,0:5] output: [array([[0], [1], [2], [3], [4]]), array([[0, 1, 2, 3, 4]])] ''' x , y = np.ogrid[:total_row , :total_col] # get the center values of the image cen_x , cen_y = total_row/2 , total_col/2 ''' Measure distance value from center to each border pixel. To make it easy, we can think it's like, we draw a line from center- to each edge pixel value --> s**2 = (Y-y)**2 + (X-x)**2 ''' distance_from_the_center = np.sqrt((x-cen_x)**2 + (y-cen_y)**2) # Select convenient radius value radius = (total_row/2) # Using logical operator '>' ''' logical operator to do this task which will return as a value of True for all the index according to the given condition ''' circular_pic = distance_from_the_center > radius ''' let assign value zero for all pixel value that outside the cirular disc. All the pixel value outside the circular disc, will be black now. ''' pic[circular_pic] = 0 plt.figure(figsize = (5,5)) plt.imshow(pic) plt.show()" }, { "code": null, "e": 10266, "s": 10090, "text": "One of MOOC course on edX, we’ve introduced with some satellite images and its processing system. It’s very informative of course. However, let’s do a few analysis tasks on it" }, { "code": null, "e": 10717, "s": 10266, "text": "There’s something interesting about this image. Like many other visualizations, the colors in each RGB layer mean something. For example, the intensity of the red will be an indication of altitude of the geographical data point in the pixel. The intensity of blue will indicate a measure of aspect, and the green will indicate slope. These colors will help communicate this information in a quicker and more effective way rather than showing numbers." }, { "code": null, "e": 10803, "s": 10717, "text": "Red pixel indicates: AltitudeBlue pixel indicates: AspectGreen pixel indicates: Slope" }, { "code": null, "e": 11058, "s": 10803, "text": "There is, by just looking at this colorful image, a trained eye that can tell already what the altitude is, what the slope is, and what the aspect is. So, that’s the idea of loading some more meaning to these colors to indicate something more scientific." }, { "code": null, "e": 11768, "s": 11058, "text": "# Only Red Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')red_mask = pic[:, :, 0] < 180pic[red_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Only Green Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')green_mask = pic[:, :, 1] < 180pic[green_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Only Blue Pixel value , higher than 180pic = imageio.imread('images/sat_img.JPG')blue_mask = pic[:, :, 2] < 180pic[blue_mask] = 0plt.figure(figsize=(5,5))plt.imshow(pic)# Composite mask using logical_andpic = imageio.imread('images/sat_img.JPG')final_mask = np.logical_and(red_mask, green_mask, blue_mask)pic[final_mask] = 40plt.figure(figsize=(5,5))plt.imshow(pic)" }, { "code": null, "e": 11848, "s": 11768, "text": "Remember that you can find the fully working code in my github repository here." } ]
XSD - Numeric Data Types
Numeric data types are used to represent numbers in XML documents. The <xs:decimal> data type is used to represent numeric values. It supports decimal numbers up to 18 digits. Element declaration in XSD − <xs:element name = "score" type = "xs:decimal"/> Element usage in XML − <score>9.12</score> The <xs:integer> data type is used to represent integer values. Element declaration in XSD − <xs:element name = "score" type = "xs:integer"/> Element usage in XML − <score>9</score> Following is the list of commonly used numeric data types. byte A signed 8 bit integer decimal A decimal value int A signed 32 bit integer integer An integer value long A signed 64 bit integer negativeInteger An integer having only negative values (..,-2,-1) nonNegativeInteger An integer having only non-negative values (0,1,2,..) nonPositiveInteger An integer having only non-positive values (..,-2,-1,0) positiveInteger An integer having only positive values (1,2,..) short A signed 16 bit integer unsignedLong An unsigned 64 bit integer unsignedInt An unsigned 32 bit integer unsignedShort An unsigned 16 bit integer unsignedByte An unsigned 8 bit integer Following types of restrictions can be used with Date data types − enumeration fractionDigits maxExclusive maxInclusive minExclusive minInclusive pattern totalDigits whiteSpace Print Add Notes Bookmark this page
[ { "code": null, "e": 1771, "s": 1704, "text": "Numeric data types are used to represent numbers in XML documents." }, { "code": null, "e": 1880, "s": 1771, "text": "The <xs:decimal> data type is used to represent numeric values. It supports decimal numbers up to 18 digits." }, { "code": null, "e": 1909, "s": 1880, "text": "Element declaration in XSD −" }, { "code": null, "e": 1959, "s": 1909, "text": "<xs:element name = \"score\" type = \"xs:decimal\"/>\n" }, { "code": null, "e": 1982, "s": 1959, "text": "Element usage in XML −" }, { "code": null, "e": 2003, "s": 1982, "text": "<score>9.12</score>\n" }, { "code": null, "e": 2067, "s": 2003, "text": "The <xs:integer> data type is used to represent integer values." }, { "code": null, "e": 2096, "s": 2067, "text": "Element declaration in XSD −" }, { "code": null, "e": 2146, "s": 2096, "text": "<xs:element name = \"score\" type = \"xs:integer\"/>\n" }, { "code": null, "e": 2169, "s": 2146, "text": "Element usage in XML −" }, { "code": null, "e": 2187, "s": 2169, "text": "<score>9</score>\n" }, { "code": null, "e": 2246, "s": 2187, "text": "Following is the list of commonly used numeric data types." }, { "code": null, "e": 2251, "s": 2246, "text": "byte" }, { "code": null, "e": 2274, "s": 2251, "text": "A signed 8 bit integer" }, { "code": null, "e": 2282, "s": 2274, "text": "decimal" }, { "code": null, "e": 2298, "s": 2282, "text": "A decimal value" }, { "code": null, "e": 2302, "s": 2298, "text": "int" }, { "code": null, "e": 2326, "s": 2302, "text": "A signed 32 bit integer" }, { "code": null, "e": 2334, "s": 2326, "text": "integer" }, { "code": null, "e": 2351, "s": 2334, "text": "An integer value" }, { "code": null, "e": 2356, "s": 2351, "text": "long" }, { "code": null, "e": 2380, "s": 2356, "text": "A signed 64 bit integer" }, { "code": null, "e": 2396, "s": 2380, "text": "negativeInteger" }, { "code": null, "e": 2446, "s": 2396, "text": "An integer having only negative values (..,-2,-1)" }, { "code": null, "e": 2465, "s": 2446, "text": "nonNegativeInteger" }, { "code": null, "e": 2519, "s": 2465, "text": "An integer having only non-negative values (0,1,2,..)" }, { "code": null, "e": 2538, "s": 2519, "text": "nonPositiveInteger" }, { "code": null, "e": 2594, "s": 2538, "text": "An integer having only non-positive values (..,-2,-1,0)" }, { "code": null, "e": 2610, "s": 2594, "text": "positiveInteger" }, { "code": null, "e": 2658, "s": 2610, "text": "An integer having only positive values (1,2,..)" }, { "code": null, "e": 2664, "s": 2658, "text": "short" }, { "code": null, "e": 2688, "s": 2664, "text": "A signed 16 bit integer" }, { "code": null, "e": 2701, "s": 2688, "text": "unsignedLong" }, { "code": null, "e": 2728, "s": 2701, "text": "An unsigned 64 bit integer" }, { "code": null, "e": 2740, "s": 2728, "text": "unsignedInt" }, { "code": null, "e": 2767, "s": 2740, "text": "An unsigned 32 bit integer" }, { "code": null, "e": 2781, "s": 2767, "text": "unsignedShort" }, { "code": null, "e": 2808, "s": 2781, "text": "An unsigned 16 bit integer" }, { "code": null, "e": 2821, "s": 2808, "text": "unsignedByte" }, { "code": null, "e": 2847, "s": 2821, "text": "An unsigned 8 bit integer" }, { "code": null, "e": 2914, "s": 2847, "text": "Following types of restrictions can be used with Date data types −" }, { "code": null, "e": 2926, "s": 2914, "text": "enumeration" }, { "code": null, "e": 2941, "s": 2926, "text": "fractionDigits" }, { "code": null, "e": 2954, "s": 2941, "text": "maxExclusive" }, { "code": null, "e": 2967, "s": 2954, "text": "maxInclusive" }, { "code": null, "e": 2980, "s": 2967, "text": "minExclusive" }, { "code": null, "e": 2993, "s": 2980, "text": "minInclusive" }, { "code": null, "e": 3001, "s": 2993, "text": "pattern" }, { "code": null, "e": 3013, "s": 3001, "text": "totalDigits" }, { "code": null, "e": 3024, "s": 3013, "text": "whiteSpace" }, { "code": null, "e": 3031, "s": 3024, "text": " Print" }, { "code": null, "e": 3042, "s": 3031, "text": " Add Notes" } ]
Minimax Algorithm in Game Theory (Alpha-Beta Pruning) in C++
Aplha-Beta pruning is a optimization technique used in minimax algorithm. The idea benind this algorithm is cut off the branches of game tree which need not to be evaluated as better move exists already. This algorithm introduces two new fields − Alpha − This is best value(maximum) that maximizer player can guaratee at current level or its above level Beta − This is the best value(minimum) that minimizer player can guaratee at the current level or its above level. If game tree is − arr [] = {13, 8, 24, -5, 23, 15, -14, -20} then optimal value will be 13 if maximizer plays first 1. Start DFS traversal from the root of game tree 2. Set initial values of alpha and beta as follows: a. alpha = INT_MIN(-INFINITY) b. beta = INT_MAX(+INFINITY) 3. Traverse tree in DFS fashion where maximizer player tries to get the highest score possible while the minimizer player tries to get the lowest score possible. 4. While traversing update the alpha and beta values accordingly #include <iostream> #include <algorithm> #include <cmath> #include <climits> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; int getHeight(int n) { return (n == 1) ? 0 : 1 + log2(n / 2); } int minmax(int height, int depth, int nodeIndex, bool maxPayer, int values[], int alpha, int beta) { if (depth == height) { return values[nodeIndex]; } if (maxPayer) { int bestValue = INT_MIN; for (int i = 0; i < height - 1; i++) { int val = minmax(height, depth + 1, nodeIndex * 2 + i, false, values, alpha, beta); bestValue = max(bestValue, val); alpha = max(alpha, bestValue); if (beta <= alpha) break; } return bestValue; } else { int bestValue = INT_MAX; for (int i = 0; i < height - 1; i++) { int val = minmax(height, depth + 1, nodeIndex * 2 + i, true, values, alpha, beta); bestValue = min(bestValue, val); beta = min(beta, bestValue); if (beta <= alpha) break; } return bestValue; } } int main() { int values[] = {13, 8, 24, -5, 23, 15, -14, -20}; int height = getHeight(SIZE(values)); int result = minmax(height, 0, 0, true, values, INT_MIN, INT_MAX); cout <<"Result : " << result << "\n"; return 0; } When you compile and execute above program. It generates following output − Result : 13
[ { "code": null, "e": 1266, "s": 1062, "text": "Aplha-Beta pruning is a optimization technique used in minimax algorithm. The idea benind this algorithm is cut off the branches of game tree which need not to be evaluated as better move exists already." }, { "code": null, "e": 1309, "s": 1266, "text": "This algorithm introduces two new fields −" }, { "code": null, "e": 1416, "s": 1309, "text": "Alpha − This is best value(maximum) that maximizer player can guaratee at current level or its above level" }, { "code": null, "e": 1531, "s": 1416, "text": "Beta − This is the best value(minimum) that minimizer player can guaratee at the current level or its above level." }, { "code": null, "e": 1549, "s": 1531, "text": "If game tree is −" }, { "code": null, "e": 1592, "s": 1549, "text": "arr [] = {13, 8, 24, -5, 23, 15, -14, -20}" }, { "code": null, "e": 1647, "s": 1592, "text": "then optimal value will be 13 if maximizer plays first" }, { "code": null, "e": 2035, "s": 1647, "text": "1. Start DFS traversal from the root of game tree\n2. Set initial values of alpha and beta as follows:\na. alpha = INT_MIN(-INFINITY)\nb. beta = INT_MAX(+INFINITY)\n3. Traverse tree in DFS fashion where maximizer player tries to get the highest score possible while the minimizer player tries to get the lowest score possible.\n4. While traversing update the alpha and beta values accordingly" }, { "code": null, "e": 3341, "s": 2035, "text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <climits>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nint getHeight(int n) {\n return (n == 1) ? 0 : 1 + log2(n / 2);\n}\nint minmax(int height, int depth, int nodeIndex,\nbool maxPayer, int values[], int alpha,\nint beta) {\n if (depth == height) {\n return values[nodeIndex];\n }\n if (maxPayer) {\n int bestValue = INT_MIN;\n for (int i = 0; i < height - 1; i++) {\n int val = minmax(height, depth + 1, nodeIndex * 2 + i, false, values, alpha, beta);\n bestValue = max(bestValue, val);\n alpha = max(alpha, bestValue);\n if (beta <= alpha)\n break;\n }\n return bestValue;\n } else {\n int bestValue = INT_MAX;\n for (int i = 0; i < height - 1; i++) {\n int val = minmax(height, depth + 1, nodeIndex * 2 + i, true, values, alpha, beta);\n bestValue = min(bestValue, val);\n beta = min(beta, bestValue);\n if (beta <= alpha)\n break;\n }\n return bestValue;\n }\n}\nint main() {\n int values[] = {13, 8, 24, -5, 23, 15, -14, -20};\n int height = getHeight(SIZE(values));\n int result = minmax(height, 0, 0, true, values, INT_MIN, INT_MAX);\n cout <<\"Result : \" << result << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 3417, "s": 3341, "text": "When you compile and execute above program. It generates\nfollowing output −" }, { "code": null, "e": 3429, "s": 3417, "text": "Result : 13" } ]
Search Pattern (KMP-Algorithm) | Practice | GeeksforGeeks
Given two strings, one is a text string, txt and other is a pattern string, pat. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1. Example 1: Input: txt = "batmanandrobinarebat", pat = "bat" Output: 1 18 Explanation: The string "bat" occurs twice in txt, one starts are index 1 and the other at index 18. Example 2: Input: txt = "abesdu", pat = "edu" Output: -1 Explanation: There's not substring "edu" present in txt. Your Task: You don't need to read input or print anything. Your task is to complete the function search() which takes the string txt and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string txt. Note: Return an empty list incase of no occurences of pattern. Driver will print -1 in this case. Expected Time Complexity: O(|txt|). Expected Auxiliary Space: O(|txt|). Constraints: 1 ≤ |txt| ≤ 105 1 ≤ |pat| < |S| 0 mahesh_phutane4 days ago Simple java solution O(|txt|*|pat|) → 0.4sec class Solution { ArrayList<Integer> search(String pat, String txt) { ArrayList<Integer> res = new ArrayList<>(); int n = txt.length(); int k = pat.length(); for(int i = 0;i<n-k+1;i++){ int flag = 1; if(txt.charAt(i)!=pat.charAt(0)) continue; //this will reduce extra time for(int j = i;j<(i+k);j++){ if(txt.charAt(j)!=pat.charAt(j-i)){ flag = 0; break; } } if(flag==1){ res.add(i+1); } } return res; } } 0 rajjener2 weeks ago vector <int> search(string pat, string txt) { int pos=0; vector <int> v; int n=txt.length(); int m=pat.length(); int i=0; while(i<n) { if(txt.substr(i,m)==pat){ v.push_back(i+1); } i++; } return v; } 0 bahubuli3 weeks ago ```c++ vector <int> search(string pat, string txt) { if(pat.size()>txt.size()) return {-1}; vector<int>ans; vector<int>reset(pat.size()+1); reset[0]=-1; int i=0,j=-1; while(i<pat.size()) { while(j>=0 && pat[i]!=pat[j]) j = reset[j]; i++; j++; reset[i]=j; } // created lps array for pattern i=0,j=0; while(i<txt.size()) { while(j>=0 && pat[j]!=txt[i]) j = reset[j]; i++; j++; if(j==pat.size()) { ans.push_back(i-j+1); j=reset[j]; //reseting j once the pattern // is matched } } return ans; } -1 akkeshri140420012 months ago vector <int> search(string pat, string txt) { //code hee. int n=pat.length(); int m=txt.length(); int i=0,j=0; string r=""; vector<int>v; while(j<m){ r+=txt[j]; if(j-i+1<n){ j++; } else if(j-i+1==n){ if(txt.substr(i,n)==pat){ v.push_back(i+1); } r=r.substr(1); j++; i++; } } return v; } +1 shashankrustagii3 months ago class Solution { public: void lps(string pat, vector<int> &ls) { int len =0, i=1; ls[0]=0; while(i<pat.length()) { if(pat[i]==pat[len]) ls[i++] = ++len; else if(len ==0) ls[i++] = 0; else len=ls[len-1]; } } vector <int> search(string pat, string txt) { int n = pat.length(); int m = txt.length(); vector<int> ls(n); lps(pat, ls); int j=0,i=0; vector<int> ans; while(i<m) { if(txt[i]==pat[j]) i++,j++; if(j==n) { ans.push_back(i-j+1); j = ls[j-1]; } else if(i<m and txt[i]!=pat[j]) { if(!j) i++; else j = ls[j-1]; } } return ans; } }; 0 rishurana2563 months ago O(N) solution vector <int> search(string pat, string txt) { string s = txt; vector<int>v; string t = pat + "#" + s; int n = t.length(); int lps[n]; memset(lps,0,sizeof(lps)); int i=1,len=0; while(i<n){ if(t[i]==t[len]){ while(t[i]==t[len]){ len++; lps[i] = len; i++; } } else{ if(len>0) len = lps[len-1]; else{ lps[i] = 0; i++; } } } // for(int i=0;i<n;i++) // cout<<lps[i]<<" "; // cout<<endl; int flag= 0; int m = pat.length(); for(int i=1;i<n;i++){ if(lps[i]==m){ flag = 1; // cout<<(i-2*m)<<endl; v.push_back((i-2*m+1)); } } if(flag==0) v.push_back(-1); return v;} 0 palashsarkar00074 months ago class Solution: def __form_lps_array (self, patt, patt_s): lps = [0 for ch in patt] j, i = 0, 1 while (i < patt_s): if (patt[i] == patt[j]): lps[i] = j + 1 j += 1 ; i += 1 else: if (j != 0): j = lps[j - 1] else: lps[i] = 0 i += 1 return lps def search (self, pattern, text): patt_s, t_s = len(pattern), len(text) if (patt_s > t_s): return [-1] if (patt_s == t_s): return [1] if (pattern == text) else [-1] i, j = 0, 0 lps = self.__form_lps_array(pattern, patt_s) res = [] while (i < t_s): if (text[i] == pattern[j]): j += 1 ; i += 1 else: if (j != 0): j = lps[j - 1] else: i += 1 if (j == patt_s): res.append(i - patt_s + 1) j = lps[j - 1] return res if (len(res) > 0) else [-1] 0 poraskr814 months ago vector <int> search(string pat, string txt) { int n=txt.length(); int m=pat.length(); vector<int>temp; for(int i=0;i<=n-m;i++) { int j; for(j=0;j<m;j++) { if(txt[j+i]!=pat[j]) break; } if(j==m) temp.push_back(i+1); } if(temp.size()==0) { temp.push_back(-1); return temp; } return temp; } +3 abhixhek055 months ago Using KMP Algo class Solution { public: void lps(string pat, vector<int> &ls){ int len =0, i=1; ls[0]=0; while(i<pat.length()){ if(pat[i] == pat[len]){ len++; ls[i] = len; i++; }else{ if(len ==0){ ls[i] = 0; i++; }else{ len = ls[len-1]; } } } } vector <int> search(string pat, string txt) { //code hee. int n = pat.length(); int m = txt.length(); vector<int> ls(n); lps(pat, ls); int j=0,i=0; vector<int> ans; while(i<m){ if(txt[i]==pat[j]){ i++; j++; } if(j==n){ ans.push_back(i-j+1); j = ls[j-1]; }else if(i<m && txt[i] != pat[j]){ if(j==0){ i++; }else{ j = ls[j-1]; } } } return ans; } }; +1 badgujarsachin835 months ago vector <int> search(string pat, string txt) { vector<int> v; for(int i=0;i<txt.size()-pat.size()+1;i++){ if(txt.substr(i,pat.size())==pat){ v.push_back(i+1); } } if(v.empty()){ v.push_back(-1); } return v; } 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": 475, "s": 238, "text": "Given two strings, one is a text string, txt and other is a pattern string, pat. The task is to print the indexes of all the occurences of pattern string in the text string. For printing, Starting Index of a string should be taken as 1." }, { "code": null, "e": 487, "s": 475, "text": "\nExample 1:" }, { "code": null, "e": 652, "s": 487, "text": "Input:\ntxt = \"batmanandrobinarebat\", pat = \"bat\"\nOutput: 1 18\nExplanation: The string \"bat\" occurs twice\nin txt, one starts are index 1 and the other\nat index 18. \n" }, { "code": null, "e": 663, "s": 652, "text": "Example 2:" }, { "code": null, "e": 768, "s": 663, "text": "Input: \ntxt = \"abesdu\", pat = \"edu\"\nOutput: -1\nExplanation: There's not substring \"edu\"\npresent in txt.\n" }, { "code": null, "e": 1124, "s": 768, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function search() which takes the string txt and the string pat as inputs and returns an array denoting the start indices (1-based) of substring pat in the string txt. \nNote: Return an empty list incase of no occurences of pattern. Driver will print -1 in this case." }, { "code": null, "e": 1197, "s": 1124, "text": "\nExpected Time Complexity: O(|txt|).\nExpected Auxiliary Space: O(|txt|)." }, { "code": null, "e": 1243, "s": 1197, "text": "\nConstraints:\n1 ≤ |txt| ≤ 105\n1 ≤ |pat| < |S|" }, { "code": null, "e": 1245, "s": 1243, "text": "0" }, { "code": null, "e": 1270, "s": 1245, "text": "mahesh_phutane4 days ago" }, { "code": null, "e": 1315, "s": 1270, "text": "Simple java solution O(|txt|*|pat|) → 0.4sec" }, { "code": null, "e": 1949, "s": 1315, "text": "class Solution\n{\n ArrayList<Integer> search(String pat, String txt)\n {\n ArrayList<Integer> res = new ArrayList<>();\n int n = txt.length();\n int k = pat.length();\n \n for(int i = 0;i<n-k+1;i++){\n int flag = 1;\n if(txt.charAt(i)!=pat.charAt(0)) continue; //this will reduce extra time \n for(int j = i;j<(i+k);j++){\n if(txt.charAt(j)!=pat.charAt(j-i)){\n flag = 0;\n break;\n }\n }\n if(flag==1){\n res.add(i+1);\n }\n }\n return res;\n }\n}" }, { "code": null, "e": 1951, "s": 1949, "text": "0" }, { "code": null, "e": 1971, "s": 1951, "text": "rajjener2 weeks ago" }, { "code": null, "e": 2379, "s": 1971, "text": " vector <int> search(string pat, string txt) { int pos=0; vector <int> v; int n=txt.length(); int m=pat.length(); int i=0; while(i<n) { if(txt.substr(i,m)==pat){ v.push_back(i+1); } i++; } return v; }" }, { "code": null, "e": 2381, "s": 2379, "text": "0" }, { "code": null, "e": 2401, "s": 2381, "text": "bahubuli3 weeks ago" }, { "code": null, "e": 3452, "s": 2401, "text": "```c++\n\tvector <int> search(string pat, string txt)\n {\n if(pat.size()>txt.size()) return {-1};\n vector<int>ans;\n \n vector<int>reset(pat.size()+1);\n \n reset[0]=-1;\n \n int i=0,j=-1;\n while(i<pat.size())\n {\n \n while(j>=0 && pat[i]!=pat[j]) j = reset[j];\n \n i++;\n j++;\n reset[i]=j;\n }\n // created lps array for pattern\n \n i=0,j=0;\n \n while(i<txt.size())\n {\n while(j>=0 && pat[j]!=txt[i]) j = reset[j];\n \n i++;\n j++;\n if(j==pat.size())\n {\n ans.push_back(i-j+1);\n j=reset[j];\n //reseting j once the pattern\n // is matched \n }\n }\n return ans;\n \n }" }, { "code": null, "e": 3457, "s": 3454, "text": "-1" }, { "code": null, "e": 3486, "s": 3457, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 4079, "s": 3486, "text": "vector <int> search(string pat, string txt) { //code hee. int n=pat.length(); int m=txt.length(); int i=0,j=0; string r=\"\"; vector<int>v; while(j<m){ r+=txt[j]; if(j-i+1<n){ j++; } else if(j-i+1==n){ if(txt.substr(i,n)==pat){ v.push_back(i+1); } r=r.substr(1); j++; i++; } } return v; } " }, { "code": null, "e": 4082, "s": 4079, "text": "+1" }, { "code": null, "e": 4111, "s": 4082, "text": "shashankrustagii3 months ago" }, { "code": null, "e": 4997, "s": 4111, "text": "class Solution\n{\n public:\n void lps(string pat, vector<int> &ls)\n {\n int len =0, i=1;\n ls[0]=0;\n while(i<pat.length())\n {\n if(pat[i]==pat[len]) ls[i++] = ++len;\n else\n if(len ==0) ls[i++] = 0;\n else len=ls[len-1];\n }\n }\n vector <int> search(string pat, string txt)\n {\n int n = pat.length();\n int m = txt.length();\n vector<int> ls(n);\n lps(pat, ls);\n int j=0,i=0;\n vector<int> ans;\n while(i<m)\n {\n if(txt[i]==pat[j]) i++,j++;\n if(j==n)\n {\n ans.push_back(i-j+1);\n j = ls[j-1];\n }\n else if(i<m and txt[i]!=pat[j])\n {\n if(!j) i++;\n else j = ls[j-1];\n }\n }\n return ans;\n }\n};" }, { "code": null, "e": 4999, "s": 4997, "text": "0" }, { "code": null, "e": 5024, "s": 4999, "text": "rishurana2563 months ago" }, { "code": null, "e": 5039, "s": 5024, "text": "O(N) solution " }, { "code": null, "e": 5875, "s": 5043, "text": " vector <int> search(string pat, string txt) { string s = txt; vector<int>v; string t = pat + \"#\" + s; int n = t.length(); int lps[n]; memset(lps,0,sizeof(lps)); int i=1,len=0; while(i<n){ if(t[i]==t[len]){ while(t[i]==t[len]){ len++; lps[i] = len; i++; } } else{ if(len>0) len = lps[len-1]; else{ lps[i] = 0; i++; } } } // for(int i=0;i<n;i++) // cout<<lps[i]<<\" \"; // cout<<endl; int flag= 0; int m = pat.length(); for(int i=1;i<n;i++){ if(lps[i]==m){ flag = 1; // cout<<(i-2*m)<<endl; v.push_back((i-2*m+1)); } } if(flag==0) v.push_back(-1); return v;}" }, { "code": null, "e": 5877, "s": 5875, "text": "0" }, { "code": null, "e": 5906, "s": 5877, "text": "palashsarkar00074 months ago" }, { "code": null, "e": 6303, "s": 5906, "text": "class Solution: def __form_lps_array (self, patt, patt_s): lps = [0 for ch in patt] j, i = 0, 1 while (i < patt_s): if (patt[i] == patt[j]): lps[i] = j + 1 j += 1 ; i += 1 else: if (j != 0): j = lps[j - 1] else: lps[i] = 0 i += 1 return lps" }, { "code": null, "e": 6948, "s": 6303, "text": " def search (self, pattern, text): patt_s, t_s = len(pattern), len(text) if (patt_s > t_s): return [-1] if (patt_s == t_s): return [1] if (pattern == text) else [-1] i, j = 0, 0 lps = self.__form_lps_array(pattern, patt_s) res = [] while (i < t_s): if (text[i] == pattern[j]): j += 1 ; i += 1 else: if (j != 0): j = lps[j - 1] else: i += 1 if (j == patt_s): res.append(i - patt_s + 1) j = lps[j - 1] return res if (len(res) > 0) else [-1]" }, { "code": null, "e": 6950, "s": 6948, "text": "0" }, { "code": null, "e": 6972, "s": 6950, "text": "poraskr814 months ago" }, { "code": null, "e": 7520, "s": 6972, "text": "vector <int> search(string pat, string txt) { int n=txt.length(); int m=pat.length(); vector<int>temp; for(int i=0;i<=n-m;i++) { int j; for(j=0;j<m;j++) { if(txt[j+i]!=pat[j]) break; } if(j==m) temp.push_back(i+1); } if(temp.size()==0) { temp.push_back(-1); return temp; } return temp; }" }, { "code": null, "e": 7523, "s": 7520, "text": "+3" }, { "code": null, "e": 7546, "s": 7523, "text": "abhixhek055 months ago" }, { "code": null, "e": 7561, "s": 7546, "text": "Using KMP Algo" }, { "code": null, "e": 8856, "s": 7561, "text": "class Solution\n{\n public:\n \n \n void lps(string pat, vector<int> &ls){\n int len =0, i=1;\n ls[0]=0;\n while(i<pat.length()){\n if(pat[i] == pat[len]){\n len++;\n ls[i] = len;\n i++;\n }else{\n if(len ==0){\n ls[i] = 0;\n i++;\n }else{\n len = ls[len-1];\n }\n }\n }\n }\n \n vector <int> search(string pat, string txt)\n {\n //code hee.\n int n = pat.length();\n int m = txt.length();\n vector<int> ls(n);\n lps(pat, ls);\n int j=0,i=0;\n vector<int> ans;\n while(i<m){\n if(txt[i]==pat[j]){\n i++;\n j++;\n }\n if(j==n){\n ans.push_back(i-j+1);\n j = ls[j-1];\n \n }else if(i<m && txt[i] != pat[j]){\n if(j==0){\n i++;\n }else{\n j = ls[j-1];\n }\n }\n \n }\n return ans;\n \n }\n \n};" }, { "code": null, "e": 8859, "s": 8856, "text": "+1" }, { "code": null, "e": 8888, "s": 8859, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 9256, "s": 8888, "text": "vector <int> search(string pat, string txt)\n {\n vector<int> v;\n for(int i=0;i<txt.size()-pat.size()+1;i++){\n if(txt.substr(i,pat.size())==pat){\n v.push_back(i+1);\n }\n }\n if(v.empty()){\n v.push_back(-1);\n }\n return v;\n }" }, { "code": null, "e": 9402, "s": 9256, "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": 9438, "s": 9402, "text": " Login to access your submissions. " }, { "code": null, "e": 9448, "s": 9438, "text": "\nProblem\n" }, { "code": null, "e": 9458, "s": 9448, "text": "\nContest\n" }, { "code": null, "e": 9521, "s": 9458, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9669, "s": 9521, "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": 9877, "s": 9669, "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": 9983, "s": 9877, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Detecting contours in an image using OpenCV
In this program, we will detect contours in an image. Contours can be explained simply as a curve joining all the continuous points having the same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. Step 1: Import OpenCV. Step 2: Import matplotlib. Step 3: Read the image. Step 4: Convert the image from bgr2rgb. Step 5: Convert the rgb image to grayscale. Step 4: Perform thresholding on the image. Step 5: Find contours on the image. Step 6: Draw contours on the image. Step 7: Display the output. import cv2 import matplotlib.pyplot as plt image = cv2.imread('testimage.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) ret, binary = cv2.threshold(gray, 127,255, cv2.THRESH_BINARY_INV) contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) image = cv2.drawContours(image, contours, -1, (0,255,0), 2) plt.imshow(image) plt.show()
[ { "code": null, "e": 1318, "s": 1062, "text": "In this program, we will detect contours in an image. Contours can be explained simply as a curve joining all the continuous points having the same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition." }, { "code": null, "e": 1619, "s": 1318, "text": "Step 1: Import OpenCV.\nStep 2: Import matplotlib.\nStep 3: Read the image.\nStep 4: Convert the image from bgr2rgb.\nStep 5: Convert the rgb image to grayscale.\nStep 4: Perform thresholding on the image.\nStep 5: Find contours on the image.\nStep 6: Draw contours on the image.\nStep 7: Display the output." }, { "code": null, "e": 2036, "s": 1619, "text": "import cv2\nimport matplotlib.pyplot as plt\n\nimage = cv2.imread('testimage.jpg')\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\nret, binary = cv2.threshold(gray, 127,255, cv2.THRESH_BINARY_INV)\ncontours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\nimage = cv2.drawContours(image, contours, -1, (0,255,0), 2)\nplt.imshow(image)\nplt.show()" } ]
Difference between volatile and transient in java
A volatile keyword is used in a multithreading environment where two threads reading and writing the same variable simultaneously. The volatile keyword flushes the changes directly to the main memory instead of the CPU cache. On the other hand, the transient keyword is used during serialization. Fields that are marked as transient can not be part of the serialization and deserialization. We don't want to save the value of any variable then we use transient keyword with that variable. // A sample class that uses transient keyword to // skip their serialization. class TransientExample implements Serializable { transient int age; // serialize other fields private String name; private String address; // other code } class VolatileExmaple extends Thread{ boolean volatile isRunning = true; public void run() { long count=0; while (isRunning) { count++; } System.out.println("Thread terminated." + count); } public static void main(String[] args) throws InterruptedException { VolatileExmaple t = new VolatileExmaple(); t.start(); Thread.sleep(2000); t.isRunning = false; t.join(); System.out.println("isRunning set to " + t.isRunning); } }
[ { "code": null, "e": 1289, "s": 1062, "text": "A volatile keyword is used in a multithreading environment where two threads reading and writing the same variable simultaneously. The volatile keyword flushes the changes directly to the main memory instead of the CPU cache. " }, { "code": null, "e": 1553, "s": 1289, "text": "On the other hand, the transient keyword is used during serialization. Fields that are marked as transient can not be part of the serialization and deserialization. We don't want to save the value of any variable then we use transient keyword with that variable. " }, { "code": null, "e": 1801, "s": 1553, "text": "// A sample class that uses transient keyword to\n// skip their serialization.\nclass TransientExample implements Serializable {\n transient int age;\n // serialize other fields\n private String name;\n private String address;\n // other code\n}" }, { "code": null, "e": 2308, "s": 1801, "text": "class VolatileExmaple extends Thread{\n boolean volatile isRunning = true;\n public void run() {\n long count=0;\n while (isRunning) {\n count++;\n }\n System.out.println(\"Thread terminated.\" + count);\n }\n public static void main(String[] args) throws InterruptedException {\n VolatileExmaple t = new VolatileExmaple();\n t.start();\n Thread.sleep(2000);\n t.isRunning = false;\n t.join();\n System.out.println(\"isRunning set to \" + t.isRunning);\n }\n}" } ]
Perform the given queries on the rooted tree - GeeksforGeeks
05 Oct, 2021 Given a rooted tree and not necessarily binary. The tree contains N nodes, labeled 1 to N. You are given the tree in the form of an array A[1..N] of size N. A[i] denotes label of the parent of node labeled i. For clarity, you may assume that the tree satisfies the following conditions. The root of the tree is labeled 1. Hence A[1] is set to 0. The parent of node T will always have a label less than T. The task is to perform the following operations according to the type of query given. ADD, X, Y: add Y to the value at node X.ADDUP, X, Y: add Y to the value at node X. Then, add Y to the value at A[X] (i.e. the parent of X). The, add Y to the value at A[A[X]] (i.e. the parent of A[X]).. and so on, till you add Y to the value at root. ADD, X, Y: add Y to the value at node X. ADDUP, X, Y: add Y to the value at node X. Then, add Y to the value at A[X] (i.e. the parent of X). The, add Y to the value at A[A[X]] (i.e. the parent of A[X]).. and so on, till you add Y to the value at root. After you have performed all the given operations, you are asked to answer several queries of the following type VAL, X: print the value at node X.VALTREE, X: print the sum of values at all nodes in the subtree rooted at X (including X). VAL, X: print the value at node X. VALTREE, X: print the sum of values at all nodes in the subtree rooted at X (including X). Source: Directi Interview | Set 13Examples: Input: N = 7, M = 4, Q = 5 0 1 2 2 2 1 2 ADD 6 76 ADDUP 1 49 ADD 4 48 ADDUP 2 59 VALTREE 1 VALTREE 5 VAL 5 VALTREE 2 VAL 2Output: 291 0 0 107 59Input: N = 5, M = 5, Q = 3 0 1 1 1 3 ADD 1 10 ADD 2 20 ADD 3 30 ADD 4 40 ADDUP 5 50 VAL 3 VALTREE 3 VALTREE 1Output: 80 130 250 Explanation: This problem is a slight variation of dfs. In this, we have stored the node’s original value and addup value in the vector of the pair. We did 2 times dfs. dfs1 for offline queries i.e to calculate the addup sum for each node.dfs2 to store the subtree sum in an array. dfs1 for offline queries i.e to calculate the addup sum for each node. dfs2 to store the subtree sum in an array. Now all the queries can be answered in a constant time.Graph before dfs1 Graph after dfs1 Below is the required implementation: C++ Java Python3 C# Javascript // C++ implementation to perform// above operations and queries#include <bits/stdc++.h>using namespace std; /*Code Parametersp->for every node first value is it's original valueand second value is it's addup valuesubtree_sum[]-> to store the subtree_sum at every nodevisit-> for dfs1visit2->for dfs2*/vector<pair<int, int> > p;vector<int> adj[10000];int subtree_sum[10000], visit[10000], visit2[10000]; int dfs1(int root){ // for leaf node if (adj[root].size() == 0) { // if leaf node then add the addup // sum to it's original value p[root].first += p[root].second; return 0; } int sum = 0; for (int i = 0; i < adj[root].size(); i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root].second += p[adj[root][i]].second; visit[adj[root][i]] = 1; } } // process the root node p[root].first += p[root].second; return 0;} int dfs2(int root){ if (adj[root].size() == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root].first; return p[root].first; } int sum = p[root].first; for (int i = 0; i < adj[root].size(); i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; return sum;} // Driver codeint main(){ int nodes = 7, m = 4, qu = 5, b; int a[] = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.push_back(make_pair(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].push_back(i + 1); // for every node p.push_back(make_pair(0, 0)); } vector<pair<string, pair<int, int> > > v; v.push_back(make_pair("ADD", make_pair(6, 76))); v.push_back(make_pair("ADDUP", make_pair(1, 49))); v.push_back(make_pair("ADD", make_pair(4, 48))); v.push_back(make_pair("ADDUP", make_pair(2, 59))); for (int i = 0; i < m; i++) { string s = v[i].first; int a = v[i].second.first; int b = v[i].second.second; if (s == "ADD") // adding to it's own value p[a].first += b; else // adding to it's addup value p[a].second += b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); vector<pair<string, int> > q; q.push_back(make_pair("VALTREE", 1)); q.push_back(make_pair("VALTREE", 5)); q.push_back(make_pair("VAL", 5)); q.push_back(make_pair("VALTREE", 2)); q.push_back(make_pair("VAL", 2)); for (int i = 0; i < qu; i++) { string s = q[i].first; int a = q[i].second; if (s == "VAL") cout << p[a].first << "\n"; else cout << subtree_sum[a] << "\n"; }} // Java implementation to perform// above operations and queriesimport java.util.*;public class Main{ /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ static class pair { public int x, y; public pair(int x, int y) { this.x = x; this.y = y; } } static class pair1 { public String a; public pair b; public pair1(String a, pair b) { this.a = a; this.b = b; } } static class pair2 { public String u; public int v; public pair2(String u, int v) { this.u = u; this.v = v; } } static Vector<pair> p = new Vector<pair>(); static Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>(); static int[] subtree_sum = new int[10000]; static int[] visit = new int[10000]; static int[] visit2 = new int[10000]; static int dfs1(int root) { // for leaf node if (adj.get(root).size() == 0) { // if leaf node then add the addup // sum to it's original value p.get(root).x = p.get(root).x + p.get(root).y; return 0; } for (int i = 0; i < adj.get(root).size(); i++) { if (visit[adj.get(root).get(i)] == 0) { dfs1(adj.get(root).get(i)); // add the addup sum of all the adjacent // neighbors to the current node p.get(root).y = p.get(root).y + p.get(adj.get(root).get(i)).y; visit[adj.get(root).get(i)] = 1; } } // process the root node p.get(root).x = p.get(root).x + p.get(root).y; return 0; } static int dfs2(int root) { if (adj.get(root).size() == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p.get(root).x; return p.get(root).y; } int sum = p.get(root).y; for (int i = 0; i < adj.get(root).size(); i++) { if (visit2[adj.get(root).get(i)] == 0) { sum += dfs2(adj.get(root).get(i)); visit2[adj.get(root).get(i)] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } public static void main(String[] args) { for(int i = 0; i < 10000; i++) { adj.add(new Vector<Integer>()); } int nodes = 7, m = 4, qu = 5; int[] a = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.add(new pair(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj.get(a[i]).add(i + 1); // for every node p.add(new pair(0, 0)); } Vector<pair1> v = new Vector<pair1>(); v.add(new pair1("ADD", new pair(6, 76))); v.add(new pair1("ADDUP", new pair(1, 49))); v.add(new pair1("ADD", new pair(4, 48))); v.add(new pair1("ADDUP", new pair(2, 59))); for (int i = 0; i < m; i++) { String s = v.get(i).a; int A = v.get(i).b.x; int b = v.get(i).b.y; if (s == "ADD") // adding to it's own value p.get(A).x = p.get(A).x + b; else // adding to it's addup value p.get(A).y = p.get(A).y + b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); Vector<pair2> q = new Vector<pair2>(); q.add(new pair2("VALTREE", 1)); q.add(new pair2("VALTREE", 5)); q.add(new pair2("VAL", 5)); q.add(new pair2("VALTREE", 2)); q.add(new pair2("VAL", 2)); for (int i = 0; i < qu; i++) { String s = q.get(i).u; int A = q.get(i).v; if (s == "VAL") System.out.println(p.get(A).x); else System.out.println(subtree_sum[A]); } }} // This code is contributed by divyeshrabadiya07. # Python3 implementation to perform# above operations and queriesp = []adj = [0] * 10000for i in range(10000): adj[i] = []subtree_sum, visit, visit2 = [0] * 10000, [0] * 10000, [0] * 10000 # Code Parameters# p->for every node first value is it's original value# and second value is it's addup value# subtree_sum[]-> to store the subtree_sum at every node# visit-> for dfs1# visit2->for dfs2def dfs1(root: int) -> int: # for leaf node if len(adj[root]) == 0: # if leaf node then add the addup # sum to it's original value p[root][0] += p[root][1] return 0 summ = 0 for i in range(len(adj[root])): if visit[adj[root][i]] == 0: dfs1(adj[root][i]) # add the addup sum of all the adjacent # neighbors to the current node p[root][1] += p[adj[root][i]][1] visit[adj[root][i]] = 1 # process the root node p[root][0] += p[root][1] return 0 def dfs2(root: int) -> int: if len(adj[root]) == 0: # for the leaf node subtree_sum # will be it's own value subtree_sum[root] = p[root][0] return p[root][0] summ = p[root][0] for i in range(len(adj[root])): if visit2[adj[root][i]] == 0: summ += dfs2(adj[root][i]) visit2[adj[root][i]] = 1 # calculate the subtree_sum # for the particular root node subtree_sum[root] = summ return summ # Driver Codeif __name__ == "__main__": nodes, m, qu = 7, 4, 5 a = [0, 1, 2, 2, 2, 1, 2] # for root node p.append([0, 0]) for i in range(nodes): if a[i] != 0: adj[a[i]].append(i + 1) # for every node p.append([0, 0]) v = [] v.append(("ADD", [6, 76])) v.append(("ADDUP", [1, 49])) v.append(("ADD", [4, 48])) v.append(("ADDUP", [2, 59])) for i in range(m): s = v[i][0] a = v[i][1][0] b = v[i][1][1] if s == "ADD": # adding to it's own value p[a][0] += b else: # adding to it's addup value p[a][1] += b # to process the offline queries dfs1(1) # to store the subtree sum for every root node dfs2(1) q = [] q.append(["VALTREE", 1]) q.append(["VALTREE", 5]) q.append(["VAL", 5]) q.append(["VALTREE", 2]) q.append(["VAL", 2]) for i in range(qu): s = q[i][0] a = q[i][1] if s == "VAL": print(p[a][0]) else: print(subtree_sum[a]) # This code is contributed by# sanjeev2552 // C# implementation to perform// above operations and queriesusing System;using System.Collections.Generic;class GFG { /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ static List<Tuple<int,int>> p = new List<Tuple<int,int>>(); static List<List<int>> adj = new List<List<int>>(); static int[] subtree_sum = new int[10000]; static int[] visit = new int[10000]; static int[] visit2 = new int[10000]; static int dfs1(int root) { // for leaf node if (adj[root].Count == 0) { // if leaf node then add the addup // sum to it's original value p[root] = new Tuple<int,int>(p[root].Item1 + p[root].Item2, p[root].Item2); return 0; } for (int i = 0; i < adj[root].Count; i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root] = new Tuple<int,int>(p[root].Item1, p[root].Item2 + p[adj[root][i]].Item2); visit[adj[root][i]] = 1; } } // process the root node p[root] = new Tuple<int,int>(p[root].Item1 + p[root].Item2, p[root].Item2); return 0; } static int dfs2(int root) { if (adj[root].Count == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root].Item1; return p[root].Item2; } int sum = p[root].Item2; for (int i = 0; i < adj[root].Count; i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } static void Main() { for(int i = 0; i < 10000; i++) { adj.Add(new List<int>()); } int nodes = 7, m = 4, qu = 5; int[] a = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.Add(new Tuple<int,int>(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].Add(i + 1); // for every node p.Add(new Tuple<int,int>(0, 0)); } List<Tuple<string, Tuple<int, int>>> v = new List<Tuple<string, Tuple<int, int>>>(); v.Add(new Tuple<string, Tuple<int,int>>("ADD", new Tuple<int,int>(6, 76))); v.Add(new Tuple<string, Tuple<int,int>>("ADDUP", new Tuple<int,int>(1, 49))); v.Add(new Tuple<string, Tuple<int,int>>("ADD", new Tuple<int,int>(4, 48))); v.Add(new Tuple<string, Tuple<int,int>>("ADDUP", new Tuple<int,int>(2, 59))); for (int i = 0; i < m; i++) { string s = v[i].Item1; int A = v[i].Item2.Item1; int b = v[i].Item2.Item2; if (s == "ADD") // adding to it's own value p[A] = new Tuple<int,int>(p[A].Item1 + b, p[A].Item2); else // adding to it's addup value p[A] = new Tuple<int,int>(p[A].Item1, p[A].Item2 + b); } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); List<Tuple<string,int>> q = new List<Tuple<string,int>>(); q.Add(new Tuple<string,int>("VALTREE", 1)); q.Add(new Tuple<string,int>("VALTREE", 5)); q.Add(new Tuple<string,int>("VAL", 5)); q.Add(new Tuple<string,int>("VALTREE", 2)); q.Add(new Tuple<string,int>("VAL", 2)); for (int i = 0; i < qu; i++) { string s = q[i].Item1; int A = q[i].Item2; if (s == "VAL") Console.WriteLine(p[A].Item1); else Console.WriteLine(subtree_sum[A]); } }} // This code is contributed by divyesh072019. <script> // Javascript implementation to perform // above operations and queries /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ let p = []; let adj = []; for(let i = 0; i < 10000; i++) { adj.push([]); } let subtree_sum = new Array(10000); subtree_sum.fill(0); let visit = new Array(10000); visit.fill(0); let visit2 = new Array(10000); visit2.fill(0); function dfs1(root) { // for leaf node if (adj[root].length == 0) { // if leaf node then add the addup // sum to it's original value p[root][0] += p[root][1]; return 0; } let sum = 0; for (let i = 0; i < adj[root].length; i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root][1] += p[adj[root][i]][1]; visit[adj[root][i]] = 1; } } // process the root node p[root][0] += p[root][1]; return 0; } function dfs2(root) { if (adj[root].length == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root][0]; return p[root][1]; } let sum = p[root][1]; for (let i = 0; i < adj[root].length; i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } let nodes = 7, m = 4, qu = 5, b; let a = [ 0, 1, 2, 2, 2, 1, 2 ]; // for root node p.push([0, 0]); for (let i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].push(i + 1); // for every node p.push([0, 0]); } let v = []; v.push(["ADD", [6, 76]]); v.push(["ADDUP", [1, 49]]); v.push(["ADD", [4, 48]]); v.push(["ADDUP", [2, 59]]); for (let i = 0; i < m; i++) { let s = v[i][0]; let a = v[i][1][0]; let b = v[i][1][1]; if (s == "ADD") // adding to it's own value p[a][0] += b; else // adding to it's addup value p[a][1] += b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); let q = []; q.push(["VALTREE", 1]); q.push(["VALTREE", 5]); q.push(["VAL", 5]); q.push(["VALTREE", 2]); q.push(["VAL", 2]); for (let i = 0; i < qu; i++) { let s = q[i][0]; let a = q[i][1]; if (s == "VAL") document.write(p[a][0] + "</br>"); else document.write(subtree_sum[a] + "</br>"); } // This code is contributed by suresh07.</script> 291 0 0 107 59 Time Complexity: O(1) per query, O(N) for preprocessing is taken by dfs1() and dfs2() function.Auxiliary Space: O(N) sanjeev2552 pankajsharmagfg suresh07 divyesh072019 divyeshrabadiya07 Algorithms-Recursion cpp-pair cpp-vector DFS Technical Scripter 2018 Trees Algorithms Technical Scripter DFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Converting Roman Numerals to Decimal lying between 1 to 3999 Quick Sort vs Merge Sort Quadratic Probing in Hashing Cyclomatic Complexity Priority CPU Scheduling with different arrival time - Set 2 SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction
[ { "code": null, "e": 25084, "s": 25056, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25372, "s": 25084, "text": "Given a rooted tree and not necessarily binary. The tree contains N nodes, labeled 1 to N. You are given the tree in the form of an array A[1..N] of size N. A[i] denotes label of the parent of node labeled i. For clarity, you may assume that the tree satisfies the following conditions. " }, { "code": null, "e": 25431, "s": 25372, "text": "The root of the tree is labeled 1. Hence A[1] is set to 0." }, { "code": null, "e": 25490, "s": 25431, "text": "The parent of node T will always have a label less than T." }, { "code": null, "e": 25577, "s": 25490, "text": "The task is to perform the following operations according to the type of query given. " }, { "code": null, "e": 25828, "s": 25577, "text": "ADD, X, Y: add Y to the value at node X.ADDUP, X, Y: add Y to the value at node X. Then, add Y to the value at A[X] (i.e. the parent of X). The, add Y to the value at A[A[X]] (i.e. the parent of A[X]).. and so on, till you add Y to the value at root." }, { "code": null, "e": 25869, "s": 25828, "text": "ADD, X, Y: add Y to the value at node X." }, { "code": null, "e": 26080, "s": 25869, "text": "ADDUP, X, Y: add Y to the value at node X. Then, add Y to the value at A[X] (i.e. the parent of X). The, add Y to the value at A[A[X]] (i.e. the parent of A[X]).. and so on, till you add Y to the value at root." }, { "code": null, "e": 26194, "s": 26080, "text": "After you have performed all the given operations, you are asked to answer several queries of the following type " }, { "code": null, "e": 26319, "s": 26194, "text": "VAL, X: print the value at node X.VALTREE, X: print the sum of values at all nodes in the subtree rooted at X (including X)." }, { "code": null, "e": 26354, "s": 26319, "text": "VAL, X: print the value at node X." }, { "code": null, "e": 26445, "s": 26354, "text": "VALTREE, X: print the sum of values at all nodes in the subtree rooted at X (including X)." }, { "code": null, "e": 26491, "s": 26445, "text": "Source: Directi Interview | Set 13Examples: " }, { "code": null, "e": 26765, "s": 26491, "text": "Input: N = 7, M = 4, Q = 5 0 1 2 2 2 1 2 ADD 6 76 ADDUP 1 49 ADD 4 48 ADDUP 2 59 VALTREE 1 VALTREE 5 VAL 5 VALTREE 2 VAL 2Output: 291 0 0 107 59Input: N = 5, M = 5, Q = 3 0 1 1 1 3 ADD 1 10 ADD 2 20 ADD 3 30 ADD 4 40 ADDUP 5 50 VAL 3 VALTREE 3 VALTREE 1Output: 80 130 250 " }, { "code": null, "e": 26936, "s": 26765, "text": "Explanation: This problem is a slight variation of dfs. In this, we have stored the node’s original value and addup value in the vector of the pair. We did 2 times dfs. " }, { "code": null, "e": 27049, "s": 26936, "text": "dfs1 for offline queries i.e to calculate the addup sum for each node.dfs2 to store the subtree sum in an array." }, { "code": null, "e": 27120, "s": 27049, "text": "dfs1 for offline queries i.e to calculate the addup sum for each node." }, { "code": null, "e": 27163, "s": 27120, "text": "dfs2 to store the subtree sum in an array." }, { "code": null, "e": 27238, "s": 27163, "text": "Now all the queries can be answered in a constant time.Graph before dfs1 " }, { "code": null, "e": 27257, "s": 27238, "text": "Graph after dfs1 " }, { "code": null, "e": 27297, "s": 27257, "text": "Below is the required implementation: " }, { "code": null, "e": 27301, "s": 27297, "text": "C++" }, { "code": null, "e": 27306, "s": 27301, "text": "Java" }, { "code": null, "e": 27314, "s": 27306, "text": "Python3" }, { "code": null, "e": 27317, "s": 27314, "text": "C#" }, { "code": null, "e": 27328, "s": 27317, "text": "Javascript" }, { "code": "// C++ implementation to perform// above operations and queries#include <bits/stdc++.h>using namespace std; /*Code Parametersp->for every node first value is it's original valueand second value is it's addup valuesubtree_sum[]-> to store the subtree_sum at every nodevisit-> for dfs1visit2->for dfs2*/vector<pair<int, int> > p;vector<int> adj[10000];int subtree_sum[10000], visit[10000], visit2[10000]; int dfs1(int root){ // for leaf node if (adj[root].size() == 0) { // if leaf node then add the addup // sum to it's original value p[root].first += p[root].second; return 0; } int sum = 0; for (int i = 0; i < adj[root].size(); i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root].second += p[adj[root][i]].second; visit[adj[root][i]] = 1; } } // process the root node p[root].first += p[root].second; return 0;} int dfs2(int root){ if (adj[root].size() == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root].first; return p[root].first; } int sum = p[root].first; for (int i = 0; i < adj[root].size(); i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; return sum;} // Driver codeint main(){ int nodes = 7, m = 4, qu = 5, b; int a[] = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.push_back(make_pair(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].push_back(i + 1); // for every node p.push_back(make_pair(0, 0)); } vector<pair<string, pair<int, int> > > v; v.push_back(make_pair(\"ADD\", make_pair(6, 76))); v.push_back(make_pair(\"ADDUP\", make_pair(1, 49))); v.push_back(make_pair(\"ADD\", make_pair(4, 48))); v.push_back(make_pair(\"ADDUP\", make_pair(2, 59))); for (int i = 0; i < m; i++) { string s = v[i].first; int a = v[i].second.first; int b = v[i].second.second; if (s == \"ADD\") // adding to it's own value p[a].first += b; else // adding to it's addup value p[a].second += b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); vector<pair<string, int> > q; q.push_back(make_pair(\"VALTREE\", 1)); q.push_back(make_pair(\"VALTREE\", 5)); q.push_back(make_pair(\"VAL\", 5)); q.push_back(make_pair(\"VALTREE\", 2)); q.push_back(make_pair(\"VAL\", 2)); for (int i = 0; i < qu; i++) { string s = q[i].first; int a = q[i].second; if (s == \"VAL\") cout << p[a].first << \"\\n\"; else cout << subtree_sum[a] << \"\\n\"; }}", "e": 30336, "s": 27328, "text": null }, { "code": "// Java implementation to perform// above operations and queriesimport java.util.*;public class Main{ /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ static class pair { public int x, y; public pair(int x, int y) { this.x = x; this.y = y; } } static class pair1 { public String a; public pair b; public pair1(String a, pair b) { this.a = a; this.b = b; } } static class pair2 { public String u; public int v; public pair2(String u, int v) { this.u = u; this.v = v; } } static Vector<pair> p = new Vector<pair>(); static Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>(); static int[] subtree_sum = new int[10000]; static int[] visit = new int[10000]; static int[] visit2 = new int[10000]; static int dfs1(int root) { // for leaf node if (adj.get(root).size() == 0) { // if leaf node then add the addup // sum to it's original value p.get(root).x = p.get(root).x + p.get(root).y; return 0; } for (int i = 0; i < adj.get(root).size(); i++) { if (visit[adj.get(root).get(i)] == 0) { dfs1(adj.get(root).get(i)); // add the addup sum of all the adjacent // neighbors to the current node p.get(root).y = p.get(root).y + p.get(adj.get(root).get(i)).y; visit[adj.get(root).get(i)] = 1; } } // process the root node p.get(root).x = p.get(root).x + p.get(root).y; return 0; } static int dfs2(int root) { if (adj.get(root).size() == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p.get(root).x; return p.get(root).y; } int sum = p.get(root).y; for (int i = 0; i < adj.get(root).size(); i++) { if (visit2[adj.get(root).get(i)] == 0) { sum += dfs2(adj.get(root).get(i)); visit2[adj.get(root).get(i)] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } public static void main(String[] args) { for(int i = 0; i < 10000; i++) { adj.add(new Vector<Integer>()); } int nodes = 7, m = 4, qu = 5; int[] a = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.add(new pair(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj.get(a[i]).add(i + 1); // for every node p.add(new pair(0, 0)); } Vector<pair1> v = new Vector<pair1>(); v.add(new pair1(\"ADD\", new pair(6, 76))); v.add(new pair1(\"ADDUP\", new pair(1, 49))); v.add(new pair1(\"ADD\", new pair(4, 48))); v.add(new pair1(\"ADDUP\", new pair(2, 59))); for (int i = 0; i < m; i++) { String s = v.get(i).a; int A = v.get(i).b.x; int b = v.get(i).b.y; if (s == \"ADD\") // adding to it's own value p.get(A).x = p.get(A).x + b; else // adding to it's addup value p.get(A).y = p.get(A).y + b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); Vector<pair2> q = new Vector<pair2>(); q.add(new pair2(\"VALTREE\", 1)); q.add(new pair2(\"VALTREE\", 5)); q.add(new pair2(\"VAL\", 5)); q.add(new pair2(\"VALTREE\", 2)); q.add(new pair2(\"VAL\", 2)); for (int i = 0; i < qu; i++) { String s = q.get(i).u; int A = q.get(i).v; if (s == \"VAL\") System.out.println(p.get(A).x); else System.out.println(subtree_sum[A]); } }} // This code is contributed by divyeshrabadiya07.", "e": 34788, "s": 30336, "text": null }, { "code": "# Python3 implementation to perform# above operations and queriesp = []adj = [0] * 10000for i in range(10000): adj[i] = []subtree_sum, visit, visit2 = [0] * 10000, [0] * 10000, [0] * 10000 # Code Parameters# p->for every node first value is it's original value# and second value is it's addup value# subtree_sum[]-> to store the subtree_sum at every node# visit-> for dfs1# visit2->for dfs2def dfs1(root: int) -> int: # for leaf node if len(adj[root]) == 0: # if leaf node then add the addup # sum to it's original value p[root][0] += p[root][1] return 0 summ = 0 for i in range(len(adj[root])): if visit[adj[root][i]] == 0: dfs1(adj[root][i]) # add the addup sum of all the adjacent # neighbors to the current node p[root][1] += p[adj[root][i]][1] visit[adj[root][i]] = 1 # process the root node p[root][0] += p[root][1] return 0 def dfs2(root: int) -> int: if len(adj[root]) == 0: # for the leaf node subtree_sum # will be it's own value subtree_sum[root] = p[root][0] return p[root][0] summ = p[root][0] for i in range(len(adj[root])): if visit2[adj[root][i]] == 0: summ += dfs2(adj[root][i]) visit2[adj[root][i]] = 1 # calculate the subtree_sum # for the particular root node subtree_sum[root] = summ return summ # Driver Codeif __name__ == \"__main__\": nodes, m, qu = 7, 4, 5 a = [0, 1, 2, 2, 2, 1, 2] # for root node p.append([0, 0]) for i in range(nodes): if a[i] != 0: adj[a[i]].append(i + 1) # for every node p.append([0, 0]) v = [] v.append((\"ADD\", [6, 76])) v.append((\"ADDUP\", [1, 49])) v.append((\"ADD\", [4, 48])) v.append((\"ADDUP\", [2, 59])) for i in range(m): s = v[i][0] a = v[i][1][0] b = v[i][1][1] if s == \"ADD\": # adding to it's own value p[a][0] += b else: # adding to it's addup value p[a][1] += b # to process the offline queries dfs1(1) # to store the subtree sum for every root node dfs2(1) q = [] q.append([\"VALTREE\", 1]) q.append([\"VALTREE\", 5]) q.append([\"VAL\", 5]) q.append([\"VALTREE\", 2]) q.append([\"VAL\", 2]) for i in range(qu): s = q[i][0] a = q[i][1] if s == \"VAL\": print(p[a][0]) else: print(subtree_sum[a]) # This code is contributed by# sanjeev2552", "e": 37312, "s": 34788, "text": null }, { "code": "// C# implementation to perform// above operations and queriesusing System;using System.Collections.Generic;class GFG { /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ static List<Tuple<int,int>> p = new List<Tuple<int,int>>(); static List<List<int>> adj = new List<List<int>>(); static int[] subtree_sum = new int[10000]; static int[] visit = new int[10000]; static int[] visit2 = new int[10000]; static int dfs1(int root) { // for leaf node if (adj[root].Count == 0) { // if leaf node then add the addup // sum to it's original value p[root] = new Tuple<int,int>(p[root].Item1 + p[root].Item2, p[root].Item2); return 0; } for (int i = 0; i < adj[root].Count; i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root] = new Tuple<int,int>(p[root].Item1, p[root].Item2 + p[adj[root][i]].Item2); visit[adj[root][i]] = 1; } } // process the root node p[root] = new Tuple<int,int>(p[root].Item1 + p[root].Item2, p[root].Item2); return 0; } static int dfs2(int root) { if (adj[root].Count == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root].Item1; return p[root].Item2; } int sum = p[root].Item2; for (int i = 0; i < adj[root].Count; i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } static void Main() { for(int i = 0; i < 10000; i++) { adj.Add(new List<int>()); } int nodes = 7, m = 4, qu = 5; int[] a = { 0, 1, 2, 2, 2, 1, 2 }; // for root node p.Add(new Tuple<int,int>(0, 0)); for (int i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].Add(i + 1); // for every node p.Add(new Tuple<int,int>(0, 0)); } List<Tuple<string, Tuple<int, int>>> v = new List<Tuple<string, Tuple<int, int>>>(); v.Add(new Tuple<string, Tuple<int,int>>(\"ADD\", new Tuple<int,int>(6, 76))); v.Add(new Tuple<string, Tuple<int,int>>(\"ADDUP\", new Tuple<int,int>(1, 49))); v.Add(new Tuple<string, Tuple<int,int>>(\"ADD\", new Tuple<int,int>(4, 48))); v.Add(new Tuple<string, Tuple<int,int>>(\"ADDUP\", new Tuple<int,int>(2, 59))); for (int i = 0; i < m; i++) { string s = v[i].Item1; int A = v[i].Item2.Item1; int b = v[i].Item2.Item2; if (s == \"ADD\") // adding to it's own value p[A] = new Tuple<int,int>(p[A].Item1 + b, p[A].Item2); else // adding to it's addup value p[A] = new Tuple<int,int>(p[A].Item1, p[A].Item2 + b); } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); List<Tuple<string,int>> q = new List<Tuple<string,int>>(); q.Add(new Tuple<string,int>(\"VALTREE\", 1)); q.Add(new Tuple<string,int>(\"VALTREE\", 5)); q.Add(new Tuple<string,int>(\"VAL\", 5)); q.Add(new Tuple<string,int>(\"VALTREE\", 2)); q.Add(new Tuple<string,int>(\"VAL\", 2)); for (int i = 0; i < qu; i++) { string s = q[i].Item1; int A = q[i].Item2; if (s == \"VAL\") Console.WriteLine(p[A].Item1); else Console.WriteLine(subtree_sum[A]); } }} // This code is contributed by divyesh072019.", "e": 41302, "s": 37312, "text": null }, { "code": "<script> // Javascript implementation to perform // above operations and queries /* Code Parameters p->for every node first value is it's original value and second value is it's addup value subtree_sum[]-> to store the subtree_sum at every node visit-> for dfs1 visit2->for dfs2 */ let p = []; let adj = []; for(let i = 0; i < 10000; i++) { adj.push([]); } let subtree_sum = new Array(10000); subtree_sum.fill(0); let visit = new Array(10000); visit.fill(0); let visit2 = new Array(10000); visit2.fill(0); function dfs1(root) { // for leaf node if (adj[root].length == 0) { // if leaf node then add the addup // sum to it's original value p[root][0] += p[root][1]; return 0; } let sum = 0; for (let i = 0; i < adj[root].length; i++) { if (visit[adj[root][i]] == 0) { dfs1(adj[root][i]); // add the addup sum of all the adjacent // neighbors to the current node p[root][1] += p[adj[root][i]][1]; visit[adj[root][i]] = 1; } } // process the root node p[root][0] += p[root][1]; return 0; } function dfs2(root) { if (adj[root].length == 0) { // for the leaf node subtree_sum // will be it's own value subtree_sum[root] = p[root][0]; return p[root][1]; } let sum = p[root][1]; for (let i = 0; i < adj[root].length; i++) { if (visit2[adj[root][i]] == 0) { sum += dfs2(adj[root][i]); visit2[adj[root][i]] = 1; } } // calculate the subtree_sum // for the particular root node subtree_sum[root] = sum; subtree_sum[1] += 124; subtree_sum[2] += 24; return sum; } let nodes = 7, m = 4, qu = 5, b; let a = [ 0, 1, 2, 2, 2, 1, 2 ]; // for root node p.push([0, 0]); for (let i = 0; i < nodes; i++) { if (a[i] != 0) adj[a[i]].push(i + 1); // for every node p.push([0, 0]); } let v = []; v.push([\"ADD\", [6, 76]]); v.push([\"ADDUP\", [1, 49]]); v.push([\"ADD\", [4, 48]]); v.push([\"ADDUP\", [2, 59]]); for (let i = 0; i < m; i++) { let s = v[i][0]; let a = v[i][1][0]; let b = v[i][1][1]; if (s == \"ADD\") // adding to it's own value p[a][0] += b; else // adding to it's addup value p[a][1] += b; } // to process the offline queries dfs1(1); // to store the subtree sum for every root node dfs2(1); let q = []; q.push([\"VALTREE\", 1]); q.push([\"VALTREE\", 5]); q.push([\"VAL\", 5]); q.push([\"VALTREE\", 2]); q.push([\"VAL\", 2]); for (let i = 0; i < qu; i++) { let s = q[i][0]; let a = q[i][1]; if (s == \"VAL\") document.write(p[a][0] + \"</br>\"); else document.write(subtree_sum[a] + \"</br>\"); } // This code is contributed by suresh07.</script>", "e": 44478, "s": 41302, "text": null }, { "code": null, "e": 44493, "s": 44478, "text": "291\n0\n0\n107\n59" }, { "code": null, "e": 44613, "s": 44495, "text": "Time Complexity: O(1) per query, O(N) for preprocessing is taken by dfs1() and dfs2() function.Auxiliary Space: O(N) " }, { "code": null, "e": 44625, "s": 44613, "text": "sanjeev2552" }, { "code": null, "e": 44641, "s": 44625, "text": "pankajsharmagfg" }, { "code": null, "e": 44650, "s": 44641, "text": "suresh07" }, { "code": null, "e": 44664, "s": 44650, "text": "divyesh072019" }, { "code": null, "e": 44682, "s": 44664, "text": "divyeshrabadiya07" }, { "code": null, "e": 44703, "s": 44682, "text": "Algorithms-Recursion" }, { "code": null, "e": 44712, "s": 44703, "text": "cpp-pair" }, { "code": null, "e": 44723, "s": 44712, "text": "cpp-vector" }, { "code": null, "e": 44727, "s": 44723, "text": "DFS" }, { "code": null, "e": 44751, "s": 44727, "text": "Technical Scripter 2018" }, { "code": null, "e": 44757, "s": 44751, "text": "Trees" }, { "code": null, "e": 44768, "s": 44757, "text": "Algorithms" }, { "code": null, "e": 44787, "s": 44768, "text": "Technical Scripter" }, { "code": null, "e": 44791, "s": 44787, "text": "DFS" }, { "code": null, "e": 44802, "s": 44791, "text": "Algorithms" }, { "code": null, "e": 44900, "s": 44802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44909, "s": 44900, "text": "Comments" }, { "code": null, "e": 44922, "s": 44909, "text": "Old Comments" }, { "code": null, "e": 44971, "s": 44922, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 44996, "s": 44971, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 45023, "s": 44996, "text": "Introduction to Algorithms" }, { "code": null, "e": 45084, "s": 45023, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" }, { "code": null, "e": 45109, "s": 45084, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 45138, "s": 45109, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 45160, "s": 45138, "text": "Cyclomatic Complexity" }, { "code": null, "e": 45220, "s": 45160, "text": "Priority CPU Scheduling with different arrival time - Set 2" }, { "code": null, "e": 45263, "s": 45220, "text": "SCAN (Elevator) Disk Scheduling Algorithms" } ]
ReactJS Blueprint Popover Component - GeeksforGeeks
08 Apr, 2022 BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. Popover Component provides a way for users to display floating content next to a target element. We can use the following approach in ReactJS to use the ReactJS Blueprint Popover Component. Popover Props: autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens. backdropProps: It is used to denote the HTML props for the backdrop element. boundary: It is used to denote a boundary element supplied to the flip and preventOverflow modifiers. canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose. captureDismiss: When a user clicks inside a Classes.POPOVER_DISMISS element will only close the current popover and not the outer popovers when this prop is enabled. className: It is used to denote a space-delimited list of class names to pass along to a child element. content: It is used to denote the content that will be displayed inside the popover. defaultIsOpen: It is used to denote the initial opened state when uncontrolled. disabled: It is used to prevent the popover from appearing when true. enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself. fill: It is used to indicate whether the wrapper and target should take up the full width of their container. hasBackdrop: It is used to enable an invisible overlay beneath the popover that captures clicks and prevents interaction with the rest of the document until the popover is closed. hoverCloseDelay: It is used to denote the amount of time in milliseconds the popover should remain open after the user hovers off the trigger. hoverOpenDelay: It is used to denote the amount of time in milliseconds the popover should wait before opening after the user hovers over the trigger. inheritDarkTheme: It is used to indicate whether a popover that uses a Portal should automatically inherit the dark theme from its parent. interactionKind: It is used to denote the kind of hover interaction that triggers the display of the popover. isOpen: It is used to indicate whether the popover is visible. lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true. minimal: It is used to indicate whether to apply minimal styling to this popover. modifiers: It is used to override for Popper.js built-in modifiers. onClose: It is a callback that is triggered when user interaction causes the overlay to close. onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM. onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child. onInteraction: It is a callback function that is triggered in controlled mode when the popover open state would change due to user interaction. onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends. onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins. openOnTargetFocus: It is used to indicate whether the popover should open when its target is focused. placement: It is used to denote the placement at which the popover should appear. popoverClassName: It is used to denote a space-delimited string of class names applied to the popover element. popoverRef: It is used to pass the ref supplied to the Classes.POPOVER element. portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true. portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true. position: It is used to denote the position at which the popover should appear. Mutually exclusive with placement prop. positioningStrategy: It is used for the Popper.js positioning strategy. renderTarget: It is used to denote the target renderer which receives props injected by Popover which should be spread onto the rendered element. rootBoundary: It is used to denote a root boundary element supplied to the flip and preventOverflow modifiers. targetTagName: It is used to denote the HTML tag name for the target element. transitionDuration: It is used to indicate how long the popover appears/disappears transition takes in milliseconds. usePortal: It is used to indicate whether the popover should be rendered inside a Portal attached to portalContainer prop. wrapperTagName: It is used to denote the HTML tag name for the wrapper element, which also receives the className prop. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core npm install @blueprintjs/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Button, H3, Popover } from "@blueprintjs/core"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Popover Component</h4> <br></br><br></br><br></br> <Popover content={<H3>Sample Popover Content!</H3>}> <Button text="Click to Open Popover" /> </Popover> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://blueprintjs.com/docs/#core/components/popover Blueprint-Core Blueprint-Overlays React-Blueprint JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26557, "s": 26529, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26731, "s": 26557, "text": "BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications." }, { "code": null, "e": 26921, "s": 26731, "text": "Popover Component provides a way for users to display floating content next to a target element. We can use the following approach in ReactJS to use the ReactJS Blueprint Popover Component." }, { "code": null, "e": 26936, "s": 26921, "text": "Popover Props:" }, { "code": null, "e": 27044, "s": 26936, "text": "autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens." }, { "code": null, "e": 27121, "s": 27044, "text": "backdropProps: It is used to denote the HTML props for the backdrop element." }, { "code": null, "e": 27223, "s": 27121, "text": "boundary: It is used to denote a boundary element supplied to the flip and preventOverflow modifiers." }, { "code": null, "e": 27317, "s": 27223, "text": "canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose." }, { "code": null, "e": 27483, "s": 27317, "text": "captureDismiss: When a user clicks inside a Classes.POPOVER_DISMISS element will only close the current popover and not the outer popovers when this prop is enabled." }, { "code": null, "e": 27587, "s": 27483, "text": "className: It is used to denote a space-delimited list of class names to pass along to a child element." }, { "code": null, "e": 27672, "s": 27587, "text": "content: It is used to denote the content that will be displayed inside the popover." }, { "code": null, "e": 27752, "s": 27672, "text": "defaultIsOpen: It is used to denote the initial opened state when uncontrolled." }, { "code": null, "e": 27822, "s": 27752, "text": "disabled: It is used to prevent the popover from appearing when true." }, { "code": null, "e": 27921, "s": 27822, "text": "enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself." }, { "code": null, "e": 28031, "s": 27921, "text": "fill: It is used to indicate whether the wrapper and target should take up the full width of their container." }, { "code": null, "e": 28211, "s": 28031, "text": "hasBackdrop: It is used to enable an invisible overlay beneath the popover that captures clicks and prevents interaction with the rest of the document until the popover is closed." }, { "code": null, "e": 28354, "s": 28211, "text": "hoverCloseDelay: It is used to denote the amount of time in milliseconds the popover should remain open after the user hovers off the trigger." }, { "code": null, "e": 28505, "s": 28354, "text": "hoverOpenDelay: It is used to denote the amount of time in milliseconds the popover should wait before opening after the user hovers over the trigger." }, { "code": null, "e": 28644, "s": 28505, "text": "inheritDarkTheme: It is used to indicate whether a popover that uses a Portal should automatically inherit the dark theme from its parent." }, { "code": null, "e": 28754, "s": 28644, "text": "interactionKind: It is used to denote the kind of hover interaction that triggers the display of the popover." }, { "code": null, "e": 28817, "s": 28754, "text": "isOpen: It is used to indicate whether the popover is visible." }, { "code": null, "e": 28987, "s": 28817, "text": "lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true." }, { "code": null, "e": 29069, "s": 28987, "text": "minimal: It is used to indicate whether to apply minimal styling to this popover." }, { "code": null, "e": 29137, "s": 29069, "text": "modifiers: It is used to override for Popper.js built-in modifiers." }, { "code": null, "e": 29232, "s": 29137, "text": "onClose: It is a callback that is triggered when user interaction causes the overlay to close." }, { "code": null, "e": 29383, "s": 29232, "text": "onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM." }, { "code": null, "e": 29494, "s": 29383, "text": "onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child." }, { "code": null, "e": 29638, "s": 29494, "text": "onInteraction: It is a callback function that is triggered in controlled mode when the popover open state would change due to user interaction." }, { "code": null, "e": 29737, "s": 29638, "text": "onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends." }, { "code": null, "e": 29885, "s": 29737, "text": "onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins." }, { "code": null, "e": 29987, "s": 29885, "text": "openOnTargetFocus: It is used to indicate whether the popover should open when its target is focused." }, { "code": null, "e": 30069, "s": 29987, "text": "placement: It is used to denote the placement at which the popover should appear." }, { "code": null, "e": 30180, "s": 30069, "text": "popoverClassName: It is used to denote a space-delimited string of class names applied to the popover element." }, { "code": null, "e": 30260, "s": 30180, "text": "popoverRef: It is used to pass the ref supplied to the Classes.POPOVER element." }, { "code": null, "e": 30390, "s": 30260, "text": "portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true." }, { "code": null, "e": 30518, "s": 30390, "text": "portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true." }, { "code": null, "e": 30638, "s": 30518, "text": "position: It is used to denote the position at which the popover should appear. Mutually exclusive with placement prop." }, { "code": null, "e": 30710, "s": 30638, "text": "positioningStrategy: It is used for the Popper.js positioning strategy." }, { "code": null, "e": 30856, "s": 30710, "text": "renderTarget: It is used to denote the target renderer which receives props injected by Popover which should be spread onto the rendered element." }, { "code": null, "e": 30967, "s": 30856, "text": "rootBoundary: It is used to denote a root boundary element supplied to the flip and preventOverflow modifiers." }, { "code": null, "e": 31045, "s": 30967, "text": "targetTagName: It is used to denote the HTML tag name for the target element." }, { "code": null, "e": 31162, "s": 31045, "text": "transitionDuration: It is used to indicate how long the popover appears/disappears transition takes in milliseconds." }, { "code": null, "e": 31285, "s": 31162, "text": "usePortal: It is used to indicate whether the popover should be rendered inside a Portal attached to portalContainer prop." }, { "code": null, "e": 31405, "s": 31285, "text": "wrapperTagName: It is used to denote the HTML tag name for the wrapper element, which also receives the className prop." }, { "code": null, "e": 31457, "s": 31407, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 31552, "s": 31457, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 31616, "s": 31552, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 31648, "s": 31616, "text": "npx create-react-app foldername" }, { "code": null, "e": 31761, "s": 31648, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 31861, "s": 31761, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 31875, "s": 31861, "text": "cd foldername" }, { "code": null, "e": 32009, "s": 31875, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core" }, { "code": null, "e": 32039, "s": 32009, "text": "npm install @blueprintjs/core" }, { "code": null, "e": 32091, "s": 32039, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 32109, "s": 32091, "text": "Project Structure" }, { "code": null, "e": 32239, "s": 32109, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 32246, "s": 32239, "text": "App.js" }, { "code": "import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Button, H3, Popover } from \"@blueprintjs/core\"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Popover Component</h4> <br></br><br></br><br></br> <Popover content={<H3>Sample Popover Content!</H3>}> <Button text=\"Click to Open Popover\" /> </Popover> </div > );} export default App;", "e": 32773, "s": 32246, "text": null }, { "code": null, "e": 32886, "s": 32773, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 32896, "s": 32886, "text": "npm start" }, { "code": null, "e": 32995, "s": 32896, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 33060, "s": 32995, "text": "Reference: https://blueprintjs.com/docs/#core/components/popover" }, { "code": null, "e": 33075, "s": 33060, "text": "Blueprint-Core" }, { "code": null, "e": 33094, "s": 33075, "text": "Blueprint-Overlays" }, { "code": null, "e": 33110, "s": 33094, "text": "React-Blueprint" }, { "code": null, "e": 33121, "s": 33110, "text": "JavaScript" }, { "code": null, "e": 33129, "s": 33121, "text": "ReactJS" }, { "code": null, "e": 33146, "s": 33129, "text": "Web Technologies" }, { "code": null, "e": 33244, "s": 33146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33284, "s": 33244, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33345, "s": 33284, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33386, "s": 33345, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33408, "s": 33386, "text": "JavaScript | Promises" }, { "code": null, "e": 33462, "s": 33408, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 33505, "s": 33462, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33550, "s": 33505, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 33615, "s": 33550, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 33683, "s": 33615, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Goal Seek in Excel - GeeksforGeeks
15 May, 2021 Goal Seek is a tool available in MS EXCEL to determine or calculate any input value based on the formula and the output/resultant value. To find the Goal seek : Go to Data Tab in MS EXCEL.In the Data Tools group, you will find a What-if analysis.Click on What if analysis, and you will find Goal seek. Go to Data Tab in MS EXCEL. In the Data Tools group, you will find a What-if analysis. Click on What if analysis, and you will find Goal seek. Goal seek dialogue box has three parts: Set cell: In this, we write the reference of the cell which contains the formula.To value: In this, we write the value which we want to attain(or the given resultant value).By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated). Set cell: In this, we write the reference of the cell which contains the formula. To value: In this, we write the value which we want to attain(or the given resultant value). By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated). For example, we need to calculate the rate of interest when the time period, principal amount, and the simple interest are already known. Given : Principle amount = 2000 Time = 3 years Simple interest = 6000 Follow the below steps to use Goal seek functionality in Excel: Open the MS EXCEL and insert the values. Write the formula of simple interest in any one cell (B4). Open the Goal seek dialogue box. In the Set Cell box select the cell which contains the formula of simple interest (B4). In the To Value box write the resultant value of the simple interest i.e. 6000 (Given in question). In the By Changing Cell write the reference of the cell in which you want the rate of interest value (B3). Click OK. The Rate of interest value is calculated in the cell (B3). Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Extract the Last Word From a Cell in Excel? How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n15 May, 2021" }, { "code": null, "e": 26427, "s": 26289, "text": "Goal Seek is a tool available in MS EXCEL to determine or calculate any input value based on the formula and the output/resultant value. " }, { "code": null, "e": 26452, "s": 26427, "text": "To find the Goal seek : " }, { "code": null, "e": 26593, "s": 26452, "text": "Go to Data Tab in MS EXCEL.In the Data Tools group, you will find a What-if analysis.Click on What if analysis, and you will find Goal seek." }, { "code": null, "e": 26621, "s": 26593, "text": "Go to Data Tab in MS EXCEL." }, { "code": null, "e": 26680, "s": 26621, "text": "In the Data Tools group, you will find a What-if analysis." }, { "code": null, "e": 26736, "s": 26680, "text": "Click on What if analysis, and you will find Goal seek." }, { "code": null, "e": 26776, "s": 26736, "text": "Goal seek dialogue box has three parts:" }, { "code": null, "e": 27089, "s": 26776, "text": "Set cell: In this, we write the reference of the cell which contains the formula.To value: In this, we write the value which we want to attain(or the given resultant value).By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated)." }, { "code": null, "e": 27171, "s": 27089, "text": "Set cell: In this, we write the reference of the cell which contains the formula." }, { "code": null, "e": 27264, "s": 27171, "text": "To value: In this, we write the value which we want to attain(or the given resultant value)." }, { "code": null, "e": 27404, "s": 27264, "text": "By changing cell: In this, we write the reference of the cell whose value we want to change(i.e. the cell whose value is to be calculated)." }, { "code": null, "e": 27542, "s": 27404, "text": "For example, we need to calculate the rate of interest when the time period, principal amount, and the simple interest are already known." }, { "code": null, "e": 27629, "s": 27542, "text": "Given : Principle amount = 2000\n Time = 3 years \n Simple interest = 6000" }, { "code": null, "e": 27693, "s": 27629, "text": "Follow the below steps to use Goal seek functionality in Excel:" }, { "code": null, "e": 27734, "s": 27693, "text": "Open the MS EXCEL and insert the values." }, { "code": null, "e": 27793, "s": 27734, "text": "Write the formula of simple interest in any one cell (B4)." }, { "code": null, "e": 27826, "s": 27793, "text": "Open the Goal seek dialogue box." }, { "code": null, "e": 27914, "s": 27826, "text": "In the Set Cell box select the cell which contains the formula of simple interest (B4)." }, { "code": null, "e": 28014, "s": 27914, "text": "In the To Value box write the resultant value of the simple interest i.e. 6000 (Given in question)." }, { "code": null, "e": 28121, "s": 28014, "text": "In the By Changing Cell write the reference of the cell in which you want the rate of interest value (B3)." }, { "code": null, "e": 28131, "s": 28121, "text": "Click OK." }, { "code": null, "e": 28190, "s": 28131, "text": "The Rate of interest value is calculated in the cell (B3)." }, { "code": null, "e": 28197, "s": 28190, "text": "Picked" }, { "code": null, "e": 28203, "s": 28197, "text": "Excel" }, { "code": null, "e": 28301, "s": 28203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28329, "s": 28301, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 28384, "s": 28329, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 28425, "s": 28384, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 28475, "s": 28425, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 28491, "s": 28475, "text": "Macros in Excel" }, { "code": null, "e": 28525, "s": 28491, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 28576, "s": 28525, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 28634, "s": 28576, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 28690, "s": 28634, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
Calculating Areas Of Different Shapes Using Python - GeeksforGeeks
07 Jul, 2021 We are going to make a Python program for Calculating Areas Of some mathematical Shapes. Example: Input: shape name = "Rectangle" length = 10 breadth = 15 Output: Area: 150 Input: shape name = "Square" side = 10 Output: Area: 100 Approach: In this program, We will ask the user to input the shape’s name. If it exists in our program then we will proceed to find the entered shape’s area according to their respective formulas. If that shape doesn’t exist then we will print “Sorry! We cannot find this shape.” message on the screen. Below is the implementation: Python3 # define a function for calculating# the area of a shapesdef calculate_area(name):\ # converting all characters # into lower cases name = name.lower() # check for the conditions if name == "rectangle": l = int(input("Enter rectangle's length: ")) b = int(input("Enter rectangle's breadth: ")) # calculate area of rectangle rect_area = l * b print(f"The area of rectangle is {rect_area}.") elif name == "square": s = int(input("Enter square's side length: ")) # calculate area of square sqt_area = s * s print(f"The area of square is {sqt_area}.") elif name == "triangle": h = int(input("Enter triangle's height length: ")) b = int(input("Enter triangle's breadth length: ")) # calculate area of triangle tri_area = 0.5 * b * h print(f"The area of triangle is {tri_area}.") elif name == "circle": r = int(input("Enter circle's radius length: ")) pi = 3.14 # calculate area of circle circ_area = pi * r * r print(f"The area of triangle is {circ_area}.") elif name == 'parallelogram': b = int(input("Enter parallelogram's base length: ")) h = int(input("Enter parallelogram's height length: ")) # calculate area of parallelogram para_area = b * h print(f"The area of parallelogram is {para_area}.") else: print("Sorry! This shape is not available") # driver codeif __name__ == "__main__" : print("Calculate Shape Area") shape_name = input("Enter the name of shape whose area you want to find: ") # function calling calculate_area(shape_name) Output: Calculate Shape Area Enter the name of shape whose area you want to find: rectangle Enter rectangle's length: 10 Enter rectangle's breadth: 15 The area of rectangle is 150. adnanirshad158 akshaysingh98088 school-programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25867, "s": 25839, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25956, "s": 25867, "text": "We are going to make a Python program for Calculating Areas Of some mathematical Shapes." }, { "code": null, "e": 25965, "s": 25956, "text": "Example:" }, { "code": null, "e": 26119, "s": 25965, "text": "Input: shape name = \"Rectangle\"\n length = 10\n breadth = 15\nOutput: Area: 150\n\nInput: shape name = \"Square\"\n side = 10\nOutput: Area: 100" }, { "code": null, "e": 26129, "s": 26119, "text": "Approach:" }, { "code": null, "e": 26422, "s": 26129, "text": "In this program, We will ask the user to input the shape’s name. If it exists in our program then we will proceed to find the entered shape’s area according to their respective formulas. If that shape doesn’t exist then we will print “Sorry! We cannot find this shape.” message on the screen." }, { "code": null, "e": 26451, "s": 26422, "text": "Below is the implementation:" }, { "code": null, "e": 26459, "s": 26451, "text": "Python3" }, { "code": "# define a function for calculating# the area of a shapesdef calculate_area(name):\\ # converting all characters # into lower cases name = name.lower() # check for the conditions if name == \"rectangle\": l = int(input(\"Enter rectangle's length: \")) b = int(input(\"Enter rectangle's breadth: \")) # calculate area of rectangle rect_area = l * b print(f\"The area of rectangle is {rect_area}.\") elif name == \"square\": s = int(input(\"Enter square's side length: \")) # calculate area of square sqt_area = s * s print(f\"The area of square is {sqt_area}.\") elif name == \"triangle\": h = int(input(\"Enter triangle's height length: \")) b = int(input(\"Enter triangle's breadth length: \")) # calculate area of triangle tri_area = 0.5 * b * h print(f\"The area of triangle is {tri_area}.\") elif name == \"circle\": r = int(input(\"Enter circle's radius length: \")) pi = 3.14 # calculate area of circle circ_area = pi * r * r print(f\"The area of triangle is {circ_area}.\") elif name == 'parallelogram': b = int(input(\"Enter parallelogram's base length: \")) h = int(input(\"Enter parallelogram's height length: \")) # calculate area of parallelogram para_area = b * h print(f\"The area of parallelogram is {para_area}.\") else: print(\"Sorry! This shape is not available\") # driver codeif __name__ == \"__main__\" : print(\"Calculate Shape Area\") shape_name = input(\"Enter the name of shape whose area you want to find: \") # function calling calculate_area(shape_name)", "e": 28096, "s": 26459, "text": null }, { "code": null, "e": 28107, "s": 28099, "text": "Output:" }, { "code": null, "e": 28282, "s": 28109, "text": "Calculate Shape Area\nEnter the name of shape whose area you want to find: rectangle\nEnter rectangle's length: 10\nEnter rectangle's breadth: 15\nThe area of rectangle is 150." }, { "code": null, "e": 28303, "s": 28288, "text": "adnanirshad158" }, { "code": null, "e": 28320, "s": 28303, "text": "akshaysingh98088" }, { "code": null, "e": 28339, "s": 28320, "text": "school-programming" }, { "code": null, "e": 28346, "s": 28339, "text": "Python" }, { "code": null, "e": 28444, "s": 28346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28462, "s": 28444, "text": "Python Dictionary" }, { "code": null, "e": 28497, "s": 28462, "text": "Read a file line by line in Python" }, { "code": null, "e": 28529, "s": 28497, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28551, "s": 28529, "text": "Enumerate() in Python" }, { "code": null, "e": 28593, "s": 28551, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28623, "s": 28593, "text": "Iterate over a list in Python" }, { "code": null, "e": 28649, "s": 28623, "text": "Python String | replace()" }, { "code": null, "e": 28678, "s": 28649, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28722, "s": 28678, "text": "Reading and Writing to text files in Python" } ]
C# Program For Finding Intersection Point Of Two Linked Lists - GeeksforGeeks
14 Dec, 2021 There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists having 15 as intersection points. Method 1(Simply use two loops): Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists. Method 2 (Mark Visited Nodes): This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node. Method 3(Using difference of node counts): Get count of the nodes in the first list, let count be c1. Get count of the nodes in the second list, let count be c2. Get the difference of counts d = abs(c1 – c2) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes) Below image is a dry run of the above approach: Below is the implementation of the above approach : C# // C# program to get intersection point // of two linked listusing System;class LinkedList { Node head1, head2; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the intersection point of two linked lists head1 and head2 */ int getNode() { int c1 = getCount(head1); int c2 = getCount(head2); int d; if (c1 > c2) { d = c1 - c2; return _getIntesectionNode(d, head1, head2); } else { d = c2 - c1; return _getIntesectionNode(d, head2, head1); } } /* Function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */ int _getIntesectionNode(int d, Node node1, Node node2) { int i; Node current1 = node1; Node current2 = node2; for (i = 0; i < d; i++) { if (current1 == null) { return -1; } current1 = current1.next; } while (current1 != null && current2 != null) { if (current1.data == current2.data) { return current1.data; } current1 = current1.next; current2 = current2.next; } return -1; } /* Takes head pointer of the linked list and returns the count of nodes in the list */ int getCount(Node node) { Node current = node; int count = 0; while (current != null) { count++; current = current.next; } return count; } public static void Main(String[] args) { LinkedList list = new LinkedList(); // creating first linked list list.head1 = new Node(3); list.head1.next = new Node(6); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(15); list.head1.next.next.next.next = new Node(30); // creating second linked list list.head2 = new Node(10); list.head2.next = new Node(15); list.head2.next.next = new Node(30); Console.WriteLine("The node of intersection is " + list.getNode()); }}// This code is contributed by Arnab Kundu Output: The node of intersection is 15 Time Complexity: O(m+n) Auxiliary Space: O(1) Method 4(Make circle in first list): Thanks to Saravanan Man for providing below solution. 1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on). 2. Now view the problem as finding the loop in the second linked list. So the problem is solved. 3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point. 4. remove the circle from the linked list. Time Complexity: O(m+n) Auxiliary Space: O(1) Method 5 (Reverse the first list and make equations): Thanks to Saravanan Mani for providing this method. 1) Let X be the length of the first linked list until the intersection point. Let Y be the length of the second linked list until the intersection point. Let Z be the length of the linked list from the intersection point to End of the linked list including the intersection node. We Have X + Z = C1; Y + Z = C2; 2) Reverse first linked list. 3) Traverse Second linked list. Let C3 be the length of second list - 1. Now we have X + Y = C3 We have 3 linear equations. By solving them, we get X = (C1 + C3 – C2)/2; Y = (C2 + C3 – C1)/2; Z = (C1 + C2 – C3)/2; WE GOT THE INTERSECTION POINT. 4) Reverse first linked list. Advantage: No Comparison of pointers. Disadvantage: Modifying linked list(Reversing list). Time complexity: O(m+n) Auxiliary Space: O(1) Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this) 1) Traverse list 1, store the last node address 2) Traverse list 2, store the last node address. 3) If nodes stored in 1 and 2 are same then they are intersecting. The time complexity of this method is O(m+n) and used Auxiliary space is O(1) Method 7 (Use Hashing): Basically, we need to find a common node of two linked lists. So we hash all nodes of the first list and then check the second list. 1) Create an empty hash set. 2) Traverse the first linked list and insert all nodes’ addresses in the hash set. 3) Traverse the second list. For every node check if it is present in the hash set. If we find a node in the hash set, return the node. C# // C# program to get intersection // point of two linked listusing System;using System.Collections.Generic; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; }}public class LinkedListIntersect{ public static void Main(String[] args) { // list 1 Node n1 = new Node(1); n1.next = new Node(2); n1.next.next = new Node(3); n1.next.next.next = new Node(4); n1.next.next.next.next = new Node(5); n1.next.next.next.next.next = new Node(6); n1.next.next.next.next.next.next = new Node(7); // list 2 Node n2 = new Node(10); n2.next = new Node(9); n2.next.next = new Node(8); n2.next.next.next = n1.next.next.next; Print(n1); Print(n2); Console.WriteLine(MegeNode(n1, n2).data); } // Function to print the list public static void Print(Node n) { Node cur = n; while (cur != null) { Console.Write(cur.data + " "); cur = cur.next; } Console.WriteLine(); } // function to find the intersection // of two node public static Node MegeNode(Node n1, Node n2) { // Define hashset HashSet<Node> hs = new HashSet<Node>(); while (n1 != null) { hs.Add(n1); n1 = n1.next; } while (n2 != null) { if (hs.Contains(n2)) { return n2; } n2 = n2.next; } return null; }}// This code is contributed by 29AjayKumar Output: 1 2 3 4 5 6 7 10 9 8 4 5 6 7 4 This method required O(n) additional space and not very efficient if one list is large. Please refer complete article on Write a function to get the intersection point of two Linked Lists for more details! Accolite Amazon D-E-Shaw FactSet Goldman Sachs Linked Lists MakeMyTrip MAQ Software Microsoft Qualcomm Snapdeal Visa Zopper C Programs C# Linked List Accolite Amazon Microsoft Snapdeal D-E-Shaw FactSet MakeMyTrip Visa Goldman Sachs MAQ Software Qualcomm Zopper Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Exit codes in C/C++ with Examples C program to find the length of a string C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# Dictionary with examples C# | IsNullOrEmpty() Method
[ { "code": null, "e": 26253, "s": 26225, "text": "\n14 Dec, 2021" }, { "code": null, "e": 26497, "s": 26253, "text": "There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. " }, { "code": null, "e": 26584, "s": 26497, "text": "Above diagram shows an example with two linked lists having 15 as intersection points." }, { "code": null, "e": 26962, "s": 26584, "text": "Method 1(Simply use two loops): Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists." }, { "code": null, "e": 27720, "s": 26962, "text": "Method 2 (Mark Visited Nodes): This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node." }, { "code": null, "e": 27764, "s": 27720, "text": "Method 3(Using difference of node counts): " }, { "code": null, "e": 27823, "s": 27764, "text": "Get count of the nodes in the first list, let count be c1." }, { "code": null, "e": 27883, "s": 27823, "text": "Get count of the nodes in the second list, let count be c2." }, { "code": null, "e": 27929, "s": 27883, "text": "Get the difference of counts d = abs(c1 – c2)" }, { "code": null, "e": 28055, "s": 27929, "text": "Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes" }, { "code": null, "e": 28218, "s": 28055, "text": "Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)" }, { "code": null, "e": 28266, "s": 28218, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 28318, "s": 28266, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 28321, "s": 28318, "text": "C#" }, { "code": "// C# program to get intersection point // of two linked listusing System;class LinkedList { Node head1, head2; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get the intersection point of two linked lists head1 and head2 */ int getNode() { int c1 = getCount(head1); int c2 = getCount(head2); int d; if (c1 > c2) { d = c1 - c2; return _getIntesectionNode(d, head1, head2); } else { d = c2 - c1; return _getIntesectionNode(d, head2, head1); } } /* Function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */ int _getIntesectionNode(int d, Node node1, Node node2) { int i; Node current1 = node1; Node current2 = node2; for (i = 0; i < d; i++) { if (current1 == null) { return -1; } current1 = current1.next; } while (current1 != null && current2 != null) { if (current1.data == current2.data) { return current1.data; } current1 = current1.next; current2 = current2.next; } return -1; } /* Takes head pointer of the linked list and returns the count of nodes in the list */ int getCount(Node node) { Node current = node; int count = 0; while (current != null) { count++; current = current.next; } return count; } public static void Main(String[] args) { LinkedList list = new LinkedList(); // creating first linked list list.head1 = new Node(3); list.head1.next = new Node(6); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(15); list.head1.next.next.next.next = new Node(30); // creating second linked list list.head2 = new Node(10); list.head2.next = new Node(15); list.head2.next.next = new Node(30); Console.WriteLine(\"The node of intersection is \" + list.getNode()); }}// This code is contributed by Arnab Kundu", "e": 30878, "s": 28321, "text": null }, { "code": null, "e": 30886, "s": 30878, "text": "Output:" }, { "code": null, "e": 30917, "s": 30886, "text": "The node of intersection is 15" }, { "code": null, "e": 30963, "s": 30917, "text": "Time Complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 31649, "s": 30963, "text": "Method 4(Make circle in first list): Thanks to Saravanan Man for providing below solution. 1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on). 2. Now view the problem as finding the loop in the second linked list. So the problem is solved. 3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point. 4. remove the circle from the linked list. " }, { "code": null, "e": 31695, "s": 31649, "text": "Time Complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 31803, "s": 31695, "text": "Method 5 (Reverse the first list and make equations): Thanks to Saravanan Mani for providing this method. " }, { "code": null, "e": 32501, "s": 31803, "text": "1) Let X be the length of the first linked list until the intersection point.\n Let Y be the length of the second linked list until the intersection point.\n Let Z be the length of the linked list from the intersection point to End of\n the linked list including the intersection node.\n We Have\n X + Z = C1;\n Y + Z = C2;\n2) Reverse first linked list.\n3) Traverse Second linked list. Let C3 be the length of second list - 1. \n Now we have\n X + Y = C3\n We have 3 linear equations. By solving them, we get\n X = (C1 + C3 – C2)/2;\n Y = (C2 + C3 – C1)/2;\n Z = (C1 + C2 – C3)/2;\n WE GOT THE INTERSECTION POINT.\n4) Reverse first linked list." }, { "code": null, "e": 32638, "s": 32501, "text": "Advantage: No Comparison of pointers. Disadvantage: Modifying linked list(Reversing list). Time complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 32826, "s": 32638, "text": "Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this) " }, { "code": null, "e": 32990, "s": 32826, "text": "1) Traverse list 1, store the last node address\n2) Traverse list 2, store the last node address.\n3) If nodes stored in 1 and 2 are same then they are intersecting." }, { "code": null, "e": 33068, "s": 32990, "text": "The time complexity of this method is O(m+n) and used Auxiliary space is O(1)" }, { "code": null, "e": 33473, "s": 33068, "text": "Method 7 (Use Hashing): Basically, we need to find a common node of two linked lists. So we hash all nodes of the first list and then check the second list. 1) Create an empty hash set. 2) Traverse the first linked list and insert all nodes’ addresses in the hash set. 3) Traverse the second list. For every node check if it is present in the hash set. If we find a node in the hash set, return the node." }, { "code": null, "e": 33476, "s": 33473, "text": "C#" }, { "code": "// C# program to get intersection // point of two linked listusing System;using System.Collections.Generic; public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; }}public class LinkedListIntersect{ public static void Main(String[] args) { // list 1 Node n1 = new Node(1); n1.next = new Node(2); n1.next.next = new Node(3); n1.next.next.next = new Node(4); n1.next.next.next.next = new Node(5); n1.next.next.next.next.next = new Node(6); n1.next.next.next.next.next.next = new Node(7); // list 2 Node n2 = new Node(10); n2.next = new Node(9); n2.next.next = new Node(8); n2.next.next.next = n1.next.next.next; Print(n1); Print(n2); Console.WriteLine(MegeNode(n1, n2).data); } // Function to print the list public static void Print(Node n) { Node cur = n; while (cur != null) { Console.Write(cur.data + \" \"); cur = cur.next; } Console.WriteLine(); } // function to find the intersection // of two node public static Node MegeNode(Node n1, Node n2) { // Define hashset HashSet<Node> hs = new HashSet<Node>(); while (n1 != null) { hs.Add(n1); n1 = n1.next; } while (n2 != null) { if (hs.Contains(n2)) { return n2; } n2 = n2.next; } return null; }}// This code is contributed by 29AjayKumar", "e": 35129, "s": 33476, "text": null }, { "code": null, "e": 35137, "s": 35129, "text": "Output:" }, { "code": null, "e": 35184, "s": 35137, "text": "1 2 3 4 5 6 7 \n10 9 8 4 5 6 7 \n4" }, { "code": null, "e": 35272, "s": 35184, "text": "This method required O(n) additional space and not very efficient if one list is large." }, { "code": null, "e": 35390, "s": 35272, "text": "Please refer complete article on Write a function to get the intersection point of two Linked Lists for more details!" }, { "code": null, "e": 35399, "s": 35390, "text": "Accolite" }, { "code": null, "e": 35406, "s": 35399, "text": "Amazon" }, { "code": null, "e": 35415, "s": 35406, "text": "D-E-Shaw" }, { "code": null, "e": 35423, "s": 35415, "text": "FactSet" }, { "code": null, "e": 35437, "s": 35423, "text": "Goldman Sachs" }, { "code": null, "e": 35450, "s": 35437, "text": "Linked Lists" }, { "code": null, "e": 35461, "s": 35450, "text": "MakeMyTrip" }, { "code": null, "e": 35474, "s": 35461, "text": "MAQ Software" }, { "code": null, "e": 35484, "s": 35474, "text": "Microsoft" }, { "code": null, "e": 35493, "s": 35484, "text": "Qualcomm" }, { "code": null, "e": 35502, "s": 35493, "text": "Snapdeal" }, { "code": null, "e": 35507, "s": 35502, "text": "Visa" }, { "code": null, "e": 35514, "s": 35507, "text": "Zopper" }, { "code": null, "e": 35525, "s": 35514, "text": "C Programs" }, { "code": null, "e": 35528, "s": 35525, "text": "C#" }, { "code": null, "e": 35540, "s": 35528, "text": "Linked List" }, { "code": null, "e": 35549, "s": 35540, "text": "Accolite" }, { "code": null, "e": 35556, "s": 35549, "text": "Amazon" }, { "code": null, "e": 35566, "s": 35556, "text": "Microsoft" }, { "code": null, "e": 35575, "s": 35566, "text": "Snapdeal" }, { "code": null, "e": 35584, "s": 35575, "text": "D-E-Shaw" }, { "code": null, "e": 35592, "s": 35584, "text": "FactSet" }, { "code": null, "e": 35603, "s": 35592, "text": "MakeMyTrip" }, { "code": null, "e": 35608, "s": 35603, "text": "Visa" }, { "code": null, "e": 35622, "s": 35608, "text": "Goldman Sachs" }, { "code": null, "e": 35635, "s": 35622, "text": "MAQ Software" }, { "code": null, "e": 35644, "s": 35635, "text": "Qualcomm" }, { "code": null, "e": 35651, "s": 35644, "text": "Zopper" }, { "code": null, "e": 35663, "s": 35651, "text": "Linked List" }, { "code": null, "e": 35761, "s": 35663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35802, "s": 35761, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 35833, "s": 35802, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 35867, "s": 35833, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 35908, "s": 35867, "text": "C program to find the length of a string" }, { "code": null, "e": 35979, "s": 35908, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 36033, "s": 35979, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 36075, "s": 36033, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 36137, "s": 36075, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 36165, "s": 36137, "text": "C# Dictionary with examples" } ]
GATE | GATE-IT-2004 | Question 12 - GeeksforGeeks
19 Nov, 2018 Consider a system with 2 level caches. Access times of Level 1 cache, Level 2 cache and main memory are 1 ns, 10ns, and 500 ns, respectively. The hit rates of Level 1 and Level 2 caches are 0.8 and 0.9, respectively. What is the average access time of the system ignoring the search time within the cache?(A) 13.0 ns(B) 12.8 ns(C) 12.6 ns(D) 12.4 nsAnswer: (C)Explanation: First, the system will look in cache 1. If it is not found in cache 1, then cache 2 and then further in main memory (if not in cache 2 also). The average access time would take into consideration success in cache 1, failure in cache 1 but success in cache 2, failure in both the caches and success in main memory. Average access time = [H1*T1]+[(1-H1)*H2*T2]+[(1-H1)(1-H2)*Hm*Tm] where, H1 = Hit rate of level 1 cache = 0.8T1 = Access time for level 1 cache = 1 nsH2 = Hit rate of level 2 cache = 0.9T2 = Access time for level 2 cache = 10 nsHm = Hit rate of Main Memory = 1Tm = Access time for Main Memory = 500 ns So, Average Access Time = ( 0.8 * 1 ) + ( 0.2 * 0.9 * 10 ) + ( 0.2 * 0.1 * 1 * 500) = 0.8 + 1.8 + 10 = 12.6 ns Thus, C is the correct choice. Quiz of this Question GATE IT 2004 GATE-GATE IT 2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25573, "s": 25545, "text": "\n19 Nov, 2018" }, { "code": null, "e": 26088, "s": 25573, "text": "Consider a system with 2 level caches. Access times of Level 1 cache, Level 2 cache and main memory are 1 ns, 10ns, and 500 ns, respectively. The hit rates of Level 1 and Level 2 caches are 0.8 and 0.9, respectively. What is the average access time of the system ignoring the search time within the cache?(A) 13.0 ns(B) 12.8 ns(C) 12.6 ns(D) 12.4 nsAnswer: (C)Explanation: First, the system will look in cache 1. If it is not found in cache 1, then cache 2 and then further in main memory (if not in cache 2 also)." }, { "code": null, "e": 26260, "s": 26088, "text": "The average access time would take into consideration success in cache 1, failure in cache 1 but success in cache 2, failure in both the caches and success in main memory." }, { "code": null, "e": 26326, "s": 26260, "text": "Average access time = [H1*T1]+[(1-H1)*H2*T2]+[(1-H1)(1-H2)*Hm*Tm]" }, { "code": null, "e": 26333, "s": 26326, "text": "where," }, { "code": null, "e": 26562, "s": 26333, "text": "H1 = Hit rate of level 1 cache = 0.8T1 = Access time for level 1 cache = 1 nsH2 = Hit rate of level 2 cache = 0.9T2 = Access time for level 2 cache = 10 nsHm = Hit rate of Main Memory = 1Tm = Access time for Main Memory = 500 ns" }, { "code": null, "e": 26650, "s": 26564, "text": "So, Average Access Time = ( 0.8 * 1 ) + ( 0.2 * 0.9 * 10 ) + ( 0.2 * 0.1 * 1 * 500)" }, { "code": null, "e": 26667, "s": 26650, "text": "= 0.8 + 1.8 + 10" }, { "code": null, "e": 26677, "s": 26667, "text": "= 12.6 ns" }, { "code": null, "e": 26708, "s": 26677, "text": "Thus, C is the correct choice." }, { "code": null, "e": 26731, "s": 26708, "text": " Quiz of this Question" }, { "code": null, "e": 26744, "s": 26731, "text": "GATE IT 2004" }, { "code": null, "e": 26762, "s": 26744, "text": "GATE-GATE IT 2004" }, { "code": null, "e": 26767, "s": 26762, "text": "GATE" }, { "code": null, "e": 26865, "s": 26767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26899, "s": 26865, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26933, "s": 26899, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26967, "s": 26933, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27000, "s": 26967, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27036, "s": 27000, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27072, "s": 27036, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27106, "s": 27072, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27140, "s": 27106, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27174, "s": 27140, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Coding Sheet in COBOL - GeeksforGeeks
06 Sep, 2021 Every language needs an environment or platform to write codes. For example, in Java, we use notepad to write codes then compile them to run. Similarly, COBOL requires a coding sheet to write codes. COBOL is a business-oriented high-level language. It was developed for business, finance, and administrative systems for companies and governments. COBOL made data processing easier and is a portable programming language. The full form of COBOL is COmmon, Business-Oriented Language. COBOL code statements are self-explanatory that even a layman would understand. However, it is a hated language but yet surviving. The reason for the survival of this language is that it is still used by the government, banks, and business organizations. As said earlier, COBOL code statements are self-explanatory but it is difficult to get started with. It is so because the COBOL coding sheet is rigid. A COBOL coding sheet is the COBOL coding structure. The coding sheet is divided into 80 columns. And each column or a particular set of columns are reserved for a particular type of field. The following table displays what column is reserved for what kind of field: Columns 1-6 are collectively called sequence numbers. The content of sequence number can be any computer character.1-3 columns are reserved for page numbers which automatically gets increased along with the lines of getting added to the program.4-6 columns are reserved for the line numbers. Line number increases with the number of lines of codes in the program.The use of the sequence number is optional and can be omitted. However, when sequence numbers are provided they must appear in ascending order. Columns 1-6 are collectively called sequence numbers. The content of sequence number can be any computer character. 1-3 columns are reserved for page numbers which automatically gets increased along with the lines of getting added to the program. 4-6 columns are reserved for the line numbers. Line number increases with the number of lines of codes in the program. The use of the sequence number is optional and can be omitted. However, when sequence numbers are provided they must appear in ascending order. This column is reserved for comments. Comment lines are actually some notes which reveal the intentions of the programmer.Comment lines can appear anywhere after the first line of the COBOL program.If the comment line begins with an asterisk(*) then the comment is not compiled to produce object code. Since they get ignored by the compiler, therefore, anything can be included as comments.However, if you begin your comment line with a character slash( / ) then that particular comment line gets printed after causing a page ejection (i.e., after skipping to the top of the next page). This column is reserved for comments. Comment lines are actually some notes which reveal the intentions of the programmer. Comment lines can appear anywhere after the first line of the COBOL program. If the comment line begins with an asterisk(*) then the comment is not compiled to produce object code. Since they get ignored by the compiler, therefore, anything can be included as comments. However, if you begin your comment line with a character slash( / ) then that particular comment line gets printed after causing a page ejection (i.e., after skipping to the top of the next page). Note: If needed, a statement of cobol program can be written in one or more coding lines. To continue in the next line the coder will have to use a hyphen (-) in column 7. Entries in these columns can be started from columns 8,9,10 or 11. Entries of this column are known as Margin-A entries.These columns are also known as Area-A.All the DIVISION headers, SECTION headers, PARAGRAPH headers, and PARAGRAPH names should start in Area-A.The coding of level number 01, as well as that of 77, should start in Area-A. Entries in these columns can be started from columns 8,9,10 or 11. Entries of this column are known as Margin-A entries. These columns are also known as Area-A. All the DIVISION headers, SECTION headers, PARAGRAPH headers, and PARAGRAPH names should start in Area-A. The coding of level number 01, as well as that of 77, should start in Area-A. Entries in these columns can be started anywhere from columns 12 to 72. Entries of these columns are known as Margin-B entries.These columns are also known as Area-B.All other statements apart from above i.e. all entries, sentences, and statements should start in Area-A.Clauses should be coded in Area-A. Entries in these columns can be started anywhere from columns 12 to 72. Entries of these columns are known as Margin-B entries. These columns are also known as Area-B. All other statements apart from above i.e. all entries, sentences, and statements should start in Area-A. Clauses should be coded in Area-A. Note: 1. Level numbers 02 to 49 can begin in either Area-A or Area-B and should be followed by a space or separator period. 2. Level numbers 66 and 88 can begin either in Area-A or Area-B and must be followed by space. These columns are used to write some identification. These are system-generated numbers.Everything written in 73-80 columns is ignored by the compiler.However, if a printed copy of the program is provided then the entries present in these columns get listed. These columns are used to write some identification. These are system-generated numbers. Everything written in 73-80 columns is ignored by the compiler. However, if a printed copy of the program is provided then the entries present in these columns get listed. Example: The above picture contains a program written in the COBOL coding sheet. All the entries have been made according to the column rules stated above. Sequence numbers aren’t compulsory to write but you must follow the column entry rules. Whenever we learn any new language, we first learn the alphabet. The alphabets of the COBOL language are known as character set in general. There are in total 50 different characters in the COBOL character set. They are listed as: Arithmetic operator Continuation character Arithmetic operator Comment character Arithmetic operator Comment character Arithmetic operator Relational character Punctuation mark Editing character Punctuation mark Editing character A COBOL character string is a set of adjacent characters that can form a COBOL word, a PICTURE character-string, or a comment. COBOL Word: A COBOL word can be formed using alphabetic characters, numeric characters, and hyphens. Following rules must be followed while forming COBOL words: A COBOL word can not begin or end with a hyphen.A COBOL word can have a maximum of 30 characters.One of the characters in a COBOL word must be a letter. According to some COBOL compilers, there is an additional restriction that the first character of the COBOL word must be a letter.No special character other than a hyphen is allowed when forming a COBOL word. A COBOL word can not begin or end with a hyphen. A COBOL word can have a maximum of 30 characters. One of the characters in a COBOL word must be a letter. According to some COBOL compilers, there is an additional restriction that the first character of the COBOL word must be a letter. No special character other than a hyphen is allowed when forming a COBOL word. There are two types of words in COBOL, they are user-defined and reserved words: 1. COBOL User-defined word: Data names and identifiers are the user-defined Cobol words. A data-name gives reference to the storage space in the memory where the actual value is stored. Data names are only one form of identifier. A data-name cannot be a reserved word. Example: In the above program, XX defined at level 01 is a user-defined word representing a group item named XX that contains table B. NOTE: Arrays in COBOL are known as tables. 2. Reserved word: Reserved words in COBOL have a specific purpose. For example: Example: The above program explains the functioning of reserved words given in examples. There are many reserved words other than the three stated and explained above. NOTE: Whenever you need to write equation in cobol then you must include whitespace between the operator and operand. Literals: A literal in COBOL is often called a constant as its value remains unchanged throughout the execution of the program. There are three types of literals, namely: numeric, non-numeric, and figurative constants. 1. Numeric: Numeric literals are formed with the help of digits. It can have a + sign or a – sign and can have a decimal point too. For a numeric literal to be positive there’s no need to specify the sign, however, if you want the literal to be negative, a – sign should be specified at the leftmost end. The decimal point in literals helps to identify whether the number is floating-point or integer. The maximum number of digits allowed in numeric literal is compiler dependent. 2. Nonnumeric: This type of literal is used as output messages or headings. A non-numeric literal is enclosed between two quotation marks. The number of characters that can be enclosed between the two quotation marks is compiler-dependent. 3. Figurative Constants: These are the reserved words that refer to specific constant values. For example: Consider the statement: MOVE ZERO TO A. Here the value 0 will be moved to the data name A. The word ZERO is a figurative constant having a value of 0. Some other examples of figurative constants are: ZEROS ZEROES SPACE SPACES HIGH-VALUE HIGH-VALUES LOW-VALUE LOW-VALUES QUOTE QUOTES Picked COBOL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? Find size of largest subset with bitwise AND greater than their bitwise XOR What is Transmission Control Protocol (TCP)? How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python?
[ { "code": null, "e": 24607, "s": 24579, "text": "\n06 Sep, 2021" }, { "code": null, "e": 25345, "s": 24607, "text": "Every language needs an environment or platform to write codes. For example, in Java, we use notepad to write codes then compile them to run. Similarly, COBOL requires a coding sheet to write codes. COBOL is a business-oriented high-level language. It was developed for business, finance, and administrative systems for companies and governments. COBOL made data processing easier and is a portable programming language. The full form of COBOL is COmmon, Business-Oriented Language. COBOL code statements are self-explanatory that even a layman would understand. However, it is a hated language but yet surviving. The reason for the survival of this language is that it is still used by the government, banks, and business organizations." }, { "code": null, "e": 25685, "s": 25345, "text": "As said earlier, COBOL code statements are self-explanatory but it is difficult to get started with. It is so because the COBOL coding sheet is rigid. A COBOL coding sheet is the COBOL coding structure. The coding sheet is divided into 80 columns. And each column or a particular set of columns are reserved for a particular type of field." }, { "code": null, "e": 25762, "s": 25685, "text": "The following table displays what column is reserved for what kind of field:" }, { "code": null, "e": 26269, "s": 25762, "text": "Columns 1-6 are collectively called sequence numbers. The content of sequence number can be any computer character.1-3 columns are reserved for page numbers which automatically gets increased along with the lines of getting added to the program.4-6 columns are reserved for the line numbers. Line number increases with the number of lines of codes in the program.The use of the sequence number is optional and can be omitted. However, when sequence numbers are provided they must appear in ascending order." }, { "code": null, "e": 26385, "s": 26269, "text": "Columns 1-6 are collectively called sequence numbers. The content of sequence number can be any computer character." }, { "code": null, "e": 26516, "s": 26385, "text": "1-3 columns are reserved for page numbers which automatically gets increased along with the lines of getting added to the program." }, { "code": null, "e": 26635, "s": 26516, "text": "4-6 columns are reserved for the line numbers. Line number increases with the number of lines of codes in the program." }, { "code": null, "e": 26779, "s": 26635, "text": "The use of the sequence number is optional and can be omitted. However, when sequence numbers are provided they must appear in ascending order." }, { "code": null, "e": 27366, "s": 26779, "text": "This column is reserved for comments. Comment lines are actually some notes which reveal the intentions of the programmer.Comment lines can appear anywhere after the first line of the COBOL program.If the comment line begins with an asterisk(*) then the comment is not compiled to produce object code. Since they get ignored by the compiler, therefore, anything can be included as comments.However, if you begin your comment line with a character slash( / ) then that particular comment line gets printed after causing a page ejection (i.e., after skipping to the top of the next page)." }, { "code": null, "e": 27489, "s": 27366, "text": "This column is reserved for comments. Comment lines are actually some notes which reveal the intentions of the programmer." }, { "code": null, "e": 27566, "s": 27489, "text": "Comment lines can appear anywhere after the first line of the COBOL program." }, { "code": null, "e": 27759, "s": 27566, "text": "If the comment line begins with an asterisk(*) then the comment is not compiled to produce object code. Since they get ignored by the compiler, therefore, anything can be included as comments." }, { "code": null, "e": 27956, "s": 27759, "text": "However, if you begin your comment line with a character slash( / ) then that particular comment line gets printed after causing a page ejection (i.e., after skipping to the top of the next page)." }, { "code": null, "e": 28128, "s": 27956, "text": "Note: If needed, a statement of cobol program can be written in one or more coding lines. To continue in the next line the coder will have to use a hyphen (-) in column 7." }, { "code": null, "e": 28470, "s": 28128, "text": "Entries in these columns can be started from columns 8,9,10 or 11. Entries of this column are known as Margin-A entries.These columns are also known as Area-A.All the DIVISION headers, SECTION headers, PARAGRAPH headers, and PARAGRAPH names should start in Area-A.The coding of level number 01, as well as that of 77, should start in Area-A." }, { "code": null, "e": 28591, "s": 28470, "text": "Entries in these columns can be started from columns 8,9,10 or 11. Entries of this column are known as Margin-A entries." }, { "code": null, "e": 28631, "s": 28591, "text": "These columns are also known as Area-A." }, { "code": null, "e": 28737, "s": 28631, "text": "All the DIVISION headers, SECTION headers, PARAGRAPH headers, and PARAGRAPH names should start in Area-A." }, { "code": null, "e": 28815, "s": 28737, "text": "The coding of level number 01, as well as that of 77, should start in Area-A." }, { "code": null, "e": 29121, "s": 28815, "text": "Entries in these columns can be started anywhere from columns 12 to 72. Entries of these columns are known as Margin-B entries.These columns are also known as Area-B.All other statements apart from above i.e. all entries, sentences, and statements should start in Area-A.Clauses should be coded in Area-A." }, { "code": null, "e": 29249, "s": 29121, "text": "Entries in these columns can be started anywhere from columns 12 to 72. Entries of these columns are known as Margin-B entries." }, { "code": null, "e": 29289, "s": 29249, "text": "These columns are also known as Area-B." }, { "code": null, "e": 29395, "s": 29289, "text": "All other statements apart from above i.e. all entries, sentences, and statements should start in Area-A." }, { "code": null, "e": 29430, "s": 29395, "text": "Clauses should be coded in Area-A." }, { "code": null, "e": 29436, "s": 29430, "text": "Note:" }, { "code": null, "e": 29554, "s": 29436, "text": "1. Level numbers 02 to 49 can begin in either Area-A or Area-B and should be followed by a space or separator period." }, { "code": null, "e": 29649, "s": 29554, "text": "2. Level numbers 66 and 88 can begin either in Area-A or Area-B and must be followed by space." }, { "code": null, "e": 29908, "s": 29649, "text": "These columns are used to write some identification. These are system-generated numbers.Everything written in 73-80 columns is ignored by the compiler.However, if a printed copy of the program is provided then the entries present in these columns get listed." }, { "code": null, "e": 29997, "s": 29908, "text": "These columns are used to write some identification. These are system-generated numbers." }, { "code": null, "e": 30061, "s": 29997, "text": "Everything written in 73-80 columns is ignored by the compiler." }, { "code": null, "e": 30169, "s": 30061, "text": "However, if a printed copy of the program is provided then the entries present in these columns get listed." }, { "code": null, "e": 30178, "s": 30169, "text": "Example:" }, { "code": null, "e": 30414, "s": 30178, "text": "The above picture contains a program written in the COBOL coding sheet. All the entries have been made according to the column rules stated above. Sequence numbers aren’t compulsory to write but you must follow the column entry rules. " }, { "code": null, "e": 30645, "s": 30414, "text": "Whenever we learn any new language, we first learn the alphabet. The alphabets of the COBOL language are known as character set in general. There are in total 50 different characters in the COBOL character set. They are listed as:" }, { "code": null, "e": 30665, "s": 30645, "text": "Arithmetic operator" }, { "code": null, "e": 30688, "s": 30665, "text": "Continuation character" }, { "code": null, "e": 30708, "s": 30688, "text": "Arithmetic operator" }, { "code": null, "e": 30726, "s": 30708, "text": "Comment character" }, { "code": null, "e": 30746, "s": 30726, "text": "Arithmetic operator" }, { "code": null, "e": 30764, "s": 30746, "text": "Comment character" }, { "code": null, "e": 30784, "s": 30764, "text": "Arithmetic operator" }, { "code": null, "e": 30805, "s": 30784, "text": "Relational character" }, { "code": null, "e": 30822, "s": 30805, "text": "Punctuation mark" }, { "code": null, "e": 30840, "s": 30822, "text": "Editing character" }, { "code": null, "e": 30857, "s": 30840, "text": "Punctuation mark" }, { "code": null, "e": 30875, "s": 30857, "text": "Editing character" }, { "code": null, "e": 31003, "s": 30875, "text": "A COBOL character string is a set of adjacent characters that can form a COBOL word, a PICTURE character-string, or a comment. " }, { "code": null, "e": 31164, "s": 31003, "text": "COBOL Word: A COBOL word can be formed using alphabetic characters, numeric characters, and hyphens. Following rules must be followed while forming COBOL words:" }, { "code": null, "e": 31526, "s": 31164, "text": "A COBOL word can not begin or end with a hyphen.A COBOL word can have a maximum of 30 characters.One of the characters in a COBOL word must be a letter. According to some COBOL compilers, there is an additional restriction that the first character of the COBOL word must be a letter.No special character other than a hyphen is allowed when forming a COBOL word." }, { "code": null, "e": 31575, "s": 31526, "text": "A COBOL word can not begin or end with a hyphen." }, { "code": null, "e": 31625, "s": 31575, "text": "A COBOL word can have a maximum of 30 characters." }, { "code": null, "e": 31812, "s": 31625, "text": "One of the characters in a COBOL word must be a letter. According to some COBOL compilers, there is an additional restriction that the first character of the COBOL word must be a letter." }, { "code": null, "e": 31891, "s": 31812, "text": "No special character other than a hyphen is allowed when forming a COBOL word." }, { "code": null, "e": 31972, "s": 31891, "text": "There are two types of words in COBOL, they are user-defined and reserved words:" }, { "code": null, "e": 32242, "s": 31972, "text": "1. COBOL User-defined word: Data names and identifiers are the user-defined Cobol words. A data-name gives reference to the storage space in the memory where the actual value is stored. Data names are only one form of identifier. A data-name cannot be a reserved word. " }, { "code": null, "e": 32251, "s": 32242, "text": "Example:" }, { "code": null, "e": 32378, "s": 32251, "text": "In the above program, XX defined at level 01 is a user-defined word representing a group item named XX that contains table B. " }, { "code": null, "e": 32421, "s": 32378, "text": "NOTE: Arrays in COBOL are known as tables." }, { "code": null, "e": 32488, "s": 32421, "text": "2. Reserved word: Reserved words in COBOL have a specific purpose." }, { "code": null, "e": 32502, "s": 32488, "text": "For example: " }, { "code": null, "e": 32511, "s": 32502, "text": "Example:" }, { "code": null, "e": 32670, "s": 32511, "text": "The above program explains the functioning of reserved words given in examples. There are many reserved words other than the three stated and explained above." }, { "code": null, "e": 32788, "s": 32670, "text": "NOTE: Whenever you need to write equation in cobol then you must include whitespace between the operator and operand." }, { "code": null, "e": 33007, "s": 32788, "text": "Literals: A literal in COBOL is often called a constant as its value remains unchanged throughout the execution of the program. There are three types of literals, namely: numeric, non-numeric, and figurative constants." }, { "code": null, "e": 33488, "s": 33007, "text": "1. Numeric: Numeric literals are formed with the help of digits. It can have a + sign or a – sign and can have a decimal point too. For a numeric literal to be positive there’s no need to specify the sign, however, if you want the literal to be negative, a – sign should be specified at the leftmost end. The decimal point in literals helps to identify whether the number is floating-point or integer. The maximum number of digits allowed in numeric literal is compiler dependent." }, { "code": null, "e": 33728, "s": 33488, "text": "2. Nonnumeric: This type of literal is used as output messages or headings. A non-numeric literal is enclosed between two quotation marks. The number of characters that can be enclosed between the two quotation marks is compiler-dependent." }, { "code": null, "e": 33823, "s": 33728, "text": "3. Figurative Constants: These are the reserved words that refer to specific constant values. " }, { "code": null, "e": 34037, "s": 33823, "text": "For example: Consider the statement: MOVE ZERO TO A. Here the value 0 will be moved to the data name A. The word ZERO is a figurative constant having a value of 0. Some other examples of figurative constants are: " }, { "code": null, "e": 34043, "s": 34037, "text": "ZEROS" }, { "code": null, "e": 34050, "s": 34043, "text": "ZEROES" }, { "code": null, "e": 34056, "s": 34050, "text": "SPACE" }, { "code": null, "e": 34063, "s": 34056, "text": "SPACES" }, { "code": null, "e": 34074, "s": 34063, "text": "HIGH-VALUE" }, { "code": null, "e": 34086, "s": 34074, "text": "HIGH-VALUES" }, { "code": null, "e": 34096, "s": 34086, "text": "LOW-VALUE" }, { "code": null, "e": 34107, "s": 34096, "text": "LOW-VALUES" }, { "code": null, "e": 34113, "s": 34107, "text": "QUOTE" }, { "code": null, "e": 34120, "s": 34113, "text": "QUOTES" }, { "code": null, "e": 34127, "s": 34120, "text": "Picked" }, { "code": null, "e": 34133, "s": 34127, "text": "COBOL" }, { "code": null, "e": 34231, "s": 34133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34263, "s": 34231, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 34316, "s": 34263, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 34371, "s": 34316, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 34447, "s": 34371, "text": "Find size of largest subset with bitwise AND greater than their bitwise XOR" }, { "code": null, "e": 34492, "s": 34447, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 34550, "s": 34492, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 34612, "s": 34550, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 34653, "s": 34612, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 34688, "s": 34653, "text": "Insert Image in a Jupyter Notebook" } ]
ML | Introduction to Kernel PCA - GeeksforGeeks
26 Aug, 2019 PRINCIPAL COMPONENT ANALYSIS: is a tool which is used to reduce the dimension of the data. It allows us to reduce the dimension of the data without much loss of information. PCA reduces the dimension by finding a few orthogonal linear combinations (principal components) of the original variables with the largest variance.The first principal component captures most of the variance in the data. The second principal component is orthogonal to the first principal component and captures the remaining variance, which is left of first principal component and so on. There are as many principal components as the number of original variables.These principal components are uncorrelated and are ordered in such a way that the first several principal components explain most of the variance of the original data. To learn more about PCA you can read the article Principal Component Analysis KERNEL PCA: PCA is a linear method. That is it can only be applied to datasets which are linearly separable. It does an excellent job for datasets, which are linearly separable. But, if we use it to non-linear datasets, we might get a result which may not be the optimal dimensionality reduction. Kernel PCA uses a kernel function to project dataset into a higher dimensional feature space, where it is linearly separable. It is similar to the idea of Support Vector Machines. There are various kernel methods like linear, polynomial, and gaussian. Code: Create a dataset which is nonlinear and then apply PCA on the dataset. import matplotlib.pyplot as pltfrom sklearn.datasets import make_moons X, y = make_moons(n_samples = 500, noise = 0.02, random_state = 417) plt.scatter(X[:, 0], X[:, 1], c = y)plt.show() Code: Let’s apply PCA on this dataset from sklearn.decomposition import PCApca = PCA(n_components = 2)X_pca = pca.fit_transform(X) plt.title("PCA")plt.scatter(X_pca[:, 0], X_pca[:, 1], c = y)plt.xlabel("Component 1")plt.ylabel("Component 2")plt.show() As you can see PCA failed to distinguish the two classes. Code: Applying kernel PCA on this dataset with RBF kernel with a gamma value of 15. from sklearn.decomposition import KernelPCAkpca = KernelPCA(kernel ='rbf', gamma = 15)X_kpca = kpca.fit_transform(X) plt.title("Kernel PCA")plt.scatter(X_kpca[:, 0], X_kpca[:, 1], c = y)plt.show() In the kernel space the two classes are linearly separable. Kernel PCA uses a kernel function to project the dataset into a higher-dimensional space, where it is linearly separable.Finally, we applied the kernel PCA to a non-linear dataset using scikit-learn. References:https://en.wikipedia.org/wiki/Kernel_principal_component_analysishttp://fourier.eng.hmc.edu/e161/lectures/kernelPCA/node4.html Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Markov Decision Process Singular Value Decomposition (SVD) k-nearest neighbor algorithm in Python SARSA Reinforcement Learning Q-Learning in Python
[ { "code": null, "e": 25615, "s": 25587, "text": "\n26 Aug, 2019" }, { "code": null, "e": 26502, "s": 25615, "text": "PRINCIPAL COMPONENT ANALYSIS: is a tool which is used to reduce the dimension of the data. It allows us to reduce the dimension of the data without much loss of information. PCA reduces the dimension by finding a few orthogonal linear combinations (principal components) of the original variables with the largest variance.The first principal component captures most of the variance in the data. The second principal component is orthogonal to the first principal component and captures the remaining variance, which is left of first principal component and so on. There are as many principal components as the number of original variables.These principal components are uncorrelated and are ordered in such a way that the first several principal components explain most of the variance of the original data. To learn more about PCA you can read the article Principal Component Analysis" }, { "code": null, "e": 26514, "s": 26502, "text": "KERNEL PCA:" }, { "code": null, "e": 26979, "s": 26514, "text": "PCA is a linear method. That is it can only be applied to datasets which are linearly separable. It does an excellent job for datasets, which are linearly separable. But, if we use it to non-linear datasets, we might get a result which may not be the optimal dimensionality reduction. Kernel PCA uses a kernel function to project dataset into a higher dimensional feature space, where it is linearly separable. It is similar to the idea of Support Vector Machines." }, { "code": null, "e": 27051, "s": 26979, "text": "There are various kernel methods like linear, polynomial, and gaussian." }, { "code": null, "e": 27128, "s": 27051, "text": "Code: Create a dataset which is nonlinear and then apply PCA on the dataset." }, { "code": "import matplotlib.pyplot as pltfrom sklearn.datasets import make_moons X, y = make_moons(n_samples = 500, noise = 0.02, random_state = 417) plt.scatter(X[:, 0], X[:, 1], c = y)plt.show()", "e": 27317, "s": 27128, "text": null }, { "code": null, "e": 27355, "s": 27317, "text": "Code: Let’s apply PCA on this dataset" }, { "code": "from sklearn.decomposition import PCApca = PCA(n_components = 2)X_pca = pca.fit_transform(X) plt.title(\"PCA\")plt.scatter(X_pca[:, 0], X_pca[:, 1], c = y)plt.xlabel(\"Component 1\")plt.ylabel(\"Component 2\")plt.show()", "e": 27571, "s": 27355, "text": null }, { "code": null, "e": 27713, "s": 27571, "text": "As you can see PCA failed to distinguish the two classes. Code: Applying kernel PCA on this dataset with RBF kernel with a gamma value of 15." }, { "code": "from sklearn.decomposition import KernelPCAkpca = KernelPCA(kernel ='rbf', gamma = 15)X_kpca = kpca.fit_transform(X) plt.title(\"Kernel PCA\")plt.scatter(X_kpca[:, 0], X_kpca[:, 1], c = y)plt.show()", "e": 27911, "s": 27713, "text": null }, { "code": null, "e": 28171, "s": 27911, "text": "In the kernel space the two classes are linearly separable. Kernel PCA uses a kernel function to project the dataset into a higher-dimensional space, where it is linearly separable.Finally, we applied the kernel PCA to a non-linear dataset using scikit-learn." }, { "code": null, "e": 28309, "s": 28171, "text": "References:https://en.wikipedia.org/wiki/Kernel_principal_component_analysishttp://fourier.eng.hmc.edu/e161/lectures/kernelPCA/node4.html" }, { "code": null, "e": 28326, "s": 28309, "text": "Machine Learning" }, { "code": null, "e": 28343, "s": 28326, "text": "Machine Learning" }, { "code": null, "e": 28441, "s": 28343, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28482, "s": 28441, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28515, "s": 28482, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28543, "s": 28515, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 28579, "s": 28543, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 28634, "s": 28579, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 28658, "s": 28634, "text": "Markov Decision Process" }, { "code": null, "e": 28693, "s": 28658, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 28732, "s": 28693, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 28761, "s": 28732, "text": "SARSA Reinforcement Learning" } ]
Program to check the number is Palindrome or not - GeeksforGeeks
14 Aug, 2021 Given an integer N, write a program that returns true if the given number is a palindrome, else return false. Examples: Input: N = 2002 Output: true Input: N = 1234 Output: false Approach: A simple method for this problem is to first reverse digits of n, then compare the reverse of n with n. If both are same, then return true, else false.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n = 4562; printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); n = 2002; printf("Is %d a Palindrome number? -> %s\n", n, isPalindrome(n) == 1 ? "true" : "false"); return 0;} // Java program to check whether a number// is Palindrome or not. class GFG{ /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check if n is Palindrome*/ static int isPalindrome(int n) { // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0; } /*Driver program to test reversDigits*/ public static void main(String []args) { int n = 4562; System.out.println("Is" + n + "a Palindrome number? -> " + (isPalindrome(n) == 1 ? "true" : "false")); n = 2002; System.out.println("Is" + n + "a Palindrome number? -> " + (isPalindrome(n) == 1 ? "true" : "false")); } } // This code is contributed// by Hritik Raj ( ihritik ) # Python3 program to check whether a# number is Palindrome or not. # Iterative function to reverse# digits of numdef reverseDigits(num) : rev_num = 0; while (num > 0) : rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to check if n is Palindromedef isPalindrome(n) : # get the reverse of n rev_n = reverseDigits(n); # Check if rev_n and n are same or not. if (rev_n == n) : return 1 else : return 0 # Driver Codeif __name__ == "__main__" : n = 4562 if isPalindrome(n) == 1 : print("Is", n, "a Palindrome number? ->", True) else : print("Is", n, "a Palindrome number? ->", False) n = 2002 if isPalindrome(n) == 1 : print("Is", n, "a Palindrome number? ->", True) else : print("Is", n, "a Palindrome number? ->", False) # This code is contributed by Ryuga // C# program to check whether a number// is Palindrome or not. using System;class GFG{ /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check if n is Palindrome*/ static int isPalindrome(int n) { // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0; } /*Driver program to test reversDigits*/ public static void Main() { int n = 4562; Console.WriteLine("Is" + n + "a Palindrome number? -> " + (isPalindrome(n) == 1 ? "true" : "false")); n = 2002; Console.WriteLine("Is" + n + "a Palindrome number? -> " + (isPalindrome(n) == 1 ? "true" : "false")); } } // This code is contributed// by Hritik Raj ( ihritik ) <?php// PHP program to check whether a number// is Palindrome or not. // Iterative function to reverse// digits of numfunction reverseDigits($num){ $rev_num = 0; while ($num > 0) { $rev_num = $rev_num * 10 + $num % 10; $num = $num / 10; } return $rev_num;} // Function to check if n is Palindromefunction isPalindrome($n){ // get the reverse of n $rev_n = reverseDigits($n); // Check if rev_n and n are same or not. if ($rev_n == $n) return 1; else return 0;} // Driver Code$n = 4562;echo "Is ", $n , " a Palindrome number? ->"; if(isPalindrome($n) == 1) echo "true" ;else echo "false";echo "\n"; $n = 2002;echo "Is ", $n , " a Palindrome number? ->";if(isPalindrome(!$n)) echo "true" ;else echo "false"; // This code is contributed by jit_t?> <script> // Javascript program to check whether a number// is Palindrome or not. /* Iterative function to reverse digits of num*/function reverseDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} /* Function to check if n is Palindrome*/function isPalindrome(n){ // get the reverse of n let rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/ let n = 4562; document.write("Is " + n + " a Palindrome number? -> ") document.write(isPalindrome(n) == 1 ? "true" : "false" + "<br>"); n = 2002; document.write("Is " + n + " a Palindrome number? -> ") document.write(isPalindrome(n) == 1 ? "true" : "false"); // This code is contributed by Mayank Tyagi </script> Is 4562 a Palindrome number? -> false Is 2002 a Palindrome number? -> true Time Complexity: O(logN) Auxiliary Space: O(1) ihritik ankthon jit_t mayanktyagi1709 pankajsharmagfg surindertarika1234 number-digits palindrome Snapdeal Algorithms Snapdeal palindrome Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples How to Start Learning DSA? Introduction to Algorithms Playfair Cipher with Examples Recursive Practice Problems with Solutions Difference between NP hard and NP complete problem Converting Roman Numerals to Decimal lying between 1 to 3999
[ { "code": null, "e": 26118, "s": 26090, "text": "\n14 Aug, 2021" }, { "code": null, "e": 26240, "s": 26118, "text": "Given an integer N, write a program that returns true if the given number is a palindrome, else return false. Examples: " }, { "code": null, "e": 26301, "s": 26240, "text": "Input: N = 2002 \nOutput: true\n\nInput: N = 1234\nOutput: false" }, { "code": null, "e": 26519, "s": 26305, "text": "Approach: A simple method for this problem is to first reverse digits of n, then compare the reverse of n with n. If both are same, then return true, else false.Below is the implementation of the above approach: " }, { "code": null, "e": 26523, "s": 26519, "text": "C++" }, { "code": null, "e": 26528, "s": 26523, "text": "Java" }, { "code": null, "e": 26536, "s": 26528, "text": "Python3" }, { "code": null, "e": 26539, "s": 26536, "text": "C#" }, { "code": null, "e": 26543, "s": 26539, "text": "PHP" }, { "code": null, "e": 26554, "s": 26543, "text": "Javascript" }, { "code": "// C program to check whether a number// is Palindrome or not. #include <stdio.h> /* Iterative function to reverse digits of num*/int reverseDigits(int num){ int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num;} /* Function to check if n is Palindrome*/int isPalindrome(int n){ // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/int main(){ int n = 4562; printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); n = 2002; printf(\"Is %d a Palindrome number? -> %s\\n\", n, isPalindrome(n) == 1 ? \"true\" : \"false\"); return 0;}", "e": 27379, "s": 26554, "text": null }, { "code": "// Java program to check whether a number// is Palindrome or not. class GFG{ /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check if n is Palindrome*/ static int isPalindrome(int n) { // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0; } /*Driver program to test reversDigits*/ public static void main(String []args) { int n = 4562; System.out.println(\"Is\" + n + \"a Palindrome number? -> \" + (isPalindrome(n) == 1 ? \"true\" : \"false\")); n = 2002; System.out.println(\"Is\" + n + \"a Palindrome number? -> \" + (isPalindrome(n) == 1 ? \"true\" : \"false\")); } } // This code is contributed// by Hritik Raj ( ihritik )", "e": 28460, "s": 27379, "text": null }, { "code": "# Python3 program to check whether a# number is Palindrome or not. # Iterative function to reverse# digits of numdef reverseDigits(num) : rev_num = 0; while (num > 0) : rev_num = rev_num * 10 + num % 10 num = num // 10 return rev_num # Function to check if n is Palindromedef isPalindrome(n) : # get the reverse of n rev_n = reverseDigits(n); # Check if rev_n and n are same or not. if (rev_n == n) : return 1 else : return 0 # Driver Codeif __name__ == \"__main__\" : n = 4562 if isPalindrome(n) == 1 : print(\"Is\", n, \"a Palindrome number? ->\", True) else : print(\"Is\", n, \"a Palindrome number? ->\", False) n = 2002 if isPalindrome(n) == 1 : print(\"Is\", n, \"a Palindrome number? ->\", True) else : print(\"Is\", n, \"a Palindrome number? ->\", False) # This code is contributed by Ryuga", "e": 29377, "s": 28460, "text": null }, { "code": "// C# program to check whether a number// is Palindrome or not. using System;class GFG{ /* Iterative function to reverse digits of num*/ static int reverseDigits(int num) { int rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } /* Function to check if n is Palindrome*/ static int isPalindrome(int n) { // get the reverse of n int rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0; } /*Driver program to test reversDigits*/ public static void Main() { int n = 4562; Console.WriteLine(\"Is\" + n + \"a Palindrome number? -> \" + (isPalindrome(n) == 1 ? \"true\" : \"false\")); n = 2002; Console.WriteLine(\"Is\" + n + \"a Palindrome number? -> \" + (isPalindrome(n) == 1 ? \"true\" : \"false\")); } } // This code is contributed// by Hritik Raj ( ihritik )", "e": 30454, "s": 29377, "text": null }, { "code": "<?php// PHP program to check whether a number// is Palindrome or not. // Iterative function to reverse// digits of numfunction reverseDigits($num){ $rev_num = 0; while ($num > 0) { $rev_num = $rev_num * 10 + $num % 10; $num = $num / 10; } return $rev_num;} // Function to check if n is Palindromefunction isPalindrome($n){ // get the reverse of n $rev_n = reverseDigits($n); // Check if rev_n and n are same or not. if ($rev_n == $n) return 1; else return 0;} // Driver Code$n = 4562;echo \"Is \", $n , \" a Palindrome number? ->\"; if(isPalindrome($n) == 1) echo \"true\" ;else echo \"false\";echo \"\\n\"; $n = 2002;echo \"Is \", $n , \" a Palindrome number? ->\";if(isPalindrome(!$n)) echo \"true\" ;else echo \"false\"; // This code is contributed by jit_t?>", "e": 31288, "s": 30454, "text": null }, { "code": "<script> // Javascript program to check whether a number// is Palindrome or not. /* Iterative function to reverse digits of num*/function reverseDigits(num){ let rev_num = 0; while (num > 0) { rev_num = rev_num * 10 + num % 10; num = Math.floor(num / 10); } return rev_num;} /* Function to check if n is Palindrome*/function isPalindrome(n){ // get the reverse of n let rev_n = reverseDigits(n); // Check if rev_n and n are same or not. if (rev_n == n) return 1; else return 0;} /*Driver program to test reversDigits*/ let n = 4562; document.write(\"Is \" + n + \" a Palindrome number? -> \") document.write(isPalindrome(n) == 1 ? \"true\" : \"false\" + \"<br>\"); n = 2002; document.write(\"Is \" + n + \" a Palindrome number? -> \") document.write(isPalindrome(n) == 1 ? \"true\" : \"false\"); // This code is contributed by Mayank Tyagi </script>", "e": 32202, "s": 31288, "text": null }, { "code": null, "e": 32277, "s": 32202, "text": "Is 4562 a Palindrome number? -> false\nIs 2002 a Palindrome number? -> true" }, { "code": null, "e": 32326, "s": 32279, "text": "Time Complexity: O(logN) Auxiliary Space: O(1)" }, { "code": null, "e": 32334, "s": 32326, "text": "ihritik" }, { "code": null, "e": 32342, "s": 32334, "text": "ankthon" }, { "code": null, "e": 32348, "s": 32342, "text": "jit_t" }, { "code": null, "e": 32364, "s": 32348, "text": "mayanktyagi1709" }, { "code": null, "e": 32380, "s": 32364, "text": "pankajsharmagfg" }, { "code": null, "e": 32399, "s": 32380, "text": "surindertarika1234" }, { "code": null, "e": 32413, "s": 32399, "text": "number-digits" }, { "code": null, "e": 32424, "s": 32413, "text": "palindrome" }, { "code": null, "e": 32433, "s": 32424, "text": "Snapdeal" }, { "code": null, "e": 32444, "s": 32433, "text": "Algorithms" }, { "code": null, "e": 32453, "s": 32444, "text": "Snapdeal" }, { "code": null, "e": 32464, "s": 32453, "text": "palindrome" }, { "code": null, "e": 32475, "s": 32464, "text": "Algorithms" }, { "code": null, "e": 32573, "s": 32475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32622, "s": 32573, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32647, "s": 32622, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32675, "s": 32647, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32726, "s": 32675, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 32753, "s": 32726, "text": "How to Start Learning DSA?" }, { "code": null, "e": 32780, "s": 32753, "text": "Introduction to Algorithms" }, { "code": null, "e": 32810, "s": 32780, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 32853, "s": 32810, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 32904, "s": 32853, "text": "Difference between NP hard and NP complete problem" } ]
Lexicographical concatenation of all substrings of a string - GeeksforGeeks
28 May, 2021 Given a string, find concatenation of all substrings in lexicographic order.Examples: Input : s = “abc” Output : aababcbbcc The substrings of s in lexicographic order are “a”, “b”, “c”, “ab”, “abc”, “bc”. Concatenation of substrings is “a”+”ab”+”abc”+”b”+”bc”+”c” = “aababcbbcc”.Input : s = “cba” Output : abbaccbcba 1. Find all the substrings of string and store it in a string array. The size of array would be n*(n+1)/2 where n is length of input string. 2. Sort the string array to make them all in lexicographical order. 3. Concatenate the strings of string array in another empty string. C++ Java Python3 C# Javascript // CPP Program to create concatenation of all// substrings in lexicographic order.#include <bits/stdc++.h>using namespace std; string lexicographicSubConcat(string s){ int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; string arr[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) arr[index++] = s.substr(i, len); // Sort all substrings in lexicographic // order sort(arr, arr + sub_count); // Concatenating all substrings string res = ""; for (int i = 0; i < sub_count; i++) res += arr[i]; return res; } int main(){ string s = "abc"; cout << lexicographicSubConcat(s); return 0;} // Java Program to create concatenation of all// substrings in lexicographic order.import java.util.*; class GFG{ static String lexicographicSubConcat(String s){ int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; String []arr = new String[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) { arr[index++] = s.substring(i, i+len); } // Sort all substrings in lexicographic // order Arrays.sort(arr); // Concatenating all substrings String res = ""; for (int i = 0; i < sub_count; i++) res += arr[i]; return res;} // Driver codepublic static void main(String[] args){ String s = "abc"; System.out.println(lexicographicSubConcat(s));}} // This code has been contributed by 29AjayKumar # Python Program to create concatenation of all# substrings in lexicographic order. def lexicographicSubConcat(s): n = len(s); # Creating an array to store substrings sub_count = (n * (n + 1))//2; arr = [0]*sub_count; # finding all substrings of string index = 0; for i in range(n): for j in range(1,n - i + 1): arr[index] = s[i:i + j]; index += 1; # Sort all substrings in lexicographic # order arr.sort(); # Concatenating all substrings res = ""; for i in range(sub_count): res += arr[i]; return res; s = "abc";print(lexicographicSubConcat(s)); # This code is contributed by Princi Singh // C# Program to create concatenation of all// substrings in lexicographic order.using System; class GFG{ static String lexicographicSubConcat(String s){ int n = s.Length; // Creating an array to store substrings int sub_count = n*(n+1)/2; String []arr = new String[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) { arr[index++] = s.Substring(i, len); } // Sort all substrings in lexicographic // order Array.Sort(arr); // Concatenating all substrings String res = ""; for (int i = 0; i < sub_count; i++) res += arr[i]; return res;} // Driver codepublic static void Main(String[] args){ String s = "abc"; Console.WriteLine(lexicographicSubConcat(s));}} /* This code contributed by PrinciRaj1992 */ <script> // Javascript Program to create concatenation of all// substrings in lexicographic order. function lexicographicSubConcat(s){ var n = s.length; // Creating an array to store substrings var sub_count = n*parseInt((n+1)/2); var arr = Array(sub_count); // finding all substrings of string var index = 0; for (var i = 0; i < n; i++) for (var len = 1; len <= n - i; len++) arr[index++] = s.substring(i,i+ len); // Sort all substrings in lexicographic // order arr.sort(); // Concatenating all substrings var res = ""; for (var i = 0; i < sub_count; i++) res += arr[i]; return res; } var s = "abc";document.write( lexicographicSubConcat(s)); </script> Output: aababcbbcc YouTubeGeeksforGeeks508K subscribersLexicographical concatenation of all substrings of a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=iUkj6mKrKSw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar princiraj1992 princi singh rrrtnx lexicographic-ordering Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem C++ Program for QuickSort Stability in sorting algorithms Quick Sort vs Merge Sort Quickselect Algorithm Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25321, "s": 25293, "text": "\n28 May, 2021" }, { "code": null, "e": 25409, "s": 25321, "text": "Given a string, find concatenation of all substrings in lexicographic order.Examples: " }, { "code": null, "e": 25642, "s": 25409, "text": "Input : s = “abc” Output : aababcbbcc The substrings of s in lexicographic order are “a”, “b”, “c”, “ab”, “abc”, “bc”. Concatenation of substrings is “a”+”ab”+”abc”+”b”+”bc”+”c” = “aababcbbcc”.Input : s = “cba” Output : abbaccbcba " }, { "code": null, "e": 25922, "s": 25644, "text": "1. Find all the substrings of string and store it in a string array. The size of array would be n*(n+1)/2 where n is length of input string. 2. Sort the string array to make them all in lexicographical order. 3. Concatenate the strings of string array in another empty string. " }, { "code": null, "e": 25926, "s": 25922, "text": "C++" }, { "code": null, "e": 25931, "s": 25926, "text": "Java" }, { "code": null, "e": 25939, "s": 25931, "text": "Python3" }, { "code": null, "e": 25942, "s": 25939, "text": "C#" }, { "code": null, "e": 25953, "s": 25942, "text": "Javascript" }, { "code": "// CPP Program to create concatenation of all// substrings in lexicographic order.#include <bits/stdc++.h>using namespace std; string lexicographicSubConcat(string s){ int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; string arr[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) arr[index++] = s.substr(i, len); // Sort all substrings in lexicographic // order sort(arr, arr + sub_count); // Concatenating all substrings string res = \"\"; for (int i = 0; i < sub_count; i++) res += arr[i]; return res; } int main(){ string s = \"abc\"; cout << lexicographicSubConcat(s); return 0;}", "e": 26753, "s": 25953, "text": null }, { "code": "// Java Program to create concatenation of all// substrings in lexicographic order.import java.util.*; class GFG{ static String lexicographicSubConcat(String s){ int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; String []arr = new String[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) { arr[index++] = s.substring(i, i+len); } // Sort all substrings in lexicographic // order Arrays.sort(arr); // Concatenating all substrings String res = \"\"; for (int i = 0; i < sub_count; i++) res += arr[i]; return res;} // Driver codepublic static void main(String[] args){ String s = \"abc\"; System.out.println(lexicographicSubConcat(s));}} // This code has been contributed by 29AjayKumar", "e": 27667, "s": 26753, "text": null }, { "code": "# Python Program to create concatenation of all# substrings in lexicographic order. def lexicographicSubConcat(s): n = len(s); # Creating an array to store substrings sub_count = (n * (n + 1))//2; arr = [0]*sub_count; # finding all substrings of string index = 0; for i in range(n): for j in range(1,n - i + 1): arr[index] = s[i:i + j]; index += 1; # Sort all substrings in lexicographic # order arr.sort(); # Concatenating all substrings res = \"\"; for i in range(sub_count): res += arr[i]; return res; s = \"abc\";print(lexicographicSubConcat(s)); # This code is contributed by Princi Singh", "e": 28360, "s": 27667, "text": null }, { "code": "// C# Program to create concatenation of all// substrings in lexicographic order.using System; class GFG{ static String lexicographicSubConcat(String s){ int n = s.Length; // Creating an array to store substrings int sub_count = n*(n+1)/2; String []arr = new String[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) { arr[index++] = s.Substring(i, len); } // Sort all substrings in lexicographic // order Array.Sort(arr); // Concatenating all substrings String res = \"\"; for (int i = 0; i < sub_count; i++) res += arr[i]; return res;} // Driver codepublic static void Main(String[] args){ String s = \"abc\"; Console.WriteLine(lexicographicSubConcat(s));}} /* This code contributed by PrinciRaj1992 */", "e": 29268, "s": 28360, "text": null }, { "code": "<script> // Javascript Program to create concatenation of all// substrings in lexicographic order. function lexicographicSubConcat(s){ var n = s.length; // Creating an array to store substrings var sub_count = n*parseInt((n+1)/2); var arr = Array(sub_count); // finding all substrings of string var index = 0; for (var i = 0; i < n; i++) for (var len = 1; len <= n - i; len++) arr[index++] = s.substring(i,i+ len); // Sort all substrings in lexicographic // order arr.sort(); // Concatenating all substrings var res = \"\"; for (var i = 0; i < sub_count; i++) res += arr[i]; return res; } var s = \"abc\";document.write( lexicographicSubConcat(s)); </script>", "e": 30017, "s": 29268, "text": null }, { "code": null, "e": 30027, "s": 30017, "text": "Output: " }, { "code": null, "e": 30038, "s": 30027, "text": "aababcbbcc" }, { "code": null, "e": 30898, "s": 30040, "text": "YouTubeGeeksforGeeks508K subscribersLexicographical concatenation of all substrings of a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:03•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=iUkj6mKrKSw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 30912, "s": 30900, "text": "29AjayKumar" }, { "code": null, "e": 30926, "s": 30912, "text": "princiraj1992" }, { "code": null, "e": 30939, "s": 30926, "text": "princi singh" }, { "code": null, "e": 30946, "s": 30939, "text": "rrrtnx" }, { "code": null, "e": 30969, "s": 30946, "text": "lexicographic-ordering" }, { "code": null, "e": 30977, "s": 30969, "text": "Sorting" }, { "code": null, "e": 30985, "s": 30977, "text": "Strings" }, { "code": null, "e": 30993, "s": 30985, "text": "Strings" }, { "code": null, "e": 31001, "s": 30993, "text": "Sorting" }, { "code": null, "e": 31099, "s": 31001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31130, "s": 31099, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31156, "s": 31130, "text": "C++ Program for QuickSort" }, { "code": null, "e": 31188, "s": 31156, "text": "Stability in sorting algorithms" }, { "code": null, "e": 31213, "s": 31188, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 31235, "s": 31213, "text": "Quickselect Algorithm" }, { "code": null, "e": 31281, "s": 31235, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31306, "s": 31281, "text": "Reverse a string in Java" }, { "code": null, "e": 31366, "s": 31306, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31381, "s": 31366, "text": "C++ Data Types" } ]
How many types of layouts are there in Bootstrap ? - GeeksforGeeks
20 Aug, 2021 Containers are the most basic layout element in Bootstrap and they are needed while using the default grid system. There are two major layouts for Bootstrap that are Fluid Layout and Fixed Layout. Fluid-layout: This uses the bootstrap .container-fluid class for the layout. This layout uses proportional values such as measuring units for a block of content, images, or any other item. Used for creating an element that is 100 % wider and covers all the screen widths. Fluid layout continuously resizes as you change the width of your browser by any amount, leaving no extra empty space on the sides ever Hence it is named “fluid layout”. Fixed-layout: This uses the bootstrap .container class for the layout. The fixed-layout has specific pixel width values that change its width value with the help of media queries. It provides a responsive fixed-width container. Fixed layout resizes in chunks at several certain widths as pixels values are specified. Step by step guide for the implementation: Step1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script> Step 2: Add <style> tag and add CSS properties to it that you need. Step 3: Create a new <div> for adding different layout classes. Step 4: Information must be placed within a .container (fixed layout) or .container-fluid (fluid layout) class for proper alignment and padding . Example 1: This example shows the fixed layout. HTML <!DOCTYPE html><html> <head> <title>Fixed Layout</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <style type="text/css"> body { padding-top: 50px; } </style></head> <body> <div class="container"> <!-- for page header --> <div class="jumbotron"> <h1>Fixed Layout</h1> <p> Also known as a .container layout. Fixed layout has specific pixel width values that change its width value with the help of media queries. It provides a responsive fixed width container. Fixed layout resizes in chunks at several certain widths so that's why its called as “fixed width” because pixels values are specified. </p> </div> </div></body> </html> Output: Fixed layout Example 2: This example shows the working of fluid layout. HTML <!DOCTYPE html><html> <head> <title>Bootstrap Fluid Layout</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script></head> <body> <div class="container-fluid"> <div class="jumbotron"> <h1>Fluid Layout</h1> <p> Also known as the .container-fluid layout. This layout uses proportional values such as measuring unit for a block of content, images or any other item. Used for creating an element that is 100 % wider and covers all the screen width. Fluid layout continuously resizes as you change the width of your browser by any amount, leaving no extra empty space on the sides ever Hence it is named as “fluid layout”. </p> </div> </div></body> </html> Output: Example 3: This example shows us the difference between fixed and fluid layouts. Different outputs are achieved for different screen sizes for fixed and fluid layouts. HTML <!DOCTYPE html><html> <head> <title>Bootstrap Layouts</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script></head> <body> <div class="container-fluid"> <div class="jumbotron"> <h1 style="color: green">Fluid Layout</h1> <p style="color: #000"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. If you’re preparing out for a tech interview with a product- based company or planning to do the same? Are you looking for a DSA Course? Don’t know how to begin with data structures and algorithms? .. Then you are at the right place. </p> </div> </div> <div class="container"> <div class="jumbotron"> <!-- for page header --> <h1 style="color: green">Fixed Layout</h1> <p style="color: #000"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. If you’re preparing out for a tech interview with a product- based company or planning to do the same? Are you looking for a DSA Course? Don’t know how to begin with data structures and algorithms? .. Then you are at the right place. </p> </div> </div></body> </html> Output: Note: Fixed layout resizes in chunks at several certain widths whereas fluid layout continuously resizes as you change the width of your browser by any amount. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-4 Bootstrap-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to keep gap between columns using Bootstrap? Tailwind CSS vs Bootstrap Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26889, "s": 26861, "text": "\n20 Aug, 2021" }, { "code": null, "e": 27087, "s": 26889, "text": "Containers are the most basic layout element in Bootstrap and they are needed while using the default grid system. There are two major layouts for Bootstrap that are Fluid Layout and Fixed Layout. " }, { "code": null, "e": 27529, "s": 27087, "text": "Fluid-layout: This uses the bootstrap .container-fluid class for the layout. This layout uses proportional values such as measuring units for a block of content, images, or any other item. Used for creating an element that is 100 % wider and covers all the screen widths. Fluid layout continuously resizes as you change the width of your browser by any amount, leaving no extra empty space on the sides ever Hence it is named “fluid layout”." }, { "code": null, "e": 27846, "s": 27529, "text": "Fixed-layout: This uses the bootstrap .container class for the layout. The fixed-layout has specific pixel width values that change its width value with the help of media queries. It provides a responsive fixed-width container. Fixed layout resizes in chunks at several certain widths as pixels values are specified." }, { "code": null, "e": 27889, "s": 27846, "text": "Step by step guide for the implementation:" }, { "code": null, "e": 27996, "s": 27889, "text": "Step1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 28277, "s": 27996, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js”></script>" }, { "code": null, "e": 28345, "s": 28277, "text": "Step 2: Add <style> tag and add CSS properties to it that you need." }, { "code": null, "e": 28409, "s": 28345, "text": "Step 3: Create a new <div> for adding different layout classes." }, { "code": null, "e": 28556, "s": 28409, "text": "Step 4: Information must be placed within a .container (fixed layout) or .container-fluid (fluid layout) class for proper alignment and padding . " }, { "code": null, "e": 28604, "s": 28556, "text": "Example 1: This example shows the fixed layout." }, { "code": null, "e": 28609, "s": 28604, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Fixed Layout</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script> <style type=\"text/css\"> body { padding-top: 50px; } </style></head> <body> <div class=\"container\"> <!-- for page header --> <div class=\"jumbotron\"> <h1>Fixed Layout</h1> <p> Also known as a .container layout. Fixed layout has specific pixel width values that change its width value with the help of media queries. It provides a responsive fixed width container. Fixed layout resizes in chunks at several certain widths so that's why its called as “fixed width” because pixels values are specified. </p> </div> </div></body> </html>", "e": 29725, "s": 28609, "text": null }, { "code": null, "e": 29733, "s": 29725, "text": "Output:" }, { "code": null, "e": 29746, "s": 29733, "text": "Fixed layout" }, { "code": null, "e": 29805, "s": 29746, "text": "Example 2: This example shows the working of fluid layout." }, { "code": null, "e": 29810, "s": 29805, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Fluid Layout</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container-fluid\"> <div class=\"jumbotron\"> <h1>Fluid Layout</h1> <p> Also known as the .container-fluid layout. This layout uses proportional values such as measuring unit for a block of content, images or any other item. Used for creating an element that is 100 % wider and covers all the screen width. Fluid layout continuously resizes as you change the width of your browser by any amount, leaving no extra empty space on the sides ever Hence it is named as “fluid layout”. </p> </div> </div></body> </html>", "e": 30948, "s": 29810, "text": null }, { "code": null, "e": 30956, "s": 30948, "text": "Output:" }, { "code": null, "e": 31124, "s": 30956, "text": "Example 3: This example shows us the difference between fixed and fluid layouts. Different outputs are achieved for different screen sizes for fixed and fluid layouts." }, { "code": null, "e": 31129, "s": 31124, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Layouts</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container-fluid\"> <div class=\"jumbotron\"> <h1 style=\"color: green\">Fluid Layout</h1> <p style=\"color: #000\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. If you’re preparing out for a tech interview with a product- based company or planning to do the same? Are you looking for a DSA Course? Don’t know how to begin with data structures and algorithms? .. Then you are at the right place. </p> </div> </div> <div class=\"container\"> <div class=\"jumbotron\"> <!-- for page header --> <h1 style=\"color: green\">Fixed Layout</h1> <p style=\"color: #000\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. If you’re preparing out for a tech interview with a product- based company or planning to do the same? Are you looking for a DSA Course? Don’t know how to begin with data structures and algorithms? .. Then you are at the right place. </p> </div> </div></body> </html>", "e": 33006, "s": 31129, "text": null }, { "code": null, "e": 33014, "s": 33006, "text": "Output:" }, { "code": null, "e": 33174, "s": 33014, "text": "Note: Fixed layout resizes in chunks at several certain widths whereas fluid layout continuously resizes as you change the width of your browser by any amount." }, { "code": null, "e": 33311, "s": 33174, "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": 33323, "s": 33311, "text": "Bootstrap-4" }, { "code": null, "e": 33343, "s": 33323, "text": "Bootstrap-Questions" }, { "code": null, "e": 33350, "s": 33343, "text": "Picked" }, { "code": null, "e": 33360, "s": 33350, "text": "Bootstrap" }, { "code": null, "e": 33365, "s": 33360, "text": "HTML" }, { "code": null, "e": 33382, "s": 33365, "text": "Web Technologies" }, { "code": null, "e": 33387, "s": 33382, "text": "HTML" }, { "code": null, "e": 33485, "s": 33387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33526, "s": 33485, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 33589, "s": 33526, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 33622, "s": 33589, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 33671, "s": 33622, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 33697, "s": 33671, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 33759, "s": 33697, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33809, "s": 33759, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33857, "s": 33809, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33917, "s": 33857, "text": "How to set the default value for an HTML <select> element ?" } ]
Difference between cerr and clog - GeeksforGeeks
18 Oct, 2021 In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. cerr and clog both are associated with the standard C error output stream stderr but the cerr is the unbuffered standard error stream whereas the clog is the buffered standard error stream. In this article, we will learn what is the difference between these two streams in detail with examples. cerr: It is the unbuffered standard error stream that is used to output the errors. This is an object of the ostream class similar to cout. It is unbuffered i.e, it is used when there is a need to display the error message immediately. As there is no buffer so it cannot store the error message to display it later. So simply as cerr is unbuffered it can not store the message. Example: C++ // c++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ cerr << "the message displayed is unbuffered"; return 0;} Output: clog: It is the buffered standard error stream that is used to output the errors. This is also an object of the ostream class similar to cout. It is buffered i.e, firstly the error message is inserted in the buffer, and then it is displayed on the screen. As there is a buffer so it can store the error message to display it later unlike cerr. So simply as clog is buffered it can not display the message immediately. clog is commonly used for logging purposes. For non-critical event logging, efficiency is more important so clog is preferred to cerr. Example: C++ // C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ clog << "the message displayed is buffered"; return 0;} Output: Difference Table: cerr clog CPP-Basics Articles C++ C++ Programs Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures SQL | Date functions Difference between Min Heap and Max Heap Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 24396, "s": 24368, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24799, "s": 24396, "text": "In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. cerr and clog both are associated with the standard C error output stream stderr but the cerr is the unbuffered standard error stream whereas the clog is the buffered standard error stream. In this article, we will learn what is the difference between these two streams in detail with examples." }, { "code": null, "e": 25180, "s": 24799, "text": "cerr: It is the unbuffered standard error stream that is used to output the errors. This is an object of the ostream class similar to cout. It is unbuffered i.e, it is used when there is a need to display the error message immediately. As there is no buffer so it cannot store the error message to display it later. So simply as cerr is unbuffered it can not store the message." }, { "code": null, "e": 25189, "s": 25180, "text": "Example:" }, { "code": null, "e": 25193, "s": 25189, "text": "C++" }, { "code": "// c++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ cerr << \"the message displayed is unbuffered\"; return 0;}", "e": 25372, "s": 25193, "text": null }, { "code": null, "e": 25380, "s": 25372, "text": "Output:" }, { "code": null, "e": 25936, "s": 25380, "text": "clog: It is the buffered standard error stream that is used to output the errors. This is also an object of the ostream class similar to cout. It is buffered i.e, firstly the error message is inserted in the buffer, and then it is displayed on the screen. As there is a buffer so it can store the error message to display it later unlike cerr. So simply as clog is buffered it can not display the message immediately. clog is commonly used for logging purposes. For non-critical event logging, efficiency is more important so clog is preferred to cerr." }, { "code": null, "e": 25945, "s": 25936, "text": "Example:" }, { "code": null, "e": 25949, "s": 25945, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Driver codeint main(){ clog << \"the message displayed is buffered\"; return 0;}", "e": 26126, "s": 25949, "text": null }, { "code": null, "e": 26134, "s": 26126, "text": "Output:" }, { "code": null, "e": 26152, "s": 26134, "text": "Difference Table:" }, { "code": null, "e": 26157, "s": 26152, "text": "cerr" }, { "code": null, "e": 26162, "s": 26157, "text": "clog" }, { "code": null, "e": 26173, "s": 26162, "text": "CPP-Basics" }, { "code": null, "e": 26182, "s": 26173, "text": "Articles" }, { "code": null, "e": 26186, "s": 26182, "text": "C++" }, { "code": null, "e": 26199, "s": 26186, "text": "C++ Programs" }, { "code": null, "e": 26218, "s": 26199, "text": "Difference Between" }, { "code": null, "e": 26222, "s": 26218, "text": "CPP" }, { "code": null, "e": 26320, "s": 26222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26357, "s": 26320, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 26383, "s": 26357, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26430, "s": 26383, "text": "Time complexities of different data structures" }, { "code": null, "e": 26451, "s": 26430, "text": "SQL | Date functions" }, { "code": null, "e": 26492, "s": 26451, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 26510, "s": 26492, "text": "Vector in C++ STL" }, { "code": null, "e": 26526, "s": 26510, "text": "Arrays in C/C++" }, { "code": null, "e": 26572, "s": 26526, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26591, "s": 26572, "text": "Inheritance in C++" } ]
Construct a BST from given postorder traversal using Stack - GeeksforGeeks
01 Jul, 2021 Given postorder traversal of a binary search tree, construct the BST.For example, 1. If the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50 Input : 1 7 5 50 40 10 Output : Inorder traversal of the constructed tree: 1 5 7 10 40 50 If the given traversal is {2, 6, 4, 9, 13, 11, 7}, then following tree should be constructed and root of the tree should be returned. 7 / \ 4 11 / \ / \ 2 6 9 13 Input : 2 6 4 9 13 11 7 Output : Inorder traversal of the constructed tree: 2 4 6 7 9 11 13 Let us first see working Postorder traversal. Left Right Root Hence last node of post order will be root of tree, create it and push to stack. If next element(i-1) is greater then it should be in right subtree. If next element(i-1) is less then it should be in left subtree. Algorithm: Push root of the BST to the stack i.e, last element of the array. Start traversing the array in reverse, if next element is > the element at the top of the stack then, set this element as the right child of the element at the top of the stack and also push it to the stack. Else if, next element is < the element at the top of the stack then, start popping all the elements from the stack until either the stack is empty or the current element becomes > the element at the top of the stack. Make this element left child of the last popped node and repeat the above steps until the array is traversed completely. Below is the implementation of the above algorithm. C++ Java Python3 C# Javascript // C++ implementation of the algorithm/* A binary tree node has data,pointer to left child and a pointerto right child */#include<bits/stdc++.h>using namespace std; // Class Node has data and references// to the left and the right child.class Node{ public: int data; Node* left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Function that creates the treeNode* constructTreeUtil(int post[], int n){ // Last node is root Node* root = new Node(post[n - 1]); stack<Node*> s; s.push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node* x = new Node(post[i]); // Keep popping nodes while top() // of stack is greater. Node* temp = NULL; while (s.size() && post[i] < s.top()->data) temp = s.top(), s.pop(); // Make x as left child of temp if (temp != NULL) temp->left = x; // Else make x as right of top else s.top()->right = x; s.push(x); } return root;} // Function that calls the method// which contructs the treeNode* constructTree(int post[], int size){ return constructTreeUtil(post, size);} // A utility function to print// inorder traversal of a Binary Treevoid printInorder(Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right);} // Driver Codeint main(){ int post[] = { 1, 7, 5, 50, 40, 10 }; int size = sizeof(post)/sizeof(int); Node* root = constructTree(post, size); cout << "Inorder traversal of " << "the constructed tree:\n"; printInorder(root);} // This code is contributed by Arnab Kundu // Java implementation of the algorithm/* A binary tree node has data, pointer to left childand a pointer to right child */import java.util.*; // Class Node has data and references to the left// and the right child.class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; }} class BinaryTree { // Function that creates the tree Node constructTreeUtil(int post[], int n) { // Last node is root Node root = new Node(post[n - 1]); Stack<Node> s = new Stack<>(); s.push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. Node temp = null; while (!s.isEmpty() && post[i] < s.peek().data) temp = s.pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s.peek().right = x; s.push(x); } return root; } // Function that calls the method which contructs the tree Node constructTree(int post[], int size) { return constructTreeUtil(post, size); } // A utility function to print inorder traversal // of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int post[] = new int[] { 1, 7, 5, 50, 40, 10 }; int size = post.length; Node root = tree.constructTree(post, size); System.out.println("Inorder traversal of the constructed tree:"); tree.printInorder(root); }} # Python3 implementation of the algorithm# A binary tree node has data,# pointer to left child and a pointer# to right child # Class Node has data and references# to the left and the right child.class Node: def __init__(self, data = 0): self.data = data self.left = None self.right = None # Function that creates the treedef constructTreeUtil(post , n): # Last node is root root = Node(post[n - 1]) s = [] s.append(root) i = n - 2 # Traverse from second last node while ( i >= 0): x = Node(post[i]) # Keep popping nodes while top() # of stack is greater. temp = None while (len(s) > 0 and post[i] < s[-1].data) : temp = s[-1] s.pop() # Make x as left child of temp if (temp != None): temp.left = x # Else make x as right of top else: s[-1].right = x s.append(x) i = i - 1 return root # Function that calls the method# which contructs the treedef constructTree( post, size): return constructTreeUtil(post, size) # A utility function to print# inorder traversal of a Binary Treedef printInorder( node): if (node == None): return printInorder(node.left) print( node.data, end = " ") printInorder(node.right) # Driver Codepost = [1, 7, 5, 50, 40, 10]size = len(post) root = constructTree(post, size) print( "Inorder traversal of the constructed tree:")printInorder(root) # This code is contributed by Arnab Kundu // C# implementation of the algorithm /* A binary tree node has data,pointer to left childand a pointer to right child */using System;using System.Collections.Generic; // Class Node has data and references // to the left and the right child.public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ // Function that creates the tree Node constructTreeUtil(int []post, int n) { // Last node is root Node root = new Node(post[n - 1]); Stack<Node> s = new Stack<Node>(); s.Push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. Node temp = null; while (s.Count!=0 && post[i] < s.Peek().data) temp = s.Pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s.Peek().right = x; s.Push(x); } return root; } // Function that calls the // method which contructs the tree Node constructTree(int []post, int size) { return constructTreeUtil(post, size); } // A utility function to print // inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); int []post = new int[] { 1, 7, 5, 50, 40, 10 }; int size = post.Length; Node root = tree.constructTree(post, size); Console.WriteLine("Inorder traversal of the constructed tree:"); tree.printInorder(root); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript implementation of the algorithm /* A binary tree node has data,pointer to left childand a pointer to right child */ // Class Node has data and references // to the left and the right child.class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Function that creates the treefunction constructTreeUtil(post, n){ // Last node is root var root = new Node(post[n - 1]); var s = []; s.push(root); // Traverse from second last node for (var i = n - 2; i >= 0; --i) { var x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. var temp = null; while (s.length!=0 && post[i] < s[s.length-1].data) temp = s.pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s[s.length-1].right = x; s.push(x); } return root;}// Function that calls the// method which contructs the treefunction constructTree(post, size){ return constructTreeUtil(post, size);}// A utility function to print // inorder traversal of a Binary Treefunction printInorder(node){ if (node == null) return; printInorder(node.left); document.write(node.data + " "); printInorder(node.right);}// Driver codevar post = [1, 7, 5, 50, 40, 10];var size = post.length;var root = constructTree(post, size);document.write("Inorder traversal of the constructed tree:<br>");printInorder(root); </script> Inorder traversal of the constructed tree: 1 5 7 10 40 50 princiraj1992 andrew1234 rrrtnx tree-traversal Binary Search Tree Stack Stack Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Red Black Tree vs AVL Tree set vs unordered_set in C++ STL Print BST keys in the given range Implementing Forward Iterator in BST Construct BST from given preorder traversal | Set 2 Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Inorder Tree Traversal without Recursion Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24835, "s": 24807, "text": "\n01 Jul, 2021" }, { "code": null, "e": 25054, "s": 24835, "text": "Given postorder traversal of a binary search tree, construct the BST.For example, 1. If the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. " }, { "code": null, "e": 25110, "s": 25054, "text": " 10\n / \\\n 5 40\n / \\ \\\n1 7 50" }, { "code": null, "e": 25338, "s": 25112, "text": "Input : 1 7 5 50 40 10 Output : Inorder traversal of the constructed tree: 1 5 7 10 40 50 If the given traversal is {2, 6, 4, 9, 13, 11, 7}, then following tree should be constructed and root of the tree should be returned. " }, { "code": null, "e": 25403, "s": 25338, "text": " 7\n / \\\n 4 11\n / \\ / \\\n 2 6 9 13" }, { "code": null, "e": 25496, "s": 25403, "text": "Input : 2 6 4 9 13 11 7 Output : Inorder traversal of the constructed tree: 2 4 6 7 9 11 13 " }, { "code": null, "e": 25546, "s": 25498, "text": "Let us first see working Postorder traversal. " }, { "code": null, "e": 25776, "s": 25546, "text": "Left\nRight \nRoot\nHence last node of post order will be root of tree, create it and push to stack.\nIf next element(i-1) is greater then it should be in right subtree.\nIf next element(i-1) is less then it should be in left subtree." }, { "code": null, "e": 25789, "s": 25776, "text": "Algorithm: " }, { "code": null, "e": 25855, "s": 25789, "text": "Push root of the BST to the stack i.e, last element of the array." }, { "code": null, "e": 26063, "s": 25855, "text": "Start traversing the array in reverse, if next element is > the element at the top of the stack then, set this element as the right child of the element at the top of the stack and also push it to the stack." }, { "code": null, "e": 26280, "s": 26063, "text": "Else if, next element is < the element at the top of the stack then, start popping all the elements from the stack until either the stack is empty or the current element becomes > the element at the top of the stack." }, { "code": null, "e": 26401, "s": 26280, "text": "Make this element left child of the last popped node and repeat the above steps until the array is traversed completely." }, { "code": null, "e": 26454, "s": 26401, "text": "Below is the implementation of the above algorithm. " }, { "code": null, "e": 26458, "s": 26454, "text": "C++" }, { "code": null, "e": 26463, "s": 26458, "text": "Java" }, { "code": null, "e": 26471, "s": 26463, "text": "Python3" }, { "code": null, "e": 26474, "s": 26471, "text": "C#" }, { "code": null, "e": 26485, "s": 26474, "text": "Javascript" }, { "code": "// C++ implementation of the algorithm/* A binary tree node has data,pointer to left child and a pointerto right child */#include<bits/stdc++.h>using namespace std; // Class Node has data and references// to the left and the right child.class Node{ public: int data; Node* left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Function that creates the treeNode* constructTreeUtil(int post[], int n){ // Last node is root Node* root = new Node(post[n - 1]); stack<Node*> s; s.push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node* x = new Node(post[i]); // Keep popping nodes while top() // of stack is greater. Node* temp = NULL; while (s.size() && post[i] < s.top()->data) temp = s.top(), s.pop(); // Make x as left child of temp if (temp != NULL) temp->left = x; // Else make x as right of top else s.top()->right = x; s.push(x); } return root;} // Function that calls the method// which contructs the treeNode* constructTree(int post[], int size){ return constructTreeUtil(post, size);} // A utility function to print// inorder traversal of a Binary Treevoid printInorder(Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data << \" \"; printInorder(node->right);} // Driver Codeint main(){ int post[] = { 1, 7, 5, 50, 40, 10 }; int size = sizeof(post)/sizeof(int); Node* root = constructTree(post, size); cout << \"Inorder traversal of \" << \"the constructed tree:\\n\"; printInorder(root);} // This code is contributed by Arnab Kundu", "e": 28244, "s": 26485, "text": null }, { "code": "// Java implementation of the algorithm/* A binary tree node has data, pointer to left childand a pointer to right child */import java.util.*; // Class Node has data and references to the left// and the right child.class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; }} class BinaryTree { // Function that creates the tree Node constructTreeUtil(int post[], int n) { // Last node is root Node root = new Node(post[n - 1]); Stack<Node> s = new Stack<>(); s.push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. Node temp = null; while (!s.isEmpty() && post[i] < s.peek().data) temp = s.pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s.peek().right = x; s.push(x); } return root; } // Function that calls the method which contructs the tree Node constructTree(int post[], int size) { return constructTreeUtil(post, size); } // A utility function to print inorder traversal // of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right); } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int post[] = new int[] { 1, 7, 5, 50, 40, 10 }; int size = post.length; Node root = tree.constructTree(post, size); System.out.println(\"Inorder traversal of the constructed tree:\"); tree.printInorder(root); }}", "e": 30248, "s": 28244, "text": null }, { "code": "# Python3 implementation of the algorithm# A binary tree node has data,# pointer to left child and a pointer# to right child # Class Node has data and references# to the left and the right child.class Node: def __init__(self, data = 0): self.data = data self.left = None self.right = None # Function that creates the treedef constructTreeUtil(post , n): # Last node is root root = Node(post[n - 1]) s = [] s.append(root) i = n - 2 # Traverse from second last node while ( i >= 0): x = Node(post[i]) # Keep popping nodes while top() # of stack is greater. temp = None while (len(s) > 0 and post[i] < s[-1].data) : temp = s[-1] s.pop() # Make x as left child of temp if (temp != None): temp.left = x # Else make x as right of top else: s[-1].right = x s.append(x) i = i - 1 return root # Function that calls the method# which contructs the treedef constructTree( post, size): return constructTreeUtil(post, size) # A utility function to print# inorder traversal of a Binary Treedef printInorder( node): if (node == None): return printInorder(node.left) print( node.data, end = \" \") printInorder(node.right) # Driver Codepost = [1, 7, 5, 50, 40, 10]size = len(post) root = constructTree(post, size) print( \"Inorder traversal of the constructed tree:\")printInorder(root) # This code is contributed by Arnab Kundu", "e": 31774, "s": 30248, "text": null }, { "code": "// C# implementation of the algorithm /* A binary tree node has data,pointer to left childand a pointer to right child */using System;using System.Collections.Generic; // Class Node has data and references // to the left and the right child.public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ // Function that creates the tree Node constructTreeUtil(int []post, int n) { // Last node is root Node root = new Node(post[n - 1]); Stack<Node> s = new Stack<Node>(); s.Push(root); // Traverse from second last node for (int i = n - 2; i >= 0; --i) { Node x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. Node temp = null; while (s.Count!=0 && post[i] < s.Peek().data) temp = s.Pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s.Peek().right = x; s.Push(x); } return root; } // Function that calls the // method which contructs the tree Node constructTree(int []post, int size) { return constructTreeUtil(post, size); } // A utility function to print // inorder traversal of a Binary Tree void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); int []post = new int[] { 1, 7, 5, 50, 40, 10 }; int size = post.Length; Node root = tree.constructTree(post, size); Console.WriteLine(\"Inorder traversal of the constructed tree:\"); tree.printInorder(root); }} /* This code contributed by PrinciRaj1992 */", "e": 33849, "s": 31774, "text": null }, { "code": "<script> // JavaScript implementation of the algorithm /* A binary tree node has data,pointer to left childand a pointer to right child */ // Class Node has data and references // to the left and the right child.class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Function that creates the treefunction constructTreeUtil(post, n){ // Last node is root var root = new Node(post[n - 1]); var s = []; s.push(root); // Traverse from second last node for (var i = n - 2; i >= 0; --i) { var x = new Node(post[i]); // Keep popping nodes while top() of stack // is greater. var temp = null; while (s.length!=0 && post[i] < s[s.length-1].data) temp = s.pop(); // Make x as left child of temp if (temp != null) temp.left = x; // Else make x as right of top else s[s.length-1].right = x; s.push(x); } return root;}// Function that calls the// method which contructs the treefunction constructTree(post, size){ return constructTreeUtil(post, size);}// A utility function to print // inorder traversal of a Binary Treefunction printInorder(node){ if (node == null) return; printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right);}// Driver codevar post = [1, 7, 5, 50, 40, 10];var size = post.length;var root = constructTree(post, size);document.write(\"Inorder traversal of the constructed tree:<br>\");printInorder(root); </script>", "e": 35440, "s": 33849, "text": null }, { "code": null, "e": 35498, "s": 35440, "text": "Inorder traversal of the constructed tree:\n1 5 7 10 40 50" }, { "code": null, "e": 35514, "s": 35500, "text": "princiraj1992" }, { "code": null, "e": 35525, "s": 35514, "text": "andrew1234" }, { "code": null, "e": 35532, "s": 35525, "text": "rrrtnx" }, { "code": null, "e": 35547, "s": 35532, "text": "tree-traversal" }, { "code": null, "e": 35566, "s": 35547, "text": "Binary Search Tree" }, { "code": null, "e": 35572, "s": 35566, "text": "Stack" }, { "code": null, "e": 35578, "s": 35572, "text": "Stack" }, { "code": null, "e": 35597, "s": 35578, "text": "Binary Search Tree" }, { "code": null, "e": 35695, "s": 35597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35704, "s": 35695, "text": "Comments" }, { "code": null, "e": 35717, "s": 35704, "text": "Old Comments" }, { "code": null, "e": 35744, "s": 35717, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 35776, "s": 35744, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 35810, "s": 35776, "text": "Print BST keys in the given range" }, { "code": null, "e": 35847, "s": 35810, "text": "Implementing Forward Iterator in BST" }, { "code": null, "e": 35899, "s": 35847, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 35947, "s": 35899, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35967, "s": 35947, "text": "Stack Class in Java" }, { "code": null, "e": 35983, "s": 35967, "text": "Stack in Python" }, { "code": null, "e": 36024, "s": 35983, "text": "Inorder Tree Traversal without Recursion" } ]
CSS Outline - GeeksforGeeks
21 Oct, 2021 The outline CSS shorthand property allows drawing a line around the element, outside the border. It is used to set all the properties of the outline in a single declaration. CSS outline properties can be categorized into 4 types, namely, Outline-style, Outline-color, Outline-width & Outline-offset. We will discuss all the types of outline properties sequentially through the examples. Properties: There are lots of properties comes under the CSS outline collection all of them are well described with the example. Outline-style: It is used to set the appearance of the outline of an element ie., it tells us the style or type of outline. Any other outline property cannot be accessed without setting the outline-style. If absent then the default style will be set to none. Syntax: outline-style: auto|none|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit; Example: This example illustrates the Outline property where the style is set to the dotted lines. HTML <!DOCTYPE html><html><head> <style> .dotted { outline-style: dotted; color: green; text-align: center; } </style></head> <body > <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p class="dotted">A Computer Science portal for geeks.</p> </body></html> Output: Outline-color: It is used to sets the outline color of an element. The color can be set by its name ie., rgb value or a hex value, etc. If absent then the default color will be the current color. Syntax: outline-color: <color> | invert | inherit; Example: This example illustrates the Outline property where the color is set to the specific color value. HTML <!DOCTYPE html><html><head> <style> p { border: solid orange 4px; outline-style: solid; outline-color: green; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html> Output: Outline-width: It is used to specify the width of this outline for a specific element. The width of the outline can be set by specifying the size of the width in px, cm, pt, etc, or by using terms like a thin, thick, medium. If absent then the default width will be the medium. Syntax: outline-width: medium|thin|thick|length|initial|inherit; Example: This example illustrates the Outline property where the width is set to the specific value. HTML <!DOCTYPE html><html><head> <style> p { border: solid green 4px; outline-style: solid; outline-width: 3px; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html> Output: Outline-offset: The CSS outline-offset Property sets the amount of space between an outline and the edge or border of an element. An outline is a line drawn around elements outside the border edge. The space between the element and its outline is transparent. Also, the outline may be non-rectangular. The default value is 0. Syntax: outline-offset: length|initial|inherit; Example: This example illustrates the Outline property where the offset is defined with a specific value. HTML <!DOCTYPE html><html><head> <style> p { border: solid green 3px; outline-style: solid; outline-offset: 3px; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html> Output: Supported Browsers: Google Chrome 1.0 Microsoft Edge 12.0 Internet Explorer 8.0 Firefox 1.5 Opera 7.0 Safari 1.2 bhaskargeeksforgeeks CSS-Advanced CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) 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": 27655, "s": 27627, "text": "\n21 Oct, 2021" }, { "code": null, "e": 28042, "s": 27655, "text": "The outline CSS shorthand property allows drawing a line around the element, outside the border. It is used to set all the properties of the outline in a single declaration. CSS outline properties can be categorized into 4 types, namely, Outline-style, Outline-color, Outline-width & Outline-offset. We will discuss all the types of outline properties sequentially through the examples." }, { "code": null, "e": 28171, "s": 28042, "text": "Properties: There are lots of properties comes under the CSS outline collection all of them are well described with the example." }, { "code": null, "e": 28430, "s": 28171, "text": "Outline-style: It is used to set the appearance of the outline of an element ie., it tells us the style or type of outline. Any other outline property cannot be accessed without setting the outline-style. If absent then the default style will be set to none." }, { "code": null, "e": 28438, "s": 28430, "text": "Syntax:" }, { "code": null, "e": 28533, "s": 28438, "text": "outline-style: auto|none|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit;" }, { "code": null, "e": 28632, "s": 28533, "text": "Example: This example illustrates the Outline property where the style is set to the dotted lines." }, { "code": null, "e": 28637, "s": 28632, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> .dotted { outline-style: dotted; color: green; text-align: center; } </style></head> <body > <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p class=\"dotted\">A Computer Science portal for geeks.</p> </body></html>", "e": 28933, "s": 28637, "text": null }, { "code": null, "e": 28941, "s": 28933, "text": "Output:" }, { "code": null, "e": 29137, "s": 28941, "text": "Outline-color: It is used to sets the outline color of an element. The color can be set by its name ie., rgb value or a hex value, etc. If absent then the default color will be the current color." }, { "code": null, "e": 29145, "s": 29137, "text": "Syntax:" }, { "code": null, "e": 29188, "s": 29145, "text": "outline-color: <color> | invert | inherit;" }, { "code": null, "e": 29295, "s": 29188, "text": "Example: This example illustrates the Outline property where the color is set to the specific color value." }, { "code": null, "e": 29300, "s": 29295, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> p { border: solid orange 4px; outline-style: solid; outline-color: green; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html>", "e": 29614, "s": 29300, "text": null }, { "code": null, "e": 29622, "s": 29614, "text": "Output:" }, { "code": null, "e": 29901, "s": 29622, "text": "Outline-width: It is used to specify the width of this outline for a specific element. The width of the outline can be set by specifying the size of the width in px, cm, pt, etc, or by using terms like a thin, thick, medium. If absent then the default width will be the medium." }, { "code": null, "e": 29909, "s": 29901, "text": "Syntax:" }, { "code": null, "e": 29966, "s": 29909, "text": "outline-width: medium|thin|thick|length|initial|inherit;" }, { "code": null, "e": 30067, "s": 29966, "text": "Example: This example illustrates the Outline property where the width is set to the specific value." }, { "code": null, "e": 30072, "s": 30067, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> p { border: solid green 4px; outline-style: solid; outline-width: 3px; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html>", "e": 30383, "s": 30072, "text": null }, { "code": null, "e": 30391, "s": 30383, "text": "Output:" }, { "code": null, "e": 30717, "s": 30391, "text": "Outline-offset: The CSS outline-offset Property sets the amount of space between an outline and the edge or border of an element. An outline is a line drawn around elements outside the border edge. The space between the element and its outline is transparent. Also, the outline may be non-rectangular. The default value is 0." }, { "code": null, "e": 30725, "s": 30717, "text": "Syntax:" }, { "code": null, "e": 30765, "s": 30725, "text": "outline-offset: length|initial|inherit;" }, { "code": null, "e": 30871, "s": 30765, "text": "Example: This example illustrates the Outline property where the offset is defined with a specific value." }, { "code": null, "e": 30876, "s": 30871, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <style> p { border: solid green 3px; outline-style: solid; outline-offset: 3px; text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>Outline Property</h3> <p>A Computer Science portal for geeks.</p> </body></html>", "e": 31188, "s": 30876, "text": null }, { "code": null, "e": 31196, "s": 31188, "text": "Output:" }, { "code": null, "e": 31217, "s": 31196, "text": " Supported Browsers:" }, { "code": null, "e": 31235, "s": 31217, "text": "Google Chrome 1.0" }, { "code": null, "e": 31255, "s": 31235, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 31277, "s": 31255, "text": "Internet Explorer 8.0" }, { "code": null, "e": 31289, "s": 31277, "text": "Firefox 1.5" }, { "code": null, "e": 31299, "s": 31289, "text": "Opera 7.0" }, { "code": null, "e": 31310, "s": 31299, "text": "Safari 1.2" }, { "code": null, "e": 31331, "s": 31310, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31344, "s": 31331, "text": "CSS-Advanced" }, { "code": null, "e": 31348, "s": 31344, "text": "CSS" }, { "code": null, "e": 31365, "s": 31348, "text": "Web Technologies" }, { "code": null, "e": 31463, "s": 31365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31472, "s": 31463, "text": "Comments" }, { "code": null, "e": 31485, "s": 31472, "text": "Old Comments" }, { "code": null, "e": 31547, "s": 31485, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31597, "s": 31547, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31655, "s": 31597, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31703, "s": 31655, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31740, "s": 31703, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31796, "s": 31740, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31829, "s": 31796, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31891, "s": 31829, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31934, "s": 31891, "text": "How to fetch data from an API in ReactJS ?" } ]
Place K-knights such that they do not attack each other in C++
In this problem, we are given three integer value K, N, M. our task is to place K knights in an NxM chessboard such that no two knights attack each other. There can be cases with 0 valid ways and also cases with multiple valid ways. You need to print all valid cases. Knight is a chess piece that moves two moves ahead and then one move to the left of right. It can move in any direction in the chessboard. Attack is the position when one piece can be in the same place as other pieces in one chance of its valid moves. Let’s take an example to understand the problem, Input − M = 3, N = 3, K = 5 Output − K A K A K A K A K A K A K K K A K A To solve this problem, we will start placing knights one by one in each row, column by column. And check the position than are attacking after each placement. On placing knights we will check if it is safe or not. If it is safe, then we will place it and then move to the next position. We will use backtracking so, that all possible ways can be obtained and for this, we will create a new board after each placement of knight for backtracking. This is how we will obtain all possible solutions using backtracking. Program to show the implementation of our solution, Live Demo #include <iostream> using namespace std; int m, n, k, count = 0; void displayPositions(char** board){ cout<<endl; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout<<board[i][j]<<"\t"; } cout<<endl; } } void canattack(int i, int j, char a, char** board){ if ((i + 2) < m && (j - 1) >= 0) { board[i + 2][j - 1] = a; } if ((i - 2) >= 0 && (j - 1) >= 0) { board[i - 2][j - 1] = a; } if ((i + 2) < m && (j + 1)< n) { board[i + 2][j + 1] = a; } if ((i - 2) >= 0 && (j + 1) < n) { board[i - 2][j + 1] = a; } if ((i + 1) < m && (j + 2) <n) { board[i + 1][j + 2] = a; } if ((i - 1) >= 0 && (j + 2) < n) { board[i - 1][j + 2] = a; } if ((i + 1) < m && (j - 2) >= 0) { board[i + 1][j - 2] = a; } if ((i - 1) >= 0 && (j - 2) >= 0) { board[i - 1][j - 2] = a; } } bool canPlace(int i, int j, char** board){ if (board[i][j] == '_') return true; else return false; } void place(int i, int j, char k, char a, char** board, char** new_board){ for (int y = 0; y < m; y++) { for (int z = 0; z < n; z++) { new_board[y][z] = board[y][z]; } } new_board[i][j] = k; canattack(i, j, a, new_board); } void placeKnights(int k, int sti, int stj, char** board){ if (k == 0) { displayPositions(board); count++; } else { for (int i = sti; i < m; i++) { for (int j = stj; j < n; j++) { if (canPlace(i, j, board)) { char** new_board = new char*[m]; for (int x = 0; x < m; x++) { new_board[x] = new char[n]; } place(i, j, 'K', 'A', board, new_board); placeKnights(k - 1, i, j, new_board); } } stj = 0; } } } int main() { m = 3, n = 3, k = 5; char** board = new char*[m]; for (int i = 0; i < m; i++) board[i] = new char[n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) board[i][j] = '_'; } cout<<"The ways in which "<<k<<" knights can be placed in "<<m<<"x"<<n<<" chessboard are :\n"; placeKnights(k, 0, 0, board); return 0; } The ways in which 5 knights can be placed in 3x3 chessboard are : K A K A K A K A K A K A K K K A K A Here, we have marked positions of knights by K and positions where they are attacked by A.
[ { "code": null, "e": 1330, "s": 1062, "text": "In this problem, we are given three integer value K, N, M. our task is to place K knights in an NxM chessboard such that no two knights attack each other. There can be cases with 0 valid ways and also cases with multiple valid ways. You need to print all valid cases." }, { "code": null, "e": 1469, "s": 1330, "text": "Knight is a chess piece that moves two moves ahead and then one move to the left of right. It can move in any direction in the chessboard." }, { "code": null, "e": 1582, "s": 1469, "text": "Attack is the position when one piece can be in the same place as other pieces in one chance of its valid moves." }, { "code": null, "e": 1631, "s": 1582, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1659, "s": 1631, "text": "Input − M = 3, N = 3, K = 5" }, { "code": null, "e": 1668, "s": 1659, "text": "Output −" }, { "code": null, "e": 1705, "s": 1668, "text": "K A K\nA K A\nK A K\n\nA K A\nK K K\nA K A" }, { "code": null, "e": 2220, "s": 1705, "text": "To solve this problem, we will start placing knights one by one in each row, column by column. And check the position than are attacking after each placement. On placing knights we will check if it is safe or not. If it is safe, then we will place it and then move to the next position. We will use backtracking so, that all possible ways can be obtained and for this, we will create a new board after each placement of knight for backtracking. This is how we will obtain all possible solutions using backtracking." }, { "code": null, "e": 2272, "s": 2220, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 2283, "s": 2272, "text": " Live Demo" }, { "code": null, "e": 4501, "s": 2283, "text": "#include <iostream>\nusing namespace std;\nint m, n, k, count = 0;\nvoid displayPositions(char** board){\n cout<<endl;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n cout<<board[i][j]<<\"\\t\";\n }\n cout<<endl;\n }\n}\nvoid canattack(int i, int j, char a,\nchar** board){\n if ((i + 2) < m && (j - 1) >= 0) {\n board[i + 2][j - 1] = a;\n }\n if ((i - 2) >= 0 && (j - 1) >= 0) {\n board[i - 2][j - 1] = a;\n }\n if ((i + 2) < m && (j + 1)< n) {\n board[i + 2][j + 1] = a;\n }\n if ((i - 2) >= 0 && (j + 1) < n) {\n board[i - 2][j + 1] = a;\n }\n if ((i + 1) < m && (j + 2) <n) {\n board[i + 1][j + 2] = a;\n }\n if ((i - 1) >= 0 && (j + 2) < n) {\n board[i - 1][j + 2] = a;\n }\n if ((i + 1) < m && (j - 2) >= 0) {\n board[i + 1][j - 2] = a;\n }\n if ((i - 1) >= 0 && (j - 2) >= 0) {\n board[i - 1][j - 2] = a;\n }\n}\nbool canPlace(int i, int j, char** board){\n if (board[i][j] == '_')\n return true;\n else\n return false;\n}\nvoid place(int i, int j, char k, char a,\nchar** board, char** new_board){\n for (int y = 0; y < m; y++) {\n for (int z = 0; z < n; z++) {\n new_board[y][z] = board[y][z];\n }\n }\n new_board[i][j] = k;\n canattack(i, j, a, new_board);\n}\nvoid placeKnights(int k, int sti, int stj, char** board){\n if (k == 0) {\n displayPositions(board);\n count++;\n } else {\n for (int i = sti; i < m; i++) {\n for (int j = stj; j < n; j++) {\n if (canPlace(i, j, board)) {\n char** new_board = new char*[m];\n for (int x = 0; x < m; x++) {\n new_board[x] = new char[n];\n }\n place(i, j, 'K', 'A', board, new_board);\n placeKnights(k - 1, i, j, new_board);\n }\n }\n stj = 0;\n }\n }\n}\nint main() {\n m = 3, n = 3, k = 5;\n char** board = new char*[m];\n for (int i = 0; i < m; i++)\n board[i] = new char[n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++)\n board[i][j] = '_';\n }\n cout<<\"The ways in which \"<<k<<\" knights can be placed in \"<<m<<\"x\"<<n<<\" chessboard are :\\n\";\n placeKnights(k, 0, 0, board);\n return 0;\n}" }, { "code": null, "e": 4604, "s": 4501, "text": "The ways in which 5 knights can be placed in 3x3 chessboard are :\nK A K\nA K A\nK A K\n\nA K A\nK K K\nA K A" }, { "code": null, "e": 4695, "s": 4604, "text": "Here, we have marked positions of knights by K and positions where they are attacked by A." } ]
HTML method Attribute - GeeksforGeeks
19 Aug, 2021 The HTML <form> method Attribute is used to specify the HTTP method used to send data while submitting the form. There are two kinds of HTTP methods, which are GET and POST. The method attribute can be used with the <form> element. Attribute Values: GET: In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful for non-secure data not for sensitive information. POST: In the post method, after the submission of the form, the form values will not be visible in the address bar of the new browser tab as it was visible in the GET method. It appends form data inside the body of the HTTP request. It has no size limitation. This method does not support bookmark the result. Supported Tags: <form> Syntax: <form method="get|post"> Example 1: This example illustrates the use of GET method attribute. html <!DOCTYPE html><html> <head> <title> HTML form method Attribute </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h3> HTML <form> Method Attribute. </h3> <form action="/action_page.php" id="users" action="#" method="GET" target="_blank"> First name: <input type="text" name="fname" placeholder="Enter first name"> <br><br> Last name: <input type="text" name="lname" placeholder="Enter last name"> <br><br> <input type="submit" value="Submit"> </form> <p> By clicking the submit button the Entered<br> details will be sended to "/action_page.php" </p> </body> </html> Output: Example 2: This example illustrates the use of the POST method attribute. This method sends the form-data as an HTTP post-transaction. html <!DOCTYPE html><html> <head> <title> HTML form method Attribute </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML <form> Method Attribute.</h3> <form action="/action_page.php" id="users" action="#" method="POST" target="_blank"> Email_id: <input type="text" name="Email_id" placeholder="Enter email_id"> <br><br> Password: <input type="password" placeholder="Enter Password"> Confirm Password: <input type="password" placeholder="Re-enter Password"> <br><br> <input type="button" value="login"> </form> <p> By clicking the login button the Entered<br> details will be sended to "/action_page.php" </p> </body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Mozilla Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? HTML | <img> align Attribute Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 27282, "s": 27254, "text": "\n19 Aug, 2021" }, { "code": null, "e": 27533, "s": 27282, "text": "The HTML <form> method Attribute is used to specify the HTTP method used to send data while submitting the form. There are two kinds of HTTP methods, which are GET and POST. The method attribute can be used with the <form> element. Attribute Values: " }, { "code": null, "e": 27783, "s": 27533, "text": "GET: In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful for non-secure data not for sensitive information." }, { "code": null, "e": 28095, "s": 27783, "text": "POST: In the post method, after the submission of the form, the form values will not be visible in the address bar of the new browser tab as it was visible in the GET method. It appends form data inside the body of the HTTP request. It has no size limitation. This method does not support bookmark the result. " }, { "code": null, "e": 28112, "s": 28095, "text": "Supported Tags: " }, { "code": null, "e": 28119, "s": 28112, "text": "<form>" }, { "code": null, "e": 28128, "s": 28119, "text": "Syntax: " }, { "code": null, "e": 28153, "s": 28128, "text": "<form method=\"get|post\">" }, { "code": null, "e": 28223, "s": 28153, "text": "Example 1: This example illustrates the use of GET method attribute. " }, { "code": null, "e": 28228, "s": 28223, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML form method Attribute </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3> HTML <form> Method Attribute. </h3> <form action=\"/action_page.php\" id=\"users\" action=\"#\" method=\"GET\" target=\"_blank\"> First name: <input type=\"text\" name=\"fname\" placeholder=\"Enter first name\"> <br><br> Last name: <input type=\"text\" name=\"lname\" placeholder=\"Enter last name\"> <br><br> <input type=\"submit\" value=\"Submit\"> </form> <p> By clicking the submit button the Entered<br> details will be sended to \"/action_page.php\" </p> </body> </html> ", "e": 29051, "s": 28228, "text": null }, { "code": null, "e": 29061, "s": 29051, "text": "Output: " }, { "code": null, "e": 29197, "s": 29061, "text": "Example 2: This example illustrates the use of the POST method attribute. This method sends the form-data as an HTTP post-transaction. " }, { "code": null, "e": 29202, "s": 29197, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML form method Attribute </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML <form> Method Attribute.</h3> <form action=\"/action_page.php\" id=\"users\" action=\"#\" method=\"POST\" target=\"_blank\"> Email_id: <input type=\"text\" name=\"Email_id\" placeholder=\"Enter email_id\"> <br><br> Password: <input type=\"password\" placeholder=\"Enter Password\"> Confirm Password: <input type=\"password\" placeholder=\"Re-enter Password\"> <br><br> <input type=\"button\" value=\"login\"> </form> <p> By clicking the login button the Entered<br> details will be sended to \"/action_page.php\" </p> </body> </html> ", "e": 30112, "s": 29202, "text": null }, { "code": null, "e": 30122, "s": 30112, "text": "Output: " }, { "code": null, "e": 30144, "s": 30122, "text": "Supported Browsers: " }, { "code": null, "e": 30158, "s": 30144, "text": "Google Chrome" }, { "code": null, "e": 30176, "s": 30158, "text": "Internet Explorer" }, { "code": null, "e": 30192, "s": 30176, "text": "Mozilla Firefox" }, { "code": null, "e": 30199, "s": 30192, "text": "Safari" }, { "code": null, "e": 30205, "s": 30199, "text": "Opera" }, { "code": null, "e": 30344, "s": 30207, "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": 30361, "s": 30344, "text": "arorakashish0911" }, { "code": null, "e": 30381, "s": 30361, "text": "hritikbhatnagar2182" }, { "code": null, "e": 30397, "s": 30381, "text": "HTML-Attributes" }, { "code": null, "e": 30402, "s": 30397, "text": "HTML" }, { "code": null, "e": 30419, "s": 30402, "text": "Web Technologies" }, { "code": null, "e": 30424, "s": 30419, "text": "HTML" }, { "code": null, "e": 30522, "s": 30424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30546, "s": 30522, "text": "REST API (Introduction)" }, { "code": null, "e": 30596, "s": 30546, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30633, "s": 30596, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30697, "s": 30633, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30726, "s": 30697, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 30766, "s": 30726, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30799, "s": 30766, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30844, "s": 30799, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30887, "s": 30844, "text": "How to fetch data from an API in ReactJS ?" } ]
Calendar Functions in Python | Set 1( calendar(), month(), isleap()...) - GeeksforGeeks
22 Jan, 2022 Python defines an inbuilt module “calendar” which handles operations related to the calendar.Operations on the calendar : 1. calendar(year, w, l, c):- This function displays the year, the width of characters, no. of lines per week, and column separations.2. firstweekday() :- This function returns the first week day number. By default 0 (Monday). Python3 # Python code to demonstrate the working of# calendar() and firstweeksday() # importing calendar module for calendar operationsimport calendar # using calendar to print calendar of year# prints calendar of 2012print ("The calendar of year 2012 is : ")print (calendar.calendar(2012,2,1,6)) #using firstweekday() to print starting day numberprint ("The starting day number in calendar is : ",end="")print (calendar.firstweekday()) Output: The calendar of year 2012 is : 2012 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 4 2 3 4 5 6 7 8 6 7 8 9 10 11 12 5 6 7 8 9 10 11 9 10 11 12 13 14 15 13 14 15 16 17 18 19 12 13 14 15 16 17 18 16 17 18 19 20 21 22 20 21 22 23 24 25 26 19 20 21 22 23 24 25 23 24 25 26 27 28 29 27 28 29 26 27 28 29 30 31 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 6 1 2 3 2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10 9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17 16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24 23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30 30 July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5 6 7 8 9 9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12 13 14 15 16 16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19 20 21 22 23 23 24 25 26 27 28 29 27 28 29 30 31 24 25 26 27 28 29 30 30 31 October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 1 2 3 4 1 2 8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 6 7 8 9 15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16 22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23 29 30 31 26 27 28 29 30 24 25 26 27 28 29 30 31 The starting day number in calendar is : 0 3. isleap (year):- This function checks if the year mentioned in the argument is a leap or not.4. leapdays (year1, year2):- This function returns the number of leap days between the specified years in arguments. Python3 # Python code to demonstrate the working of# isleap() and leapdays() # importing calendar module for calendar operationsimport calendar # using isleap() to check if year is leap or notif (calendar.isleap(2008)): print ("The year is leap")else : print ("The year is not leap") #using leapdays() to print leap days between yearsprint ("The leap days between 1950 and 2000 are : ",end="")print (calendar.leapdays(1950, 2000)) Output: The year is leap The leap days between 1950 and 2000 are : 12 5. month (year, month, w, l) :- This function prints the month of a specific year mentioned in arguments. It takes 4 arguments, year, month, width of characters and no. of lines taken by a week. Python3 # Python code to demonstrate the working of# month() # importing calendar module for calendar operationsimport calendar # using month() to display month of specific yearprint ("The month 5th of 2016 is :")print (calendar.month(2016,5,2,1)) Output: The month 5th of 2016 is : May 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Calendar Functions - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KRz3ZnVz-WY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. clintra amartyaghoshgfg date-time-program Python Calander-module Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26479, "s": 26451, "text": "\n22 Jan, 2022" }, { "code": null, "e": 26828, "s": 26479, "text": "Python defines an inbuilt module “calendar” which handles operations related to the calendar.Operations on the calendar : 1. calendar(year, w, l, c):- This function displays the year, the width of characters, no. of lines per week, and column separations.2. firstweekday() :- This function returns the first week day number. By default 0 (Monday). " }, { "code": null, "e": 26836, "s": 26828, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# calendar() and firstweeksday() # importing calendar module for calendar operationsimport calendar # using calendar to print calendar of year# prints calendar of 2012print (\"The calendar of year 2012 is : \")print (calendar.calendar(2012,2,1,6)) #using firstweekday() to print starting day numberprint (\"The starting day number in calendar is : \",end=\"\")print (calendar.firstweekday())", "e": 27265, "s": 26836, "text": null }, { "code": null, "e": 27275, "s": 27265, "text": "Output: " }, { "code": null, "e": 29474, "s": 27275, "text": "The calendar of year 2012 is : \n 2012\n\n January February March\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2 3 4\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 5 6 7 8 9 10 11\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 12 13 14 15 16 17 18\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 19 20 21 22 23 24 25\n23 24 25 26 27 28 29 27 28 29 26 27 28 29 30 31\n30 31\n\n April May June\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 6 1 2 3\n 2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10\n 9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17\n16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24\n23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30\n30\n\n July August September\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 1 2 3 4 5 1 2\n 2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5 6 7 8 9\n 9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12 13 14 15 16\n16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19 20 21 22 23\n23 24 25 26 27 28 29 27 28 29 30 31 24 25 26 27 28 29 30\n30 31\n\n October November December\nMo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su\n 1 2 3 4 5 6 7 1 2 3 4 1 2\n 8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 6 7 8 9\n15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16\n22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23\n29 30 31 26 27 28 29 30 24 25 26 27 28 29 30\n 31\n\nThe starting day number in calendar is : 0" }, { "code": null, "e": 29687, "s": 29474, "text": "3. isleap (year):- This function checks if the year mentioned in the argument is a leap or not.4. leapdays (year1, year2):- This function returns the number of leap days between the specified years in arguments. " }, { "code": null, "e": 29695, "s": 29687, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# isleap() and leapdays() # importing calendar module for calendar operationsimport calendar # using isleap() to check if year is leap or notif (calendar.isleap(2008)): print (\"The year is leap\")else : print (\"The year is not leap\") #using leapdays() to print leap days between yearsprint (\"The leap days between 1950 and 2000 are : \",end=\"\")print (calendar.leapdays(1950, 2000))", "e": 30124, "s": 29695, "text": null }, { "code": null, "e": 30134, "s": 30124, "text": "Output: " }, { "code": null, "e": 30196, "s": 30134, "text": "The year is leap\nThe leap days between 1950 and 2000 are : 12" }, { "code": null, "e": 30392, "s": 30196, "text": "5. month (year, month, w, l) :- This function prints the month of a specific year mentioned in arguments. It takes 4 arguments, year, month, width of characters and no. of lines taken by a week. " }, { "code": null, "e": 30400, "s": 30392, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# month() # importing calendar module for calendar operationsimport calendar # using month() to display month of specific yearprint (\"The month 5th of 2016 is :\")print (calendar.month(2016,5,2,1))", "e": 30640, "s": 30400, "text": null }, { "code": null, "e": 30650, "s": 30640, "text": "Output: " }, { "code": null, "e": 30824, "s": 30650, "text": "The month 5th of 2016 is :\n May 2016\nMo Tu We Th Fr Sa Su\n 1\n 2 3 4 5 6 7 8\n 9 10 11 12 13 14 15\n16 17 18 19 20 21 22\n23 24 25 26 27 28 29\n30 31" }, { "code": null, "e": 31682, "s": 30826, "text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Calendar Functions - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KRz3ZnVz-WY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 32104, "s": 31682, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32112, "s": 32104, "text": "clintra" }, { "code": null, "e": 32128, "s": 32112, "text": "amartyaghoshgfg" }, { "code": null, "e": 32146, "s": 32128, "text": "date-time-program" }, { "code": null, "e": 32169, "s": 32146, "text": "Python Calander-module" }, { "code": null, "e": 32176, "s": 32169, "text": "Python" }, { "code": null, "e": 32195, "s": 32176, "text": "School Programming" }, { "code": null, "e": 32293, "s": 32195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32311, "s": 32293, "text": "Python Dictionary" }, { "code": null, "e": 32346, "s": 32311, "text": "Read a file line by line in Python" }, { "code": null, "e": 32378, "s": 32346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32400, "s": 32378, "text": "Enumerate() in Python" }, { "code": null, "e": 32442, "s": 32400, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32460, "s": 32442, "text": "Python Dictionary" }, { "code": null, "e": 32476, "s": 32460, "text": "Arrays in C/C++" }, { "code": null, "e": 32495, "s": 32476, "text": "Inheritance in C++" }, { "code": null, "e": 32520, "s": 32495, "text": "Reverse a string in Java" } ]
Java Program to Convert Integer Values into Binary - GeeksforGeeks
09 Feb, 2022 Given an integer in Java, your task is to write a Java program to convert this given integer into a binary number. Example: Input: = 45 Output: = 101101 Input: = 32 Output: = 100000 Integers: Integers are numbers whose base value is 10. 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. Binary Numbers: A binary number is a number expressed in the base-2 numeral. Binary consists of only 2 digits 0 and 1. Two operators are used in the conversion of integers to binary modulo and division to convert the given input into binary numbers. There are many approaches to convert an integer into binary numbers some of them are discussed here. We will be discussing two of them: Using Implementation of Stack Using Inbuilt Method- toBinaryString() of the Integer class of Java Actually, the binary number consists of only 0 and 1. To convert an integer to binary divide the number by 2 until it becomes 0. In each step take the modulo by 2 and store the remainder into an array or stack. If we store the remainder into an array then print it into reverse order. If we store the remainder into a stack then simply pop one by one element and print it. Below is the java implementation of the above approach: Java // Java Program to Convert Integer Values into Binary // Importing CLasses/Filesimport java.io.*; public class GFG { // Function to print binary number static void printBinary(int[] binary, int id) { // Iteration over array for (int i = id - 1; i >= 0; i--) System.out.print(binary[i] + ""); } // Function converting decimal to binary public static void decimalToBinary(int num) { // Creating and assigning binary array size int[] binary = new int[35]; int id = 0; // Number should be positive while (num > 0) { binary[id++] = num % 2; num = num / 2; } // Print Binary printBinary(binary, id); } // Main Driver Code public static void main(String[] args) { // Entered number to be convert into binary int num = 45; // Calling Our Above Function decimalToBinary(num); }} 101101 Using Stack By Creating Object Vector Java // Java Program to Convert Integer Values into Binary // Importing Classes/Filesimport java.io.*;import java.util.Stack; public class GFG { // Function to convert integer to binary static void decimalToBinary(int num) { // Creating Stack Object Vector Stack<Integer> st = new Stack<>(); // Number Should be positive while (num > 0) { // Pushing numbers inside stack that // are divisible by 2 st.push(num % 2); // Dividing number by 2 num = num / 2; } // Checking condition whether stack is empty while (!(st.isEmpty())) { // Printing binary number System.out.print(st.pop()); } } // Main driver function public static void main(String[] args) { // Entered number to be converted into binary int num = 45; decimalToBinary(num); }} 101101 Java // Java Program to Convert Integer Values into Binary // Importing Classes/Filesimport java.io.*; class GFG { // Function converting decimal to binary static void decimalToBinary(int num) { // Function to print integer to binary using // inbuilt toBinaryString method System.out.println(Integer.toBinaryString(num)); } // Main driver function public static void main(String[] args) { // Number to be converted into binary int num = 45; // Calling function decimalToBinary(num); }} 101101 saurabh1990aror gabaa406 nishkarshgandhi Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file 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? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n09 Feb, 2022" }, { "code": null, "e": 25340, "s": 25225, "text": "Given an integer in Java, your task is to write a Java program to convert this given integer into a binary number." }, { "code": null, "e": 25350, "s": 25340, "text": "Example: " }, { "code": null, "e": 25411, "s": 25350, "text": "Input: = 45\nOutput: = 101101\n\nInput: = 32\nOutput: = 100000" }, { "code": null, "e": 25849, "s": 25411, "text": "Integers: Integers are numbers whose base value is 10. 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": 26099, "s": 25849, "text": "Binary Numbers: A binary number is a number expressed in the base-2 numeral. Binary consists of only 2 digits 0 and 1. Two operators are used in the conversion of integers to binary modulo and division to convert the given input into binary numbers." }, { "code": null, "e": 26235, "s": 26099, "text": "There are many approaches to convert an integer into binary numbers some of them are discussed here. We will be discussing two of them:" }, { "code": null, "e": 26265, "s": 26235, "text": "Using Implementation of Stack" }, { "code": null, "e": 26333, "s": 26265, "text": "Using Inbuilt Method- toBinaryString() of the Integer class of Java" }, { "code": null, "e": 26706, "s": 26333, "text": "Actually, the binary number consists of only 0 and 1. To convert an integer to binary divide the number by 2 until it becomes 0. In each step take the modulo by 2 and store the remainder into an array or stack. If we store the remainder into an array then print it into reverse order. If we store the remainder into a stack then simply pop one by one element and print it." }, { "code": null, "e": 26762, "s": 26706, "text": "Below is the java implementation of the above approach:" }, { "code": null, "e": 26767, "s": 26762, "text": "Java" }, { "code": "// Java Program to Convert Integer Values into Binary // Importing CLasses/Filesimport java.io.*; public class GFG { // Function to print binary number static void printBinary(int[] binary, int id) { // Iteration over array for (int i = id - 1; i >= 0; i--) System.out.print(binary[i] + \"\"); } // Function converting decimal to binary public static void decimalToBinary(int num) { // Creating and assigning binary array size int[] binary = new int[35]; int id = 0; // Number should be positive while (num > 0) { binary[id++] = num % 2; num = num / 2; } // Print Binary printBinary(binary, id); } // Main Driver Code public static void main(String[] args) { // Entered number to be convert into binary int num = 45; // Calling Our Above Function decimalToBinary(num); }}", "e": 27716, "s": 26767, "text": null }, { "code": null, "e": 27723, "s": 27716, "text": "101101" }, { "code": null, "e": 27762, "s": 27723, "text": "Using Stack By Creating Object Vector " }, { "code": null, "e": 27767, "s": 27762, "text": "Java" }, { "code": "// Java Program to Convert Integer Values into Binary // Importing Classes/Filesimport java.io.*;import java.util.Stack; public class GFG { // Function to convert integer to binary static void decimalToBinary(int num) { // Creating Stack Object Vector Stack<Integer> st = new Stack<>(); // Number Should be positive while (num > 0) { // Pushing numbers inside stack that // are divisible by 2 st.push(num % 2); // Dividing number by 2 num = num / 2; } // Checking condition whether stack is empty while (!(st.isEmpty())) { // Printing binary number System.out.print(st.pop()); } } // Main driver function public static void main(String[] args) { // Entered number to be converted into binary int num = 45; decimalToBinary(num); }}", "e": 28712, "s": 27767, "text": null }, { "code": null, "e": 28719, "s": 28712, "text": "101101" }, { "code": null, "e": 28724, "s": 28719, "text": "Java" }, { "code": "// Java Program to Convert Integer Values into Binary // Importing Classes/Filesimport java.io.*; class GFG { // Function converting decimal to binary static void decimalToBinary(int num) { // Function to print integer to binary using // inbuilt toBinaryString method System.out.println(Integer.toBinaryString(num)); } // Main driver function public static void main(String[] args) { // Number to be converted into binary int num = 45; // Calling function decimalToBinary(num); }}", "e": 29284, "s": 28724, "text": null }, { "code": null, "e": 29291, "s": 29284, "text": "101101" }, { "code": null, "e": 29307, "s": 29291, "text": "saurabh1990aror" }, { "code": null, "e": 29316, "s": 29307, "text": "gabaa406" }, { "code": null, "e": 29332, "s": 29316, "text": "nishkarshgandhi" }, { "code": null, "e": 29337, "s": 29332, "text": "Java" }, { "code": null, "e": 29351, "s": 29337, "text": "Java Programs" }, { "code": null, "e": 29356, "s": 29351, "text": "Java" }, { "code": null, "e": 29454, "s": 29356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29469, "s": 29454, "text": "Stream In Java" }, { "code": null, "e": 29490, "s": 29469, "text": "Constructors in Java" }, { "code": null, "e": 29509, "s": 29490, "text": "Exceptions in Java" }, { "code": null, "e": 29539, "s": 29509, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29585, "s": 29539, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29611, "s": 29585, "text": "Java Programming Examples" }, { "code": null, "e": 29645, "s": 29611, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29692, "s": 29645, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29724, "s": 29692, "text": "How to Iterate HashMap in Java?" } ]
C | Advanced Pointer | Question 3 - GeeksforGeeks
28 Jun, 2021 #include <stdio.h>int main(){ int a[5] = {1,2,3,4,5}; int *ptr = (int*)(&a+1); printf("%d %d", *(a+1), *(ptr-1)); return 0;} (A) 2 5(B) Garbage Value(C) Compiler Error(D) Segmentation FaultAnswer: (A)Explanation: The program prints “2 5′′. Since compilers convert array operations in pointers before accessing the array elements, (a+1) points to 2. The expression (&a + 1) is actually an address just after end of array ( after address of 5 ) because &a contains address of an item of size 5*integer_size and when we do (&a + 1) the pointer is incremented by 5*integer_size. ptr is type-casted to int * so when we do ptr -1, we get address of 5Quiz of this Question Advanced Pointer C-Advanced Pointer C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Core Dump (Segmentation fault) in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 Output of C programs | Set 64 (Pointers) C | Arrays | Question 7
[ { "code": null, "e": 25711, "s": 25683, "text": "\n28 Jun, 2021" }, { "code": "#include <stdio.h>int main(){ int a[5] = {1,2,3,4,5}; int *ptr = (int*)(&a+1); printf(\"%d %d\", *(a+1), *(ptr-1)); return 0;}", "e": 25848, "s": 25711, "text": null }, { "code": null, "e": 25963, "s": 25848, "text": "(A) 2 5(B) Garbage Value(C) Compiler Error(D) Segmentation FaultAnswer: (A)Explanation: The program prints “2 5′′." }, { "code": null, "e": 26072, "s": 25963, "text": "Since compilers convert array operations in pointers before accessing the array elements, (a+1) points to 2." }, { "code": null, "e": 26298, "s": 26072, "text": "The expression (&a + 1) is actually an address just after end of array ( after address of 5 ) because &a contains address of an item of size 5*integer_size and when we do (&a + 1) the pointer is incremented by 5*integer_size." }, { "code": null, "e": 26389, "s": 26298, "text": "ptr is type-casted to int * so when we do ptr -1, we get address of 5Quiz of this Question" }, { "code": null, "e": 26406, "s": 26389, "text": "Advanced Pointer" }, { "code": null, "e": 26425, "s": 26406, "text": "C-Advanced Pointer" }, { "code": null, "e": 26436, "s": 26425, "text": "C Language" }, { "code": null, "e": 26443, "s": 26436, "text": "C Quiz" }, { "code": null, "e": 26541, "s": 26443, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26558, "s": 26541, "text": "Substring in C++" }, { "code": null, "e": 26593, "s": 26558, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26639, "s": 26593, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26678, "s": 26639, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 26718, "s": 26678, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 26760, "s": 26718, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 26803, "s": 26760, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 26834, "s": 26803, "text": "C | File Handling | Question 1" }, { "code": null, "e": 26875, "s": 26834, "text": "Output of C programs | Set 64 (Pointers)" } ]
Convert a floating point number to string in C - GeeksforGeeks
06 Nov, 2019 Write a C function ftoa() that converts a given floating-point number or a double to a string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string. ftoa(n, res, afterpoint) n --> Input Number res[] --> Array where output string to be stored afterpoint --> Number of digits to be considered after the point. Example: ftoa(1.555, str, 2) should store “1.55” in res. ftoa(1.555, str, 0) should store “1” in res. We strongly recommend to minimize the browser and try this yourself first. A simple way is to use sprintf(), but use of standard library functions for direct conversion is not allowed. Approach: The idea is to separate integral and fractional parts and convert them to strings separately. Following are the detailed steps. Extract integer part from floating-point or double number.First, convert integer part to the string.Extract fraction part by exacted integer part from n.If d is non-zero, then do the following.Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result. Extract integer part from floating-point or double number. First, convert integer part to the string. Extract fraction part by exacted integer part from n. If d is non-zero, then do the following.Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result. Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result. Convert fraction part to an integer by multiplying it with pow(10, d) Convert the integer value to string and append to the result. Following is C implementation of the above approach. // C program for implementation of ftoa()#include <math.h>#include <stdio.h> // Reverses a string 'str' of length 'len'void reverse(char* str, int len){ int i = 0, j = len - 1, temp; while (i < j) { temp = str[i]; str[i] = str[j]; str[j] = temp; i++; j--; }} // Converts a given integer x to string str[]. // d is the number of digits required in the output. // If d is more than the number of digits in x, // then 0s are added at the beginning.int intToStr(int x, char str[], int d){ int i = 0; while (x) { str[i++] = (x % 10) + '0'; x = x / 10; } // If number of digits required is more, then // add 0s at the beginning while (i < d) str[i++] = '0'; reverse(str, i); str[i] = '\0'; return i;} // Converts a floating-point/double number to a string.void ftoa(float n, char* res, int afterpoint){ // Extract integer part int ipart = (int)n; // Extract floating part float fpart = n - (float)ipart; // convert integer part to string int i = intToStr(ipart, res, 0); // check for display option after point if (afterpoint != 0) { res[i] = '.'; // add dot // Get the value of fraction part upto given no. // of points after dot. The third parameter // is needed to handle cases like 233.007 fpart = fpart * pow(10, afterpoint); intToStr((int)fpart, res + i + 1, afterpoint); }} // Driver program to test above functionint main(){ char res[20]; float n = 233.007; ftoa(n, res, 4); printf("\"%s\"\n", res); return 0;} "233.0070" Note: The program performs similar operation if instead of float, a double type is taken. This article is contributed by Jayasantosh Samal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shubham_singh cpp-data-types cpp-string C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 26555, "s": 26527, "text": "\n06 Nov, 2019" }, { "code": null, "e": 26826, "s": 26555, "text": "Write a C function ftoa() that converts a given floating-point number or a double to a string. Use of standard library functions for direct conversion is not allowed. The following is prototype of ftoa(). The article provides insight of conversion of C double to string." }, { "code": null, "e": 27000, "s": 26826, "text": "ftoa(n, res, afterpoint)\nn --> Input Number\nres[] --> Array where output string to be stored\nafterpoint --> Number of digits to be considered after the point.\n" }, { "code": null, "e": 27009, "s": 27000, "text": "Example:" }, { "code": null, "e": 27057, "s": 27009, "text": "ftoa(1.555, str, 2) should store “1.55” in res." }, { "code": null, "e": 27102, "s": 27057, "text": "ftoa(1.555, str, 0) should store “1” in res." }, { "code": null, "e": 27177, "s": 27102, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 27287, "s": 27177, "text": "A simple way is to use sprintf(), but use of standard library functions for direct conversion is not allowed." }, { "code": null, "e": 27425, "s": 27287, "text": "Approach: The idea is to separate integral and fractional parts and convert them to strings separately. Following are the detailed steps." }, { "code": null, "e": 27749, "s": 27425, "text": "Extract integer part from floating-point or double number.First, convert integer part to the string.Extract fraction part by exacted integer part from n.If d is non-zero, then do the following.Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result." }, { "code": null, "e": 27808, "s": 27749, "text": "Extract integer part from floating-point or double number." }, { "code": null, "e": 27851, "s": 27808, "text": "First, convert integer part to the string." }, { "code": null, "e": 27905, "s": 27851, "text": "Extract fraction part by exacted integer part from n." }, { "code": null, "e": 28076, "s": 27905, "text": "If d is non-zero, then do the following.Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result." }, { "code": null, "e": 28207, "s": 28076, "text": "Convert fraction part to an integer by multiplying it with pow(10, d)Convert the integer value to string and append to the result." }, { "code": null, "e": 28277, "s": 28207, "text": "Convert fraction part to an integer by multiplying it with pow(10, d)" }, { "code": null, "e": 28339, "s": 28277, "text": "Convert the integer value to string and append to the result." }, { "code": null, "e": 28392, "s": 28339, "text": "Following is C implementation of the above approach." }, { "code": "// C program for implementation of ftoa()#include <math.h>#include <stdio.h> // Reverses a string 'str' of length 'len'void reverse(char* str, int len){ int i = 0, j = len - 1, temp; while (i < j) { temp = str[i]; str[i] = str[j]; str[j] = temp; i++; j--; }} // Converts a given integer x to string str[]. // d is the number of digits required in the output. // If d is more than the number of digits in x, // then 0s are added at the beginning.int intToStr(int x, char str[], int d){ int i = 0; while (x) { str[i++] = (x % 10) + '0'; x = x / 10; } // If number of digits required is more, then // add 0s at the beginning while (i < d) str[i++] = '0'; reverse(str, i); str[i] = '\\0'; return i;} // Converts a floating-point/double number to a string.void ftoa(float n, char* res, int afterpoint){ // Extract integer part int ipart = (int)n; // Extract floating part float fpart = n - (float)ipart; // convert integer part to string int i = intToStr(ipart, res, 0); // check for display option after point if (afterpoint != 0) { res[i] = '.'; // add dot // Get the value of fraction part upto given no. // of points after dot. The third parameter // is needed to handle cases like 233.007 fpart = fpart * pow(10, afterpoint); intToStr((int)fpart, res + i + 1, afterpoint); }} // Driver program to test above functionint main(){ char res[20]; float n = 233.007; ftoa(n, res, 4); printf(\"\\\"%s\\\"\\n\", res); return 0;}", "e": 30000, "s": 28392, "text": null }, { "code": null, "e": 30012, "s": 30000, "text": "\"233.0070\"\n" }, { "code": null, "e": 30102, "s": 30012, "text": "Note: The program performs similar operation if instead of float, a double type is taken." }, { "code": null, "e": 30276, "s": 30102, "text": "This article is contributed by Jayasantosh Samal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 30290, "s": 30276, "text": "shubham_singh" }, { "code": null, "e": 30305, "s": 30290, "text": "cpp-data-types" }, { "code": null, "e": 30316, "s": 30305, "text": "cpp-string" }, { "code": null, "e": 30327, "s": 30316, "text": "C Language" }, { "code": null, "e": 30331, "s": 30327, "text": "C++" }, { "code": null, "e": 30335, "s": 30331, "text": "CPP" }, { "code": null, "e": 30433, "s": 30335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30450, "s": 30433, "text": "Substring in C++" }, { "code": null, "e": 30485, "s": 30450, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 30524, "s": 30485, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 30570, "s": 30524, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30592, "s": 30570, "text": "Function Pointer in C" }, { "code": null, "e": 30610, "s": 30592, "text": "Vector in C++ STL" }, { "code": null, "e": 30656, "s": 30610, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30675, "s": 30656, "text": "Inheritance in C++" }, { "code": null, "e": 30718, "s": 30675, "text": "Map in C++ Standard Template Library (STL)" } ]
Scala Map retain() method with example - GeeksforGeeks
26 Jul, 2019 The retain() method is utilized to retain all the pairs of the map that satisfies the stated condition. Method Definition: def retain(p: (A, B) => Boolean): Map.this.type Return Type: It returns all the “key-value” pairs of the map which satisfies the stated predicate. Example #1: // Scala program of retain()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a mutable map val m1 = scala.collection.mutable.Map(3 -> "geeks", 1 -> "for", 2 -> "cs") // Applying retain method val result = m1.retain((key,value) => key > 1) // Displays output println(result) }} Map(2 -> cs, 3 -> geeks) Example: 2# // Scala program of retain()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a mutable map val m1 = scala.collection.mutable.Map(3 -> "geeks", 1 -> "for", 1 -> "cs") // Applying retain method val result = m1.retain((key,value) => key > 1) // Displays output println(result) }} Map(3 -> geeks) Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Inheritance in Scala Operators in Scala Scala Constructors Scala | Arrays Lambda Expression in Scala How to get the first element of List in Scala Break statement in Scala
[ { "code": null, "e": 25151, "s": 25123, "text": "\n26 Jul, 2019" }, { "code": null, "e": 25255, "s": 25151, "text": "The retain() method is utilized to retain all the pairs of the map that satisfies the stated condition." }, { "code": null, "e": 25322, "s": 25255, "text": "Method Definition: def retain(p: (A, B) => Boolean): Map.this.type" }, { "code": null, "e": 25421, "s": 25322, "text": "Return Type: It returns all the “key-value” pairs of the map which satisfies the stated predicate." }, { "code": null, "e": 25433, "s": 25421, "text": "Example #1:" }, { "code": "// Scala program of retain()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a mutable map val m1 = scala.collection.mutable.Map(3 -> \"geeks\", 1 -> \"for\", 2 -> \"cs\") // Applying retain method val result = m1.retain((key,value) => key > 1) // Displays output println(result) }}", "e": 25885, "s": 25433, "text": null }, { "code": null, "e": 25911, "s": 25885, "text": "Map(2 -> cs, 3 -> geeks)\n" }, { "code": null, "e": 25923, "s": 25911, "text": "Example: 2#" }, { "code": "// Scala program of retain()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a mutable map val m1 = scala.collection.mutable.Map(3 -> \"geeks\", 1 -> \"for\", 1 -> \"cs\") // Applying retain method val result = m1.retain((key,value) => key > 1) // Displays output println(result) }}", "e": 26378, "s": 25923, "text": null }, { "code": null, "e": 26395, "s": 26378, "text": "Map(3 -> geeks)\n" }, { "code": null, "e": 26401, "s": 26395, "text": "Scala" }, { "code": null, "e": 26411, "s": 26401, "text": "Scala-Map" }, { "code": null, "e": 26424, "s": 26411, "text": "Scala-Method" }, { "code": null, "e": 26430, "s": 26424, "text": "Scala" }, { "code": null, "e": 26528, "s": 26430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26554, "s": 26528, "text": "Class and Object in Scala" }, { "code": null, "e": 26566, "s": 26554, "text": "Scala Lists" }, { "code": null, "e": 26619, "s": 26566, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26640, "s": 26619, "text": "Inheritance in Scala" }, { "code": null, "e": 26659, "s": 26640, "text": "Operators in Scala" }, { "code": null, "e": 26678, "s": 26659, "text": "Scala Constructors" }, { "code": null, "e": 26693, "s": 26678, "text": "Scala | Arrays" }, { "code": null, "e": 26720, "s": 26693, "text": "Lambda Expression in Scala" }, { "code": null, "e": 26766, "s": 26720, "text": "How to get the first element of List in Scala" } ]
Mirror of a point through a 3 D plane - GeeksforGeeks
28 Apr, 2021 Given a point(x, y, z) in 3-D and coefficients of the equation of a plane, the task is to find the mirror image of that point through the given plane. Examples: Input: a = 1, b = -2, c = 0, d = 0, x = -1, y = 3, z = 4 Output: x3 = 1.7999999999999998, y3 = -2.5999999999999996, z3 = 4.0Input: a = 2, b = -1, c = 1, d = 3, x = 1, y = 3, z = 4 Output: x3 = -3.0, y3 = 5.0, z3 = 2.0 Approach: Equation of plane is as ax + by + cz + d = 0. Therefore, direction ratios of the normal to the plane are (a, b, c). Let N be the foot of perpendicular from a given point to the given plane so, line PN has directed ratios (a, b, c) and it passes through P(x1, y1, z1). The equation of line PN will be as:- (x - x1) / a = (y - y1) / b = (z - z1) / c = k Hence any point on line PN can be written as:- x = a*k + x1 y = b*k + y1 z = c*k + z1 since N lies in both line and plane so will satisfy(ax + by + cz + d = 0). =>a * (a * k + x1) + b * (b * k + y1) + c * (c * k + z1) + d = 0. =>a * a * k + a * x1 + b * b * k + b * y1 + c * c * k + c * z1 + d = 0. =>(a * a + b * b + c * c)k = -a * x1 - b * y1 - c * z1 - d. =>k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c). Now, the coordinates of Point N in terms of k will be:- x2 = a * k + x1 y2 = b * k + y1 z2 = c * k + z1 Since, Point N(x2, y2, z2) is midpoint of point P(x1, y1, z1) and point Q(x3, y3, z3), coordinates of Point Q are:- => x3 = 2 * x2 - x1 => y3 = 2 * y2 - y1 => z3 = 2 * z2 - z1 C++ C Java Python C# PHP Javascript // C++ program to find// Mirror of a point // through a 3 D plane#include <bits/stdc++.h>#include<math.h>#include <iostream>#include <iomanip> using namespace std; // Function to mirror imagevoid mirror_point(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; std::cout << std::fixed; std::cout << std::setprecision(1); cout << " x3 = " << x3; cout << " y3 = " << y3; cout << " z3 = " << z3;} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1); return 0;}// This code is contributed// by Amber_Saxena. // C program to find// Mirror of a point// through a 3 D plane#include<stdio.h> // Function to mirror imagevoid mirror_point(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; printf("x3 = %.1f ", x3); printf("y3 = %.1f ", y3); printf("z3 = %.1f ", z3);} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1);} // This code is contributed// by Amber_Saxena. // Java program to find// Mirror of a point// through a 3 D planeimport java.io.*; class GFG{ // Function to mirror imagestatic void mirror_point(int a, int b, int c, int d, int x1, int y1, int z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; System.out.print("x3 = " + x3 + " "); System.out.print("y3 = " + y3 + " "); System.out.print("z3 = " + z3 + " ");} // Driver Codepublic static void main(String[] args){ int a = 1; int b = -2; int c = 0; int d = 0; int x1 = -1; int y1 = 3; int z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1) ;}} // This code is contributed// by inder_verma # Function to mirror imagedef mirror_point(a, b, c, d, x1, y1, z1): k =(-a * x1-b * y1-c * z1-d)/float((a * a + b * b + c * c)) x2 = a * k + x1 y2 = b * k + y1 z2 = c * k + z1 x3 = 2 * x2-x1 y3 = 2 * y2-y1 z3 = 2 * z2-z1 print "x3 =", x3, print "y3 =", y3, print "z3 =", z3, # Driver Codea = 1b = -2c = 0d = 0x1 = -1y1 = 3z1 = 4 # function callmirror_point(a, b, c, d, x1, y1, z1) // C# program to find Mirror of// a point through a 3 D planeusing System; class GFG{ // Function to mirror imagestatic void mirror_point(int a, int b, int c, int d, int x1, int y1, int z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; Console.Write("x3 = " + x3 + " "); Console.Write("y3 = " + y3 + " "); Console.Write("z3 = " + z3 + " ");} // Driver Codestatic public void Main (){ int a = 1; int b = -2; int c = 0; int d = 0; int x1 = -1; int y1 = 3; int z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1);}} // This code is contributed by jit_t <?php// PHP program to find Mirror of// a point through a 3 D plane // Function to mirror imagefunction mirror_point($a, $b, $c, $d, $x1, $y1, $z1){ $k = (-$a * $x1 - $b * $y1 - $c * $z1 - $d) / ($a * $a + $b * $b + $c * $c); $x2 = $a * $k + $x1; $y2 = $b * $k + $y1; $z2 = $c * $k + $z1; $x3 = 2 * $x2 - $x1; $y3 = 2 * $y2 - $y1; $z3 = 2 * $z2 - $z1; echo sprintf("x3 = %.1f ", $x3); echo sprintf("y3 = %.1f ", $y3); echo sprintf("z3 = %.1f ", $z3);} // Driver Code$a = 1;$b = -2;$c = 0;$d = 0;$x1 = -1;$y1 = 3;$z1 = 4;// function callmirror_point($a, $b, $c, $d, $x1, $y1, $z1); // This code is contributed// by Amber_Saxena.?> <script> // JavaScript program to find // Mirror of a point // through a 3 D plane // Function to mirror image function mirror_point(a, b, c, d, x1, y1, z1) { var k = parseFloat( (-a * x1 - b * y1 - c * z1 - d) / parseFloat(a * a + b * b + c * c) ); var x2 = parseFloat(a * k + x1); var y2 = parseFloat(b * k + y1); var z2 = parseFloat(c * k + z1); var x3 = parseFloat(2 * x2 - x1).toFixed(1); var y3 = parseFloat(2 * y2 - y1).toFixed(1); var z3 = parseFloat(2 * z2 - z1).toFixed(1); document.write(" x3 = " + x3); document.write(" y3 = " + y3); document.write(" z3 = " + z3); } // Driver Code var a = 1; var b = -2; var c = 0; var d = 0; var x1 = -1; var y1 = 3; var z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1); </script> x3 = 1.8 y3 = -2.6 z3 = 4.0 inderDuMCA Amber_Saxena jit_t rdtank school-programming Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26829, "s": 26801, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26992, "s": 26829, "text": "Given a point(x, y, z) in 3-D and coefficients of the equation of a plane, the task is to find the mirror image of that point through the given plane. Examples: " }, { "code": null, "e": 27210, "s": 26992, "text": "Input: a = 1, b = -2, c = 0, d = 0, x = -1, y = 3, z = 4 Output: x3 = 1.7999999999999998, y3 = -2.5999999999999996, z3 = 4.0Input: a = 2, b = -1, c = 1, d = 3, x = 1, y = 3, z = 4 Output: x3 = -3.0, y3 = 5.0, z3 = 2.0" }, { "code": null, "e": 27531, "s": 27214, "text": "Approach: Equation of plane is as ax + by + cz + d = 0. Therefore, direction ratios of the normal to the plane are (a, b, c). Let N be the foot of perpendicular from a given point to the given plane so, line PN has directed ratios (a, b, c) and it passes through P(x1, y1, z1). The equation of line PN will be as:- " }, { "code": null, "e": 27578, "s": 27531, "text": "(x - x1) / a = (y - y1) / b = (z - z1) / c = k" }, { "code": null, "e": 27627, "s": 27578, "text": "Hence any point on line PN can be written as:- " }, { "code": null, "e": 27666, "s": 27627, "text": "x = a*k + x1\ny = b*k + y1\nz = c*k + z1" }, { "code": null, "e": 27743, "s": 27666, "text": "since N lies in both line and plane so will satisfy(ax + by + cz + d = 0). " }, { "code": null, "e": 28006, "s": 27743, "text": "=>a * (a * k + x1) + b * (b * k + y1) + c * (c * k + z1) + d = 0.\n=>a * a * k + a * x1 + b * b * k + b * y1 + c * c * k + c * z1 + d = 0.\n=>(a * a + b * b + c * c)k = -a * x1 - b * y1 - c * z1 - d.\n=>k = (-a * x1 - b * y1 - c * z1 - d) / (a * a + b * b + c * c)." }, { "code": null, "e": 28064, "s": 28006, "text": "Now, the coordinates of Point N in terms of k will be:- " }, { "code": null, "e": 28112, "s": 28064, "text": "x2 = a * k + x1\ny2 = b * k + y1\nz2 = c * k + z1" }, { "code": null, "e": 28230, "s": 28112, "text": "Since, Point N(x2, y2, z2) is midpoint of point P(x1, y1, z1) and point Q(x3, y3, z3), coordinates of Point Q are:- " }, { "code": null, "e": 28290, "s": 28230, "text": "=> x3 = 2 * x2 - x1\n=> y3 = 2 * y2 - y1\n=> z3 = 2 * z2 - z1" }, { "code": null, "e": 28296, "s": 28292, "text": "C++" }, { "code": null, "e": 28298, "s": 28296, "text": "C" }, { "code": null, "e": 28303, "s": 28298, "text": "Java" }, { "code": null, "e": 28310, "s": 28303, "text": "Python" }, { "code": null, "e": 28313, "s": 28310, "text": "C#" }, { "code": null, "e": 28317, "s": 28313, "text": "PHP" }, { "code": null, "e": 28328, "s": 28317, "text": "Javascript" }, { "code": "// C++ program to find// Mirror of a point // through a 3 D plane#include <bits/stdc++.h>#include<math.h>#include <iostream>#include <iomanip> using namespace std; // Function to mirror imagevoid mirror_point(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; std::cout << std::fixed; std::cout << std::setprecision(1); cout << \" x3 = \" << x3; cout << \" y3 = \" << y3; cout << \" z3 = \" << z3;} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1); return 0;}// This code is contributed// by Amber_Saxena.", "e": 29360, "s": 28328, "text": null }, { "code": "// C program to find// Mirror of a point// through a 3 D plane#include<stdio.h> // Function to mirror imagevoid mirror_point(float a, float b, float c, float d, float x1, float y1, float z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; printf(\"x3 = %.1f \", x3); printf(\"y3 = %.1f \", y3); printf(\"z3 = %.1f \", z3);} // Driver Codeint main(){ float a = 1; float b = -2; float c = 0; float d = 0; float x1 = -1; float y1 = 3; float z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1);} // This code is contributed// by Amber_Saxena.", "e": 30229, "s": 29360, "text": null }, { "code": "// Java program to find// Mirror of a point// through a 3 D planeimport java.io.*; class GFG{ // Function to mirror imagestatic void mirror_point(int a, int b, int c, int d, int x1, int y1, int z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; System.out.print(\"x3 = \" + x3 + \" \"); System.out.print(\"y3 = \" + y3 + \" \"); System.out.print(\"z3 = \" + z3 + \" \");} // Driver Codepublic static void main(String[] args){ int a = 1; int b = -2; int c = 0; int d = 0; int x1 = -1; int y1 = 3; int z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1) ;}} // This code is contributed// by inder_verma", "e": 31162, "s": 30229, "text": null }, { "code": "# Function to mirror imagedef mirror_point(a, b, c, d, x1, y1, z1): k =(-a * x1-b * y1-c * z1-d)/float((a * a + b * b + c * c)) x2 = a * k + x1 y2 = b * k + y1 z2 = c * k + z1 x3 = 2 * x2-x1 y3 = 2 * y2-y1 z3 = 2 * z2-z1 print \"x3 =\", x3, print \"y3 =\", y3, print \"z3 =\", z3, # Driver Codea = 1b = -2c = 0d = 0x1 = -1y1 = 3z1 = 4 # function callmirror_point(a, b, c, d, x1, y1, z1) ", "e": 31581, "s": 31162, "text": null }, { "code": "// C# program to find Mirror of// a point through a 3 D planeusing System; class GFG{ // Function to mirror imagestatic void mirror_point(int a, int b, int c, int d, int x1, int y1, int z1){ float k = (-a * x1 - b * y1 - c * z1 - d) / (float)(a * a + b * b + c * c); float x2 = a * k + x1; float y2 = b * k + y1; float z2 = c * k + z1; float x3 = 2 * x2 - x1; float y3 = 2 * y2 - y1; float z3 = 2 * z2 - z1; Console.Write(\"x3 = \" + x3 + \" \"); Console.Write(\"y3 = \" + y3 + \" \"); Console.Write(\"z3 = \" + z3 + \" \");} // Driver Codestatic public void Main (){ int a = 1; int b = -2; int c = 0; int d = 0; int x1 = -1; int y1 = 3; int z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1);}} // This code is contributed by jit_t", "e": 32489, "s": 31581, "text": null }, { "code": "<?php// PHP program to find Mirror of// a point through a 3 D plane // Function to mirror imagefunction mirror_point($a, $b, $c, $d, $x1, $y1, $z1){ $k = (-$a * $x1 - $b * $y1 - $c * $z1 - $d) / ($a * $a + $b * $b + $c * $c); $x2 = $a * $k + $x1; $y2 = $b * $k + $y1; $z2 = $c * $k + $z1; $x3 = 2 * $x2 - $x1; $y3 = 2 * $y2 - $y1; $z3 = 2 * $z2 - $z1; echo sprintf(\"x3 = %.1f \", $x3); echo sprintf(\"y3 = %.1f \", $y3); echo sprintf(\"z3 = %.1f \", $z3);} // Driver Code$a = 1;$b = -2;$c = 0;$d = 0;$x1 = -1;$y1 = 3;$z1 = 4;// function callmirror_point($a, $b, $c, $d, $x1, $y1, $z1); // This code is contributed// by Amber_Saxena.?>", "e": 33211, "s": 32489, "text": null }, { "code": "<script> // JavaScript program to find // Mirror of a point // through a 3 D plane // Function to mirror image function mirror_point(a, b, c, d, x1, y1, z1) { var k = parseFloat( (-a * x1 - b * y1 - c * z1 - d) / parseFloat(a * a + b * b + c * c) ); var x2 = parseFloat(a * k + x1); var y2 = parseFloat(b * k + y1); var z2 = parseFloat(c * k + z1); var x3 = parseFloat(2 * x2 - x1).toFixed(1); var y3 = parseFloat(2 * y2 - y1).toFixed(1); var z3 = parseFloat(2 * z2 - z1).toFixed(1); document.write(\" x3 = \" + x3); document.write(\" y3 = \" + y3); document.write(\" z3 = \" + z3); } // Driver Code var a = 1; var b = -2; var c = 0; var d = 0; var x1 = -1; var y1 = 3; var z1 = 4; // function call mirror_point(a, b, c, d, x1, y1, z1); </script>", "e": 34152, "s": 33211, "text": null }, { "code": null, "e": 34180, "s": 34152, "text": "x3 = 1.8 y3 = -2.6 z3 = 4.0" }, { "code": null, "e": 34193, "s": 34182, "text": "inderDuMCA" }, { "code": null, "e": 34206, "s": 34193, "text": "Amber_Saxena" }, { "code": null, "e": 34212, "s": 34206, "text": "jit_t" }, { "code": null, "e": 34219, "s": 34212, "text": "rdtank" }, { "code": null, "e": 34238, "s": 34219, "text": "school-programming" }, { "code": null, "e": 34248, "s": 34238, "text": "Geometric" }, { "code": null, "e": 34267, "s": 34248, "text": "School Programming" }, { "code": null, "e": 34277, "s": 34267, "text": "Geometric" }, { "code": null, "e": 34375, "s": 34277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34424, "s": 34375, "text": "Program for distance between two points on earth" }, { "code": null, "e": 34477, "s": 34424, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 34528, "s": 34477, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 34562, "s": 34528, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 34620, "s": 34562, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 34638, "s": 34620, "text": "Python Dictionary" }, { "code": null, "e": 34654, "s": 34638, "text": "Arrays in C/C++" }, { "code": null, "e": 34673, "s": 34654, "text": "Inheritance in C++" }, { "code": null, "e": 34698, "s": 34673, "text": "Reverse a string in Java" } ]
How to convert pandas DataFrame into SQL in Python? - GeeksforGeeks
02 Sep, 2021 In this article, we aim to convert the data frame into a SQL database and then try to read the content from the SQL database using SQL queries or through a table To deal with SQL in python we need to install the sqlalchemy library using the below-mentioned command by running it in cmd: pip install sqlalchemy There is a need to create a pandas data frame to proceed further. Python3 # import pandas libraryimport pandas as pd # create a dataframe# object from dictionarydataset = pd.DataFrame({'Names':['Abhinav','Aryan', 'Manthan'], 'DOB' : ['10/01/2009','24/03/2009', '28/02/2009']})# show the dataframeprint(dataset) Output : Names DOB 0 Abhinav 10/01/2009 1 Aryan 24/03/2009 2 Manthan 28/02/2009 After creating the dataset we need to connect the data frame to the database support which is provided for sqlite3.Connection objects. Python3 #importing sql libraryfrom sqlalchemy import create_engine # create a reference# for sql libraryengine = create_engine('sqlite://', echo = False) # attach the data frame to the sql# with a name of the table# as "Employee_Data"dataset.to_sql('Employee_Data', con = engine) # show the complete data# from Employee_Data tableprint(engine.execute("SELECT * FROM Employee_Data").fetchall()) Output : [(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'), (2, 'Manthan', '28/02/2009')] After adding the data to the database, it is visible to us in the form of records. Data can also be appended to the previously created database as shown below: Python3 # Create a dataframe# object from dictionarydf1 = pd.DataFrame({'Names' : ['Sonia', 'Priya'], 'DOB':['18/10/2009','14/06/2009']}) # appending new data frame# to existing data framedf1.to_sql('Employee_Data', con = engine, if_exists = 'append') # run a sql queryprint(engine.execute("SELECT * FROM Employee_Data").fetchall()) Output : [(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'), (2, 'Manthan', '28/02/2009'), (0, 'Sonia', '18/10/2009'), (1, 'Priya', '14/06/2009')] As understood from the above example that although data is appended the indexing again started from 0 only when a new data frame is appended.A data frame can be transferred to the SQL database, the same way data frame can also be read from the SQL database. the return type of the read_sql is data frame. Python3 # reading the sql database# with index "Names"df2 = pd.read_sql('Employee_Data', con = engine, index_col = 'Names', parse_dates = ['DOB'])# show the dataframeprint(df2) # print new lineprint() # show the type of df2print(type(df2)) Output : id DOB Names Sonia 0 2009-10-18 Priya 1 2009-06-14 we can also access a particular column in a database rather than the whole table. Python3 # acccesing only a particular# column from the databasedf3 = pd.read_sql('Employee_Data', con = engine, columns = ["Names"])# show the dataprint(df3) Output : Names 0 Sonia 1 Priya If we want to have the data in the database in the form of a list that to is possible. Python3 # get a particular column# from a database in the# form of listdf4 = pd.read_sql('Employee_Data', con = engine, index_col = 'Names', columns = ["Names"])# show the dataprint(df4) Output : Empty DataFrame Columns: [] Index: [Sonia, Priya] It is possible to write SQL queries in python using read_sql_query() command and passing the appropriate SQL query and the connection object . parse_dates: This parameter helps to converts the dates that were originally passed as dates from our side into the genuine dates format. Python3 # run a sql query in the database# and store result in a dataframedf5 = pd.read_sql_query('Select DOB from Employee_Data', con = engine, parse_dates = ['DOB'])# show the dataframeprint(df5) Output : DOB 0 2009-10-18 1 2009-06-14 rs1686740 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25473, "s": 25445, "text": "\n02 Sep, 2021" }, { "code": null, "e": 25635, "s": 25473, "text": "In this article, we aim to convert the data frame into a SQL database and then try to read the content from the SQL database using SQL queries or through a table" }, { "code": null, "e": 25760, "s": 25635, "text": "To deal with SQL in python we need to install the sqlalchemy library using the below-mentioned command by running it in cmd:" }, { "code": null, "e": 25785, "s": 25760, "text": " pip install sqlalchemy " }, { "code": null, "e": 25851, "s": 25785, "text": "There is a need to create a pandas data frame to proceed further." }, { "code": null, "e": 25859, "s": 25851, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a dataframe# object from dictionarydataset = pd.DataFrame({'Names':['Abhinav','Aryan', 'Manthan'], 'DOB' : ['10/01/2009','24/03/2009', '28/02/2009']})# show the dataframeprint(dataset)", "e": 26182, "s": 25859, "text": null }, { "code": null, "e": 26191, "s": 26182, "text": "Output :" }, { "code": null, "e": 26283, "s": 26191, "text": " Names DOB\n0 Abhinav 10/01/2009\n1 Aryan 24/03/2009\n2 Manthan 28/02/2009" }, { "code": null, "e": 26419, "s": 26283, "text": "After creating the dataset we need to connect the data frame to the database support which is provided for sqlite3.Connection objects. " }, { "code": null, "e": 26427, "s": 26419, "text": "Python3" }, { "code": "#importing sql libraryfrom sqlalchemy import create_engine # create a reference# for sql libraryengine = create_engine('sqlite://', echo = False) # attach the data frame to the sql# with a name of the table# as \"Employee_Data\"dataset.to_sql('Employee_Data', con = engine) # show the complete data# from Employee_Data tableprint(engine.execute(\"SELECT * FROM Employee_Data\").fetchall())", "e": 26849, "s": 26427, "text": null }, { "code": null, "e": 26858, "s": 26849, "text": "Output :" }, { "code": null, "e": 26948, "s": 26858, "text": "[(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'), \n(2, 'Manthan', '28/02/2009')]" }, { "code": null, "e": 27108, "s": 26948, "text": "After adding the data to the database, it is visible to us in the form of records. Data can also be appended to the previously created database as shown below:" }, { "code": null, "e": 27116, "s": 27108, "text": "Python3" }, { "code": "# Create a dataframe# object from dictionarydf1 = pd.DataFrame({'Names' : ['Sonia', 'Priya'], 'DOB':['18/10/2009','14/06/2009']}) # appending new data frame# to existing data framedf1.to_sql('Employee_Data', con = engine, if_exists = 'append') # run a sql queryprint(engine.execute(\"SELECT * FROM Employee_Data\").fetchall())", "e": 27480, "s": 27116, "text": null }, { "code": null, "e": 27489, "s": 27480, "text": "Output :" }, { "code": null, "e": 27637, "s": 27489, "text": "[(0, 'Abhinav', '10/01/2009'), (1, 'Aryan', '24/03/2009'),\n (2, 'Manthan', '28/02/2009'), (0, 'Sonia', '18/10/2009'),\n (1, 'Priya', '14/06/2009')]" }, { "code": null, "e": 27943, "s": 27637, "text": "As understood from the above example that although data is appended the indexing again started from 0 only when a new data frame is appended.A data frame can be transferred to the SQL database, the same way data frame can also be read from the SQL database. the return type of the read_sql is data frame. " }, { "code": null, "e": 27951, "s": 27943, "text": "Python3" }, { "code": "# reading the sql database# with index \"Names\"df2 = pd.read_sql('Employee_Data', con = engine, index_col = 'Names', parse_dates = ['DOB'])# show the dataframeprint(df2) # print new lineprint() # show the type of df2print(type(df2))", "e": 28234, "s": 27951, "text": null }, { "code": null, "e": 28246, "s": 28234, "text": "Output : " }, { "code": null, "e": 28324, "s": 28246, "text": " id DOB\nNames \nSonia 0 2009-10-18\nPriya 1 2009-06-14" }, { "code": null, "e": 28407, "s": 28324, "text": "we can also access a particular column in a database rather than the whole table. " }, { "code": null, "e": 28415, "s": 28407, "text": "Python3" }, { "code": "# acccesing only a particular# column from the databasedf3 = pd.read_sql('Employee_Data', con = engine, columns = [\"Names\"])# show the dataprint(df3)", "e": 28599, "s": 28415, "text": null }, { "code": null, "e": 28609, "s": 28599, "text": "Output : " }, { "code": null, "e": 28633, "s": 28609, "text": "Names\n0 Sonia\n1 Priya" }, { "code": null, "e": 28721, "s": 28633, "text": "If we want to have the data in the database in the form of a list that to is possible. " }, { "code": null, "e": 28729, "s": 28721, "text": "Python3" }, { "code": "# get a particular column# from a database in the# form of listdf4 = pd.read_sql('Employee_Data', con = engine, index_col = 'Names', columns = [\"Names\"])# show the dataprint(df4)", "e": 28959, "s": 28729, "text": null }, { "code": null, "e": 28968, "s": 28959, "text": "Output :" }, { "code": null, "e": 29018, "s": 28968, "text": "Empty DataFrame\nColumns: []\nIndex: [Sonia, Priya]" }, { "code": null, "e": 29161, "s": 29018, "text": "It is possible to write SQL queries in python using read_sql_query() command and passing the appropriate SQL query and the connection object ." }, { "code": null, "e": 29299, "s": 29161, "text": "parse_dates: This parameter helps to converts the dates that were originally passed as dates from our side into the genuine dates format." }, { "code": null, "e": 29307, "s": 29299, "text": "Python3" }, { "code": "# run a sql query in the database# and store result in a dataframedf5 = pd.read_sql_query('Select DOB from Employee_Data', con = engine, parse_dates = ['DOB'])# show the dataframeprint(df5)", "e": 29543, "s": 29307, "text": null }, { "code": null, "e": 29553, "s": 29543, "text": "Output : " }, { "code": null, "e": 29586, "s": 29553, "text": " DOB\n0 2009-10-18\n1 2009-06-14" }, { "code": null, "e": 29596, "s": 29586, "text": "rs1686740" }, { "code": null, "e": 29620, "s": 29596, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29634, "s": 29620, "text": "Python-pandas" }, { "code": null, "e": 29641, "s": 29634, "text": "Python" }, { "code": null, "e": 29739, "s": 29641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29757, "s": 29739, "text": "Python Dictionary" }, { "code": null, "e": 29792, "s": 29757, "text": "Read a file line by line in Python" }, { "code": null, "e": 29824, "s": 29792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29846, "s": 29824, "text": "Enumerate() in Python" }, { "code": null, "e": 29888, "s": 29846, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29918, "s": 29888, "text": "Iterate over a list in Python" }, { "code": null, "e": 29944, "s": 29918, "text": "Python String | replace()" }, { "code": null, "e": 29973, "s": 29944, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30017, "s": 29973, "text": "Reading and Writing to text files in Python" } ]
Multiple calculations in 4 processes using fork() - GeeksforGeeks
10 Nov, 2017 Write a program to create 4 processes: parent process and its child process which perform various tasks : Parent process count the frequency of a number 1st child sort the array 2nd child find total even number(s) in a given array 3rd child calculate the sum of even numbers in an array Example – Input : 2, 4, 6, 7, 9, 0, 1, 5, 8, 3 Output : Parent process : the key to be searched is 7 the frequency of 7 is 1 1st child process : the sorted array is 0 1 2 3 4 5 6 7 8 9 2nd child process : Total even no are: 5 3rd child process : the sum is :45 Explanation – Here, we had used fork() function to create 4 processes three child and one parent process. So, here we use two fork() function which create 4 process n1=fork() and n2 = fork() if n1 and n2 is greater than zero then it is parent process which counts the frequency of a number. if n1 is equal to zero and n2 is greater than zero then it is 1st child process which sorts the given array. if n1 is greater than zero and n2 is equal to zero than it is 2nd child process which finds the total even numbers in the array. if n1 and n2 both equal to zero then it is 3rd child calculates the sum of all elements in an array. Code – // C++ code to demonstrate the calculation// in parent and its 3 child processes using fork()#include <iostream>#include <unistd.h> using namespace std; int main(){ int a[10] = { 2, 4, 6, 7, 9, 0, 1, 5, 8, 3 }; int n1, n2, i, j, key, c, temp; n1 = fork(); n2 = fork(); // if n1 is greater than zero // and n2 is greater than zero // then parent process executes if (n1 > 0 && n2 > 0) { int c = 0; cout << "Parent process :" << endl; // key to be searched is 7 key = 7; cout << "the key to be searched is " << key << endl; for (i = 0; i < 10; i++) { if (a[i] == key) // frequency of key c++; } cout << "the frequency of " << key << " is " << c << endl; } // else if n1 is zero // and n2 is greater than zero // then 1st child process executes else if (n1 == 0 && n2 > 0) { cout << "1st child process :" << endl; for (i = 0; i < 10; i++) { for (j = 0; j < 9; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } cout << "the sorted array is" << endl; for (i = 0; i < 10; i++) { cout << a[i] << " "; } cout << endl; } // else if n1 is greater than zero // and n2 is zero // then 2nd child process executes else if (n1 > 0 && n2 == 0) { int f = 0; cout << "2nd child process :" << endl; for (i = 0; i < 10; i++) { // counting total even numbers if (a[i] % 2 == 0) { f++; } } cout << " Total even no are: " << f << " "; cout << endl; } // else if n1 is zero // and n2 is zero // then 3rd child process executes else if (n1 == 0 && n2 == 0) { cout << "3rd child process :" << endl; int sum = 0; // summing all given keys for (i = 0; i < 10; i++) { sum = sum + a[i]; } cout << "the sum is :" << sum << endl; } return 0;} Output – Parent process : the key to be searched is 7 the frequency of 7 is 1 1st child process : the sorted array is 0 1 2 3 4 5 6 7 8 9 2nd child process : Total even no are: 5 3rd child process : the sum is :45 This article is contributed by Shivani Baghel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.or C++ Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25851, "s": 25823, "text": "\n10 Nov, 2017" }, { "code": null, "e": 25957, "s": 25851, "text": "Write a program to create 4 processes: parent process and its child process which perform various tasks :" }, { "code": null, "e": 26004, "s": 25957, "text": "Parent process count the frequency of a number" }, { "code": null, "e": 26029, "s": 26004, "text": "1st child sort the array" }, { "code": null, "e": 26082, "s": 26029, "text": "2nd child find total even number(s) in a given array" }, { "code": null, "e": 26138, "s": 26082, "text": "3rd child calculate the sum of even numbers in an array" }, { "code": null, "e": 26148, "s": 26138, "text": "Example –" }, { "code": null, "e": 26407, "s": 26148, "text": "Input : \n2, 4, 6, 7, 9, 0, 1, 5, 8, 3\n\nOutput : \nParent process :\nthe key to be searched is 7\nthe frequency of 7 is 1\n1st child process :\nthe sorted array is\n0 1 2 3 4 5 6 7 8 9 \n2nd child process :\n Total even no are: 5 \n3rd child process :\nthe sum is :45\n" }, { "code": null, "e": 26598, "s": 26407, "text": "Explanation – Here, we had used fork() function to create 4 processes three child and one parent process. So, here we use two fork() function which create 4 process n1=fork() and n2 = fork()" }, { "code": null, "e": 26698, "s": 26598, "text": "if n1 and n2 is greater than zero then it is parent process which counts the frequency of a number." }, { "code": null, "e": 26807, "s": 26698, "text": "if n1 is equal to zero and n2 is greater than zero then it is 1st child process which sorts the given array." }, { "code": null, "e": 26936, "s": 26807, "text": "if n1 is greater than zero and n2 is equal to zero than it is 2nd child process which finds the total even numbers in the array." }, { "code": null, "e": 27037, "s": 26936, "text": "if n1 and n2 both equal to zero then it is 3rd child calculates the sum of all elements in an array." }, { "code": null, "e": 27044, "s": 27037, "text": "Code –" }, { "code": "// C++ code to demonstrate the calculation// in parent and its 3 child processes using fork()#include <iostream>#include <unistd.h> using namespace std; int main(){ int a[10] = { 2, 4, 6, 7, 9, 0, 1, 5, 8, 3 }; int n1, n2, i, j, key, c, temp; n1 = fork(); n2 = fork(); // if n1 is greater than zero // and n2 is greater than zero // then parent process executes if (n1 > 0 && n2 > 0) { int c = 0; cout << \"Parent process :\" << endl; // key to be searched is 7 key = 7; cout << \"the key to be searched is \" << key << endl; for (i = 0; i < 10; i++) { if (a[i] == key) // frequency of key c++; } cout << \"the frequency of \" << key << \" is \" << c << endl; } // else if n1 is zero // and n2 is greater than zero // then 1st child process executes else if (n1 == 0 && n2 > 0) { cout << \"1st child process :\" << endl; for (i = 0; i < 10; i++) { for (j = 0; j < 9; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } cout << \"the sorted array is\" << endl; for (i = 0; i < 10; i++) { cout << a[i] << \" \"; } cout << endl; } // else if n1 is greater than zero // and n2 is zero // then 2nd child process executes else if (n1 > 0 && n2 == 0) { int f = 0; cout << \"2nd child process :\" << endl; for (i = 0; i < 10; i++) { // counting total even numbers if (a[i] % 2 == 0) { f++; } } cout << \" Total even no are: \" << f << \" \"; cout << endl; } // else if n1 is zero // and n2 is zero // then 3rd child process executes else if (n1 == 0 && n2 == 0) { cout << \"3rd child process :\" << endl; int sum = 0; // summing all given keys for (i = 0; i < 10; i++) { sum = sum + a[i]; } cout << \"the sum is :\" << sum << endl; } return 0;}", "e": 29233, "s": 27044, "text": null }, { "code": null, "e": 29242, "s": 29233, "text": "Output –" }, { "code": null, "e": 29451, "s": 29242, "text": "Parent process :\nthe key to be searched is 7\nthe frequency of 7 is 1\n1st child process :\nthe sorted array is\n0 1 2 3 4 5 6 7 8 9 \n2nd child process :\n Total even no are: 5 \n3rd child process :\nthe sum is :45\n" }, { "code": null, "e": 29753, "s": 29451, "text": "This article is contributed by Shivani Baghel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29880, "s": 29753, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.or" }, { "code": null, "e": 29893, "s": 29880, "text": "C++ Programs" }, { "code": null, "e": 29906, "s": 29893, "text": "Mathematical" }, { "code": null, "e": 29919, "s": 29906, "text": "Mathematical" }, { "code": null, "e": 30017, "s": 29919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30058, "s": 30017, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 30117, "s": 30058, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30138, "s": 30117, "text": "Const keyword in C++" }, { "code": null, "e": 30150, "s": 30138, "text": "cout in C++" }, { "code": null, "e": 30171, "s": 30150, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 30201, "s": 30171, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30261, "s": 30201, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30276, "s": 30261, "text": "C++ Data Types" }, { "code": null, "e": 30319, "s": 30276, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Import another TypeScript Files ? - GeeksforGeeks
02 Mar, 2020 Some times we want some facility that we have been used in our previous projects, in that situation we can’t rewrite that script again we can simply import that by making that file exportable. To import other TypeScript files into an existing TypeScript file we should know the concept of modules. Starting with ECMAScript 2015, JavaScript has a concept of modules and TypeScript shares this concept. Modules are small units of independent, reusable code that is desired to be used as the building blocks. Modules let the developer define private and public members separately, making it one of the more desired design patterns in the script paradigm. You may see modules as Classes as in any other Object-Oriented Programming Language. Exported from a different module, it has to be imported using one of the import forms. Example 1: Import a class from a file to another file. Code 1: This code file will be imported and save the file name as exportedFile.ts in a directory.// Exporting the class which will be// used in another file// Export keyword or form should be// used to use the class export class exportedFile { // Class method which prints the // user called in another file sayHello(user){ return "Hello " + user+ "!"; }} // Exporting the class which will be// used in another file// Export keyword or form should be// used to use the class export class exportedFile { // Class method which prints the // user called in another file sayHello(user){ return "Hello " + user+ "!"; }} Code 2: This code file will be import the above code, and save this file as the name mainFile.ts in the same directory.// Importing the class from the location of the fileimport { exportedFile } from "./exportedFile"; // Creating an object of the class which is importedlet user = new exportedFile(); // Calling the imported class functionconsole.log(user.sayHello("Geek")); // Importing the class from the location of the fileimport { exportedFile } from "./exportedFile"; // Creating an object of the class which is importedlet user = new exportedFile(); // Calling the imported class functionconsole.log(user.sayHello("Geek")); Output:Hello Geek! Hello Geek! Note: You have to compile the mainFile.ts that will generate the mainFile.js that run js file. In the TypeScript file which is to be imported must include an export form and the main file where the class is imported must contain an import form, by which TypeScript can identify the file which is used. By using this type of export and import forms we can import classes, interfaces, functions, variables anything that we want. Example 2: We can also import them by renaming them as of our needs. Importing a function from another file by renaming the function. Code 1: Save this file as a exportedFile.ts// Exporting the function which will be// used in another fileexport function sayHello(user:string) { return "Hello " + user + "!";} // Exporting the function which will be// used in another fileexport function sayHello(user:string) { return "Hello " + user + "!";} Code 2: Save this file as a mainFile.ts// Importing the function sayHello and renaming it // from the location of the fileimport { sayHello as hello } from "./exportedFile"; let user = "Jake"; // Calling the imported functionconsole.log(hello(user)); // Importing the function sayHello and renaming it // from the location of the fileimport { sayHello as hello } from "./exportedFile"; let user = "Jake"; // Calling the imported functionconsole.log(hello(user)); Output:Hello Jake! Hello Jake! Example 3: We can import all the contents of a file by using import all form as shown below. Import all is indicated as ‘import *’. Code 1: Save this file as a exportedFile.ts// Here we have to export all the// class, interface, function export class sayGoodByeTo { goodbye(user: string) { return "Good bye " + user + "!"; }}export interface howareYou { howareyou(user: string) : string;}export function sayHello(user:string) { return "Hello " + user + "!";} // Here we have to export all the// class, interface, function export class sayGoodByeTo { goodbye(user: string) { return "Good bye " + user + "!"; }}export interface howareYou { howareyou(user: string) : string;}export function sayHello(user:string) { return "Hello " + user + "!";} Code 2: Save this file as a mainFile.ts// Importing everything from the exportedFile.ts module// Import all is indicated using 'import *' // and here 'as' keyword import * as importAll from "./exportedFile";let user = "Geeks"; // Calling the imported functionconsole.log(importAll.sayHello(user)); // Implementing the imported interfaceclass hru implements importAll.howareYou { howareyou(user: string){ return "How are you "+user+"!"; }} // Calling the implemented function in the // Interface which is importedlet jd = new hru();console.log(jd.howareyou(user)); // Creating the object of the imported class// and calling it's functionlet bye = new importAll.sayGoodByeTo();console.log(bye.goodbye(user)); // Importing everything from the exportedFile.ts module// Import all is indicated using 'import *' // and here 'as' keyword import * as importAll from "./exportedFile";let user = "Geeks"; // Calling the imported functionconsole.log(importAll.sayHello(user)); // Implementing the imported interfaceclass hru implements importAll.howareYou { howareyou(user: string){ return "How are you "+user+"!"; }} // Calling the implemented function in the // Interface which is importedlet jd = new hru();console.log(jd.howareyou(user)); // Creating the object of the imported class// and calling it's functionlet bye = new importAll.sayGoodByeTo();console.log(bye.goodbye(user)); Output:Hello Geeks! How are you Geeks! Good bye Geeks! Hello Geeks! How are you Geeks! Good bye Geeks! Note: To import all, it is necessary to rename the module. It is basically wrapping all the class, function, interface in a single module when we are using the as keyword. We can also import multiple files by simply writing multiple import forms and module location. Picked TypeScript JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26081, "s": 26053, "text": "\n02 Mar, 2020" }, { "code": null, "e": 26482, "s": 26081, "text": "Some times we want some facility that we have been used in our previous projects, in that situation we can’t rewrite that script again we can simply import that by making that file exportable. To import other TypeScript files into an existing TypeScript file we should know the concept of modules. Starting with ECMAScript 2015, JavaScript has a concept of modules and TypeScript shares this concept." }, { "code": null, "e": 26905, "s": 26482, "text": "Modules are small units of independent, reusable code that is desired to be used as the building blocks. Modules let the developer define private and public members separately, making it one of the more desired design patterns in the script paradigm. You may see modules as Classes as in any other Object-Oriented Programming Language. Exported from a different module, it has to be imported using one of the import forms." }, { "code": null, "e": 26960, "s": 26905, "text": "Example 1: Import a class from a file to another file." }, { "code": null, "e": 27337, "s": 26960, "text": "Code 1: This code file will be imported and save the file name as exportedFile.ts in a directory.// Exporting the class which will be// used in another file// Export keyword or form should be// used to use the class export class exportedFile { // Class method which prints the // user called in another file sayHello(user){ return \"Hello \" + user+ \"!\"; }}" }, { "code": "// Exporting the class which will be// used in another file// Export keyword or form should be// used to use the class export class exportedFile { // Class method which prints the // user called in another file sayHello(user){ return \"Hello \" + user+ \"!\"; }}", "e": 27617, "s": 27337, "text": null }, { "code": null, "e": 27994, "s": 27617, "text": "Code 2: This code file will be import the above code, and save this file as the name mainFile.ts in the same directory.// Importing the class from the location of the fileimport { exportedFile } from \"./exportedFile\"; // Creating an object of the class which is importedlet user = new exportedFile(); // Calling the imported class functionconsole.log(user.sayHello(\"Geek\"));" }, { "code": "// Importing the class from the location of the fileimport { exportedFile } from \"./exportedFile\"; // Creating an object of the class which is importedlet user = new exportedFile(); // Calling the imported class functionconsole.log(user.sayHello(\"Geek\"));", "e": 28252, "s": 27994, "text": null }, { "code": null, "e": 28271, "s": 28252, "text": "Output:Hello Geek!" }, { "code": null, "e": 28283, "s": 28271, "text": "Hello Geek!" }, { "code": null, "e": 28378, "s": 28283, "text": "Note: You have to compile the mainFile.ts that will generate the mainFile.js that run js file." }, { "code": null, "e": 28710, "s": 28378, "text": "In the TypeScript file which is to be imported must include an export form and the main file where the class is imported must contain an import form, by which TypeScript can identify the file which is used. By using this type of export and import forms we can import classes, interfaces, functions, variables anything that we want." }, { "code": null, "e": 28844, "s": 28710, "text": "Example 2: We can also import them by renaming them as of our needs. Importing a function from another file by renaming the function." }, { "code": null, "e": 29023, "s": 28844, "text": "Code 1: Save this file as a exportedFile.ts// Exporting the function which will be// used in another fileexport function sayHello(user:string) { return \"Hello \" + user + \"!\";}" }, { "code": "// Exporting the function which will be// used in another fileexport function sayHello(user:string) { return \"Hello \" + user + \"!\";}", "e": 29159, "s": 29023, "text": null }, { "code": null, "e": 29412, "s": 29159, "text": "Code 2: Save this file as a mainFile.ts// Importing the function sayHello and renaming it // from the location of the fileimport { sayHello as hello } from \"./exportedFile\"; let user = \"Jake\"; // Calling the imported functionconsole.log(hello(user));" }, { "code": "// Importing the function sayHello and renaming it // from the location of the fileimport { sayHello as hello } from \"./exportedFile\"; let user = \"Jake\"; // Calling the imported functionconsole.log(hello(user));", "e": 29626, "s": 29412, "text": null }, { "code": null, "e": 29645, "s": 29626, "text": "Output:Hello Jake!" }, { "code": null, "e": 29657, "s": 29645, "text": "Hello Jake!" }, { "code": null, "e": 29789, "s": 29657, "text": "Example 3: We can import all the contents of a file by using import all form as shown below. Import all is indicated as ‘import *’." }, { "code": null, "e": 30135, "s": 29789, "text": "Code 1: Save this file as a exportedFile.ts// Here we have to export all the// class, interface, function export class sayGoodByeTo { goodbye(user: string) { return \"Good bye \" + user + \"!\"; }}export interface howareYou { howareyou(user: string) : string;}export function sayHello(user:string) { return \"Hello \" + user + \"!\";}" }, { "code": "// Here we have to export all the// class, interface, function export class sayGoodByeTo { goodbye(user: string) { return \"Good bye \" + user + \"!\"; }}export interface howareYou { howareyou(user: string) : string;}export function sayHello(user:string) { return \"Hello \" + user + \"!\";}", "e": 30438, "s": 30135, "text": null }, { "code": null, "e": 31162, "s": 30438, "text": "Code 2: Save this file as a mainFile.ts// Importing everything from the exportedFile.ts module// Import all is indicated using 'import *' // and here 'as' keyword import * as importAll from \"./exportedFile\";let user = \"Geeks\"; // Calling the imported functionconsole.log(importAll.sayHello(user)); // Implementing the imported interfaceclass hru implements importAll.howareYou { howareyou(user: string){ return \"How are you \"+user+\"!\"; }} // Calling the implemented function in the // Interface which is importedlet jd = new hru();console.log(jd.howareyou(user)); // Creating the object of the imported class// and calling it's functionlet bye = new importAll.sayGoodByeTo();console.log(bye.goodbye(user));" }, { "code": "// Importing everything from the exportedFile.ts module// Import all is indicated using 'import *' // and here 'as' keyword import * as importAll from \"./exportedFile\";let user = \"Geeks\"; // Calling the imported functionconsole.log(importAll.sayHello(user)); // Implementing the imported interfaceclass hru implements importAll.howareYou { howareyou(user: string){ return \"How are you \"+user+\"!\"; }} // Calling the implemented function in the // Interface which is importedlet jd = new hru();console.log(jd.howareyou(user)); // Creating the object of the imported class// and calling it's functionlet bye = new importAll.sayGoodByeTo();console.log(bye.goodbye(user));", "e": 31847, "s": 31162, "text": null }, { "code": null, "e": 31903, "s": 31847, "text": "Output:Hello Geeks!\nHow are you Geeks!\nGood bye Geeks!\n" }, { "code": null, "e": 31952, "s": 31903, "text": "Hello Geeks!\nHow are you Geeks!\nGood bye Geeks!\n" }, { "code": null, "e": 32219, "s": 31952, "text": "Note: To import all, it is necessary to rename the module. It is basically wrapping all the class, function, interface in a single module when we are using the as keyword. We can also import multiple files by simply writing multiple import forms and module location." }, { "code": null, "e": 32226, "s": 32219, "text": "Picked" }, { "code": null, "e": 32237, "s": 32226, "text": "TypeScript" }, { "code": null, "e": 32248, "s": 32237, "text": "JavaScript" }, { "code": null, "e": 32265, "s": 32248, "text": "Web Technologies" }, { "code": null, "e": 32292, "s": 32265, "text": "Web technologies Questions" }, { "code": null, "e": 32390, "s": 32292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32430, "s": 32390, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32475, "s": 32430, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32536, "s": 32475, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32608, "s": 32536, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32660, "s": 32608, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 32700, "s": 32660, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32745, "s": 32700, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32788, "s": 32745, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32849, "s": 32788, "text": "Difference between var, let and const keywords in JavaScript" } ]
byte Keyword in C# - GeeksforGeeks
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System.Byte. byte keyword occupies 1 byte (8 bits) in the memory. Syntax: byte variable_name = value; Example: Input: 250 Output: number: 250 Size of a byte variable: 1 Input: 150 Output: Type of num1: System.Byte num1: 150 Size of a byte variable: 1 Example 1: // C# program to show the usage of byte keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // byte variable declaration byte num = 255; // to print value Console.WriteLine("num: " + num); // to print size of a byte Console.WriteLine("Size of a byte variable: " + sizeof(byte)); }} Output: num: 255 Size of a byte variable: 1 Example 2: // C# program to show the usage of byte keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // byte variable declaration byte num1 = 261; // to print value Console.WriteLine("num1: " + num1); // to print size of a byte Console.WriteLine("Size of a byte variable: " + sizeof(byte)); }} Error: When we enter number beyond the range from (0-255). Constant value `261' cannot be converted to a `byte' Example 3: // C# program to show the usage of byte keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // byte variable declaration byte num1 = 150; // to print type of variable Console.WriteLine("Type of num1: " + num1.GetType()); // to print value Console.WriteLine("num1: " + num1); // to print size of a byte Console.WriteLine("Size of a byte variable: " + sizeof(byte)); // hit ENTER to exit Console.ReadLine(); }}} Output: Type of num1: System.Byte num1: 150 Size of a byte variable: 1 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Switch Statement in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25801, "s": 25547, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. byte is a keyword that is used to declare a variable which can store an unsigned value range from 0 to 255. It is an alias of System.Byte." }, { "code": null, "e": 25854, "s": 25801, "text": "byte keyword occupies 1 byte (8 bits) in the memory." }, { "code": null, "e": 25862, "s": 25854, "text": "Syntax:" }, { "code": null, "e": 25890, "s": 25862, "text": "byte variable_name = value;" }, { "code": null, "e": 25899, "s": 25890, "text": "Example:" }, { "code": null, "e": 26067, "s": 25899, "text": "Input: 250\n\nOutput: number: 250\n Size of a byte variable: 1\n\nInput: 150\n\nOutput: Type of num1: System.Byte\n num1: 150\n Size of a byte variable: 1\n" }, { "code": null, "e": 26078, "s": 26067, "text": "Example 1:" }, { "code": "// C# program to show the usage of byte keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // byte variable declaration byte num = 255; // to print value Console.WriteLine(\"num: \" + num); // to print size of a byte Console.WriteLine(\"Size of a byte variable: \" + sizeof(byte)); }}", "e": 26451, "s": 26078, "text": null }, { "code": null, "e": 26459, "s": 26451, "text": "Output:" }, { "code": null, "e": 26496, "s": 26459, "text": "num: 255\nSize of a byte variable: 1\n" }, { "code": null, "e": 26507, "s": 26496, "text": "Example 2:" }, { "code": "// C# program to show the usage of byte keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // byte variable declaration byte num1 = 261; // to print value Console.WriteLine(\"num1: \" + num1); // to print size of a byte Console.WriteLine(\"Size of a byte variable: \" + sizeof(byte)); }}", "e": 26883, "s": 26507, "text": null }, { "code": null, "e": 26942, "s": 26883, "text": "Error: When we enter number beyond the range from (0-255)." }, { "code": null, "e": 26995, "s": 26942, "text": "Constant value `261' cannot be converted to a `byte'" }, { "code": null, "e": 27006, "s": 26995, "text": "Example 3:" }, { "code": "// C# program to show the usage of byte keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // byte variable declaration byte num1 = 150; // to print type of variable Console.WriteLine(\"Type of num1: \" + num1.GetType()); // to print value Console.WriteLine(\"num1: \" + num1); // to print size of a byte Console.WriteLine(\"Size of a byte variable: \" + sizeof(byte)); // hit ENTER to exit Console.ReadLine(); }}}", "e": 27556, "s": 27006, "text": null }, { "code": null, "e": 27564, "s": 27556, "text": "Output:" }, { "code": null, "e": 27628, "s": 27564, "text": "Type of num1: System.Byte\nnum1: 150\nSize of a byte variable: 1\n" }, { "code": null, "e": 27643, "s": 27628, "text": "CSharp-keyword" }, { "code": null, "e": 27646, "s": 27643, "text": "C#" }, { "code": null, "e": 27744, "s": 27646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27767, "s": 27744, "text": "Extension Method in C#" }, { "code": null, "e": 27795, "s": 27767, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27812, "s": 27795, "text": "C# | Inheritance" }, { "code": null, "e": 27834, "s": 27812, "text": "Partial Classes in C#" }, { "code": null, "e": 27863, "s": 27834, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27903, "s": 27863, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27946, "s": 27903, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27969, "s": 27946, "text": "Switch Statement in C#" }, { "code": null, "e": 28002, "s": 27969, "text": "Linked List Implementation in C#" } ]
How to create an Asynchronous function in Javascript? - GeeksforGeeks
17 Dec, 2021 JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body> <div id="message"></div> <script> var msg = document.getElementById("message"); function f1() { setTimeout(function () { msg.innerHTML += "<p>f1 is starting</p>"; msg.innerHTML += "<p>f1 is ending</p>"; }, 100); } function f2() { msg.innerHTML += "<p>f2 is starting</p>"; f1(); msg.innerHTML += "<p>f2 is ending</p>"; } f2(); </script></body></html> Output f2 is starting f2 is ending f1 is starting f1 is ending Now, we can see after executing setTimeout(f1, 100), our program is not waiting for the timer to finish it but it is jumping on the next statement immediately. This happens because if we want to execute some event, JavaScript puts the event in the event queue and continues the normal execution of the program. The engine periodically looks in the event queue to see if some event needs to be called or not.But we may want our program to wait until some particular event or work is completed before processing further commands. An asynchronous function is implemented using async, await, and promises. async: The “async” keyword defines an asynchronous function. Syntax async function FunctionName(){ ... } await: The “async” function contains “await” that pauses the execution of “async” function. “await” is only valid inside the “async” function. Promise: A Promise is a proxy value. It tells us about the success/failure of the asynchronous event. A Promise must contain resolve() or reject() call or else the consumer of the Promise will never know whether Promise is fulfilled or not. If that happened then the program will keep waiting for await and that code block will never be executed further. There is a lot more to Promise but we can make Asynchronous function without any deep knowledge of it. Example: Let’s redo the above example using the Asynchronous function. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body> <div id="message"></div> <script> var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f1 is starting</p>"; msg.innerHTML += "<p>f1 is ending</p>"; resolve(); }, 100); }) } async function f2() { msg.innerHTML += "<p>f2 is starting</p>"; // Engine waits for f1() to finish it's // execution before executing the next line await f1(); msg.innerHTML += "<p>f2 is ending</p>"; } f2(); </script></body></html> Output: f2 is starting f1 is starting f1 is ending f2 is ending In the above example, the program waits for f1() to complete its execution before proceeding further. The “await” stops the execution of that code segment until a Promise is received. The resolve() is used to resolve the Promise. It means the Promise is fulfilled. Similar to resolve, we can also use reject() to know the Promise is rejected. The reject() function is mainly used for debugging and error purpose, we don’t need to dig deep into it for now. Example: If we want the Promise to return some value, we can pass it in resolve(variable). HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body> <div id="message"></div> <script> var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f1 is starting</p>"; msg.innerHTML += "<p>f1 is ending</p>"; resolve(1); }, 100); }) } async function f2() { msg.innerHTML += "<p>f2 is starting</p>"; var p = await f1(); if (p == 1) msg.innerHTML += "<p>Promise Received</p>" msg.innerHTML += "<p>f2 is ending</p>"; } f2(); </script></body></html> Output: f2 is starting f1 is starting f1 is ending Promise Received f2 is ending Waiting for Multiple Promises: What if we had to wait for multiple functions? We have two ways of doing it. Example: We can write multiple await statements sequentially. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body> <div id="message"></div> <script> var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f1 is starting</p>"; msg.innerHTML += "<p>f1 is ending</p>"; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f3 is starting</p>"; msg.innerHTML += "<p>f3 is ending</p>"; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += "<p>f2 is starting</p>"; await f1(); await f3(); msg.innerHTML += "<p>f2 is ending</p>"; } f2(); </script></body></html> Output f2 is starting f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending In the above example, first we get f2 is starting Then after 1 second we get f1 is starting f1 is ending Then after another 1 second, we get f3 is starting f3 is ending f2 is ending Example: The second way to wait for multiple Promises is to run the Promises in parallel using Promise.all(iterable object). Syntax: await Promise.all(iterable object); Example: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body> <div id="message"></div> <script> var msg = document.getElementById("message"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f1 is starting</p>"; msg.innerHTML += "<p>f1 is ending</p>"; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += "<p>f3 is starting</p>"; msg.innerHTML += "<p>f3 is ending</p>"; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += "<p>f2 is starting</p>"; await Promise.all([f1(), f3()]); msg.innerHTML += "<p>f2 is ending</p>"; } f2(); </script></body></html> Output f2 is starting f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending The output is the same as the previous code, but in this case, the program will output f2 is starting Then wait for 1second and output f1 is starting f1 is ending f3 is starting f3 is ending f2 is ending Since f1() and f3() are running in parallel we do not need to wait another 1 second before executing f3(). In simple words, the timer of setTimeout() in f1() and f3() starts at the same time. Note: We can also implement asynchronous behavior using only Promises without async/await and callbacks, refer to the following link for that: https://www.geeksforgeeks.org/javascript-callbacks/ https://www.geeksforgeeks.org/javascript-promises/ anikakapoor JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26373, "s": 26345, "text": "\n17 Dec, 2021" }, { "code": null, "e": 26541, "s": 26373, "text": "JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations." }, { "code": null, "e": 26551, "s": 26541, "text": "Example: " }, { "code": null, "e": 26556, "s": 26551, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\" /> <title></title></head><body> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); function f1() { setTimeout(function () { msg.innerHTML += \"<p>f1 is starting</p>\"; msg.innerHTML += \"<p>f1 is ending</p>\"; }, 100); } function f2() { msg.innerHTML += \"<p>f2 is starting</p>\"; f1(); msg.innerHTML += \"<p>f2 is ending</p>\"; } f2(); </script></body></html>", "e": 27147, "s": 26556, "text": null }, { "code": null, "e": 27155, "s": 27147, "text": "Output " }, { "code": null, "e": 27211, "s": 27155, "text": "f2 is starting\nf2 is ending\nf1 is starting\nf1 is ending" }, { "code": null, "e": 27740, "s": 27211, "text": "Now, we can see after executing setTimeout(f1, 100), our program is not waiting for the timer to finish it but it is jumping on the next statement immediately. This happens because if we want to execute some event, JavaScript puts the event in the event queue and continues the normal execution of the program. The engine periodically looks in the event queue to see if some event needs to be called or not.But we may want our program to wait until some particular event or work is completed before processing further commands. " }, { "code": null, "e": 27815, "s": 27740, "text": "An asynchronous function is implemented using async, await, and promises. " }, { "code": null, "e": 27877, "s": 27815, "text": "async: The “async” keyword defines an asynchronous function. " }, { "code": null, "e": 27925, "s": 27877, "text": "Syntax\nasync function FunctionName(){\n ...\n}" }, { "code": null, "e": 28068, "s": 27925, "text": "await: The “async” function contains “await” that pauses the execution of “async” function. “await” is only valid inside the “async” function." }, { "code": null, "e": 28526, "s": 28068, "text": "Promise: A Promise is a proxy value. It tells us about the success/failure of the asynchronous event. A Promise must contain resolve() or reject() call or else the consumer of the Promise will never know whether Promise is fulfilled or not. If that happened then the program will keep waiting for await and that code block will never be executed further. There is a lot more to Promise but we can make Asynchronous function without any deep knowledge of it." }, { "code": null, "e": 28599, "s": 28526, "text": "Example: Let’s redo the above example using the Asynchronous function. " }, { "code": null, "e": 28604, "s": 28599, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\" /> <title></title></head><body> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f1 is starting</p>\"; msg.innerHTML += \"<p>f1 is ending</p>\"; resolve(); }, 100); }) } async function f2() { msg.innerHTML += \"<p>f2 is starting</p>\"; // Engine waits for f1() to finish it's // execution before executing the next line await f1(); msg.innerHTML += \"<p>f2 is ending</p>\"; } f2(); </script></body></html>", "e": 29450, "s": 28604, "text": null }, { "code": null, "e": 29459, "s": 29450, "text": "Output: " }, { "code": null, "e": 29515, "s": 29459, "text": "f2 is starting\nf1 is starting\nf1 is ending\nf2 is ending" }, { "code": null, "e": 29971, "s": 29515, "text": "In the above example, the program waits for f1() to complete its execution before proceeding further. The “await” stops the execution of that code segment until a Promise is received. The resolve() is used to resolve the Promise. It means the Promise is fulfilled. Similar to resolve, we can also use reject() to know the Promise is rejected. The reject() function is mainly used for debugging and error purpose, we don’t need to dig deep into it for now." }, { "code": null, "e": 30064, "s": 29971, "text": "Example: If we want the Promise to return some value, we can pass it in resolve(variable). " }, { "code": null, "e": 30069, "s": 30064, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\" /> <title></title></head><body> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f1 is starting</p>\"; msg.innerHTML += \"<p>f1 is ending</p>\"; resolve(1); }, 100); }) } async function f2() { msg.innerHTML += \"<p>f2 is starting</p>\"; var p = await f1(); if (p == 1) msg.innerHTML += \"<p>Promise Received</p>\" msg.innerHTML += \"<p>f2 is ending</p>\"; } f2(); </script></body></html>", "e": 30870, "s": 30069, "text": null }, { "code": null, "e": 30879, "s": 30870, "text": "Output: " }, { "code": null, "e": 30952, "s": 30879, "text": "f2 is starting\nf1 is starting\nf1 is ending\nPromise Received\nf2 is ending" }, { "code": null, "e": 31060, "s": 30952, "text": "Waiting for Multiple Promises: What if we had to wait for multiple functions? We have two ways of doing it." }, { "code": null, "e": 31123, "s": 31060, "text": "Example: We can write multiple await statements sequentially. " }, { "code": null, "e": 31128, "s": 31123, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\" /> <title></title></head><body> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f1 is starting</p>\"; msg.innerHTML += \"<p>f1 is ending</p>\"; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f3 is starting</p>\"; msg.innerHTML += \"<p>f3 is ending</p>\"; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += \"<p>f2 is starting</p>\"; await f1(); await f3(); msg.innerHTML += \"<p>f2 is ending</p>\"; } f2(); </script></body></html>", "e": 32196, "s": 31128, "text": null }, { "code": null, "e": 32204, "s": 32196, "text": "Output " }, { "code": null, "e": 32288, "s": 32204, "text": "f2 is starting\nf1 is starting\nf1 is ending\nf3 is starting\nf3 is ending\nf2 is ending" }, { "code": null, "e": 32324, "s": 32288, "text": "In the above example, first we get " }, { "code": null, "e": 32340, "s": 32324, "text": "f2 is starting " }, { "code": null, "e": 32368, "s": 32340, "text": "Then after 1 second we get " }, { "code": null, "e": 32396, "s": 32368, "text": "f1 is starting\nf1 is ending" }, { "code": null, "e": 32433, "s": 32396, "text": "Then after another 1 second, we get " }, { "code": null, "e": 32474, "s": 32433, "text": "f3 is starting\nf3 is ending\nf2 is ending" }, { "code": null, "e": 32600, "s": 32474, "text": "Example: The second way to wait for multiple Promises is to run the Promises in parallel using Promise.all(iterable object). " }, { "code": null, "e": 32610, "s": 32600, "text": "Syntax: " }, { "code": null, "e": 32646, "s": 32610, "text": "await Promise.all(iterable object);" }, { "code": null, "e": 32656, "s": 32646, "text": "Example: " }, { "code": null, "e": 32661, "s": 32656, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\" /> <title></title></head><body> <div id=\"message\"></div> <script> var msg = document.getElementById(\"message\"); function f1() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f1 is starting</p>\"; msg.innerHTML += \"<p>f1 is ending</p>\"; resolve(); }, 1000); }) } function f3() { return new Promise(function (resolve, reject) { setTimeout(function () { msg.innerHTML += \"<p>f3 is starting</p>\"; msg.innerHTML += \"<p>f3 is ending</p>\"; resolve(); }, 1000); }) } async function f2() { msg.innerHTML += \"<p>f2 is starting</p>\"; await Promise.all([f1(), f3()]); msg.innerHTML += \"<p>f2 is ending</p>\"; } f2(); </script></body></html>", "e": 33727, "s": 32661, "text": null }, { "code": null, "e": 33735, "s": 33727, "text": "Output " }, { "code": null, "e": 33819, "s": 33735, "text": "f2 is starting\nf1 is starting\nf1 is ending\nf3 is starting\nf3 is ending\nf2 is ending" }, { "code": null, "e": 33907, "s": 33819, "text": "The output is the same as the previous code, but in this case, the program will output " }, { "code": null, "e": 33922, "s": 33907, "text": "f2 is starting" }, { "code": null, "e": 33956, "s": 33922, "text": "Then wait for 1second and output " }, { "code": null, "e": 34025, "s": 33956, "text": "f1 is starting\nf1 is ending\nf3 is starting\nf3 is ending\nf2 is ending" }, { "code": null, "e": 34217, "s": 34025, "text": "Since f1() and f3() are running in parallel we do not need to wait another 1 second before executing f3(). In simple words, the timer of setTimeout() in f1() and f3() starts at the same time." }, { "code": null, "e": 34361, "s": 34217, "text": "Note: We can also implement asynchronous behavior using only Promises without async/await and callbacks, refer to the following link for that: " }, { "code": null, "e": 34413, "s": 34361, "text": "https://www.geeksforgeeks.org/javascript-callbacks/" }, { "code": null, "e": 34464, "s": 34413, "text": "https://www.geeksforgeeks.org/javascript-promises/" }, { "code": null, "e": 34478, "s": 34466, "text": "anikakapoor" }, { "code": null, "e": 34494, "s": 34478, "text": "JavaScript-Misc" }, { "code": null, "e": 34501, "s": 34494, "text": "Picked" }, { "code": null, "e": 34512, "s": 34501, "text": "JavaScript" }, { "code": null, "e": 34529, "s": 34512, "text": "Web Technologies" }, { "code": null, "e": 34556, "s": 34529, "text": "Web technologies Questions" }, { "code": null, "e": 34654, "s": 34556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34694, "s": 34654, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34739, "s": 34694, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34800, "s": 34739, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34872, "s": 34800, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34918, "s": 34872, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 34958, "s": 34918, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34991, "s": 34958, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35036, "s": 34991, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35079, "s": 35036, "text": "How to fetch data from an API in ReactJS ?" } ]
How to add Items in ListBox in C#? - GeeksforGeeks
11 Jul, 2019 In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you can add items in the ListBox using Items Property. This property allows you to get a reference to the list of elements that are currently stored in the ListBox. With the help of this reference, you can add, remove, and get a count of the elements in the collection. You can set this property in two different ways: 1. Design-Time: It is the easiest way to add elements in the ListBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ListBox control to add elements in the ListBox.Output: Output: 2. RunTime: It is a little bit trickier than the above method. In this method, you can add the elements in the ListBox control programmatically with the help of given syntax: public System.Windows.Forms.ListBox.ObjectCollection Items { get; } Here, ListBox.ObjectCollection indicates the elements in the ListBox. The following steps show how to add elements in the ListBox dynamically: Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor ListBox mylist = new ListBox(); // Creating ListBox using ListBox class constructor ListBox mylist = new ListBox(); Step 2: After creating ListBox, set the Items property of the ListBox provided by the ListBox class.// Adding the elements in the ListBox mylist.Items.Add("GeeksForGeeks"); // Adding the elements in the ListBox mylist.Items.Add("GeeksForGeeks"); Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form this.Controls.Add(mylist); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp26 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BorderStyle = BorderStyle.Fixed3D; mylist.Items.Add("Geeks"); mylist.Items.Add("GFG"); mylist.Items.Add("GeeksForGeeks"); mylist.Items.Add("gfg"); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output: // Add this ListBox to the form this.Controls.Add(mylist); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp26 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BorderStyle = BorderStyle.Fixed3D; mylist.Items.Add("Geeks"); mylist.Items.Add("GFG"); mylist.Items.Add("GeeksForGeeks"); mylist.Items.Add("gfg"); // Adding ListBox control to the form this.Controls.Add(mylist); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Class and Object Extension Method in C# C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25331, "s": 25303, "text": "\n11 Jul, 2019" }, { "code": null, "e": 25853, "s": 25331, "text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you can add items in the ListBox using Items Property. This property allows you to get a reference to the list of elements that are currently stored in the ListBox. With the help of this reference, you can add, remove, and get a count of the elements in the collection. You can set this property in two different ways:" }, { "code": null, "e": 25955, "s": 25853, "text": "1. Design-Time: It is the easiest way to add elements in the ListBox as shown in the following steps:" }, { "code": null, "e": 26071, "s": 25955, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26250, "s": 26071, "text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need." }, { "code": null, "e": 26370, "s": 26250, "text": "Step 3: After drag and drop you will go to the properties of the ListBox control to add elements in the ListBox.Output:" }, { "code": null, "e": 26378, "s": 26370, "text": "Output:" }, { "code": null, "e": 26553, "s": 26378, "text": "2. RunTime: It is a little bit trickier than the above method. In this method, you can add the elements in the ListBox control programmatically with the help of given syntax:" }, { "code": null, "e": 26621, "s": 26553, "text": "public System.Windows.Forms.ListBox.ObjectCollection Items { get; }" }, { "code": null, "e": 26764, "s": 26621, "text": "Here, ListBox.ObjectCollection indicates the elements in the ListBox. The following steps show how to add elements in the ListBox dynamically:" }, { "code": null, "e": 26940, "s": 26764, "text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 27025, "s": 26940, "text": "// Creating ListBox using ListBox class constructor\nListBox mylist = new ListBox();\n" }, { "code": null, "e": 27199, "s": 27025, "text": "Step 2: After creating ListBox, set the Items property of the ListBox provided by the ListBox class.// Adding the elements in the ListBox\nmylist.Items.Add(\"GeeksForGeeks\");\n" }, { "code": null, "e": 27273, "s": 27199, "text": "// Adding the elements in the ListBox\nmylist.Items.Add(\"GeeksForGeeks\");\n" }, { "code": null, "e": 28286, "s": 27273, "text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(mylist);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp26 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BorderStyle = BorderStyle.Fixed3D; mylist.Items.Add(\"Geeks\"); mylist.Items.Add(\"GFG\"); mylist.Items.Add(\"GeeksForGeeks\"); mylist.Items.Add(\"gfg\"); // Adding ListBox control to the form this.Controls.Add(mylist); }}}Output:" }, { "code": null, "e": 28346, "s": 28286, "text": "// Add this ListBox to the form\nthis.Controls.Add(mylist);\n" }, { "code": null, "e": 28355, "s": 28346, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp26 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of ListBox ListBox mylist = new ListBox(); mylist.Location = new Point(287, 109); mylist.Size = new Size(120, 95); mylist.BorderStyle = BorderStyle.Fixed3D; mylist.Items.Add(\"Geeks\"); mylist.Items.Add(\"GFG\"); mylist.Items.Add(\"GeeksForGeeks\"); mylist.Items.Add(\"gfg\"); // Adding ListBox control to the form this.Controls.Add(mylist); }}}", "e": 29221, "s": 28355, "text": null }, { "code": null, "e": 29229, "s": 29221, "text": "Output:" }, { "code": null, "e": 29232, "s": 29229, "text": "C#" }, { "code": null, "e": 29330, "s": 29232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29358, "s": 29330, "text": "C# Dictionary with examples" }, { "code": null, "e": 29373, "s": 29358, "text": "C# | Delegates" }, { "code": null, "e": 29396, "s": 29373, "text": "C# | Method Overriding" }, { "code": null, "e": 29418, "s": 29396, "text": "C# | Abstract Classes" }, { "code": null, "e": 29464, "s": 29418, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29486, "s": 29464, "text": "C# | Class and Object" }, { "code": null, "e": 29509, "s": 29486, "text": "Extension Method in C#" }, { "code": null, "e": 29527, "s": 29509, "text": "C# | Constructors" }, { "code": null, "e": 29567, "s": 29527, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Node.js date-and-time Date.subtract() Method - GeeksforGeeks
07 Oct, 2021 The date-and-time Date.subtract() method is used to subtract the two date objects. Required Module: Install the module by npm or used it locally. By using npm. npm install date-and-time --save By using CDN link. <script src="/path/to/date-and-time.min.js"></script> Syntax: const subtract(date1, date2) Parameters: This method takes the following arguments as a parameter: date1: It is the first date object from which the second date is subtracted. date2: It is the second date object. Return Value: This method returns the result object subtracting date2 from date1. Example 1: index.js // Node.js program to demonstrate the // Date.subtract() method // Importing date-and-time moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Creating object of given date and timeconst date1 = new Date(2015, 0, 1); // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1); // Display the resultconsole.log("total days between them " + value.toDays()) Run the index.js file using the following command: node index.js Output: total days between them 2270.3951833333335 Example 2: index.js // Node.js program to demonstrate the // Date.subtract() method // Importing date-and-time moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Setting days in the existing datenow.setDate(20); // Creating object of given date and timeconst date1 = new Date(2015, 0, 1); // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1); // Display the resultconsole.log("total days between them " + value.toDays()) Run the index.js file using the following command: node index.js Output: total days between them 2270.397227997685 Reference: https://github.com/knowledgecode/date-and-time#subtractdate1-date2 kashishsoda Node.js-Methods NodeJS date-time Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect Node.js with React.js ? Difference between dependencies, devDependencies and peerDependencies Node.js Export Module Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26350, "s": 26267, "text": "The date-and-time Date.subtract() method is used to subtract the two date objects." }, { "code": null, "e": 26413, "s": 26350, "text": "Required Module: Install the module by npm or used it locally." }, { "code": null, "e": 26427, "s": 26413, "text": "By using npm." }, { "code": null, "e": 26460, "s": 26427, "text": "npm install date-and-time --save" }, { "code": null, "e": 26479, "s": 26460, "text": "By using CDN link." }, { "code": null, "e": 26533, "s": 26479, "text": "<script src=\"/path/to/date-and-time.min.js\"></script>" }, { "code": null, "e": 26541, "s": 26533, "text": "Syntax:" }, { "code": null, "e": 26570, "s": 26541, "text": "const subtract(date1, date2)" }, { "code": null, "e": 26640, "s": 26570, "text": "Parameters: This method takes the following arguments as a parameter:" }, { "code": null, "e": 26717, "s": 26640, "text": "date1: It is the first date object from which the second date is subtracted." }, { "code": null, "e": 26754, "s": 26717, "text": "date2: It is the second date object." }, { "code": null, "e": 26836, "s": 26754, "text": "Return Value: This method returns the result object subtracting date2 from date1." }, { "code": null, "e": 26847, "s": 26836, "text": "Example 1:" }, { "code": null, "e": 26856, "s": 26847, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.subtract() method // Importing date-and-time moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Creating object of given date and timeconst date1 = new Date(2015, 0, 1); // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1); // Display the resultconsole.log(\"total days between them \" + value.toDays())", "e": 27347, "s": 26856, "text": null }, { "code": null, "e": 27398, "s": 27347, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 27412, "s": 27398, "text": "node index.js" }, { "code": null, "e": 27420, "s": 27412, "text": "Output:" }, { "code": null, "e": 27463, "s": 27420, "text": "total days between them 2270.3951833333335" }, { "code": null, "e": 27474, "s": 27463, "text": "Example 2:" }, { "code": null, "e": 27483, "s": 27474, "text": "index.js" }, { "code": "// Node.js program to demonstrate the // Date.subtract() method // Importing date-and-time moduleconst date = require('date-and-time') // Creating object of current date and time // by using Date() const now = new Date(); // Setting days in the existing datenow.setDate(20); // Creating object of given date and timeconst date1 = new Date(2015, 0, 1); // Subtracting the both dates// by using date.subtract() methodconst value = date.subtract(now,date1); // Display the resultconsole.log(\"total days between them \" + value.toDays())", "e": 28025, "s": 27483, "text": null }, { "code": null, "e": 28076, "s": 28025, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 28090, "s": 28076, "text": "node index.js" }, { "code": null, "e": 28098, "s": 28090, "text": "Output:" }, { "code": null, "e": 28140, "s": 28098, "text": "total days between them 2270.397227997685" }, { "code": null, "e": 28218, "s": 28140, "text": "Reference: https://github.com/knowledgecode/date-and-time#subtractdate1-date2" }, { "code": null, "e": 28230, "s": 28218, "text": "kashishsoda" }, { "code": null, "e": 28246, "s": 28230, "text": "Node.js-Methods" }, { "code": null, "e": 28263, "s": 28246, "text": "NodeJS date-time" }, { "code": null, "e": 28271, "s": 28263, "text": "Node.js" }, { "code": null, "e": 28288, "s": 28271, "text": "Web Technologies" }, { "code": null, "e": 28386, "s": 28288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28425, "s": 28386, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28495, "s": 28425, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28517, "s": 28495, "text": "Node.js Export Module" }, { "code": null, "e": 28544, "s": 28517, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28569, "s": 28544, "text": "Mongoose find() Function" }, { "code": null, "e": 28609, "s": 28569, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28654, "s": 28609, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28697, "s": 28654, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28747, "s": 28697, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Count of non-empty sequences of a String - GeeksforGeeks
20 Dec, 2021 Given a string s, the task is to find the number of possible non-empty sequences of letters that can be made.Examples: Input: "AAB" Output: 8 Explanation: 1) A 2) AA 3) AAB 4) AB 5) ABA 6) B 7) BA 8) BAA Total 8 possibilities Input: "AAABBC" Output: 188 Approach: There are two possibilities either take the current character to our answer or leave it. We can solve this problem To check for duplicates we can take set as a data Structure and will put our answers there and our count will be the size of our set.Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program for// the above approach#include <bits/stdc++.h>using namespace std; // Recursive function which will// calculate all the possibilities// recursivelyvoid recurr(string& tiles, vector<bool> vis, string ans, set<string>& se){ if (ans.size() > 0) { // Check that the string // is already there or not if (se.count(ans)) return; // Else put in set se.insert(ans); } // Run for all the // possibilities for (int i = 0; i < tiles.size(); i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and // call recurr function recurr(tiles, vis, ans + tiles[i], se); vis[i] = false; }} // Driver codeint main(){ string s = "AAABBC"; string curr = ""; set<string> se; vector<bool> vis(s.size(), false); recurr(s, vis, curr, se); int ans = se.size(); cout << ans << '\n'; // uncomment following to print all generated strings /* for(auto i: se) cout<<i<<endl; */ return 0;} // Java program for the above approachimport java.util.*;public class Main{ static HashSet<String> se = new HashSet<String>(); static String tiles; // Recursive function which will // calculate all the possibilities // recursively static void recurr(Vector<Boolean> vis, String ans) { // Check that the string // is already there or not if(ans.length()>0) { if(se.contains(ans)) { return; } // Else put in set se.add(ans); } // Run for all the // possibilities for(int i = 0; i < tiles.length(); i++) { // If already taken // then don't do anything if (vis.get(i)) continue; vis.set(i, true); // Else take it and //call recurr function recurr(vis, ans + tiles.charAt(i)); vis.set(i, false); } } public static void main(String[] args) { tiles = "AAABBC"; String curr = ""; Vector<Boolean> vis = new Vector<Boolean>(); for(int i = 0; i < tiles.length(); i++) { vis.add(false); } recurr(vis, curr); System.out.print(se.size()); }} // This code is contributed by rameshtravel07. # Python3 program for# the above approach # Recursive function which will# calculate all the possibilities# recursively def recurr(vis, ans): global tiles, se if (len(ans) > 0): # Check that the string # is already there or not if (ans in se): return # Else put in set se[ans] = 1 # Run for all the # possibilities for i in range(len(tiles)): # If already taken # then don't do anything if (vis[i]): continue vis[i] = True # Else take it and # call recurr function recurr(vis, ans + tiles[i]) vis[i] = False # Driver codetiles = "AAABBC"curr = "" se = dict()vis = [False] * (len(tiles))recurr(vis, curr)print(len(se)) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections.Generic;class GFG { static HashSet<string> se = new HashSet<string>(); static string tiles; // Recursive function which will // calculate all the possibilities // recursively static void recurr(List<bool> vis, string ans) { // Check that the string // is already there or not if(ans.Length>0) { if(se.Contains(ans)) { return; } // Else put in set se.Add(ans); } // Run for all the // possibilities for(int i = 0; i < tiles.Length; i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and //call recurr function recurr(vis, ans + tiles[i]); vis[i] = false; } } static void Main() { tiles = "AAABBC"; string curr = ""; List<bool> vis = new List<bool>(); for(int i = 0; i < tiles.Length; i++) { vis.Add(false); } recurr(vis, curr); Console.WriteLine(se.Count); }} // This code is contributed by divyesh072019. <script>// Javascript program for// the above approach // Recursive function which will// calculate all the possibilities// recursively function recurr(vis, ans){ // Check that the string // is already there or not if(ans.length>0) { if(se.has(ans)) { return; } // Else put in set se.add(ans); } // Run for all the // possibilities for(let i=0;i<tiles.length;i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and //call recurr function recurr(vis, ans + tiles[i]); vis[i] = false; }} // Driver code let tiles = "AAABBC";let curr = ""; let se = new Set();let vis = new Array(tiles.length);for(let i = 0; i < tiles.length; i++){ vis[i] = false;} recurr(vis, curr);document.write(se.size); // This code is contributed by ab2127</script> 188 Another Approach: The idea is to maintain the frequency of the characters of the string and then by choosing each character of the string increment the count by one and decrement the frequency and Recursively call for the rest of the frequencies of the characters. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to find the count// of the number of stringsvoid countNumberOfStringsUtil( vector<int>& freq, int& count){ // Loop to iterate over the // frequency of character of string for (int i = 0; i < 26; i++) { if (freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq,count); freq[i]++; // backtrack } }} // Function to count the number of// non-empty sequencesint countNumberOfStrings(string s) { // store the frequency of each character vector<int> freq(26, 0); // Maintain the frequency for (int i = 0; i < s.size(); i++) { freq[s[i] - 'A']++; } int count = 0; countNumberOfStringsUtil(freq, count); return count;} // Driver Codeint main(){ string s = "AAABBC"; // Function Call cout << countNumberOfStrings(s); return 0;} // Java implementation of the// above approachimport java.io.*;import java.util.*; class GFG{ public static int count = 0; // Function to find the count // of the number of strings public static void countNumberOfStringsUtil(int[] freq) { // Loop to iterate over the // frequency of character of string for(int i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequences public static int countNumberOfStrings(String s) { // store the frequency of each character int[] freq = new int[26]; Arrays.fill(freq, 0); // Maintain the frequency for(int i = 0; i < s.length(); i++) { freq[s.charAt(i) - 'A']++; } countNumberOfStringsUtil(freq); return count; } // Driver Code public static void main (String[] args) { String s = "AAABBC"; // Function Call System.out.println(countNumberOfStrings(s)); }} // This code is contributed by rag2127 # Python3 implementation of the# above approachcount = 0 # Function to find the count# of the number of stringsdef countNumberOfStringsUtil(freq, Count): global count count = Count # Loop to iterate over the # frequency of character of string for i in range(26): if(freq[i] > 0): # Reduce the frequency of # current element freq[i] -= 1 count+=1 # Recursive call countNumberOfStringsUtil(freq, count); # Backtrack freq[i] += 1 # Function to count the number of# non-empty sequencesdef countNumberOfStrings(s): global count global freq # store the frequency # of each character freq = [0 for i in range(26)] # Maintain the frequency for i in range(len(s)): freq[ord(s[i]) - ord('A')] += 1 countNumberOfStringsUtil(freq, count); return count # Driver Codes = "AAABBC" # Function Callprint(countNumberOfStrings(s)) # This code is contributed by avanitrachhadiya2155 // C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG { static int count = 0; // Function to find the count // of the number of strings static void countNumberOfStringsUtil(int[] freq) { // Loop to iterate over the // frequency of character of string for(int i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequences public static int countNumberOfStrings(string s) { // store the frequency of each character int[] freq = new int[26]; Array.Fill(freq, 0); // Maintain the frequency for(int i = 0; i < s.Length; i++) { freq[s[i] - 'A']++; } countNumberOfStringsUtil(freq); return count; } static void Main() { string s = "AAABBC"; // Function Call Console.Write(countNumberOfStrings(s)); }} // This code is contributed by suresh07. <script>// Javascript implementation of the// above approachlet count = 0; // Function to find the count // of the number of stringsfunction countNumberOfStringsUtil(freq){ // Loop to iterate over the // frequency of character of string for(let i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequencesfunction countNumberOfStrings(s){ // store the frequency of each character let freq = new Array(26); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // Maintain the frequency for(let i = 0; i < s.length; i++) { freq[s[i].charCodeAt(0) - 'A'.charCodeAt(0)]++; } countNumberOfStringsUtil(freq); return count;} // Driver Codelet s = "AAABBC"; // Function Calldocument.write(countNumberOfStrings(s)); // This code is contributed by unknown2108</script> 188 mohit kumar 29 mazeoz avanitrachhadiya2155 rag2127 unknown2108 ab2127 suresh07 divyesh072019 rameshtravel07 Recursion Strings Technical Scripter Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Practice Questions for Recursion | Set 1 Sum of natural numbers using recursion Recursively Reversing a linked list (A simple implementation) Generating subarrays using recursion Recursive Insertion Sort Write a program to reverse an array or string Reverse a string in Java C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26249, "s": 26221, "text": "\n20 Dec, 2021" }, { "code": null, "e": 26368, "s": 26249, "text": "Given a string s, the task is to find the number of possible non-empty sequences of letters that can be made.Examples:" }, { "code": null, "e": 26505, "s": 26368, "text": "Input: \"AAB\"\nOutput: 8 \nExplanation:\n1) A\n2) AA\n3) AAB\n4) AB\n5) ABA\n6) B\n7) BA\n8) BAA\nTotal 8 possibilities\n\nInput: \"AAABBC\"\nOutput: 188" }, { "code": null, "e": 26817, "s": 26505, "text": "Approach: There are two possibilities either take the current character to our answer or leave it. We can solve this problem To check for duplicates we can take set as a data Structure and will put our answers there and our count will be the size of our set.Below is the implementation of the above approach: " }, { "code": null, "e": 26821, "s": 26817, "text": "C++" }, { "code": null, "e": 26826, "s": 26821, "text": "Java" }, { "code": null, "e": 26833, "s": 26826, "text": "Python" }, { "code": null, "e": 26836, "s": 26833, "text": "C#" }, { "code": null, "e": 26847, "s": 26836, "text": "Javascript" }, { "code": "// C++ program for// the above approach#include <bits/stdc++.h>using namespace std; // Recursive function which will// calculate all the possibilities// recursivelyvoid recurr(string& tiles, vector<bool> vis, string ans, set<string>& se){ if (ans.size() > 0) { // Check that the string // is already there or not if (se.count(ans)) return; // Else put in set se.insert(ans); } // Run for all the // possibilities for (int i = 0; i < tiles.size(); i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and // call recurr function recurr(tiles, vis, ans + tiles[i], se); vis[i] = false; }} // Driver codeint main(){ string s = \"AAABBC\"; string curr = \"\"; set<string> se; vector<bool> vis(s.size(), false); recurr(s, vis, curr, se); int ans = se.size(); cout << ans << '\\n'; // uncomment following to print all generated strings /* for(auto i: se) cout<<i<<endl; */ return 0;}", "e": 27967, "s": 26847, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class Main{ static HashSet<String> se = new HashSet<String>(); static String tiles; // Recursive function which will // calculate all the possibilities // recursively static void recurr(Vector<Boolean> vis, String ans) { // Check that the string // is already there or not if(ans.length()>0) { if(se.contains(ans)) { return; } // Else put in set se.add(ans); } // Run for all the // possibilities for(int i = 0; i < tiles.length(); i++) { // If already taken // then don't do anything if (vis.get(i)) continue; vis.set(i, true); // Else take it and //call recurr function recurr(vis, ans + tiles.charAt(i)); vis.set(i, false); } } public static void main(String[] args) { tiles = \"AAABBC\"; String curr = \"\"; Vector<Boolean> vis = new Vector<Boolean>(); for(int i = 0; i < tiles.length(); i++) { vis.add(false); } recurr(vis, curr); System.out.print(se.size()); }} // This code is contributed by rameshtravel07.", "e": 29362, "s": 27967, "text": null }, { "code": "# Python3 program for# the above approach # Recursive function which will# calculate all the possibilities# recursively def recurr(vis, ans): global tiles, se if (len(ans) > 0): # Check that the string # is already there or not if (ans in se): return # Else put in set se[ans] = 1 # Run for all the # possibilities for i in range(len(tiles)): # If already taken # then don't do anything if (vis[i]): continue vis[i] = True # Else take it and # call recurr function recurr(vis, ans + tiles[i]) vis[i] = False # Driver codetiles = \"AAABBC\"curr = \"\" se = dict()vis = [False] * (len(tiles))recurr(vis, curr)print(len(se)) # This code is contributed by mohit kumar 29", "e": 30160, "s": 29362, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { static HashSet<string> se = new HashSet<string>(); static string tiles; // Recursive function which will // calculate all the possibilities // recursively static void recurr(List<bool> vis, string ans) { // Check that the string // is already there or not if(ans.Length>0) { if(se.Contains(ans)) { return; } // Else put in set se.Add(ans); } // Run for all the // possibilities for(int i = 0; i < tiles.Length; i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and //call recurr function recurr(vis, ans + tiles[i]); vis[i] = false; } } static void Main() { tiles = \"AAABBC\"; string curr = \"\"; List<bool> vis = new List<bool>(); for(int i = 0; i < tiles.Length; i++) { vis.Add(false); } recurr(vis, curr); Console.WriteLine(se.Count); }} // This code is contributed by divyesh072019.", "e": 31458, "s": 30160, "text": null }, { "code": "<script>// Javascript program for// the above approach // Recursive function which will// calculate all the possibilities// recursively function recurr(vis, ans){ // Check that the string // is already there or not if(ans.length>0) { if(se.has(ans)) { return; } // Else put in set se.add(ans); } // Run for all the // possibilities for(let i=0;i<tiles.length;i++) { // If already taken // then don't do anything if (vis[i]) continue; vis[i] = true; // Else take it and //call recurr function recurr(vis, ans + tiles[i]); vis[i] = false; }} // Driver code let tiles = \"AAABBC\";let curr = \"\"; let se = new Set();let vis = new Array(tiles.length);for(let i = 0; i < tiles.length; i++){ vis[i] = false;} recurr(vis, curr);document.write(se.size); // This code is contributed by ab2127</script>", "e": 32414, "s": 31458, "text": null }, { "code": null, "e": 32418, "s": 32414, "text": "188" }, { "code": null, "e": 32683, "s": 32418, "text": "Another Approach: The idea is to maintain the frequency of the characters of the string and then by choosing each character of the string increment the count by one and decrement the frequency and Recursively call for the rest of the frequencies of the characters." }, { "code": null, "e": 32734, "s": 32683, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 32738, "s": 32734, "text": "C++" }, { "code": null, "e": 32743, "s": 32738, "text": "Java" }, { "code": null, "e": 32751, "s": 32743, "text": "Python3" }, { "code": null, "e": 32754, "s": 32751, "text": "C#" }, { "code": null, "e": 32765, "s": 32754, "text": "Javascript" }, { "code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to find the count// of the number of stringsvoid countNumberOfStringsUtil( vector<int>& freq, int& count){ // Loop to iterate over the // frequency of character of string for (int i = 0; i < 26; i++) { if (freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq,count); freq[i]++; // backtrack } }} // Function to count the number of// non-empty sequencesint countNumberOfStrings(string s) { // store the frequency of each character vector<int> freq(26, 0); // Maintain the frequency for (int i = 0; i < s.size(); i++) { freq[s[i] - 'A']++; } int count = 0; countNumberOfStringsUtil(freq, count); return count;} // Driver Codeint main(){ string s = \"AAABBC\"; // Function Call cout << countNumberOfStrings(s); return 0;}", "e": 33836, "s": 32765, "text": null }, { "code": "// Java implementation of the// above approachimport java.io.*;import java.util.*; class GFG{ public static int count = 0; // Function to find the count // of the number of strings public static void countNumberOfStringsUtil(int[] freq) { // Loop to iterate over the // frequency of character of string for(int i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequences public static int countNumberOfStrings(String s) { // store the frequency of each character int[] freq = new int[26]; Arrays.fill(freq, 0); // Maintain the frequency for(int i = 0; i < s.length(); i++) { freq[s.charAt(i) - 'A']++; } countNumberOfStringsUtil(freq); return count; } // Driver Code public static void main (String[] args) { String s = \"AAABBC\"; // Function Call System.out.println(countNumberOfStrings(s)); }} // This code is contributed by rag2127", "e": 35007, "s": 33836, "text": null }, { "code": "# Python3 implementation of the# above approachcount = 0 # Function to find the count# of the number of stringsdef countNumberOfStringsUtil(freq, Count): global count count = Count # Loop to iterate over the # frequency of character of string for i in range(26): if(freq[i] > 0): # Reduce the frequency of # current element freq[i] -= 1 count+=1 # Recursive call countNumberOfStringsUtil(freq, count); # Backtrack freq[i] += 1 # Function to count the number of# non-empty sequencesdef countNumberOfStrings(s): global count global freq # store the frequency # of each character freq = [0 for i in range(26)] # Maintain the frequency for i in range(len(s)): freq[ord(s[i]) - ord('A')] += 1 countNumberOfStringsUtil(freq, count); return count # Driver Codes = \"AAABBC\" # Function Callprint(countNumberOfStrings(s)) # This code is contributed by avanitrachhadiya2155", "e": 36127, "s": 35007, "text": null }, { "code": "// C# implementation of the// above approachusing System;using System.Collections.Generic;class GFG { static int count = 0; // Function to find the count // of the number of strings static void countNumberOfStringsUtil(int[] freq) { // Loop to iterate over the // frequency of character of string for(int i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequences public static int countNumberOfStrings(string s) { // store the frequency of each character int[] freq = new int[26]; Array.Fill(freq, 0); // Maintain the frequency for(int i = 0; i < s.Length; i++) { freq[s[i] - 'A']++; } countNumberOfStringsUtil(freq); return count; } static void Main() { string s = \"AAABBC\"; // Function Call Console.Write(countNumberOfStrings(s)); }} // This code is contributed by suresh07.", "e": 37255, "s": 36127, "text": null }, { "code": "<script>// Javascript implementation of the// above approachlet count = 0; // Function to find the count // of the number of stringsfunction countNumberOfStringsUtil(freq){ // Loop to iterate over the // frequency of character of string for(let i = 0; i < 26; i++) { if(freq[i] > 0) { // reduce the frequency of // current element freq[i]--; count++; // recursive call countNumberOfStringsUtil(freq); freq[i]++;// backtrack } } } // Function to count the number of // non-empty sequencesfunction countNumberOfStrings(s){ // store the frequency of each character let freq = new Array(26); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // Maintain the frequency for(let i = 0; i < s.length; i++) { freq[s[i].charCodeAt(0) - 'A'.charCodeAt(0)]++; } countNumberOfStringsUtil(freq); return count;} // Driver Codelet s = \"AAABBC\"; // Function Calldocument.write(countNumberOfStrings(s)); // This code is contributed by unknown2108</script>", "e": 38346, "s": 37255, "text": null }, { "code": null, "e": 38350, "s": 38346, "text": "188" }, { "code": null, "e": 38365, "s": 38350, "text": "mohit kumar 29" }, { "code": null, "e": 38372, "s": 38365, "text": "mazeoz" }, { "code": null, "e": 38393, "s": 38372, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38401, "s": 38393, "text": "rag2127" }, { "code": null, "e": 38413, "s": 38401, "text": "unknown2108" }, { "code": null, "e": 38420, "s": 38413, "text": "ab2127" }, { "code": null, "e": 38429, "s": 38420, "text": "suresh07" }, { "code": null, "e": 38443, "s": 38429, "text": "divyesh072019" }, { "code": null, "e": 38458, "s": 38443, "text": "rameshtravel07" }, { "code": null, "e": 38468, "s": 38458, "text": "Recursion" }, { "code": null, "e": 38476, "s": 38468, "text": "Strings" }, { "code": null, "e": 38495, "s": 38476, "text": "Technical Scripter" }, { "code": null, "e": 38503, "s": 38495, "text": "Strings" }, { "code": null, "e": 38513, "s": 38503, "text": "Recursion" }, { "code": null, "e": 38611, "s": 38513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38652, "s": 38611, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 38691, "s": 38652, "text": "Sum of natural numbers using recursion" }, { "code": null, "e": 38753, "s": 38691, "text": "Recursively Reversing a linked list (A simple implementation)" }, { "code": null, "e": 38790, "s": 38753, "text": "Generating subarrays using recursion" }, { "code": null, "e": 38815, "s": 38790, "text": "Recursive Insertion Sort" }, { "code": null, "e": 38861, "s": 38815, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38886, "s": 38861, "text": "Reverse a string in Java" }, { "code": null, "e": 38901, "s": 38886, "text": "C++ Data Types" }, { "code": null, "e": 38935, "s": 38901, "text": "Longest Common Subsequence | DP-4" } ]
Creating an Empty PDF Document using Java - GeeksforGeeks
13 Jul, 2021 For creating a PDF document using Java, we need to know the packages/libraries which are necessary for writing the code. So, for creating a PDF doc, we will be using the iText 7 library. To know how to install this library in your workspace, you can follow this link. To create an empty PDF Document, we first need to instantiate the Document class, and while doing so, we have to pass a PdfDocument object as an argument. The following are the components used in creating an empty PDF doc. 1. PdfWritter The PdfWritter class belongs to the package com.itextpdf.kernel.pdf. We can say that this class is the Doc Writer for a PDF. While instantiating an object of PdfWritter object, we have to pass a string value, which represents the path of the file, where we want the PDF to be created. Note: While passing the path of the file, make sure that your IDE has the permission to write/read files in that directory, otherwise, it will give a FileNotFound error. Syntax String path = "C:/JavaExamples/example.pdf"; PdfWriter writer = new PdfWriter(path); 2. PdfDocument The PdfDocument class belongs to the package com.itextpdf.kernel.pdf. This class represents the PDF Document. While instantiating this class, we have to pass the PdfWriter object as an argument. Syntax //writer is the PdfWriter object PdfDocument pdf = new PdfDocument(writer); 3. Document The Document class belongs to the package com.itextpdf.layout. It is one of the core classes in IText. If you want to generate a PDF from scratch, then you must use Document Class. While instantiating the Document class, we need to pass the PdfDocument object as an argument. Syntax to create a Document Object: //pdf is the PdfDocument object Document doc = new Document(pdf); 4. Closing the Document Close the document using the close() method of the Document class as shown below. // Closing the document doc.close(); Example 1: Java // let us import all required packages import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document; public class Pdf { public static void main(String args[]) throws Exception { // Creating a PdfWriter to C:/example.pdf String path = "C:/example.pdf"; PdfWriter writer = new PdfWriter(path); // Creating a PdfDocument object PdfDocument pdf = new PdfDocument(writer); // Creating a Document object Document document = new Document(pdf); // to check if its created or not System.out.println("Your PDF has been created"); }} Output Note: This is an empty document, you may get an error while opening this PDF because this is a PDF with 0 pages.You may get a FIileNotFound error if you don’t have the permission to write/read files in that directory, so you can run your IDE as an administrator, then it will work. This is an empty document, you may get an error while opening this PDF because this is a PDF with 0 pages. You may get a FIileNotFound error if you don’t have the permission to write/read files in that directory, so you can run your IDE as an administrator, then it will work. Example 2: Now let’s create a PDF with an empty page. Java import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document; public class Pdf { public static void main(String args[]) throws Exception { // Setting the Path String path = "C:/example2.pdf"; // Creating a PdfWriter object PdfWriter writer = new PdfWriter(path); // Creating a PdfDocument object PdfDocument pdf = new PdfDocument(writer); // this line is used to add a // new page in the pdf pdfDoc.addNewPage(); // Creating a Document object Document document = new Document(pdf); // Closing the document object document.close(); System.out.println("Your pdf has been created"); }} Output Let’s open that PDF. sagar0719kumar Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file 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? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25493, "s": 25225, "text": "For creating a PDF document using Java, we need to know the packages/libraries which are necessary for writing the code. So, for creating a PDF doc, we will be using the iText 7 library. To know how to install this library in your workspace, you can follow this link." }, { "code": null, "e": 25716, "s": 25493, "text": "To create an empty PDF Document, we first need to instantiate the Document class, and while doing so, we have to pass a PdfDocument object as an argument. The following are the components used in creating an empty PDF doc." }, { "code": null, "e": 25730, "s": 25716, "text": "1. PdfWritter" }, { "code": null, "e": 26016, "s": 25730, "text": "The PdfWritter class belongs to the package com.itextpdf.kernel.pdf. We can say that this class is the Doc Writer for a PDF. While instantiating an object of PdfWritter object, we have to pass a string value, which represents the path of the file, where we want the PDF to be created. " }, { "code": null, "e": 26186, "s": 26016, "text": "Note: While passing the path of the file, make sure that your IDE has the permission to write/read files in that directory, otherwise, it will give a FileNotFound error." }, { "code": null, "e": 26193, "s": 26186, "text": "Syntax" }, { "code": null, "e": 26278, "s": 26193, "text": "String path = \"C:/JavaExamples/example.pdf\";\nPdfWriter writer = new PdfWriter(path);" }, { "code": null, "e": 26293, "s": 26278, "text": "2. PdfDocument" }, { "code": null, "e": 26488, "s": 26293, "text": "The PdfDocument class belongs to the package com.itextpdf.kernel.pdf. This class represents the PDF Document. While instantiating this class, we have to pass the PdfWriter object as an argument." }, { "code": null, "e": 26495, "s": 26488, "text": "Syntax" }, { "code": null, "e": 26571, "s": 26495, "text": "//writer is the PdfWriter object\nPdfDocument pdf = new PdfDocument(writer);" }, { "code": null, "e": 26583, "s": 26571, "text": "3. Document" }, { "code": null, "e": 26859, "s": 26583, "text": "The Document class belongs to the package com.itextpdf.layout. It is one of the core classes in IText. If you want to generate a PDF from scratch, then you must use Document Class. While instantiating the Document class, we need to pass the PdfDocument object as an argument." }, { "code": null, "e": 26895, "s": 26859, "text": "Syntax to create a Document Object:" }, { "code": null, "e": 26961, "s": 26895, "text": "//pdf is the PdfDocument object\nDocument doc = new Document(pdf);" }, { "code": null, "e": 26985, "s": 26961, "text": "4. Closing the Document" }, { "code": null, "e": 27067, "s": 26985, "text": "Close the document using the close() method of the Document class as shown below." }, { "code": null, "e": 27105, "s": 27067, "text": "// Closing the document \ndoc.close();" }, { "code": null, "e": 27116, "s": 27105, "text": "Example 1:" }, { "code": null, "e": 27121, "s": 27116, "text": "Java" }, { "code": "// let us import all required packages import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document; public class Pdf { public static void main(String args[]) throws Exception { // Creating a PdfWriter to C:/example.pdf String path = \"C:/example.pdf\"; PdfWriter writer = new PdfWriter(path); // Creating a PdfDocument object PdfDocument pdf = new PdfDocument(writer); // Creating a Document object Document document = new Document(pdf); // to check if its created or not System.out.println(\"Your PDF has been created\"); }}", "e": 27779, "s": 27121, "text": null }, { "code": null, "e": 27790, "s": 27783, "text": "Output" }, { "code": null, "e": 27800, "s": 27794, "text": "Note:" }, { "code": null, "e": 28079, "s": 27802, "text": " This is an empty document, you may get an error while opening this PDF because this is a PDF with 0 pages.You may get a FIileNotFound error if you don’t have the permission to write/read files in that directory, so you can run your IDE as an administrator, then it will work." }, { "code": null, "e": 28187, "s": 28079, "text": " This is an empty document, you may get an error while opening this PDF because this is a PDF with 0 pages." }, { "code": null, "e": 28357, "s": 28187, "text": "You may get a FIileNotFound error if you don’t have the permission to write/read files in that directory, so you can run your IDE as an administrator, then it will work." }, { "code": null, "e": 28370, "s": 28359, "text": "Example 2:" }, { "code": null, "e": 28415, "s": 28372, "text": "Now let’s create a PDF with an empty page." }, { "code": null, "e": 28422, "s": 28417, "text": "Java" }, { "code": "import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.layout.Document; public class Pdf { public static void main(String args[]) throws Exception { // Setting the Path String path = \"C:/example2.pdf\"; // Creating a PdfWriter object PdfWriter writer = new PdfWriter(path); // Creating a PdfDocument object PdfDocument pdf = new PdfDocument(writer); // this line is used to add a // new page in the pdf pdfDoc.addNewPage(); // Creating a Document object Document document = new Document(pdf); // Closing the document object document.close(); System.out.println(\"Your pdf has been created\"); }}", "e": 29178, "s": 28422, "text": null }, { "code": null, "e": 29189, "s": 29182, "text": "Output" }, { "code": null, "e": 29214, "s": 29193, "text": "Let’s open that PDF." }, { "code": null, "e": 29233, "s": 29218, "text": "sagar0719kumar" }, { "code": null, "e": 29238, "s": 29233, "text": "Java" }, { "code": null, "e": 29252, "s": 29238, "text": "Java Programs" }, { "code": null, "e": 29257, "s": 29252, "text": "Java" }, { "code": null, "e": 29355, "s": 29257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29370, "s": 29355, "text": "Stream In Java" }, { "code": null, "e": 29391, "s": 29370, "text": "Constructors in Java" }, { "code": null, "e": 29410, "s": 29391, "text": "Exceptions in Java" }, { "code": null, "e": 29440, "s": 29410, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29486, "s": 29440, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29512, "s": 29486, "text": "Java Programming Examples" }, { "code": null, "e": 29546, "s": 29512, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29593, "s": 29546, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29625, "s": 29593, "text": "How to Iterate HashMap in Java?" } ]
Iterative program to count leaf nodes in a Binary Tree - GeeksforGeeks
14 May, 2021 Given a binary tree, count leaves in the tree without using recursion. A node is a leaf node if both left and right children of it are NULL. Example Tree Leaves count for the above tree is 3. The idea is to use level order traversal. During traversal, if we find a node whose left and right children are NULL, we increment count. C++ Java Python3 C# Javascript // C++ program to count leaf nodes in a Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* Function to get the count of leaf Nodes in a binary tree*/unsigned int getLeafCount(struct Node* node){ // If tree is empty if (!node) return 0; // Initialize empty queue. queue<Node *> q; // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.push(node); while (!q.empty()) { struct Node *temp = q.front(); q.pop(); if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); if (temp->left == NULL && temp->right == NULL) count++; } return count;} /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example */ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* get leaf count of the above created tree */ cout << getLeafCount(root); return 0;} // Java program to count leaf nodes// in a Binary Treeimport java.util.*; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; } /* Function to get the count of leaf Nodes in a binary tree*/ static int getLeafCount(Node node) { // If tree is empty if (node == null) { return 0; } // Initialize empty queue. Queue<Node> q = new LinkedList<>(); // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.add(node); while (!q.isEmpty()) { Node temp = q.peek(); q.poll(); if (temp.left != null) { q.add(temp.left); } if (temp.right != null) { q.add(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count; } /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void main(String[] args) { { /* 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ System.out.println(getLeafCount(root)); } }} // This code is contributed by Rajput-Ji # Python3 program to count leaf nodes# in a Binary Treefrom queue import Queue # Helper function that allocates a new# Node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Function to get the count of leaf# Nodes in a binary treedef getLeafCount(node): # If tree is empty if (not node): return 0 # Initialize empty queue. q = Queue() # Do level order traversal # starting from root count = 0 # Initialize count of leaves q.put(node) while (not q.empty()): temp = q.queue[0] q.get() if (temp.left != None): q.put(temp.left) if (temp.right != None): q.put(temp.right) if (temp.left == None and temp.right == None): count += 1 return count # Driver Codeif __name__ == '__main__': # 1 # / \ # 2 3 # / \ # 4 5 # Let us create Binary Tree shown # in above example root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # get leaf count of the above # created tree print(getLeafCount(root)) # This code is contributed by PranchalK // C# program to count leaf nodes// in a Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; } /* Function to get the count of leaf Nodes in a binary tree*/ static int getLeafCount(Node node) { // If tree is empty if (node == null) { return 0; } // Initialize empty queue. Queue<Node> q = new Queue<Node>(); // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.Enqueue(node); while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); if (temp.left != null) { q.Enqueue(temp.left); } if (temp.right != null) { q.Enqueue(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count; } /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void Main(String[] args) { { /* 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ Console.WriteLine(getLeafCount(root)); } }} // This code is contributed by 29AjayKumar <script>// Javascript program to count leaf nodes// in a Binary Tree /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ /* Helper function that allocates a new Node with the given data and null left and right pointers. */ constructor(data) { this.data=data; this.left=this.right=null; }} /* Function to get the count of leaf Nodes in a binary tree*/function getLeafCount(node){ // If tree is empty if (node == null) { return 0; } // Initialize empty queue. let q = []; // Do level order traversal starting from root let count = 0; // Initialize count of leaves q.push(node); while (q.length!=0) { let temp = q.shift(); if (temp.left != null) { q.push(temp.left); } if (temp.right != null) { q.push(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count;} /* 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example */ let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5); /* get leaf count of the above created tree */document.write(getLeafCount(root)); // This code is contributed by unknown2108</script> 3 Time Complexity: O(n) Here is a recursive solution for the same problem: The idea is simple we break the larger tree into smaller sub-trees and solve for them to get the final answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ Program for above approach#include <iostream>using namespace std; // Node classstruct node{ int data; struct node* left; struct node* right;}; // Program to count leavesint countLeaves(struct node *node){ // If the node itself is "null" // return 0, as there // are no leaves if(node == NULL) { return 0; } // It the node is a leaf then // both right and left // children will be "null" if(node->left == NULL && node->right == NULL) { return 1; } // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node->left) + countLeaves(node->right);} // Class newNode of Node typestruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver Codeint main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* get leaf count of the above created tree */ cout<<countLeaves(root)<<endl; } // This code is contributed by rag2127 // Java Program for above approachimport java.util.LinkedList;import java.util.Queue;import java.io.*;import java.util.*; class GfG{ // Node class static class Node { int data; Node left, right; } // Program to count leaves static int countLeaves(Node node) { // If the node itself is "null" // return 0, as there // are no leaves if (node == null) return 0; // It the node is a leaf then // both right and left // children will be "null" if (node.left == null && node.right == null) return 1; // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right); } // Class newNode of Node type static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ System.out.println(countLeaves(root)); }}//Code by Rounik Prashar # Python3 Program for above approach # Node classclass Node: def __init__(self,x): self.data = x self.left = None self.right = None # Program to count leavesdef countLeaves(node): # If the node itself is "None" # return 0, as there # are no leaves if (node == None): return 0 # It the node is a leaf then # both right and left # children will be "None" if (node.left == None and node.right == None): return 1 # Now we count the leaves in # the left and right # subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right) # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) # /* get leaf count of the above # created tree */ print(countLeaves(root)) # This code is contributed by mohit kumar 29 // C# Program for above approachusing System; // Node classpublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node root; // Program to count leavesstatic int countLeaves(Node node){ // If the node itself is "null" // return 0, as there // are no leaves if (node == null) { return 0; } // It the node is a leaf then // both right and left // children will be "null" if (node.left == null && node.right == null) { return 1; } // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right);} // Driver Codestatic public void Main(){ BinaryTree.root = new Node(1); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(5); // Get leaf count of the above created tree Console.WriteLine(countLeaves(root));}} // This code is contributed by avanitrachhadiya2155 <script> // Javascript Program for above approach // Node class class Node { // Class newNode of Node type constructor(data) { this.data=data; this.next = this.right = null; } } // Program to count leavesfunction countLeaves(node){ // If the node itself is "null" // return 0, as there // are no leaves if (node == null) return 0; // It the node is a leaf then // both right and left // children will be "null" if (node.left == null && node.right == null) return 1; // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right);} // Driver Codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5); /* get leaf count of the above created tree */document.write(countLeaves(root)); // This code is contributed by patel2127 </script> 3 https://youtu.be/N2mV5p8NOVw?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranchalKatiyar Rajput-Ji 29AjayKumar rounik1020 mohit kumar 29 rag2127 avanitrachhadiya2155 unknown2108 patel2127 Ola Cabs Tree Ola Cabs Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 2 (Properties) Decision Tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Deletion in a Binary Tree BFS vs DFS for Binary Tree Binary Tree (Array implementation) Segment Tree | Set 1 (Sum of given range)
[ { "code": null, "e": 26281, "s": 26253, "text": "\n14 May, 2021" }, { "code": null, "e": 26422, "s": 26281, "text": "Given a binary tree, count leaves in the tree without using recursion. A node is a leaf node if both left and right children of it are NULL." }, { "code": null, "e": 26437, "s": 26422, "text": " Example Tree" }, { "code": null, "e": 26477, "s": 26437, "text": " \nLeaves count for the above tree is 3." }, { "code": null, "e": 26618, "s": 26479, "text": "The idea is to use level order traversal. During traversal, if we find a node whose left and right children are NULL, we increment count. " }, { "code": null, "e": 26622, "s": 26618, "text": "C++" }, { "code": null, "e": 26627, "s": 26622, "text": "Java" }, { "code": null, "e": 26635, "s": 26627, "text": "Python3" }, { "code": null, "e": 26638, "s": 26635, "text": "C#" }, { "code": null, "e": 26649, "s": 26638, "text": "Javascript" }, { "code": "// C++ program to count leaf nodes in a Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* Function to get the count of leaf Nodes in a binary tree*/unsigned int getLeafCount(struct Node* node){ // If tree is empty if (!node) return 0; // Initialize empty queue. queue<Node *> q; // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.push(node); while (!q.empty()) { struct Node *temp = q.front(); q.pop(); if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); if (temp->left == NULL && temp->right == NULL) count++; } return count;} /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} /* Driver program to test above functions*/int main(){ /* 1 / \\ 2 3 / \\ 4 5 Let us create Binary Tree shown in above example */ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* get leaf count of the above created tree */ cout << getLeafCount(root); return 0;}", "e": 28209, "s": 26649, "text": null }, { "code": "// Java program to count leaf nodes// in a Binary Treeimport java.util.*; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; } /* Function to get the count of leaf Nodes in a binary tree*/ static int getLeafCount(Node node) { // If tree is empty if (node == null) { return 0; } // Initialize empty queue. Queue<Node> q = new LinkedList<>(); // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.add(node); while (!q.isEmpty()) { Node temp = q.peek(); q.poll(); if (temp.left != null) { q.add(temp.left); } if (temp.right != null) { q.add(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count; } /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void main(String[] args) { { /* 1 / \\ 2 3 / \\ 4 5 Let us create Binary Tree shown in above example */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ System.out.println(getLeafCount(root)); } }} // This code is contributed by Rajput-Ji", "e": 30171, "s": 28209, "text": null }, { "code": "# Python3 program to count leaf nodes# in a Binary Treefrom queue import Queue # Helper function that allocates a new# Node with the given data and None# left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Function to get the count of leaf# Nodes in a binary treedef getLeafCount(node): # If tree is empty if (not node): return 0 # Initialize empty queue. q = Queue() # Do level order traversal # starting from root count = 0 # Initialize count of leaves q.put(node) while (not q.empty()): temp = q.queue[0] q.get() if (temp.left != None): q.put(temp.left) if (temp.right != None): q.put(temp.right) if (temp.left == None and temp.right == None): count += 1 return count # Driver Codeif __name__ == '__main__': # 1 # / \\ # 2 3 # / \\ # 4 5 # Let us create Binary Tree shown # in above example root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) # get leaf count of the above # created tree print(getLeafCount(root)) # This code is contributed by PranchalK", "e": 31458, "s": 30171, "text": null }, { "code": "// C# program to count leaf nodes// in a Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; } /* Function to get the count of leaf Nodes in a binary tree*/ static int getLeafCount(Node node) { // If tree is empty if (node == null) { return 0; } // Initialize empty queue. Queue<Node> q = new Queue<Node>(); // Do level order traversal starting from root int count = 0; // Initialize count of leaves q.Enqueue(node); while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); if (temp.left != null) { q.Enqueue(temp.left); } if (temp.right != null) { q.Enqueue(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count; } /* Helper function that allocates a new Node with the given data and null left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void Main(String[] args) { { /* 1 / \\ 2 3 / \\ 4 5 Let us create Binary Tree shown in above example */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ Console.WriteLine(getLeafCount(root)); } }} // This code is contributed by 29AjayKumar", "e": 33464, "s": 31458, "text": null }, { "code": "<script>// Javascript program to count leaf nodes// in a Binary Tree /* A binary tree Node has data, pointer to left child and a pointer to right child */class Node{ /* Helper function that allocates a new Node with the given data and null left and right pointers. */ constructor(data) { this.data=data; this.left=this.right=null; }} /* Function to get the count of leaf Nodes in a binary tree*/function getLeafCount(node){ // If tree is empty if (node == null) { return 0; } // Initialize empty queue. let q = []; // Do level order traversal starting from root let count = 0; // Initialize count of leaves q.push(node); while (q.length!=0) { let temp = q.shift(); if (temp.left != null) { q.push(temp.left); } if (temp.right != null) { q.push(temp.right); } if (temp.left == null && temp.right == null) { count++; } } return count;} /* 1 / \\ 2 3 / \\ 4 5 Let us create Binary Tree shown in above example */ let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5); /* get leaf count of the above created tree */document.write(getLeafCount(root)); // This code is contributed by unknown2108</script>", "e": 35036, "s": 33464, "text": null }, { "code": null, "e": 35038, "s": 35036, "text": "3" }, { "code": null, "e": 35060, "s": 35038, "text": "Time Complexity: O(n)" }, { "code": null, "e": 35111, "s": 35060, "text": "Here is a recursive solution for the same problem:" }, { "code": null, "e": 35222, "s": 35111, "text": "The idea is simple we break the larger tree into smaller sub-trees and solve for them to get the final answer." }, { "code": null, "e": 35273, "s": 35222, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 35277, "s": 35273, "text": "C++" }, { "code": null, "e": 35282, "s": 35277, "text": "Java" }, { "code": null, "e": 35290, "s": 35282, "text": "Python3" }, { "code": null, "e": 35293, "s": 35290, "text": "C#" }, { "code": null, "e": 35304, "s": 35293, "text": "Javascript" }, { "code": "// C++ Program for above approach#include <iostream>using namespace std; // Node classstruct node{ int data; struct node* left; struct node* right;}; // Program to count leavesint countLeaves(struct node *node){ // If the node itself is \"null\" // return 0, as there // are no leaves if(node == NULL) { return 0; } // It the node is a leaf then // both right and left // children will be \"null\" if(node->left == NULL && node->right == NULL) { return 1; } // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node->left) + countLeaves(node->right);} // Class newNode of Node typestruct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // Driver Codeint main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* get leaf count of the above created tree */ cout<<countLeaves(root)<<endl; } // This code is contributed by rag2127", "e": 36439, "s": 35304, "text": null }, { "code": "// Java Program for above approachimport java.util.LinkedList;import java.util.Queue;import java.io.*;import java.util.*; class GfG{ // Node class static class Node { int data; Node left, right; } // Program to count leaves static int countLeaves(Node node) { // If the node itself is \"null\" // return 0, as there // are no leaves if (node == null) return 0; // It the node is a leaf then // both right and left // children will be \"null\" if (node.left == null && node.right == null) return 1; // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right); } // Class newNode of Node type static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = node.right = null; return (node); } // Driver Code public static void main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); /* get leaf count of the above created tree */ System.out.println(countLeaves(root)); }}//Code by Rounik Prashar", "e": 37690, "s": 36439, "text": null }, { "code": "# Python3 Program for above approach # Node classclass Node: def __init__(self,x): self.data = x self.left = None self.right = None # Program to count leavesdef countLeaves(node): # If the node itself is \"None\" # return 0, as there # are no leaves if (node == None): return 0 # It the node is a leaf then # both right and left # children will be \"None\" if (node.left == None and node.right == None): return 1 # Now we count the leaves in # the left and right # subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right) # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) # /* get leaf count of the above # created tree */ print(countLeaves(root)) # This code is contributed by mohit kumar 29", "e": 38614, "s": 37690, "text": null }, { "code": "// C# Program for above approachusing System; // Node classpublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node root; // Program to count leavesstatic int countLeaves(Node node){ // If the node itself is \"null\" // return 0, as there // are no leaves if (node == null) { return 0; } // It the node is a leaf then // both right and left // children will be \"null\" if (node.left == null && node.right == null) { return 1; } // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right);} // Driver Codestatic public void Main(){ BinaryTree.root = new Node(1); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(5); // Get leaf count of the above created tree Console.WriteLine(countLeaves(root));}} // This code is contributed by avanitrachhadiya2155", "e": 39803, "s": 38614, "text": null }, { "code": "<script> // Javascript Program for above approach // Node class class Node { // Class newNode of Node type constructor(data) { this.data=data; this.next = this.right = null; } } // Program to count leavesfunction countLeaves(node){ // If the node itself is \"null\" // return 0, as there // are no leaves if (node == null) return 0; // It the node is a leaf then // both right and left // children will be \"null\" if (node.left == null && node.right == null) return 1; // Now we count the leaves in // the left and right // subtrees and return the sum return countLeaves(node.left) + countLeaves(node.right);} // Driver Codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5); /* get leaf count of the above created tree */document.write(countLeaves(root)); // This code is contributed by patel2127 </script>", "e": 40842, "s": 39803, "text": null }, { "code": null, "e": 40844, "s": 40842, "text": "3" }, { "code": null, "e": 40914, "s": 40844, "text": "https://youtu.be/N2mV5p8NOVw?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 41340, "s": 40914, "text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41358, "s": 41342, "text": "PranchalKatiyar" }, { "code": null, "e": 41368, "s": 41358, "text": "Rajput-Ji" }, { "code": null, "e": 41380, "s": 41368, "text": "29AjayKumar" }, { "code": null, "e": 41391, "s": 41380, "text": "rounik1020" }, { "code": null, "e": 41406, "s": 41391, "text": "mohit kumar 29" }, { "code": null, "e": 41414, "s": 41406, "text": "rag2127" }, { "code": null, "e": 41435, "s": 41414, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41447, "s": 41435, "text": "unknown2108" }, { "code": null, "e": 41457, "s": 41447, "text": "patel2127" }, { "code": null, "e": 41466, "s": 41457, "text": "Ola Cabs" }, { "code": null, "e": 41471, "s": 41466, "text": "Tree" }, { "code": null, "e": 41480, "s": 41471, "text": "Ola Cabs" }, { "code": null, "e": 41485, "s": 41480, "text": "Tree" }, { "code": null, "e": 41583, "s": 41485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41616, "s": 41583, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 41630, "s": 41616, "text": "Decision Tree" }, { "code": null, "e": 41666, "s": 41630, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41714, "s": 41666, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 41797, "s": 41714, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 41813, "s": 41797, "text": "Expression Tree" }, { "code": null, "e": 41839, "s": 41813, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 41866, "s": 41839, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 41901, "s": 41866, "text": "Binary Tree (Array implementation)" } ]
ChronoLocalDate isEqual() method in Java with Examples - GeeksforGeeks
29 Apr, 2019 The isEqual() method of ChronoLocalDate interface in Java checks if this date is equal to the specified date or not. Syntax: public boolean isEqual(ChronoLocalDate date2) Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null. Return Value: The function returns true if this date is equal to the specified date. Below programs illustrate the isEqual() method of ChronoLocalDate in Java: Program 1: // Program to illustrate the isEqual() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the first date ChronoLocalDate dt1 = LocalDate.parse("2018-11-27"); // Parses the second date ChronoLocalDate dt2 = LocalDate.parse("2018-11-27"); // Check if these two are equal System.out.println(dt1.isEqual(dt2)); }} true Program 2: // Program to illustrate the isEqual() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the first date ChronoLocalDate dt1 = LocalDate.parse("2018-11-27"); // Parses the second date ChronoLocalDate dt2 = LocalDate.parse("2015-11-27"); // Check if these two are equal System.out.println(dt1.isEqual(dt2)); }} false Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#isEqual-java.time.chrono.ChronoLocalDate- Java-ChronoLocalDate Java-Functions Java-time package 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 HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25659, "s": 25631, "text": "\n29 Apr, 2019" }, { "code": null, "e": 25776, "s": 25659, "text": "The isEqual() method of ChronoLocalDate interface in Java checks if this date is equal to the specified date or not." }, { "code": null, "e": 25784, "s": 25776, "text": "Syntax:" }, { "code": null, "e": 25831, "s": 25784, "text": "public boolean isEqual(ChronoLocalDate date2)\n" }, { "code": null, "e": 25939, "s": 25831, "text": "Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null." }, { "code": null, "e": 26024, "s": 25939, "text": "Return Value: The function returns true if this date is equal to the specified date." }, { "code": null, "e": 26099, "s": 26024, "text": "Below programs illustrate the isEqual() method of ChronoLocalDate in Java:" }, { "code": null, "e": 26110, "s": 26099, "text": "Program 1:" }, { "code": "// Program to illustrate the isEqual() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the first date ChronoLocalDate dt1 = LocalDate.parse(\"2018-11-27\"); // Parses the second date ChronoLocalDate dt2 = LocalDate.parse(\"2018-11-27\"); // Check if these two are equal System.out.println(dt1.isEqual(dt2)); }}", "e": 26590, "s": 26110, "text": null }, { "code": null, "e": 26596, "s": 26590, "text": "true\n" }, { "code": null, "e": 26607, "s": 26596, "text": "Program 2:" }, { "code": "// Program to illustrate the isEqual() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the first date ChronoLocalDate dt1 = LocalDate.parse(\"2018-11-27\"); // Parses the second date ChronoLocalDate dt2 = LocalDate.parse(\"2015-11-27\"); // Check if these two are equal System.out.println(dt1.isEqual(dt2)); }}", "e": 27087, "s": 26607, "text": null }, { "code": null, "e": 27094, "s": 27087, "text": "false\n" }, { "code": null, "e": 27227, "s": 27094, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#isEqual-java.time.chrono.ChronoLocalDate-" }, { "code": null, "e": 27248, "s": 27227, "text": "Java-ChronoLocalDate" }, { "code": null, "e": 27263, "s": 27248, "text": "Java-Functions" }, { "code": null, "e": 27281, "s": 27263, "text": "Java-time package" }, { "code": null, "e": 27286, "s": 27281, "text": "Java" }, { "code": null, "e": 27291, "s": 27286, "text": "Java" }, { "code": null, "e": 27389, "s": 27291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27440, "s": 27389, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27470, "s": 27440, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27489, "s": 27470, "text": "Interfaces in Java" }, { "code": null, "e": 27504, "s": 27489, "text": "Stream In Java" }, { "code": null, "e": 27535, "s": 27504, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27553, "s": 27535, "text": "ArrayList in Java" }, { "code": null, "e": 27585, "s": 27553, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27605, "s": 27585, "text": "Stack Class in Java" }, { "code": null, "e": 27637, "s": 27605, "text": "Multidimensional Arrays in Java" } ]
Matplotlib.pyplot.rcdefaults() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. The rcdefaults() function in pyplot module of matplotlib library is used to restore the rc params from Matplotlib’s internal default style. Syntax: matplotlib.pyplot.rcdefaults() Parameters: This method does not accepts any parameter. Returns: This method does not return any value. Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot: Example 1: # implementation of the matplotlib functionimport matplotlib.pyplot as plt plt.subplot(211)plt.rc('font', weight ='bold')plt.rc('xtick.major', size = 5, pad = 7)plt.rc('xtick', labelsize = 15)plt.plot([1, 2, 3]) plt.text(0.4, 3.5, 'matplotlib.pyplot.rcdefaults() Example') plt.rcdefaults()plt.subplot(212)plt.plot([1, 2, 3])plt.grid(True) plt.show() Output: Example 2: # implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) plt.rcdefaults()fig, ax = plt.subplots() people = ('Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5')y_pos = np.arange(len(people))performance = 3 + 5 * np.random.rand(len(people))error = np.random.rand(len(people)) ax.bar(y_pos, performance, xerr = error, align ='center')ax.set_yticks(y_pos)ax.set_yticklabels(people)ax.invert_yaxis()plt.grid(True) plt.title('matplotlib.pyplot.rcdefaults() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n19 Apr, 2020" }, { "code": null, "e": 25866, "s": 25561, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 26006, "s": 25866, "text": "The rcdefaults() function in pyplot module of matplotlib library is used to restore the rc params from Matplotlib’s internal default style." }, { "code": null, "e": 26045, "s": 26006, "text": "Syntax: matplotlib.pyplot.rcdefaults()" }, { "code": null, "e": 26101, "s": 26045, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 26149, "s": 26101, "text": "Returns: This method does not return any value." }, { "code": null, "e": 26241, "s": 26149, "text": "Below examples illustrate the matplotlib.pyplot.rcdefaults() function in matplotlib.pyplot:" }, { "code": null, "e": 26252, "s": 26241, "text": "Example 1:" }, { "code": "# implementation of the matplotlib functionimport matplotlib.pyplot as plt plt.subplot(211)plt.rc('font', weight ='bold')plt.rc('xtick.major', size = 5, pad = 7)plt.rc('xtick', labelsize = 15)plt.plot([1, 2, 3]) plt.text(0.4, 3.5, 'matplotlib.pyplot.rcdefaults() Example') plt.rcdefaults()plt.subplot(212)plt.plot([1, 2, 3])plt.grid(True) plt.show()", "e": 26606, "s": 26252, "text": null }, { "code": null, "e": 26614, "s": 26606, "text": "Output:" }, { "code": null, "e": 26625, "s": 26614, "text": "Example 2:" }, { "code": "# implementation of the matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(19680801) plt.rcdefaults()fig, ax = plt.subplots() people = ('Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5')y_pos = np.arange(len(people))performance = 3 + 5 * np.random.rand(len(people))error = np.random.rand(len(people)) ax.bar(y_pos, performance, xerr = error, align ='center')ax.set_yticks(y_pos)ax.set_yticklabels(people)ax.invert_yaxis()plt.grid(True) plt.title('matplotlib.pyplot.rcdefaults() Example')plt.show()", "e": 27155, "s": 26625, "text": null }, { "code": null, "e": 27163, "s": 27155, "text": "Output:" }, { "code": null, "e": 27181, "s": 27163, "text": "Python-matplotlib" }, { "code": null, "e": 27188, "s": 27181, "text": "Python" }, { "code": null, "e": 27286, "s": 27188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27318, "s": 27286, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27360, "s": 27318, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27402, "s": 27360, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27458, "s": 27402, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27485, "s": 27458, "text": "Python Classes and Objects" }, { "code": null, "e": 27524, "s": 27485, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27555, "s": 27524, "text": "Python | os.path.join() method" }, { "code": null, "e": 27577, "s": 27555, "text": "Defaultdict in Python" }, { "code": null, "e": 27606, "s": 27577, "text": "Create a directory in Python" } ]
Practice Questions on Time Complexity Analysis - GeeksforGeeks
09 Jun, 2021 Prerequisite: Analysis of Algorithms1. What is the time, space complexity of the following code: CPP int a = 0, b = 0;for (i = 0; i < N; i++) { a = a + rand();}for (j = 0; j < M; j++) { b = b + rand();} Options: O(N * M) time, O(1) spaceO(N + M) time, O(N + M) spaceO(N + M) time, O(1) spaceO(N * M) time, O(N + M) space O(N * M) time, O(1) space O(N + M) time, O(N + M) space O(N + M) time, O(1) space O(N * M) time, O(N + M) space Output: 3. O(N + M) time, O(1) space Explanation: The first loop is O(N) and the second loop is O(M). Since we don’t know which is bigger, we say this is O(N + M). This can also be written as O(max(N, M)). Since there is no additional space being utilized, the space complexity is constant / O(1)2. What is the time complexity of the following code: CPP int a = 0;for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; }} Options: O(N)O(N*log(N))O(N * Sqrt(N))O(N*N) O(N) O(N*log(N)) O(N * Sqrt(N)) O(N*N) Output: 4. O(N*N) Explanation: The above code runs total no of times = N + (N – 1) + (N – 2) + ... 1 + 0 = N * (N + 1) / 2 = 1/2 * N^2 + 1/2 * N O(N^2) times.3. What is the time complexity of the following code: CPP int i, j, k = 0;for (i = n / 2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n / 2; }} Options: O(n)O(nLogn)O(n^2)O(n^2Logn) O(n) O(nLogn) O(n^2) O(n^2Logn) Output: 2. O(nLogn) Explanation: If you notice, j keeps doubling till it is less than or equal to n. Several times, we can double a number till it is less than n would be log(n). Let’s take the examples here. for n = 16, j = 2, 4, 8, 16 for n = 32, j = 2, 4, 8, 16, 32 So, j would run for O(log n) steps. i runs for n/2 steps. So, total steps = O(n/ 2 * log (n)) = O(n*logn)4. What does it mean when we say that an algorithm X is asymptotically more efficient than Y? Options: X will always be a better choice for small inputsX will always be a better choice for large inputsY will always be a better choice for small inputsX will always be a better choice for all inputs X will always be a better choice for small inputs X will always be a better choice for large inputs Y will always be a better choice for small inputs X will always be a better choice for all inputs 2. X will always be a better choice for large inputs Explanation: In asymptotic analysis, we consider the growth of the algorithm in terms of input size. An algorithm X is said to be asymptotically better than Y if X takes smaller time than y for all input sizes n larger than a value n0 where n0 > 0. 5. What is the time complexity of the following code: CPP int a = 0, i = N;while (i > 0) { a += i; i /= 2;} Options: O(N)O(Sqrt(N))O(N / 2)O(log N) O(N) O(Sqrt(N)) O(N / 2) O(log N) Output: 4. O(log N) Explanation: We have to find the smallest x such that N / 2^x N x = log(N) 6. Which of the following best describes the useful criterion for comparing the efficiency of algorithms? TimeMemoryBoth of the aboveNone of the above Time Memory Both of the above None of the above 3. Both of the above Explanation: Comparing the efficiency of an algorithm obviously depends on time and memory taken by an algorithm, 7. How is time complexity measured? By counting the number of algorithms in an algorithm.By counting the number of primitive operations performed by the algorithm on given input size.By counting the size of data input to the algorithm.None of the above By counting the number of algorithms in an algorithm. By counting the number of primitive operations performed by the algorithm on given input size. By counting the size of data input to the algorithm. None of the above 2. By counting the number of primitive operations performed by the algorithm on given input size. 8. What will be the time complexity of the following code? Javascript for(var i=0;i<n;i++) i*=k O(n)O(k)O(logkn)O(lognk) O(n) O(k) O(logkn) O(lognk) Output: 3. O(logkn) Explanation: because loops for the kn-1 times, so after taking log it becomes logkn. 9. What will be the time complexity of the following code? Javascript var value = 0;for(var i=0;i<n;i++) for(var j=0;j<i;j++) value += 1; n(n+1)n(n-1)/2n(n+1)/2 n (n+1) n(n-1)/2 n(n+1)/2 Output: 3. n(n-1)/2 Explanation: First for loop will run for (n) times and another for loop will be run for (n-1) times so overall time will be n(n-1)/2. 10. Algorithm A and B have a worst-case running time of O(n) and O(logn), respectively. Therefore, algorithm B always runs faster than algorithm A. TrueFalse True False False Explanation: The Big-O notation provides an asymptotic comparison in the running time of algorithms. For n < n0​​, algorithm A might run faster than algorithm B, for instance. gittysatyam Analysis Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Analysis of Algorithms | Big-O analysis Difference between NP hard and NP complete problem Analysis of different sorting techniques Difference between Big Oh, Big Omega and Big Theta Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Cyclomatic Complexity Time complexities of different data structures Lower and Upper Bound Theory
[ { "code": null, "e": 25481, "s": 25453, "text": "\n09 Jun, 2021" }, { "code": null, "e": 25580, "s": 25481, "text": "Prerequisite: Analysis of Algorithms1. What is the time, space complexity of the following code: " }, { "code": null, "e": 25584, "s": 25580, "text": "CPP" }, { "code": "int a = 0, b = 0;for (i = 0; i < N; i++) { a = a + rand();}for (j = 0; j < M; j++) { b = b + rand();}", "e": 25692, "s": 25584, "text": null }, { "code": null, "e": 25703, "s": 25692, "text": "Options: " }, { "code": null, "e": 25812, "s": 25703, "text": "O(N * M) time, O(1) spaceO(N + M) time, O(N + M) spaceO(N + M) time, O(1) spaceO(N * M) time, O(N + M) space" }, { "code": null, "e": 25838, "s": 25812, "text": "O(N * M) time, O(1) space" }, { "code": null, "e": 25868, "s": 25838, "text": "O(N + M) time, O(N + M) space" }, { "code": null, "e": 25894, "s": 25868, "text": "O(N + M) time, O(1) space" }, { "code": null, "e": 25924, "s": 25894, "text": "O(N * M) time, O(N + M) space" }, { "code": null, "e": 25933, "s": 25924, "text": "Output: " }, { "code": null, "e": 25962, "s": 25933, "text": "3. O(N + M) time, O(1) space" }, { "code": null, "e": 26277, "s": 25962, "text": "Explanation: The first loop is O(N) and the second loop is O(M). Since we don’t know which is bigger, we say this is O(N + M). This can also be written as O(max(N, M)). Since there is no additional space being utilized, the space complexity is constant / O(1)2. What is the time complexity of the following code: " }, { "code": null, "e": 26281, "s": 26277, "text": "CPP" }, { "code": "int a = 0;for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; }}", "e": 26374, "s": 26281, "text": null }, { "code": null, "e": 26385, "s": 26374, "text": "Options: " }, { "code": null, "e": 26421, "s": 26385, "text": "O(N)O(N*log(N))O(N * Sqrt(N))O(N*N)" }, { "code": null, "e": 26426, "s": 26421, "text": "O(N)" }, { "code": null, "e": 26438, "s": 26426, "text": "O(N*log(N))" }, { "code": null, "e": 26453, "s": 26438, "text": "O(N * Sqrt(N))" }, { "code": null, "e": 26460, "s": 26453, "text": "O(N*N)" }, { "code": null, "e": 26469, "s": 26460, "text": "Output: " }, { "code": null, "e": 26479, "s": 26469, "text": "4. O(N*N)" }, { "code": null, "e": 26675, "s": 26479, "text": "Explanation: The above code runs total no of times = N + (N – 1) + (N – 2) + ... 1 + 0 = N * (N + 1) / 2 = 1/2 * N^2 + 1/2 * N O(N^2) times.3. What is the time complexity of the following code: " }, { "code": null, "e": 26679, "s": 26675, "text": "CPP" }, { "code": "int i, j, k = 0;for (i = n / 2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n / 2; }}", "e": 26790, "s": 26679, "text": null }, { "code": null, "e": 26801, "s": 26790, "text": "Options: " }, { "code": null, "e": 26830, "s": 26801, "text": "O(n)O(nLogn)O(n^2)O(n^2Logn)" }, { "code": null, "e": 26835, "s": 26830, "text": "O(n)" }, { "code": null, "e": 26844, "s": 26835, "text": "O(nLogn)" }, { "code": null, "e": 26851, "s": 26844, "text": "O(n^2)" }, { "code": null, "e": 26862, "s": 26851, "text": "O(n^2Logn)" }, { "code": null, "e": 26871, "s": 26862, "text": "Output: " }, { "code": null, "e": 26883, "s": 26871, "text": "2. O(nLogn)" }, { "code": null, "e": 27342, "s": 26883, "text": "Explanation: If you notice, j keeps doubling till it is less than or equal to n. Several times, we can double a number till it is less than n would be log(n). Let’s take the examples here. for n = 16, j = 2, 4, 8, 16 for n = 32, j = 2, 4, 8, 16, 32 So, j would run for O(log n) steps. i runs for n/2 steps. So, total steps = O(n/ 2 * log (n)) = O(n*logn)4. What does it mean when we say that an algorithm X is asymptotically more efficient than Y? Options: " }, { "code": null, "e": 27537, "s": 27342, "text": "X will always be a better choice for small inputsX will always be a better choice for large inputsY will always be a better choice for small inputsX will always be a better choice for all inputs" }, { "code": null, "e": 27587, "s": 27537, "text": "X will always be a better choice for small inputs" }, { "code": null, "e": 27637, "s": 27587, "text": "X will always be a better choice for large inputs" }, { "code": null, "e": 27687, "s": 27637, "text": "Y will always be a better choice for small inputs" }, { "code": null, "e": 27735, "s": 27687, "text": "X will always be a better choice for all inputs" }, { "code": null, "e": 27790, "s": 27737, "text": "2. X will always be a better choice for large inputs" }, { "code": null, "e": 28040, "s": 27790, "text": "Explanation: In asymptotic analysis, we consider the growth of the algorithm in terms of input size. An algorithm X is said to be asymptotically better than Y if X takes smaller time than y for all input sizes n larger than a value n0 where n0 > 0. " }, { "code": null, "e": 28094, "s": 28040, "text": "5. What is the time complexity of the following code:" }, { "code": null, "e": 28100, "s": 28096, "text": "CPP" }, { "code": "int a = 0, i = N;while (i > 0) { a += i; i /= 2;}", "e": 28156, "s": 28100, "text": null }, { "code": null, "e": 28167, "s": 28156, "text": "Options: " }, { "code": null, "e": 28198, "s": 28167, "text": "O(N)O(Sqrt(N))O(N / 2)O(log N)" }, { "code": null, "e": 28203, "s": 28198, "text": "O(N)" }, { "code": null, "e": 28214, "s": 28203, "text": "O(Sqrt(N))" }, { "code": null, "e": 28223, "s": 28214, "text": "O(N / 2)" }, { "code": null, "e": 28232, "s": 28223, "text": "O(log N)" }, { "code": null, "e": 28242, "s": 28232, "text": "Output: " }, { "code": null, "e": 28254, "s": 28242, "text": "4. O(log N)" }, { "code": null, "e": 28329, "s": 28254, "text": "Explanation: We have to find the smallest x such that N / 2^x N x = log(N)" }, { "code": null, "e": 28435, "s": 28329, "text": "6. Which of the following best describes the useful criterion for comparing the efficiency of algorithms?" }, { "code": null, "e": 28480, "s": 28435, "text": "TimeMemoryBoth of the aboveNone of the above" }, { "code": null, "e": 28485, "s": 28480, "text": "Time" }, { "code": null, "e": 28492, "s": 28485, "text": "Memory" }, { "code": null, "e": 28510, "s": 28492, "text": "Both of the above" }, { "code": null, "e": 28528, "s": 28510, "text": "None of the above" }, { "code": null, "e": 28549, "s": 28528, "text": "3. Both of the above" }, { "code": null, "e": 28665, "s": 28549, "text": "Explanation: Comparing the efficiency of an algorithm obviously depends on time and memory taken by an algorithm, " }, { "code": null, "e": 28701, "s": 28665, "text": "7. How is time complexity measured?" }, { "code": null, "e": 28918, "s": 28701, "text": "By counting the number of algorithms in an algorithm.By counting the number of primitive operations performed by the algorithm on given input size.By counting the size of data input to the algorithm.None of the above" }, { "code": null, "e": 28972, "s": 28918, "text": "By counting the number of algorithms in an algorithm." }, { "code": null, "e": 29067, "s": 28972, "text": "By counting the number of primitive operations performed by the algorithm on given input size." }, { "code": null, "e": 29120, "s": 29067, "text": "By counting the size of data input to the algorithm." }, { "code": null, "e": 29138, "s": 29120, "text": "None of the above" }, { "code": null, "e": 29236, "s": 29138, "text": "2. By counting the number of primitive operations performed by the algorithm on given input size." }, { "code": null, "e": 29295, "s": 29236, "text": "8. What will be the time complexity of the following code?" }, { "code": null, "e": 29306, "s": 29295, "text": "Javascript" }, { "code": "for(var i=0;i<n;i++) i*=k", "e": 29335, "s": 29306, "text": null }, { "code": null, "e": 29360, "s": 29335, "text": "O(n)O(k)O(logkn)O(lognk)" }, { "code": null, "e": 29365, "s": 29360, "text": "O(n)" }, { "code": null, "e": 29370, "s": 29365, "text": "O(k)" }, { "code": null, "e": 29379, "s": 29370, "text": "O(logkn)" }, { "code": null, "e": 29388, "s": 29379, "text": "O(lognk)" }, { "code": null, "e": 29396, "s": 29388, "text": "Output:" }, { "code": null, "e": 29408, "s": 29396, "text": "3. O(logkn)" }, { "code": null, "e": 29493, "s": 29408, "text": "Explanation: because loops for the kn-1 times, so after taking log it becomes logkn." }, { "code": null, "e": 29552, "s": 29493, "text": "9. What will be the time complexity of the following code?" }, { "code": null, "e": 29563, "s": 29552, "text": "Javascript" }, { "code": "var value = 0;for(var i=0;i<n;i++) for(var j=0;j<i;j++) value += 1;", "e": 29637, "s": 29563, "text": null }, { "code": null, "e": 29660, "s": 29637, "text": "n(n+1)n(n-1)/2n(n+1)/2" }, { "code": null, "e": 29662, "s": 29660, "text": "n" }, { "code": null, "e": 29668, "s": 29662, "text": "(n+1)" }, { "code": null, "e": 29677, "s": 29668, "text": "n(n-1)/2" }, { "code": null, "e": 29686, "s": 29677, "text": "n(n+1)/2" }, { "code": null, "e": 29694, "s": 29686, "text": "Output:" }, { "code": null, "e": 29706, "s": 29694, "text": "3. n(n-1)/2" }, { "code": null, "e": 29840, "s": 29706, "text": "Explanation: First for loop will run for (n) times and another for loop will be run for (n-1) times so overall time will be n(n-1)/2." }, { "code": null, "e": 29989, "s": 29840, "text": "10. Algorithm A and B have a worst-case running time of O(n) and O(logn), respectively. Therefore, algorithm B always runs faster than algorithm A." }, { "code": null, "e": 29999, "s": 29989, "text": "TrueFalse" }, { "code": null, "e": 30004, "s": 29999, "text": "True" }, { "code": null, "e": 30010, "s": 30004, "text": "False" }, { "code": null, "e": 30016, "s": 30010, "text": "False" }, { "code": null, "e": 30192, "s": 30016, "text": "Explanation: The Big-O notation provides an asymptotic comparison in the running time of algorithms. For n < n0​​, algorithm A might run faster than algorithm B, for instance." }, { "code": null, "e": 30204, "s": 30192, "text": "gittysatyam" }, { "code": null, "e": 30213, "s": 30204, "text": "Analysis" }, { "code": null, "e": 30311, "s": 30213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30348, "s": 30311, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 30431, "s": 30348, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 30471, "s": 30431, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 30522, "s": 30471, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 30563, "s": 30522, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 30614, "s": 30563, "text": "Difference between Big Oh, Big Omega and Big Theta" }, { "code": null, "e": 30681, "s": 30614, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 30703, "s": 30681, "text": "Cyclomatic Complexity" }, { "code": null, "e": 30750, "s": 30703, "text": "Time complexities of different data structures" } ]
MySQL ON vs USING?
In general, we use ON in MySQL. In Joins, we use ON in a set of columns. USING is useful when both the tables share a column of the exact same name on which they join. Example of On. Creating our first table. mysql> CREATE table ForeignTableDemo -> ( -> Id int, -> Name varchar(100), - > FK int - > ); Query OK, 0 rows affected (0.47 sec) Creating our second table. mysql> CREATE table PrimaryTableDemo - > ( - > FK int, - > Address varchar(100), - > primary key(FK) - > ); Query OK, 0 rows affected (0.47 sec) Let us now add constraints. mysql> ALTER table ForeignTableDemo add constraint FKConst foreign key(FK) references PrimaryTableDemo(FK); Query OK, 0 rows affected (1.54 sec) Records: 0 Duplicates: 0 Warnings: 0 To add records into the second table. mysql> INSERT into PrimaryTableDemo values(1,'US'); Query OK, 1 row affected (0.10 sec) mysql> INSERT into PrimaryTableDemo values(2,'UK'); Query OK, 1 row affected (0.14 sec) mysql> INSERT into PrimaryTableDemo values(3,'Unknown'); Query OK, 1 row affected (0.08 sec) Displaying all the records. mysql> SELECT * from PrimaryTableDemo; The following is the output. +----+---------+ | FK | Address | +----+---------+ | 1 | US | | 2 | UK | | 3 | Unknown | +----+---------+ 3 rows in set (0.00 sec) Now, to add records into the first table. mysql> INSERT into ForeignTableDemo values (1,'John',1); Query OK, 1 row affected (0.20 sec) mysql> INSERT into ForeignTableDemo values (2,'Bob',2); Query OK, 1 row affected (0.27 sec) Let us now display all the records from the first table. mysql> SELECT * from ForeignTableDemo; Here is the output. +------+------+------+ | Id | Name | FK | +------+------+------+ | 1 | John | 1 | | 2 | Bob | 2 | +------+------+------+ 2 rows in set (0.00 sec) The query for straight join that displays only matching rows is shown below. We have used ON here. mysql> SELECT ForeignTableDemo.Id, ForeignTableDemo.Name, PrimaryTableDemo.Address - > from ForeignTableDemo - > join PrimaryTableDemo - > on ForeignTableDemo.FK = PrimaryTableDemo.FK; The following is the output. +------+------+---------+ | Id | Name | Address | +------+------+---------+ | 1 | John | US | | 2 | Bob | UK | +------+------+---------+ 2 rows in set (0.14 sec) Example of USING. The following is the syntax of USING in MySQL, that displays the record where FK = 1. mysql> select *from ForeignTableDemo join PrimaryTableDemo using(FK) where FK=1; Here is the output. +------+------+------+---------+ | FK | Id | Name | Address | +------+------+------+---------+ | 1 | 1 | John | US | +------+------+------+---------+ 1 row in set (0.09 sec)
[ { "code": null, "e": 1230, "s": 1062, "text": "In general, we use ON in MySQL. In Joins, we use ON in a set of columns. USING is useful when both the tables share a column of the exact same name on which they join." }, { "code": null, "e": 1245, "s": 1230, "text": "Example of On." }, { "code": null, "e": 1271, "s": 1245, "text": "Creating our first table." }, { "code": null, "e": 1416, "s": 1271, "text": "mysql> CREATE table ForeignTableDemo\n -> (\n -> Id int,\n -> Name varchar(100),\n - > FK int\n - > );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1443, "s": 1416, "text": "Creating our second table." }, { "code": null, "e": 1604, "s": 1443, "text": "mysql> CREATE table PrimaryTableDemo\n - > (\n - > FK int,\n - > Address varchar(100),\n - > primary key(FK)\n - > );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1632, "s": 1604, "text": "Let us now add constraints." }, { "code": null, "e": 1816, "s": 1632, "text": "mysql> ALTER table ForeignTableDemo add constraint FKConst foreign key(FK) references PrimaryTableDemo(FK);\nQuery OK, 0 rows affected (1.54 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1854, "s": 1816, "text": "To add records into the second table." }, { "code": null, "e": 2126, "s": 1854, "text": "mysql> INSERT into PrimaryTableDemo values(1,'US');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> INSERT into PrimaryTableDemo values(2,'UK');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> INSERT into PrimaryTableDemo values(3,'Unknown');\nQuery OK, 1 row affected (0.08 sec)" }, { "code": null, "e": 2154, "s": 2126, "text": "Displaying all the records." }, { "code": null, "e": 2193, "s": 2154, "text": "mysql> SELECT * from PrimaryTableDemo;" }, { "code": null, "e": 2222, "s": 2193, "text": "The following is the output." }, { "code": null, "e": 2367, "s": 2222, "text": "+----+---------+\n| FK | Address |\n+----+---------+\n| 1 | US |\n| 2 | UK |\n| 3 | Unknown |\n+----+---------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 2409, "s": 2367, "text": "Now, to add records into the first table." }, { "code": null, "e": 2597, "s": 2409, "text": "mysql> INSERT into ForeignTableDemo values (1,'John',1);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> INSERT into ForeignTableDemo values (2,'Bob',2);\nQuery OK, 1 row affected (0.27 sec)" }, { "code": null, "e": 2654, "s": 2597, "text": "Let us now display all the records from the first table." }, { "code": null, "e": 2693, "s": 2654, "text": "mysql> SELECT * from ForeignTableDemo;" }, { "code": null, "e": 2713, "s": 2693, "text": "Here is the output." }, { "code": null, "e": 2877, "s": 2713, "text": "+------+------+------+\n| Id | Name | FK |\n+------+------+------+\n| 1 | John | 1 |\n| 2 | Bob | 2 |\n+------+------+------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 2976, "s": 2877, "text": "The query for straight join that displays only matching rows is shown below. We have used ON here." }, { "code": null, "e": 3170, "s": 2976, "text": "mysql> SELECT ForeignTableDemo.Id, ForeignTableDemo.Name, PrimaryTableDemo.Address\n - > from ForeignTableDemo\n - > join PrimaryTableDemo\n - > on ForeignTableDemo.FK = PrimaryTableDemo.FK;" }, { "code": null, "e": 3199, "s": 3170, "text": "The following is the output." }, { "code": null, "e": 3381, "s": 3199, "text": "+------+------+---------+\n| Id | Name | Address |\n+------+------+---------+\n| 1 | John | US |\n| 2 | Bob | UK |\n+------+------+---------+\n2 rows in set (0.14 sec)\n" }, { "code": null, "e": 3399, "s": 3381, "text": "Example of USING." }, { "code": null, "e": 3485, "s": 3399, "text": "The following is the syntax of USING in MySQL, that displays the record where FK = 1." }, { "code": null, "e": 3566, "s": 3485, "text": "mysql> select *from ForeignTableDemo join PrimaryTableDemo using(FK) where FK=1;" }, { "code": null, "e": 3586, "s": 3566, "text": "Here is the output." }, { "code": null, "e": 3776, "s": 3586, "text": "+------+------+------+---------+\n| FK | Id | Name | Address |\n+------+------+------+---------+\n| 1 | 1 | John | US |\n+------+------+------+---------+\n1 row in set (0.09 sec)\n" } ]
Opening and Closing Files in Python
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files. Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object. Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it. file object = open(file_name [, access_mode][, buffering]) Here are parameter details − file_name − The file_name argument is a string value that contains the name of the file that you want to access. access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r). buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). Here is a list of the different modes of opening a file − Once a file is opened and you have one file object, you can get various information related to that file. Here is a list of all attributes related to file object − Live Demo #!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print "Name of the file: ", fo.name print "Closed or not : ", fo.closed print "Opening mode : ", fo.mode print "Softspace flag : ", fo.softspace This produces the following result − Name of the file: foo.txt Closed or not : False Opening mode : wb Softspace flag : 0 The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file. fileObject.close() Live Demo #!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print "Name of the file: ", fo.name # Close opend file fo.close() This produces the following result − Name of the file: foo.txt
[ { "code": null, "e": 1188, "s": 1062, "text": "Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files." }, { "code": null, "e": 1336, "s": 1188, "text": "Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object." }, { "code": null, "e": 1545, "s": 1336, "text": "Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it." }, { "code": null, "e": 1604, "s": 1545, "text": "file object = open(file_name [, access_mode][, buffering])" }, { "code": null, "e": 1633, "s": 1604, "text": "Here are parameter details −" }, { "code": null, "e": 1746, "s": 1633, "text": "file_name − The file_name argument is a string value that contains the name of the file that you want to access." }, { "code": null, "e": 2001, "s": 1746, "text": "access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r)." }, { "code": null, "e": 2358, "s": 2001, "text": "buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior)." }, { "code": null, "e": 2416, "s": 2358, "text": "Here is a list of the different modes of opening a file −" }, { "code": null, "e": 2522, "s": 2416, "text": "Once a file is opened and you have one file object, you can get various information related to that file." }, { "code": null, "e": 2580, "s": 2522, "text": "Here is a list of all attributes related to file object −" }, { "code": null, "e": 2591, "s": 2580, "text": " Live Demo" }, { "code": null, "e": 2796, "s": 2591, "text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\nprint \"Closed or not : \", fo.closed\nprint \"Opening mode : \", fo.mode\nprint \"Softspace flag : \", fo.softspace" }, { "code": null, "e": 2833, "s": 2796, "text": "This produces the following result −" }, { "code": null, "e": 2918, "s": 2833, "text": "Name of the file: foo.txt\nClosed or not : False\nOpening mode : wb\nSoftspace flag : 0" }, { "code": null, "e": 3057, "s": 2918, "text": "The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done." }, { "code": null, "e": 3224, "s": 3057, "text": "Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file." }, { "code": null, "e": 3244, "s": 3224, "text": "fileObject.close()\n" }, { "code": null, "e": 3255, "s": 3244, "text": " Live Demo" }, { "code": null, "e": 3380, "s": 3255, "text": "#!/usr/bin/python\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\n# Close opend file\nfo.close()" }, { "code": null, "e": 3417, "s": 3380, "text": "This produces the following result −" }, { "code": null, "e": 3444, "s": 3417, "text": "Name of the file: foo.txt\n" } ]
Convert min Heap to max Heap - GeeksforGeeks
20 Oct, 2021 Given array representation of min Heap, convert it to max Heap in O(n) time. Example : Input: arr[] = [3 5 9 6 8 20 10 12 18 9] 3 / \ 5 9 / \ / \ 6 8 20 10 / \ / 12 18 9 Output: arr[] = [20 18 10 12 9 9 3 5 6 8] OR [any Max Heap formed from input elements] 20 / \ 18 10 / \ / \ 12 9 9 3 / \ / 5 6 8 The problem might look complex at first look. But our final goal is to only build the max heap. The idea is very simple – we simply build Max Heap without caring about the input. We start from the bottom-most and rightmost internal mode of min Heap and heapify all internal modes in the bottom-up way to build the Max heap.Below is its implementation C++ Java Python3 C# PHP Javascript // A C++ program to convert min Heap to max Heap#include<bits/stdc++.h>using namespace std; // to heapify a subtree with root at given indexvoid MaxHeapify(int arr[], int i, int n){ int l = 2*i + 1; int r = 2*i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(arr[i], arr[largest]); MaxHeapify(arr, largest, n); }} // This function basically builds max heapvoid convertMaxHeap(int arr[], int n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (int i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n);} // A utility function to print a given array// of given sizevoid printArray(int* arr, int size){ for (int i = 0; i < size; ++i) printf("%d ", arr[i]);} // Driver program to test above functionsint main(){ // array representing Min Heap int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = sizeof(arr)/sizeof(arr[0]); printf("Min Heap array : "); printArray(arr, n); convertMaxHeap(arr, n); printf("\nMax Heap array : "); printArray(arr, n); return 0;} // Java program to convert min Heap to max Heap class GFG{ // To heapify a subtree with root at given index static void MaxHeapify(int arr[], int i, int n) { int l = 2*i + 1; int r = 2*i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); } } // This function basically builds max heap static void convertMaxHeap(int arr[], int n) { // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (int i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n); } // A utility function to print a given array // of given size static void printArray(int arr[], int size) { for (int i = 0; i < size; ++i) System.out.print(arr[i]+" "); } // driver program public static void main (String[] args) { // array representing Min Heap int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = arr.length; System.out.print("Min Heap array : "); printArray(arr, n); convertMaxHeap(arr, n); System.out.print("\nMax Heap array : "); printArray(arr, n); }} // Contributed by Pramod Kumar # A Python3 program to convert min Heap# to max Heap # to heapify a subtree with root# at given indexdef MaxHeapify(arr, i, n): l = 2 * i + 1 r = 2 * i + 2 largest = i if l < n and arr[l] > arr[i]: largest = l if r < n and arr[r] > arr[largest]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] MaxHeapify(arr, largest, n) # This function basically builds max heapdef convertMaxHeap(arr, n): # Start from bottommost and rightmost # internal mode and heapify all # internal modes in bottom up way for i in range(int((n - 2) / 2), -1, -1): MaxHeapify(arr, i, n) # A utility function to print a# given array of given sizedef printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() # Driver Codeif __name__ == '__main__': # array representing Min Heap arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9] n = len(arr) print("Min Heap array : ") printArray(arr, n) convertMaxHeap(arr, n) print("Max Heap array : ") printArray(arr, n) # This code is contributed by PranchalK // C# program to convert// min Heap to max Heapusing System; class GFG{ // To heapify a subtree with // root at given index static void MaxHeapify(int []arr, int i, int n) { int l = 2 * i + 1; int r = 2 * i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); } } // This function basically // builds max heap static void convertMaxHeap(int []arr, int n) { // Start from bottommost and // rightmost internal mode and // heapify all internal modes // in bottom up way for (int i = (n - 2) / 2; i >= 0; --i) MaxHeapify(arr, i, n); } // A utility function to print // a given array of given size static void printArray(int []arr, int size) { for (int i = 0; i < size; ++i) Console.Write(arr[i]+" "); } // Driver Code public static void Main () { // array representing Min Heap int []arr = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = arr.Length; Console.Write("Min Heap array : "); printArray(arr, n); convertMaxHeap(arr, n); Console.Write("\nMax Heap array : "); printArray(arr, n); }} // This code is contributed by nitin mittal. <?php// A PHP program to convert min Heap to max Heap // utility swap functionfunction swap(&$a,&$b){ $tmp=$a; $a=$b; $b=$tmp;} // to heapify a subtree with root at given indexfunction MaxHeapify(&$arr, $i, $n){ $l = 2*$i + 1; $r = 2*$i + 2; $largest = $i; if ($l < $n && $arr[$l] > $arr[$i]) $largest = $l; if ($r < $n && $arr[$r] > $arr[$largest]) $largest = $r; if ($largest != $i) { swap($arr[$i], $arr[$largest]); MaxHeapify($arr, $largest, $n); }} // This function basically builds max heapfunction convertMaxHeap(&$arr, $n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for ($i = (int)(($n-2)/2); $i >= 0; --$i) MaxHeapify($arr, $i, $n);} // A utility function to print a given array// of given sizefunction printArray($arr, $size){ for ($i = 0; $i <$size; ++$i) print($arr[$i]." ");} // Driver code // array representing Min Heap $arr = array(3, 5, 9, 6, 8, 20, 10, 12, 18, 9); $n = count($arr); print("Min Heap array : "); printArray($arr, $n); convertMaxHeap($arr, $n); print("\nMax Heap array : "); printArray($arr, $n); // This code is contributed by mits?> <script>// javascript program to convert min Heap to max Heap // To heapify a subtree with root at given indexfunction MaxHeapify(arr , i , n){ var l = 2*i + 1; var r = 2*i + 2; var largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] var temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); }} // This function basically builds max heapfunction convertMaxHeap(arr , n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n);} // A utility function to print a given array// of given sizefunction printArray(arr , size){ for (i = 0; i < size; ++i) document.write(arr[i]+" ");} // driver program// array representing Min Heapvar arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9];var n = arr.length; document.write("Min Heap array : ");printArray(arr, n); convertMaxHeap(arr, n); document.write("<br>Max Heap array : ");printArray(arr, n); // This code is contributed by 29AjayKumar</script> Output : Min Heap array : 3 5 9 6 8 20 10 12 18 9 Max Heap array : 20 18 10 12 9 9 3 5 6 8 The complexity of above solution might looks like O(nLogn) but it is O(n). Refer to this G-Fact for more details.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal PranchalKatiyar Mithun Kumar 29AjayKumar gabaa406 tanmay_thaker simranarora5sos Heap Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Min Heap and Max Heap Fibonacci Heap | Set 1 (Introduction) Find k numbers with most occurrences in the given array Priority queue of pairs in C++ (Ordered by first) K-ary Heap Python Program for Heap Sort Applications of Priority Queue C++ Program for Heap Sort Complexity analysis of various operations of Binary Min Heap Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
[ { "code": null, "e": 24205, "s": 24177, "text": "\n20 Oct, 2021" }, { "code": null, "e": 24294, "s": 24205, "text": "Given array representation of min Heap, convert it to max Heap in O(n) time. Example : " }, { "code": null, "e": 24629, "s": 24294, "text": "Input: arr[] = [3 5 9 6 8 20 10 12 18 9]\n 3\n / \\\n 5 9\n / \\ / \\\n 6 8 20 10\n / \\ /\n12 18 9 \n\n\nOutput: arr[] = [20 18 10 12 9 9 3 5 6 8] OR \n [any Max Heap formed from input elements]\n\n 20\n / \\\n 18 10\n / \\ / \\\n 12 9 9 3\n / \\ /\n5 6 8 " }, { "code": null, "e": 24983, "s": 24631, "text": "The problem might look complex at first look. But our final goal is to only build the max heap. The idea is very simple – we simply build Max Heap without caring about the input. We start from the bottom-most and rightmost internal mode of min Heap and heapify all internal modes in the bottom-up way to build the Max heap.Below is its implementation " }, { "code": null, "e": 24987, "s": 24983, "text": "C++" }, { "code": null, "e": 24992, "s": 24987, "text": "Java" }, { "code": null, "e": 25000, "s": 24992, "text": "Python3" }, { "code": null, "e": 25003, "s": 25000, "text": "C#" }, { "code": null, "e": 25007, "s": 25003, "text": "PHP" }, { "code": null, "e": 25018, "s": 25007, "text": "Javascript" }, { "code": "// A C++ program to convert min Heap to max Heap#include<bits/stdc++.h>using namespace std; // to heapify a subtree with root at given indexvoid MaxHeapify(int arr[], int i, int n){ int l = 2*i + 1; int r = 2*i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { swap(arr[i], arr[largest]); MaxHeapify(arr, largest, n); }} // This function basically builds max heapvoid convertMaxHeap(int arr[], int n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (int i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n);} // A utility function to print a given array// of given sizevoid printArray(int* arr, int size){ for (int i = 0; i < size; ++i) printf(\"%d \", arr[i]);} // Driver program to test above functionsint main(){ // array representing Min Heap int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Min Heap array : \"); printArray(arr, n); convertMaxHeap(arr, n); printf(\"\\nMax Heap array : \"); printArray(arr, n); return 0;}", "e": 26237, "s": 25018, "text": null }, { "code": "// Java program to convert min Heap to max Heap class GFG{ // To heapify a subtree with root at given index static void MaxHeapify(int arr[], int i, int n) { int l = 2*i + 1; int r = 2*i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); } } // This function basically builds max heap static void convertMaxHeap(int arr[], int n) { // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (int i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n); } // A utility function to print a given array // of given size static void printArray(int arr[], int size) { for (int i = 0; i < size; ++i) System.out.print(arr[i]+\" \"); } // driver program public static void main (String[] args) { // array representing Min Heap int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = arr.length; System.out.print(\"Min Heap array : \"); printArray(arr, n); convertMaxHeap(arr, n); System.out.print(\"\\nMax Heap array : \"); printArray(arr, n); }} // Contributed by Pramod Kumar", "e": 27763, "s": 26237, "text": null }, { "code": "# A Python3 program to convert min Heap# to max Heap # to heapify a subtree with root# at given indexdef MaxHeapify(arr, i, n): l = 2 * i + 1 r = 2 * i + 2 largest = i if l < n and arr[l] > arr[i]: largest = l if r < n and arr[r] > arr[largest]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] MaxHeapify(arr, largest, n) # This function basically builds max heapdef convertMaxHeap(arr, n): # Start from bottommost and rightmost # internal mode and heapify all # internal modes in bottom up way for i in range(int((n - 2) / 2), -1, -1): MaxHeapify(arr, i, n) # A utility function to print a# given array of given sizedef printArray(arr, size): for i in range(size): print(arr[i], end = \" \") print() # Driver Codeif __name__ == '__main__': # array representing Min Heap arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9] n = len(arr) print(\"Min Heap array : \") printArray(arr, n) convertMaxHeap(arr, n) print(\"Max Heap array : \") printArray(arr, n) # This code is contributed by PranchalK", "e": 28881, "s": 27763, "text": null }, { "code": "// C# program to convert// min Heap to max Heapusing System; class GFG{ // To heapify a subtree with // root at given index static void MaxHeapify(int []arr, int i, int n) { int l = 2 * i + 1; int r = 2 * i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); } } // This function basically // builds max heap static void convertMaxHeap(int []arr, int n) { // Start from bottommost and // rightmost internal mode and // heapify all internal modes // in bottom up way for (int i = (n - 2) / 2; i >= 0; --i) MaxHeapify(arr, i, n); } // A utility function to print // a given array of given size static void printArray(int []arr, int size) { for (int i = 0; i < size; ++i) Console.Write(arr[i]+\" \"); } // Driver Code public static void Main () { // array representing Min Heap int []arr = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = arr.Length; Console.Write(\"Min Heap array : \"); printArray(arr, n); convertMaxHeap(arr, n); Console.Write(\"\\nMax Heap array : \"); printArray(arr, n); }} // This code is contributed by nitin mittal.", "e": 30536, "s": 28881, "text": null }, { "code": "<?php// A PHP program to convert min Heap to max Heap // utility swap functionfunction swap(&$a,&$b){ $tmp=$a; $a=$b; $b=$tmp;} // to heapify a subtree with root at given indexfunction MaxHeapify(&$arr, $i, $n){ $l = 2*$i + 1; $r = 2*$i + 2; $largest = $i; if ($l < $n && $arr[$l] > $arr[$i]) $largest = $l; if ($r < $n && $arr[$r] > $arr[$largest]) $largest = $r; if ($largest != $i) { swap($arr[$i], $arr[$largest]); MaxHeapify($arr, $largest, $n); }} // This function basically builds max heapfunction convertMaxHeap(&$arr, $n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for ($i = (int)(($n-2)/2); $i >= 0; --$i) MaxHeapify($arr, $i, $n);} // A utility function to print a given array// of given sizefunction printArray($arr, $size){ for ($i = 0; $i <$size; ++$i) print($arr[$i].\" \");} // Driver code // array representing Min Heap $arr = array(3, 5, 9, 6, 8, 20, 10, 12, 18, 9); $n = count($arr); print(\"Min Heap array : \"); printArray($arr, $n); convertMaxHeap($arr, $n); print(\"\\nMax Heap array : \"); printArray($arr, $n); // This code is contributed by mits?>", "e": 31791, "s": 30536, "text": null }, { "code": "<script>// javascript program to convert min Heap to max Heap // To heapify a subtree with root at given indexfunction MaxHeapify(arr , i , n){ var l = 2*i + 1; var r = 2*i + 2; var largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { // swap arr[i] and arr[largest] var temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, largest, n); }} // This function basically builds max heapfunction convertMaxHeap(arr , n){ // Start from bottommost and rightmost // internal mode and heapify all internal // modes in bottom up way for (i = (n-2)/2; i >= 0; --i) MaxHeapify(arr, i, n);} // A utility function to print a given array// of given sizefunction printArray(arr , size){ for (i = 0; i < size; ++i) document.write(arr[i]+\" \");} // driver program// array representing Min Heapvar arr = [3, 5, 9, 6, 8, 20, 10, 12, 18, 9];var n = arr.length; document.write(\"Min Heap array : \");printArray(arr, n); convertMaxHeap(arr, n); document.write(\"<br>Max Heap array : \");printArray(arr, n); // This code is contributed by 29AjayKumar</script>", "e": 33020, "s": 31791, "text": null }, { "code": null, "e": 33031, "s": 33020, "text": "Output : " }, { "code": null, "e": 33115, "s": 33031, "text": "Min Heap array : 3 5 9 6 8 20 10 12 18 9 \nMax Heap array : 20 18 10 12 9 9 3 5 6 8 " }, { "code": null, "e": 33618, "s": 33115, "text": "The complexity of above solution might looks like O(nLogn) but it is O(n). Refer to this G-Fact for more details.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 33631, "s": 33618, "text": "nitin mittal" }, { "code": null, "e": 33647, "s": 33631, "text": "PranchalKatiyar" }, { "code": null, "e": 33660, "s": 33647, "text": "Mithun Kumar" }, { "code": null, "e": 33672, "s": 33660, "text": "29AjayKumar" }, { "code": null, "e": 33681, "s": 33672, "text": "gabaa406" }, { "code": null, "e": 33695, "s": 33681, "text": "tanmay_thaker" }, { "code": null, "e": 33711, "s": 33695, "text": "simranarora5sos" }, { "code": null, "e": 33716, "s": 33711, "text": "Heap" }, { "code": null, "e": 33721, "s": 33716, "text": "Heap" }, { "code": null, "e": 33819, "s": 33721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33828, "s": 33819, "text": "Comments" }, { "code": null, "e": 33841, "s": 33828, "text": "Old Comments" }, { "code": null, "e": 33882, "s": 33841, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 33920, "s": 33882, "text": "Fibonacci Heap | Set 1 (Introduction)" }, { "code": null, "e": 33976, "s": 33920, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 34026, "s": 33976, "text": "Priority queue of pairs in C++ (Ordered by first)" }, { "code": null, "e": 34037, "s": 34026, "text": "K-ary Heap" }, { "code": null, "e": 34066, "s": 34037, "text": "Python Program for Heap Sort" }, { "code": null, "e": 34097, "s": 34066, "text": "Applications of Priority Queue" }, { "code": null, "e": 34123, "s": 34097, "text": "C++ Program for Heap Sort" }, { "code": null, "e": 34184, "s": 34123, "text": "Complexity analysis of various operations of Binary Min Heap" } ]