title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
SAP ABAP - Report Programming
A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation. A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters. These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action. Following is a table describing the events and descriptions − INITIALIZATON Triggered before displaying the selection screen. AT SELECTION-SCREEN Triggered after processing of the user input on the selection screen. This event verifies the user input prior to the execution of a program. After processing the user input, the selection screen remains in the active mode. START-OF-SELECTION Triggered only after the processing of the selection screen is over; that is, when the user clicks the Execute icon on the selection screen. END-OF-SELECTION Triggered after the last statement in the START-OF-SELECTON event is executed. TOP-OF-PAGE Triggered by the first WRITE statement to display the data on a new page. END-OF-PAGE Triggered to display the text at the end of a page in a report. Note, that this event is the last event while creating a report, and should be combined with the LINE-COUNT clause of the REPORT statement. Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor. REPORT ZREPORT2 LINE-SIZE 75 LINE-COUNT 30(3) NO STANDARD PAGE HEADING. Tables: MARA. TYPES: Begin of itab, MATNR TYPE MARA-MATNR, MBRSH TYPE MARA-MBRSH, MEINS TYPE MARA-MEINS, MTART TYPE MARA-MTART, End of itab. DATA: wa_ma TYPE itab, it_ma TYPE STANDARD TABLE OF itab. SELECT-OPTIONS: MATS FOR MARA-MATNR OBLIGATORY. INITIALIZATION. MATS-LOW = '1'. MATS-HIGH = '500'. APPEND MATS. AT SELECTION-SCREEN. . IF MATS-LOW = ' '. MESSAGE I000(ZKMESSAGE). ELSEIF MATS-HIGH = ' '. MESSAGE I001(ZKMESSAGE). ENDIF. TOP-OF-PAGE. WRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA FROM THE TABLE MARA' COLOR 7. ULINE. WRITE:/ 'MATERIAL' COLOR 1, 24 'INDUSTRY' COLOR 2, 38 'UNITS' COLOR 3, 53 'MATERIAL TYPE' COLOR 4. ULINE. END-OF-PAGE. START-OF-SELECTION. SELECT MATNR MBRSH MEINS MTART FROM MARA INTO TABLE it_ma WHERE MATNR IN MATS. LOOP AT it_ma into wa_ma. WRITE:/ wa_ma-MATNR, 25 wa_ma-MBRSH, 40 wa_ma-MEINS, 55 wa_ma-MTART. ENDLOOP. END-OF-SELECTION. ULINE. WRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7. ULINE. SKIP. The above code produces the following output containing the general material data from the standard table MARA −
[ { "code": null, "e": 3242, "s": 3032, "text": "A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation." }, { "code": null, "e": 3529, "s": 3242, "text": "A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters." }, { "code": null, "e": 3876, "s": 3529, "text": "These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action." }, { "code": null, "e": 3938, "s": 3876, "text": "Following is a table describing the events and descriptions −" }, { "code": null, "e": 3952, "s": 3938, "text": "INITIALIZATON" }, { "code": null, "e": 4002, "s": 3952, "text": "Triggered before displaying the selection screen." }, { "code": null, "e": 4022, "s": 4002, "text": "AT SELECTION-SCREEN" }, { "code": null, "e": 4246, "s": 4022, "text": "Triggered after processing of the user input on the selection screen. This event verifies the user input prior to the execution of a program. After processing the user input, the selection screen remains in the active mode." }, { "code": null, "e": 4265, "s": 4246, "text": "START-OF-SELECTION" }, { "code": null, "e": 4406, "s": 4265, "text": "Triggered only after the processing of the selection screen is over; that is, when the user clicks the Execute icon on the selection screen." }, { "code": null, "e": 4423, "s": 4406, "text": "END-OF-SELECTION" }, { "code": null, "e": 4502, "s": 4423, "text": "Triggered after the last statement in the START-OF-SELECTON event is executed." }, { "code": null, "e": 4514, "s": 4502, "text": "TOP-OF-PAGE" }, { "code": null, "e": 4588, "s": 4514, "text": "Triggered by the first WRITE statement to display the data on a new page." }, { "code": null, "e": 4600, "s": 4588, "text": "END-OF-PAGE" }, { "code": null, "e": 4804, "s": 4600, "text": "Triggered to display the text at the end of a page in a report. Note, that this event is the last event while creating a report, and should be combined with the LINE-COUNT clause of the REPORT statement." }, { "code": null, "e": 4989, "s": 4804, "text": "Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor." }, { "code": null, "e": 6082, "s": 4989, "text": "REPORT ZREPORT2 \nLINE-SIZE 75 \nLINE-COUNT 30(3) \nNO STANDARD PAGE HEADING. \nTables: MARA. \nTYPES: Begin of itab, \n\nMATNR TYPE MARA-MATNR, \nMBRSH TYPE MARA-MBRSH, \nMEINS TYPE MARA-MEINS, \nMTART TYPE MARA-MTART, \n\nEnd of itab. \n\nDATA: wa_ma TYPE itab,\n it_ma TYPE STANDARD TABLE OF itab.\n\t\t\nSELECT-OPTIONS: MATS FOR MARA-MATNR OBLIGATORY. \nINITIALIZATION. \nMATS-LOW = '1'. \nMATS-HIGH = '500'. \n\nAPPEND MATS. \nAT SELECTION-SCREEN. .\nIF MATS-LOW = ' '. \nMESSAGE I000(ZKMESSAGE). \nELSEIF MATS-HIGH = ' '. \nMESSAGE I001(ZKMESSAGE). \nENDIF. \n\nTOP-OF-PAGE. \nWRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA \nFROM THE TABLE MARA' COLOR 7. \nULINE. \nWRITE:/ 'MATERIAL' COLOR 1, \n\n24 'INDUSTRY' COLOR 2, \n38 'UNITS' COLOR 3, \n53 'MATERIAL TYPE' COLOR 4. \nULINE. \nEND-OF-PAGE. \n\nSTART-OF-SELECTION. \nSELECT MATNR MBRSH MEINS MTART FROM MARA \nINTO TABLE it_ma WHERE MATNR IN MATS. \nLOOP AT it_ma into wa_ma. \nWRITE:/ wa_ma-MATNR, \n\n25 wa_ma-MBRSH, \n40 wa_ma-MEINS, \n55 wa_ma-MTART. \nENDLOOP. \nEND-OF-SELECTION. \n\nULINE. \nWRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7.\nULINE. \nSKIP. " } ]
Polybius Square Cipher
24 Jul, 2018 A Polybius Square is a table that allows someone to convert letters into numbers. To make the encryption little harder, this table can be randomized and shared with the recipient. In order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters ‘i’ and ‘j’ are usually combined into a single cell. Originally there was no such problem because the ancient greek alphabet has 24 letters. A table of bigger size could be used if a language contain large number of alphabets. Examples: Input : bus Output : 124543 Input : geeksforgeeks Output : 22151525432134422215152543 C++ Java Python C# PHP // CPP Program to implement polybius cipher#include <cmath>#include <iostream>using namespace std; // function to display polybius cipher textvoid polybiusCipher(string s) { int row, col; // convert each character to its encrypted code for (int i = 0; s[i]; i++) { // finding row of the table row = ceil((s[i] - 'a') / 5) + 1; // finding column of the table col = ((s[i] - 'a') % 5) + 1; // if character is 'k' if (s[i] == 'k') { row = row - 1; col = 5 - col + 1; } // if character is greater than 'j' else if (s[i] >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } cout << row << col; } cout << endl;} // Driver's Codeint main() { string s = "geeksforgeeks"; polybiusCipher(s); return 0;} // Java Program to implement polybius cipher class GFG{ // Function to display polybius // cipher text static void polybiusCipher(String s) { int row, col; // convert each character // to its encrypted code for (int i = 0;i < s.length(); i++) { // finding row of the table row = (int)Math.ceil((s.charAt(i) - 'a') / 5) + 1; // finding column of the table col = ((s.charAt(i) - 'a') % 5) + 1; // if character is 'k' if (s.charAt(i) == 'k') { row = row - 1; col = 5 - col + 1; } // if character is greater than 'j' else if (s.charAt(i) >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } System.out.print(row +""+ col); } System.out.println(); } // Driver code public static void main (String[] args) { String s = "geeksforgeeks"; polybiusCipher(s); }} // This code is contributed by Anant Agarwal. # Python Program to implement polybius cipher # function to display polybius cipher textdef polybiusCipher(s): # convert each character to its encrypted code for char in s: # finding row of the table row = int((ord(char) - ord('a')) / 5) + 1 # finding column of the table col = ((ord(char) - ord('a')) % 5) + 1 # if character is 'k' if char == 'k': row = row - 1 col = 5 - col + 1 # if character is greater than 'j' elif ord(char) >= ord('j'): if col == 1 : col = 6 row = row - 1 col = col - 1 print(row, col, end ='', sep ='') # Driver's Codeif __name__ == "__main__": s = "geeksforgeeks" # print the cipher of "geeksforgeeks" polybiusCipher(s) // C# Program to implement// polybius cipherusing System; class GFG{ // Function to display // polybius cipher text static void polybiusCipher(string s) { int row, col; // convert each character // to its encrypted code for (int i = 0; i < s.Length; i++) { // finding row of the table row = (int)Math.Floor((s[i] - 'a') / 5.0) + 1; // finding column // of the table col = ((s[i] - 'a') % 5) + 1; // if character is 'k' if (s[i] == 'k') { row = row - 1; col = 5 - col + 1; } // if character is // greater than 'j' else if (s[i] >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } Console.Write(row + "" + col); } Console.WriteLine(); } // Driver code static void Main () { string s = "geeksforgeeks"; polybiusCipher(s); }} // This code is contributed by // Manish Shaw(manishshaw1) <?php// PHP Program to implement // polybius cipher // function to display // polybius cipher textfunction polybiusCipher($s){$row = 0;$col = 0; // convert each character // to its encrypted codefor ($i = 0; $i < strlen($s); $i++) { // finding row // of the table $row = floor((ord($s[$i]) - ord('a')) / 5) + 1; // finding column // of the table $col = ((ord($s[$i]) - ord('a')) % 5) + 1; // if character is 'k' if ($s[$i] == 'k') { $row = $row - 1; $col = 5 - $col + 1; } // if character is // greater than 'j' else if ($s[$i] >= 'j') { if ($col == 1) { $col = 6; $row = $row - 1; } $col = $col - 1; } echo ($row.$col);} echo ("\n");} // Driver Code$s = "geeksforgeeks";polybiusCipher($s); // This code is contributed by // Manish Shaw(manishshaw1)?> Output: 22151525432134422215152543 manishshaw1 encoding-decoding Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Data Structure: Types, Classifications and Applications Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Palindrome Partitioning | DP-17 Find the smallest window in a string containing all characters of another string Convert character array to string in C++ Remove first and last character of a string in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jul, 2018" }, { "code": null, "e": 472, "s": 52, "text": "A Polybius Square is a table that allows someone to convert letters into numbers. To make the encryption little harder, this table can be randomized and shared with the recipient. In order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters ‘i’ and ‘j’ are usually combined into a single cell. Originally there was no such problem because the ancient greek alphabet has 24 letters." }, { "code": null, "e": 558, "s": 472, "text": "A table of bigger size could be used if a language contain large number of alphabets." }, { "code": null, "e": 568, "s": 558, "text": "Examples:" }, { "code": null, "e": 660, "s": 568, "text": "Input : bus\nOutput : 124543\n\nInput : geeksforgeeks \nOutput : 22151525432134422215152543 \n" }, { "code": null, "e": 664, "s": 660, "text": "C++" }, { "code": null, "e": 669, "s": 664, "text": "Java" }, { "code": null, "e": 676, "s": 669, "text": "Python" }, { "code": null, "e": 679, "s": 676, "text": "C#" }, { "code": null, "e": 683, "s": 679, "text": "PHP" }, { "code": "// CPP Program to implement polybius cipher#include <cmath>#include <iostream>using namespace std; // function to display polybius cipher textvoid polybiusCipher(string s) { int row, col; // convert each character to its encrypted code for (int i = 0; s[i]; i++) { // finding row of the table row = ceil((s[i] - 'a') / 5) + 1; // finding column of the table col = ((s[i] - 'a') % 5) + 1; // if character is 'k' if (s[i] == 'k') { row = row - 1; col = 5 - col + 1; } // if character is greater than 'j' else if (s[i] >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } cout << row << col; } cout << endl;} // Driver's Codeint main() { string s = \"geeksforgeeks\"; polybiusCipher(s); return 0;}", "e": 1486, "s": 683, "text": null }, { "code": "// Java Program to implement polybius cipher class GFG{ // Function to display polybius // cipher text static void polybiusCipher(String s) { int row, col; // convert each character // to its encrypted code for (int i = 0;i < s.length(); i++) { // finding row of the table row = (int)Math.ceil((s.charAt(i) - 'a') / 5) + 1; // finding column of the table col = ((s.charAt(i) - 'a') % 5) + 1; // if character is 'k' if (s.charAt(i) == 'k') { row = row - 1; col = 5 - col + 1; } // if character is greater than 'j' else if (s.charAt(i) >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } System.out.print(row +\"\"+ col); } System.out.println(); } // Driver code public static void main (String[] args) { String s = \"geeksforgeeks\"; polybiusCipher(s); }} // This code is contributed by Anant Agarwal.", "e": 2734, "s": 1486, "text": null }, { "code": "# Python Program to implement polybius cipher # function to display polybius cipher textdef polybiusCipher(s): # convert each character to its encrypted code for char in s: # finding row of the table row = int((ord(char) - ord('a')) / 5) + 1 # finding column of the table col = ((ord(char) - ord('a')) % 5) + 1 # if character is 'k' if char == 'k': row = row - 1 col = 5 - col + 1 # if character is greater than 'j' elif ord(char) >= ord('j'): if col == 1 : col = 6 row = row - 1 col = col - 1 print(row, col, end ='', sep ='') # Driver's Codeif __name__ == \"__main__\": s = \"geeksforgeeks\" # print the cipher of \"geeksforgeeks\" polybiusCipher(s)", "e": 3813, "s": 2734, "text": null }, { "code": "// C# Program to implement// polybius cipherusing System; class GFG{ // Function to display // polybius cipher text static void polybiusCipher(string s) { int row, col; // convert each character // to its encrypted code for (int i = 0; i < s.Length; i++) { // finding row of the table row = (int)Math.Floor((s[i] - 'a') / 5.0) + 1; // finding column // of the table col = ((s[i] - 'a') % 5) + 1; // if character is 'k' if (s[i] == 'k') { row = row - 1; col = 5 - col + 1; } // if character is // greater than 'j' else if (s[i] >= 'j') { if (col == 1) { col = 6; row = row - 1; } col = col - 1; } Console.Write(row + \"\" + col); } Console.WriteLine(); } // Driver code static void Main () { string s = \"geeksforgeeks\"; polybiusCipher(s); }} // This code is contributed by // Manish Shaw(manishshaw1)", "e": 5121, "s": 3813, "text": null }, { "code": "<?php// PHP Program to implement // polybius cipher // function to display // polybius cipher textfunction polybiusCipher($s){$row = 0;$col = 0; // convert each character // to its encrypted codefor ($i = 0; $i < strlen($s); $i++) { // finding row // of the table $row = floor((ord($s[$i]) - ord('a')) / 5) + 1; // finding column // of the table $col = ((ord($s[$i]) - ord('a')) % 5) + 1; // if character is 'k' if ($s[$i] == 'k') { $row = $row - 1; $col = 5 - $col + 1; } // if character is // greater than 'j' else if ($s[$i] >= 'j') { if ($col == 1) { $col = 6; $row = $row - 1; } $col = $col - 1; } echo ($row.$col);} echo (\"\\n\");} // Driver Code$s = \"geeksforgeeks\";polybiusCipher($s); // This code is contributed by // Manish Shaw(manishshaw1)?>", "e": 6035, "s": 5121, "text": null }, { "code": null, "e": 6043, "s": 6035, "text": "Output:" }, { "code": null, "e": 6071, "s": 6043, "text": "22151525432134422215152543\n" }, { "code": null, "e": 6083, "s": 6071, "text": "manishshaw1" }, { "code": null, "e": 6101, "s": 6083, "text": "encoding-decoding" }, { "code": null, "e": 6109, "s": 6101, "text": "Strings" }, { "code": null, "e": 6117, "s": 6109, "text": "Strings" }, { "code": null, "e": 6215, "s": 6117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6279, "s": 6215, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6324, "s": 6279, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 6369, "s": 6324, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 6404, "s": 6369, "text": "Print all subsequences of a string" }, { "code": null, "e": 6469, "s": 6404, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 6498, "s": 6469, "text": "String class in Java | Set 1" }, { "code": null, "e": 6530, "s": 6498, "text": "Palindrome Partitioning | DP-17" }, { "code": null, "e": 6611, "s": 6530, "text": "Find the smallest window in a string containing all characters of another string" }, { "code": null, "e": 6652, "s": 6611, "text": "Convert character array to string in C++" } ]
MongoDB - PHP
To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default) and add the following line to your php.ini file − extension = php_mongo.dll To make a connection, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically. Following is the code snippet to connect to the database − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Following is the code snippet to create a collection − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->createCollection("mycol"); echo "Collection created succsessfully"; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection created succsessfully To insert a document into MongoDB, insert() method is used. Following is the code snippet to insert a document − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->mycol; echo "Collection selected succsessfully"; $document = array( "title" => "MongoDB", "description" => "database", "likes" => 100, "url" => "http://www.tutorialspoint.com/mongodb/", "by" => "tutorials point" ); $collection->insert($document); echo "Document inserted successfully"; ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully Document inserted successfully To select all documents from the collection, find() method is used. Following is the code snippet to select all documents − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->mycol; echo "Collection selected succsessfully"; $cursor = $collection->find(); // iterate cursor to display title of documents foreach ($cursor as $document) { echo $document["title"] . "\n"; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully { "title": "MongoDB" } To update a document, you need to use the update() method. In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->mycol; echo "Collection selected succsessfully"; // now update the document $collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB Tutorial"))); echo "Document updated successfully"; // now display the updated document $cursor = $collection->find(); // iterate cursor to display title of documents echo "Updated document"; foreach ($cursor as $document) { echo $document["title"] . "\n"; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected succsessfully Document updated successfully Updated document { "title": "MongoDB Tutorial" } To delete a document, you need to use remove() method. In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document − <?php // connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; echo "Database mydb selected"; $collection = $db->mycol; echo "Collection selected succsessfully"; // now remove the document $collection->remove(array("title"=>"MongoDB Tutorial"),false); echo "Documents deleted successfully"; // now display the available documents $cursor = $collection->find(); // iterate cursor to display title of documents echo "Updated document"; foreach ($cursor as $document) { echo $document["title"] . "\n"; } ?> When the program is executed, it will produce the following result − Connection to database successfully Database mydb selected Collection selected successfully Documents deleted successfully In the above example, the second parameter is boolean type and used for justOne field of remove() method. Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above.
[ { "code": null, "e": 2995, "s": 2687, "text": "To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo.dll in your PHP extension directory (\"ext\" by default) and add the following line to your php.ini file −" }, { "code": null, "e": 3022, "s": 2995, "text": "extension = php_mongo.dll\n" }, { "code": null, "e": 3152, "s": 3022, "text": "To make a connection, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically." }, { "code": null, "e": 3211, "s": 3152, "text": "Following is the code snippet to connect to the database −" }, { "code": null, "e": 3400, "s": 3211, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n\t\n echo \"Connection to database successfully\";\n // select a database\n $db = $m->mydb;\n\t\n echo \"Database mydb selected\";\n?>" }, { "code": null, "e": 3469, "s": 3400, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 3529, "s": 3469, "text": "Connection to database successfully\nDatabase mydb selected\n" }, { "code": null, "e": 3584, "s": 3529, "text": "Following is the code snippet to create a collection −" }, { "code": null, "e": 3864, "s": 3584, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n echo \"Connection to database successfully\";\n\t\n // select a database\n $db = $m->mydb;\n echo \"Database mydb selected\";\n $collection = $db->createCollection(\"mycol\");\n echo \"Collection created succsessfully\";\n?>" }, { "code": null, "e": 3933, "s": 3864, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 4026, "s": 3933, "text": "Connection to database successfully\nDatabase mydb selected\nCollection created succsessfully\n" }, { "code": null, "e": 4086, "s": 4026, "text": "To insert a document into MongoDB, insert() method is used." }, { "code": null, "e": 4139, "s": 4086, "text": "Following is the code snippet to insert a document −" }, { "code": null, "e": 4686, "s": 4139, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n echo \"Connection to database successfully\";\n\t\n // select a database\n $db = $m->mydb;\n echo \"Database mydb selected\";\n $collection = $db->mycol;\n echo \"Collection selected succsessfully\";\n\t\n $document = array( \n \"title\" => \"MongoDB\", \n \"description\" => \"database\", \n \"likes\" => 100,\n \"url\" => \"http://www.tutorialspoint.com/mongodb/\",\n \"by\" => \"tutorials point\"\n );\n\t\n $collection->insert($document);\n echo \"Document inserted successfully\";\n?>" }, { "code": null, "e": 4755, "s": 4686, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 4880, "s": 4755, "text": "Connection to database successfully\nDatabase mydb selected\nCollection selected succsessfully\nDocument inserted successfully\n" }, { "code": null, "e": 4948, "s": 4880, "text": "To select all documents from the collection, find() method is used." }, { "code": null, "e": 5004, "s": 4948, "text": "Following is the code snippet to select all documents −" }, { "code": null, "e": 5431, "s": 5004, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n echo \"Connection to database successfully\";\n\t\n // select a database\n $db = $m->mydb;\n echo \"Database mydb selected\";\n $collection = $db->mycol;\n echo \"Collection selected succsessfully\";\n $cursor = $collection->find();\n // iterate cursor to display title of documents\n\t\n foreach ($cursor as $document) {\n echo $document[\"title\"] . \"\\n\";\n }\n?>" }, { "code": null, "e": 5500, "s": 5431, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 5620, "s": 5500, "text": "Connection to database successfully\nDatabase mydb selected\nCollection selected succsessfully {\n \"title\": \"MongoDB\"\n}\n" }, { "code": null, "e": 5679, "s": 5620, "text": "To update a document, you need to use the update() method." }, { "code": null, "e": 5825, "s": 5679, "text": "In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document −" }, { "code": null, "e": 6503, "s": 5825, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n echo \"Connection to database successfully\";\n\t\n // select a database\n $db = $m->mydb;\n echo \"Database mydb selected\";\n $collection = $db->mycol;\n echo \"Collection selected succsessfully\";\n // now update the document\n $collection->update(array(\"title\"=>\"MongoDB\"), \n array('$set'=>array(\"title\"=>\"MongoDB Tutorial\")));\n echo \"Document updated successfully\";\n\t\n // now display the updated document\n $cursor = $collection->find();\n\t\n // iterate cursor to display title of documents\n echo \"Updated document\";\n\t\n foreach ($cursor as $document) {\n echo $document[\"title\"] . \"\\n\";\n }\n?>" }, { "code": null, "e": 6572, "s": 6503, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 6748, "s": 6572, "text": "Connection to database successfully\nDatabase mydb selected\nCollection selected succsessfully\nDocument updated successfully\nUpdated document {\n \"title\": \"MongoDB Tutorial\"\n}\n" }, { "code": null, "e": 6803, "s": 6748, "text": "To delete a document, you need to use remove() method." }, { "code": null, "e": 6948, "s": 6803, "text": "In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document −" }, { "code": null, "e": 7593, "s": 6948, "text": "<?php\n // connect to mongodb\n $m = new MongoClient();\n echo \"Connection to database successfully\";\n\t\n // select a database\n $db = $m->mydb;\n echo \"Database mydb selected\";\n $collection = $db->mycol;\n echo \"Collection selected succsessfully\";\n \n // now remove the document\n $collection->remove(array(\"title\"=>\"MongoDB Tutorial\"),false);\n echo \"Documents deleted successfully\";\n \n // now display the available documents\n $cursor = $collection->find();\n\t\n // iterate cursor to display title of documents\n echo \"Updated document\";\n\t\n foreach ($cursor as $document) {\n echo $document[\"title\"] . \"\\n\";\n }\n?>" }, { "code": null, "e": 7662, "s": 7593, "text": "When the program is executed, it will produce the following result −" }, { "code": null, "e": 7786, "s": 7662, "text": "Connection to database successfully\nDatabase mydb selected\nCollection selected successfully\nDocuments deleted successfully\n" }, { "code": null, "e": 7892, "s": 7786, "text": "In the above example, the second parameter is boolean type and used for justOne field of remove() method." } ]
How to add a header to a CSV file in Python?
11 Dec, 2020 A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file. In this article, we are going to add a header to a CSV file in Python. Method #1: Using header argument in to_csv() method. Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method. The following CSV file gfg.csv is used for the operation: Python3 # importing python packageimport pandas as pd # read contents of csv filefile = pd.read_csv("gfg.csv")print("\nOriginal file:")print(file) # adding headerheaderList = ['id', 'name', 'profession'] # converting data frame to csvfile.to_csv("gfg2.csv", header=headerList, index=False) # display modified csv filefile2 = pd.read_csv("gfg2.csv")print('\nModified file:')print(file2) Output: The CSV file gfg2.csv is created: Method #2: Using DictWriter() method Another approach of using DictWriter() can be used to append a header to the contents of a CSV file. The fieldnames attribute can be used to specify the header of the CSV file and the delimiter argument separates the values by the delimiter given in csv module is needed to carry out the addition of header. The writeheader() method is then invoked on csvwriter object, without passing any arguments. Python3 # import required modulesimport pandas as pdimport csv # assign header columnsheaderList = ['col1', 'col2', 'col3', 'col4'] # open CSV file and assign headerwith open("gfg3.csv", 'w') as file: dw = csv.DictWriter(file, delimiter=',', fieldnames=headerList) dw.writeheader() # display csv filefileContent = pd.read_csv("gfg3.csv")fileContent Output: The new CSV file gfg3.csv created is: Note: This method is only applicable to empty CSV files. python-csv Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 620, "s": 28, "text": "A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file. " }, { "code": null, "e": 691, "s": 620, "text": "In this article, we are going to add a header to a CSV file in Python." }, { "code": null, "e": 744, "s": 691, "text": "Method #1: Using header argument in to_csv() method." }, { "code": null, "e": 858, "s": 744, "text": "Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method." }, { "code": null, "e": 916, "s": 858, "text": "The following CSV file gfg.csv is used for the operation:" }, { "code": null, "e": 924, "s": 916, "text": "Python3" }, { "code": "# importing python packageimport pandas as pd # read contents of csv filefile = pd.read_csv(\"gfg.csv\")print(\"\\nOriginal file:\")print(file) # adding headerheaderList = ['id', 'name', 'profession'] # converting data frame to csvfile.to_csv(\"gfg2.csv\", header=headerList, index=False) # display modified csv filefile2 = pd.read_csv(\"gfg2.csv\")print('\\nModified file:')print(file2)", "e": 1306, "s": 924, "text": null }, { "code": null, "e": 1315, "s": 1306, "text": "Output: " }, { "code": null, "e": 1349, "s": 1315, "text": "The CSV file gfg2.csv is created:" }, { "code": null, "e": 1386, "s": 1349, "text": "Method #2: Using DictWriter() method" }, { "code": null, "e": 1787, "s": 1386, "text": "Another approach of using DictWriter() can be used to append a header to the contents of a CSV file. The fieldnames attribute can be used to specify the header of the CSV file and the delimiter argument separates the values by the delimiter given in csv module is needed to carry out the addition of header. The writeheader() method is then invoked on csvwriter object, without passing any arguments." }, { "code": null, "e": 1795, "s": 1787, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport csv # assign header columnsheaderList = ['col1', 'col2', 'col3', 'col4'] # open CSV file and assign headerwith open(\"gfg3.csv\", 'w') as file: dw = csv.DictWriter(file, delimiter=',', fieldnames=headerList) dw.writeheader() # display csv filefileContent = pd.read_csv(\"gfg3.csv\")fileContent", "e": 2169, "s": 1795, "text": null }, { "code": null, "e": 2177, "s": 2169, "text": "Output:" }, { "code": null, "e": 2215, "s": 2177, "text": "The new CSV file gfg3.csv created is:" }, { "code": null, "e": 2272, "s": 2215, "text": "Note: This method is only applicable to empty CSV files." }, { "code": null, "e": 2283, "s": 2272, "text": "python-csv" }, { "code": null, "e": 2297, "s": 2283, "text": "Python-pandas" }, { "code": null, "e": 2304, "s": 2297, "text": "Python" }, { "code": null, "e": 2402, "s": 2304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2434, "s": 2402, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2461, "s": 2434, "text": "Python Classes and Objects" }, { "code": null, "e": 2482, "s": 2461, "text": "Python OOPs Concepts" }, { "code": null, "e": 2505, "s": 2482, "text": "Introduction To PYTHON" }, { "code": null, "e": 2536, "s": 2505, "text": "Python | os.path.join() method" }, { "code": null, "e": 2592, "s": 2536, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2634, "s": 2592, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2676, "s": 2634, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2715, "s": 2676, "text": "Python | Get unique values from a list" } ]
fmt.Printf() Function in Golang With Examples
05 Mar, 2021 In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Printf() function in Go language formats according to a format specifier and writes to standard output. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. Syntax: func Printf(format string, a ...interface{}) (n int, err error) Parameters: This function accepts two parameters which are illustrated below: format string: This contains some strings along with some verbs. a ...interface{}: This contains specified constant variables. Return Value: It returns the number of bytes written and any write error encountered. Conversion Characters: Example 1: Go // Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling Printf() function fmt.Printf("%s is a %s Portal.\n", name, dept) // It is conventional not to worry about any // error returned by Printf. } Output: GeeksforGeeks is a CS portal. Example 2: Go // Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 10, 15 // Calling Printf() function fmt.Printf("%d + %d = %d\n", num1, num2, num3) // It is conventional not to worry about any // error returned by Printf. } Output: 5 + 10 = 15 Example 3: Go // Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main(){ var str = "Geeksforgeeks" fmt.Printf("The string is %s \n", str) var num1 int = 21 fmt.Printf("The decimal value is %d \n", num1) var num2 float32 = 7.786 fmt.Printf("The floating point is %g \n", num2) var num3 int = 14 fmt.Printf("The binary value of num3 is %b \n", num3) var num4 = 4 + 1i fmt.Printf("Scientific Notation of num4 : %e \n", num4)} Output: The string is Geeksforgeeks The decimal value is 21 The floating point is 7.786 The binary value of num3 is 1110 Scientific Notation of num4 : (4.000000e+00+1.000000e+00i) yuvraj_chandra Golang-fmt Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2021" }, { "code": null, "e": 390, "s": 28, "text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Printf() function in Go language formats according to a format specifier and writes to standard output. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions." }, { "code": null, "e": 399, "s": 390, "text": "Syntax: " }, { "code": null, "e": 463, "s": 399, "text": "func Printf(format string, a ...interface{}) (n int, err error)" }, { "code": null, "e": 542, "s": 463, "text": "Parameters: This function accepts two parameters which are illustrated below: " }, { "code": null, "e": 607, "s": 542, "text": "format string: This contains some strings along with some verbs." }, { "code": null, "e": 669, "s": 607, "text": "a ...interface{}: This contains specified constant variables." }, { "code": null, "e": 755, "s": 669, "text": "Return Value: It returns the number of bytes written and any write error encountered." }, { "code": null, "e": 778, "s": 755, "text": "Conversion Characters:" }, { "code": null, "e": 789, "s": 778, "text": "Example 1:" }, { "code": null, "e": 792, "s": 789, "text": "Go" }, { "code": "// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const name, dept = \"GeeksforGeeks\", \"CS\" // Calling Printf() function fmt.Printf(\"%s is a %s Portal.\\n\", name, dept) // It is conventional not to worry about any // error returned by Printf. }", "e": 1215, "s": 792, "text": null }, { "code": null, "e": 1224, "s": 1215, "text": "Output: " }, { "code": null, "e": 1254, "s": 1224, "text": "GeeksforGeeks is a CS portal." }, { "code": null, "e": 1265, "s": 1254, "text": "Example 2:" }, { "code": null, "e": 1268, "s": 1265, "text": "Go" }, { "code": "// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 10, 15 // Calling Printf() function fmt.Printf(\"%d + %d = %d\\n\", num1, num2, num3) // It is conventional not to worry about any // error returned by Printf. }", "e": 1685, "s": 1268, "text": null }, { "code": null, "e": 1694, "s": 1685, "text": "Output: " }, { "code": null, "e": 1706, "s": 1694, "text": "5 + 10 = 15" }, { "code": null, "e": 1717, "s": 1706, "text": "Example 3:" }, { "code": null, "e": 1720, "s": 1717, "text": "Go" }, { "code": "// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main(){ var str = \"Geeksforgeeks\" fmt.Printf(\"The string is %s \\n\", str) var num1 int = 21 fmt.Printf(\"The decimal value is %d \\n\", num1) var num2 float32 = 7.786 fmt.Printf(\"The floating point is %g \\n\", num2) var num3 int = 14 fmt.Printf(\"The binary value of num3 is %b \\n\", num3) var num4 = 4 + 1i fmt.Printf(\"Scientific Notation of num4 : %e \\n\", num4)}", "e": 2283, "s": 1720, "text": null }, { "code": null, "e": 2291, "s": 2283, "text": "Output:" }, { "code": null, "e": 2471, "s": 2291, "text": "The string is Geeksforgeeks \nThe decimal value is 21 \nThe floating point is 7.786 \nThe binary value of num3 is 1110 \nScientific Notation of num4 : (4.000000e+00+1.000000e+00i)" }, { "code": null, "e": 2486, "s": 2471, "text": "yuvraj_chandra" }, { "code": null, "e": 2497, "s": 2486, "text": "Golang-fmt" }, { "code": null, "e": 2509, "s": 2497, "text": "Go Language" } ]
Difference Between set, multiset, unordered_set, unordered_multiset in C++
28 Apr, 2022 In C++ Standard Template Library, set, multiset, unordered_set, unordered_multiset are used to store elements. Although they are similar but differ from each other in some functionalities. The differences are discussed below: 1. Set: They are associative containers that store unique elements following a specific order. Following are the properties of sets: Stores the values in sorted order. Stores only unique values. Elements can only be inserted or deleted but cannot be modified. We can erase more than 1 element by giving the start iterator and end iterator position. Traversal using iterators. Sets are implemented as Binary Search Tree. Syntax: set<datatype> setname; The following example demonstrates the application of set. CPP // CPP program to demonstrate insert and// delete in set#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // set declare set<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements set<int>::iterator it, it1, it2; cout << "Set elements after sort and " "removing duplicates:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\n'; it1 = s.find(10); it2 = s.find(90); // elements from 10 to elements before // 90 erased s.erase(it1, it2); cout << "Set Elements after erase:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;} Set elements after sort and removing duplicates: 2 10 12 45 85 90 Set Elements after erase: 2 90 2. Multiset: They are associative containers that store multiple elements having equivalent values following a specific order. Following are the properties of multisets: Stores elements in sorted order. It allows the storage of multiple elements. We can erase more than 1 element by giving the start iterator and end iterator. Note: All other properties are similar to the set. Syntax: multiset<datatype> multisetName; The following example demonstrates the application of Multiset. CPP // CPP program to demonstrate insert and// delete in set#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // multiset declare multiset<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements multiset<int>::iterator it, it1, it2; cout << "Multiset elements after sort\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\n'; it1 = s.find(10); it2 = s.find(90); // elements from 10 to elements before 90 // erased s.erase(it1, it2); cout << "Multiset Elements after erase:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;} Multiset elements after sort 2 10 10 12 45 85 90 Multiset Elements after erase: 2 90 3. unordered_set: They are associative containers that store unique elements in no particular order. Following are the properties of Unordered_sets: Elements can be stored in any order. ( no sorted order ) Stores only unique values. Hash-table used to store elements. We can erase only the element for which the iterator position is given. Note: All other properties are similar to the set. Syntax: unordered_set<datatype> setname; The following example demonstrates the application of Unordered set. CPP // CPP program to demonstrate insert and// delete in unordered_set#include <bits/stdc++.h>using namespace std;int main(){ // unordered_set declare unordered_set<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); s.insert(12); s.insert(70); // Iterator declared to traverse // set elements unordered_set<int>::iterator it, it1; cout << "Unordered_set elements after sort:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\n'; it1 = s.find(10); // element 10 erased s.erase(it1); cout << "Unordered_set Elements after erase:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;} Unordered_set elements after sort: 10 45 12 70 2 90 85 Unordered_set Elements after erase: 45 12 70 2 90 85 4. Unordered_multiset: It is an associative container that contains a set of non-unique elements in unsorted order. Following are the properties of Unordered_multiset: Elements can be stored in any order. Duplicate elements can be stored. Hash-table used to store elements. We can erase only the element for which the iterator position is given. Note: All other properties are similar to the set. Syntax: unordered_multiset<datatype> multisetName; The following example demonstrates the application of Unordered multiset. CPP // CPP program to demonstrate insert and// delete in unordered_multiset#include <bits/stdc++.h>using namespace std;int main(){ // unordered_multiset declare unordered_multiset<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements unordered_multiset<int>::iterator it, it1; cout << "Unordered-Multiset elements after sort:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\n'; it1 = s.find(10); // element 10 trained s.erase(it1); cout << "Unordered-Multiset Elements after " "erase:\n"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;} Unordered-Multiset elements after sort: 45 10 10 12 2 90 85 Unordered-Multiset Elements after erase: 45 10 12 2 90 85 Difference between set, multiset, unordered_set, unordered_multiset: In simple words, set is a container that stores sorted and unique elements. If unordered is added means elements are not sorted. If multiset is added means duplicate elements storage is allowed. This article is contributed by SHAURYA UPPAL. 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. go_lang anshikajain26 surinderdawra388 cpp-unordered_set STL C++ Difference Between STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 278, "s": 52, "text": "In C++ Standard Template Library, set, multiset, unordered_set, unordered_multiset are used to store elements. Although they are similar but differ from each other in some functionalities. The differences are discussed below:" }, { "code": null, "e": 411, "s": 278, "text": "1. Set: They are associative containers that store unique elements following a specific order. Following are the properties of sets:" }, { "code": null, "e": 447, "s": 411, "text": "Stores the values in sorted order. " }, { "code": null, "e": 475, "s": 447, "text": "Stores only unique values. " }, { "code": null, "e": 541, "s": 475, "text": "Elements can only be inserted or deleted but cannot be modified. " }, { "code": null, "e": 631, "s": 541, "text": "We can erase more than 1 element by giving the start iterator and end iterator position. " }, { "code": null, "e": 659, "s": 631, "text": "Traversal using iterators. " }, { "code": null, "e": 703, "s": 659, "text": "Sets are implemented as Binary Search Tree." }, { "code": null, "e": 711, "s": 703, "text": "Syntax:" }, { "code": null, "e": 734, "s": 711, "text": "set<datatype> setname;" }, { "code": null, "e": 793, "s": 734, "text": "The following example demonstrates the application of set." }, { "code": null, "e": 797, "s": 793, "text": "CPP" }, { "code": "// CPP program to demonstrate insert and// delete in set#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ // set declare set<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements set<int>::iterator it, it1, it2; cout << \"Set elements after sort and \" \"removing duplicates:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\\n'; it1 = s.find(10); it2 = s.find(90); // elements from 10 to elements before // 90 erased s.erase(it1, it2); cout << \"Set Elements after erase:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;}", "e": 1639, "s": 797, "text": null }, { "code": null, "e": 1738, "s": 1639, "text": "Set elements after sort and removing duplicates:\n2 10 12 45 85 90 \nSet Elements after erase:\n2 90 " }, { "code": null, "e": 1908, "s": 1738, "text": "2. Multiset: They are associative containers that store multiple elements having equivalent values following a specific order. Following are the properties of multisets:" }, { "code": null, "e": 1942, "s": 1908, "text": "Stores elements in sorted order. " }, { "code": null, "e": 1987, "s": 1942, "text": "It allows the storage of multiple elements. " }, { "code": null, "e": 2068, "s": 1987, "text": "We can erase more than 1 element by giving the start iterator and end iterator. " }, { "code": null, "e": 2119, "s": 2068, "text": "Note: All other properties are similar to the set." }, { "code": null, "e": 2127, "s": 2119, "text": "Syntax:" }, { "code": null, "e": 2160, "s": 2127, "text": "multiset<datatype> multisetName;" }, { "code": null, "e": 2224, "s": 2160, "text": "The following example demonstrates the application of Multiset." }, { "code": null, "e": 2228, "s": 2224, "text": "CPP" }, { "code": "// CPP program to demonstrate insert and// delete in set#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // multiset declare multiset<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements multiset<int>::iterator it, it1, it2; cout << \"Multiset elements after sort\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\\n'; it1 = s.find(10); it2 = s.find(90); // elements from 10 to elements before 90 // erased s.erase(it1, it2); cout << \"Multiset Elements after erase:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;}", "e": 3057, "s": 2228, "text": null }, { "code": null, "e": 3144, "s": 3057, "text": "Multiset elements after sort\n2 10 10 12 45 85 90 \nMultiset Elements after erase:\n2 90 " }, { "code": null, "e": 3294, "s": 3144, "text": "3. unordered_set: They are associative containers that store unique elements in no particular order. Following are the properties of Unordered_sets: " }, { "code": null, "e": 3352, "s": 3294, "text": "Elements can be stored in any order. ( no sorted order ) " }, { "code": null, "e": 3380, "s": 3352, "text": "Stores only unique values. " }, { "code": null, "e": 3416, "s": 3380, "text": "Hash-table used to store elements. " }, { "code": null, "e": 3489, "s": 3416, "text": "We can erase only the element for which the iterator position is given. " }, { "code": null, "e": 3541, "s": 3489, "text": "Note: All other properties are similar to the set. " }, { "code": null, "e": 3549, "s": 3541, "text": "Syntax:" }, { "code": null, "e": 3582, "s": 3549, "text": "unordered_set<datatype> setname;" }, { "code": null, "e": 3651, "s": 3582, "text": "The following example demonstrates the application of Unordered set." }, { "code": null, "e": 3655, "s": 3651, "text": "CPP" }, { "code": "// CPP program to demonstrate insert and// delete in unordered_set#include <bits/stdc++.h>using namespace std;int main(){ // unordered_set declare unordered_set<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); s.insert(12); s.insert(70); // Iterator declared to traverse // set elements unordered_set<int>::iterator it, it1; cout << \"Unordered_set elements after sort:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\\n'; it1 = s.find(10); // element 10 erased s.erase(it1); cout << \"Unordered_set Elements after erase:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;}", "e": 4473, "s": 3655, "text": null }, { "code": null, "e": 4583, "s": 4473, "text": "Unordered_set elements after sort:\n10 45 12 70 2 90 85 \nUnordered_set Elements after erase:\n45 12 70 2 90 85 " }, { "code": null, "e": 4752, "s": 4583, "text": "4. Unordered_multiset: It is an associative container that contains a set of non-unique elements in unsorted order. Following are the properties of Unordered_multiset: " }, { "code": null, "e": 4790, "s": 4752, "text": "Elements can be stored in any order. " }, { "code": null, "e": 4825, "s": 4790, "text": "Duplicate elements can be stored. " }, { "code": null, "e": 4861, "s": 4825, "text": "Hash-table used to store elements. " }, { "code": null, "e": 4934, "s": 4861, "text": "We can erase only the element for which the iterator position is given. " }, { "code": null, "e": 4986, "s": 4934, "text": "Note: All other properties are similar to the set. " }, { "code": null, "e": 4994, "s": 4986, "text": "Syntax:" }, { "code": null, "e": 5037, "s": 4994, "text": "unordered_multiset<datatype> multisetName;" }, { "code": null, "e": 5111, "s": 5037, "text": "The following example demonstrates the application of Unordered multiset." }, { "code": null, "e": 5115, "s": 5111, "text": "CPP" }, { "code": "// CPP program to demonstrate insert and// delete in unordered_multiset#include <bits/stdc++.h>using namespace std;int main(){ // unordered_multiset declare unordered_multiset<int> s; // Elements added to set s.insert(12); s.insert(10); s.insert(2); // duplicate added s.insert(10); s.insert(90); s.insert(85); s.insert(45); // Iterator declared to traverse // set elements unordered_multiset<int>::iterator it, it1; cout << \"Unordered-Multiset elements after sort:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; cout << '\\n'; it1 = s.find(10); // element 10 trained s.erase(it1); cout << \"Unordered-Multiset Elements after \" \"erase:\\n\"; for (it = s.begin(); it != s.end(); it++) cout << *it << ' '; return 0;}", "e": 5945, "s": 5115, "text": null }, { "code": null, "e": 6065, "s": 5945, "text": "Unordered-Multiset elements after sort:\n45 10 10 12 2 90 85 \nUnordered-Multiset Elements after erase:\n45 10 12 2 90 85 " }, { "code": null, "e": 6135, "s": 6065, "text": "Difference between set, multiset, unordered_set, unordered_multiset: " }, { "code": null, "e": 6264, "s": 6135, "text": "In simple words, set is a container that stores sorted and unique elements. If unordered is added means elements are not sorted." }, { "code": null, "e": 6330, "s": 6264, "text": "If multiset is added means duplicate elements storage is allowed." }, { "code": null, "e": 6753, "s": 6330, "text": "This article is contributed by SHAURYA UPPAL. 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": 6761, "s": 6753, "text": "go_lang" }, { "code": null, "e": 6775, "s": 6761, "text": "anshikajain26" }, { "code": null, "e": 6792, "s": 6775, "text": "surinderdawra388" }, { "code": null, "e": 6810, "s": 6792, "text": "cpp-unordered_set" }, { "code": null, "e": 6814, "s": 6810, "text": "STL" }, { "code": null, "e": 6818, "s": 6814, "text": "C++" }, { "code": null, "e": 6837, "s": 6818, "text": "Difference Between" }, { "code": null, "e": 6841, "s": 6837, "text": "STL" }, { "code": null, "e": 6845, "s": 6841, "text": "CPP" } ]
Automated software testing with Python
07 Jul, 2022 Software testing is the process in which a developer ensures that the actual output of the software matches with the desired output by providing some test inputs to the software. Software testing is an important step because if performed properly, it can help the developer to find bugs in the software in very less amount of time. Software testing can be divided into two classes, Manual testing and Automated testing. Automated testing is the execution of your tests using a script instead of a human. In this article, we’ll discuss some of the methods of automated software testing with Python. Let’s write a simple application over which we will perform all the tests. class Square: def __init__(self, side): """ creates a square having the given side """ self.side = side def area(self): """ returns area of the square """ return self.side**2 def perimeter(self): """ returns perimeter of the square """ return 4 * self.side def __repr__(self): """ declares how a Square object should be printed """ s = 'Square with side = ' + str(self.side) + '\n' + \ 'Area = ' + str(self.area()) + '\n' + \ 'Perimeter = ' + str(self.perimeter()) return s if __name__ == '__main__': # read input from the user side = int(input('enter the side length to create a Square: ')) # create a square with the provided side square = Square(side) # print the created square print(square) Note: For more information about the function __repr__(), refer this article. Now that we have our software ready, let’s have a look at the directory structure of our project folder and after that, we’ll start testing our software. ---Software_Testing |--- __init__.py (to initialize the directory as python package) |--- app.py (our software) |--- tests (folder to keep all test files) |--- __init__.py One of the major problems with manual testing is that it requires time and effort. In manual testing, we test the application over some input, if it fails, either we note it down or we debug the application for that particular test input, and then we repeat the process. With unittest, all the test inputs can be provided at once and then you can test your application. In the end, you get a detailed report with all the failed test cases clearly specified, if any. The unittest module has both a built-in testing framework and a test runner. A testing framework is a set of rules which must be followed while writing test cases, while a test runner is a tool which executes these tests with a bunch of settings, and collects the results. Installation: unittest is available at PyPI and can be installed with the following command – pip install unittest Use: We write the tests in a Python module (.py). To run our tests, we simply execute the test module using any IDE or terminal. Now, let’s write some tests for our small software discussed above using the unittest module. Create a file named tests.py in the folder named “tests”.In tests.py import unittest.Create a class named TestClass which inherits from the class unittest.TestCase.Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase.Create a test method as shown below.Rule 2: Name of each and every test method should start with “test” otherwise it’ll be skipped by the test runner.def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units')Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python.The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails).To run the tests we just defined, we need to call the method unittest.main(), add the following lines in the “tests.py” module.if __name__ == '__main__': unittest.main()Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed. Create a file named tests.py in the folder named “tests”. In tests.py import unittest. Create a class named TestClass which inherits from the class unittest.TestCase.Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase. Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase. Create a test method as shown below.Rule 2: Name of each and every test method should start with “test” otherwise it’ll be skipped by the test runner.def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units')Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python.The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails). def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units') Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python. The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails). To run the tests we just defined, we need to call the method unittest.main(), add the following lines in the “tests.py” module.if __name__ == '__main__': unittest.main()Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed. if __name__ == '__main__': unittest.main() Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed. Finally the “tests.py” module should resemble the code given below. import unittestfrom .. import app class TestSum(unittest.TestCase): def test_area(self): sq = app.Square(2) self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} rather than 9') if __name__ == '__main__': unittest.main() Having written our test cases let us now test our application for any bugs. To test your application you simply need to execute the test file “tests.py” using the command prompt or any IDE of your choice. The output should be something like this. . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK In the first line, a .(dot) represents a successful test while an ‘F’ would represent a failed test case. The OK message, in the end, tells us that all the tests were passed successfully. Let’s add a few more tests in “tests.py” and retest our application. import unittestfrom .. import app class TestSum(unittest.TestCase): def test_area(self): sq = app.Square(2) self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} rather than 9') def test_area_negative(self): sq = app.Square(-3) self.assertEqual(sq.area(), -1, f'Area is shown {sq.area()} rather than -1') def test_perimeter(self): sq = app.Square(5) self.assertEqual(sq.perimeter(), 20, f'Perimeter is {sq.perimeter()} rather than 20') def test_perimeter_negative(self): sq = app.Square(-6) self.assertEqual(sq.perimeter(), -1, f'Perimeter is {sq.perimeter()} rather than -1') if __name__ == '__main__': unittest.main() .F.F ====================================================================== FAIL: test_area_negative (__main__.TestSum) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests_unittest.py", line 11, in test_area_negative self.assertEqual(sq.area(), -1, f'Area is shown {sq.area()} rather than -1 for negative side length') AssertionError: 9 != -1 : Area is shown 9 rather than -1 for negative side length ====================================================================== FAIL: test_perimeter_negative (__main__.TestSum) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests_unittest.py", line 19, in test_perimeter_negative self.assertEqual(sq.perimeter(), -1, f'Perimeter is {sq.perimeter()} rather than -1 for negative side length') AssertionError: -24 != -1 : Perimeter is -24 rather than -1 for negative side length ---------------------------------------------------------------------- Ran 4 tests in 0.001s FAILED (failures=2) A few things to note in the above test report are – The first line represents that test 1 and test 3 executed successfully while test 2 and test 4 failed Each failed test case is described in the report, the first line of the description contains the name of the failed test case and the last line contains the error message we defined for that test case. At the end of the report you can see the number of failed tests, if no test fails the report will end with OK Note: For further knowledge you can read the complete documentation of unittest. The purpose of nose2 is to extend unittest to make testing easier. nose2 is compatible with tests written using the unittest testing framework and can be used as a replacement of the unittest test runner. Installation: nose2 can be installed from PyPI using the command, pip install nose2 Use: nose2 does not have any testing framework and is merely a test runner which is compatible with the unittest testing framework. Therefore we’ll the run same tests we wrote above (for unittest) using nose2. To run the tests we use the following command in the project source directory (“Software_Testing” in our case), nose2 In nose2 terminology all the python modules (.py) with name starting from “test” (i.e. test_file.py, test_1.py) are considered as test files. On execution, nose2 will look for all test files in all the sub-directories which lie under one or more of the following categories, which are python packages (contain “__init__.py”). whose name starts with “test” after being lowercased, i.e. TestFiles, tests. which are named either “src” or “lib”. nose2 first loads all the test files present in the project and then the tests are executed. Thus, with nose2 we get the freedom to split our tests among various test files in different folders and execute them at once, which is very useful when dealing with large number of tests. Let’s now learn about different customisation options provided by nose2 which can help us during the testing process. Changing the search directory –If we want to change the directory in which nose2 searchs for test files, we can do that using the command line arguments -s or --start-dir as,nose2 -s DIR_ADD DIR_NAMEhere, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time.Running specific test cases –Using nose2 we can also run a specific test at a time by using the command line arguments -s and --start-dir as,nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAMETEST_NAME: name of the test method.TEST_CLASS: class in which the test method is defined.TEST_FILE: name of the test file in which the test case is defined i.e. test.py.DIR_NAME: directory in which the test file exists.DIR_ADD: address of the parent directory of DIR_NAME relative to the project source.Using this feature we can test our software on specific inputs.Running tests in a single module –nose2 can also be used like unittest by calling the function nose2.main() just like we called unittest.main() in previous examples.Apart from above basic customisations nose2 provides advanced features like, loading various plugins and config files or creating your own test runner. Changing the search directory –If we want to change the directory in which nose2 searchs for test files, we can do that using the command line arguments -s or --start-dir as,nose2 -s DIR_ADD DIR_NAMEhere, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time. nose2 -s DIR_ADD DIR_NAME here, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time. Running specific test cases –Using nose2 we can also run a specific test at a time by using the command line arguments -s and --start-dir as,nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAMETEST_NAME: name of the test method.TEST_CLASS: class in which the test method is defined.TEST_FILE: name of the test file in which the test case is defined i.e. test.py.DIR_NAME: directory in which the test file exists.DIR_ADD: address of the parent directory of DIR_NAME relative to the project source.Using this feature we can test our software on specific inputs. nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAME TEST_NAME: name of the test method. TEST_CLASS: class in which the test method is defined. TEST_FILE: name of the test file in which the test case is defined i.e. test.py. DIR_NAME: directory in which the test file exists. DIR_ADD: address of the parent directory of DIR_NAME relative to the project source. Using this feature we can test our software on specific inputs. Running tests in a single module –nose2 can also be used like unittest by calling the function nose2.main() just like we called unittest.main() in previous examples. Apart from above basic customisations nose2 provides advanced features like, loading various plugins and config files or creating your own test runner. pytest is the most popular testing framework for python. Using pytest you can test anything from basic python scripts to databases, APIs and UIs. Though pytest is mainly used for API testing, in this article we’ll cover only the basics of pytest. Installation: You can install pytest from PyPI using the command, pip install pytest Use: The pytest test runner is called using the following command in project source, py.test Unlike nose2, pytest looks for test files in all the locations inside the project directory. Any file with name starting with “test_” or ending with “_test” is considered a test file in the pytest terminology. Let’s create a file “test_file1.py” in the folder “tests” as our test file. Creating test methods:pytest supports the test methods written in the unittest framework, but the pytest framework provides easier syntax to write tests. See the code below to understand the test method syntax of the pytest framework. from .. import app def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f"area for side {sq.side} units is {sq.area()}" def test_file1_perimeter(): sq = app.Square(-1) assert sq.perimeter() == -1, f'perimeter is shown {sq.perimeter()} rather than -1' Note: similar to unittest, pytest requires all test names to start with “test”. Unlike unittest, pytest uses the default python assert statements which make it further easier to use. Note that, now the “tests” folder contains two files namely, “tests.py” (written in unittest framework) and “test_file1.py” (written in pytest framework). Now let’s run the pytest test runner. py.test You’ll get a similar report as obtained by using unittest. ============================= test session starts ============================== platform linux -- Python 3.6.7, pytest-4.4.1, py-1.8.0, pluggy-0.9.0 rootdir: /home/manthan/articles/Software_testing_in_Python collected 6 items tests/test_file1.py .F [ 33%] tests/test_file2.py .F.F [100%] =================================== FAILURES =================================== The percentages on the right side of the report show the percentage of tests that have been completed at that moment, i.e. 2 out of the 6 test cases were completed at the end of the “test_file1.py”. Here are a few more basic customisations that come with pytest. Running specific test files: To run only a specific test file, use the command,py.test <filename>Substring matching: Suppose we want to test only the area() method of our Square class, we can do this using substring matching as follows,py.test -k "area"With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc.Marking: As a substitute to substring matching, marking is another method using which we can run a specific set of tests. In this method we put a mark on the tests we want to run. Observe the code example given below,# @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f"area for side {sq.side} units is {sq.area()}"In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command,py.test -m <tag_name>Parallel Processing: If you have a large number of tests then pytest can be customised to run these test methods in parallel. For that you need to install pytest-xdist which can be installed using the command,pip install pytest-xdistNow you can use the following command to execute your tests faster using multiprocessing,py.test -n 4With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs.If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command,pytest --workers 4 Running specific test files: To run only a specific test file, use the command,py.test <filename> py.test <filename> Substring matching: Suppose we want to test only the area() method of our Square class, we can do this using substring matching as follows,py.test -k "area"With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc. py.test -k "area" With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc. Marking: As a substitute to substring matching, marking is another method using which we can run a specific set of tests. In this method we put a mark on the tests we want to run. Observe the code example given below,# @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f"area for side {sq.side} units is {sq.area()}"In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command,py.test -m <tag_name> # @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f"area for side {sq.side} units is {sq.area()}" In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command, py.test -m <tag_name> Parallel Processing: If you have a large number of tests then pytest can be customised to run these test methods in parallel. For that you need to install pytest-xdist which can be installed using the command,pip install pytest-xdistNow you can use the following command to execute your tests faster using multiprocessing,py.test -n 4With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs.If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command,pytest --workers 4 pip install pytest-xdist Now you can use the following command to execute your tests faster using multiprocessing, py.test -n 4 With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs. If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command, pytest --workers 4 sidhanthnandansaaho python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2022" }, { "code": null, "e": 360, "s": 28, "text": "Software testing is the process in which a developer ensures that the actual output of the software matches with the desired output by providing some test inputs to the software. Software testing is an important step because if performed properly, it can help the developer to find bugs in the software in very less amount of time." }, { "code": null, "e": 626, "s": 360, "text": "Software testing can be divided into two classes, Manual testing and Automated testing. Automated testing is the execution of your tests using a script instead of a human. In this article, we’ll discuss some of the methods of automated software testing with Python." }, { "code": null, "e": 701, "s": 626, "text": "Let’s write a simple application over which we will perform all the tests." }, { "code": "class Square: def __init__(self, side): \"\"\" creates a square having the given side \"\"\" self.side = side def area(self): \"\"\" returns area of the square \"\"\" return self.side**2 def perimeter(self): \"\"\" returns perimeter of the square \"\"\" return 4 * self.side def __repr__(self): \"\"\" declares how a Square object should be printed \"\"\" s = 'Square with side = ' + str(self.side) + '\\n' + \\ 'Area = ' + str(self.area()) + '\\n' + \\ 'Perimeter = ' + str(self.perimeter()) return s if __name__ == '__main__': # read input from the user side = int(input('enter the side length to create a Square: ')) # create a square with the provided side square = Square(side) # print the created square print(square)", "e": 1549, "s": 701, "text": null }, { "code": null, "e": 1627, "s": 1549, "text": "Note: For more information about the function __repr__(), refer this article." }, { "code": null, "e": 1781, "s": 1627, "text": "Now that we have our software ready, let’s have a look at the directory structure of our project folder and after that, we’ll start testing our software." }, { "code": null, "e": 1974, "s": 1781, "text": "---Software_Testing\n |--- __init__.py (to initialize the directory as python package)\n |--- app.py (our software)\n |--- tests (folder to keep all test files)\n |--- __init__.py\n" }, { "code": null, "e": 2440, "s": 1974, "text": "One of the major problems with manual testing is that it requires time and effort. In manual testing, we test the application over some input, if it fails, either we note it down or we debug the application for that particular test input, and then we repeat the process. With unittest, all the test inputs can be provided at once and then you can test your application. In the end, you get a detailed report with all the failed test cases clearly specified, if any." }, { "code": null, "e": 2713, "s": 2440, "text": "The unittest module has both a built-in testing framework and a test runner. A testing framework is a set of rules which must be followed while writing test cases, while a test runner is a tool which executes these tests with a bunch of settings, and collects the results." }, { "code": null, "e": 2807, "s": 2713, "text": "Installation: unittest is available at PyPI and can be installed with the following command –" }, { "code": null, "e": 2828, "s": 2807, "text": "pip install unittest" }, { "code": null, "e": 2957, "s": 2828, "text": "Use: We write the tests in a Python module (.py). To run our tests, we simply execute the test module using any IDE or terminal." }, { "code": null, "e": 3051, "s": 2957, "text": "Now, let’s write some tests for our small software discussed above using the unittest module." }, { "code": null, "e": 4463, "s": 3051, "text": "Create a file named tests.py in the folder named “tests”.In tests.py import unittest.Create a class named TestClass which inherits from the class unittest.TestCase.Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase.Create a test method as shown below.Rule 2: Name of each and every test method should start with “test” otherwise it’ll be skipped by the test runner.def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units')Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python.The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails).To run the tests we just defined, we need to call the method unittest.main(), add the following lines in the “tests.py” module.if __name__ == '__main__': unittest.main()Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed." }, { "code": null, "e": 4521, "s": 4463, "text": "Create a file named tests.py in the folder named “tests”." }, { "code": null, "e": 4550, "s": 4521, "text": "In tests.py import unittest." }, { "code": null, "e": 4743, "s": 4550, "text": "Create a class named TestClass which inherits from the class unittest.TestCase.Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase." }, { "code": null, "e": 4857, "s": 4743, "text": "Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase." }, { "code": null, "e": 5667, "s": 4857, "text": "Create a test method as shown below.Rule 2: Name of each and every test method should start with “test” otherwise it’ll be skipped by the test runner.def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units')Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python.The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails)." }, { "code": "def test_area(self): # testing the method Square.area(). sq = Square(2) # creates a Square of side 2 units. # test if the area of the above square is 4 units, # display an error message if it's not. self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} for side = {sq.side} units')", "e": 5989, "s": 5667, "text": null }, { "code": null, "e": 6100, "s": 5989, "text": "Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python." }, { "code": null, "e": 6329, "s": 6100, "text": "The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails)." }, { "code": null, "e": 6655, "s": 6329, "text": "To run the tests we just defined, we need to call the method unittest.main(), add the following lines in the “tests.py” module.if __name__ == '__main__': unittest.main()Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed." }, { "code": "if __name__ == '__main__': unittest.main()", "e": 6701, "s": 6655, "text": null }, { "code": null, "e": 6855, "s": 6701, "text": "Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed." }, { "code": null, "e": 6923, "s": 6855, "text": "Finally the “tests.py” module should resemble the code given below." }, { "code": "import unittestfrom .. import app class TestSum(unittest.TestCase): def test_area(self): sq = app.Square(2) self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} rather than 9') if __name__ == '__main__': unittest.main()", "e": 7187, "s": 6923, "text": null }, { "code": null, "e": 7434, "s": 7187, "text": "Having written our test cases let us now test our application for any bugs. To test your application you simply need to execute the test file “tests.py” using the command prompt or any IDE of your choice. The output should be something like this." }, { "code": null, "e": 7533, "s": 7434, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n" }, { "code": null, "e": 7721, "s": 7533, "text": "In the first line, a .(dot) represents a successful test while an ‘F’ would represent a failed test case. The OK message, in the end, tells us that all the tests were passed successfully." }, { "code": null, "e": 7790, "s": 7721, "text": "Let’s add a few more tests in “tests.py” and retest our application." }, { "code": "import unittestfrom .. import app class TestSum(unittest.TestCase): def test_area(self): sq = app.Square(2) self.assertEqual(sq.area(), 4, f'Area is shown {sq.area()} rather than 9') def test_area_negative(self): sq = app.Square(-3) self.assertEqual(sq.area(), -1, f'Area is shown {sq.area()} rather than -1') def test_perimeter(self): sq = app.Square(5) self.assertEqual(sq.perimeter(), 20, f'Perimeter is {sq.perimeter()} rather than 20') def test_perimeter_negative(self): sq = app.Square(-6) self.assertEqual(sq.perimeter(), -1, f'Perimeter is {sq.perimeter()} rather than -1') if __name__ == '__main__': unittest.main()", "e": 8544, "s": 7790, "text": null }, { "code": null, "e": 9623, "s": 8544, "text": ".F.F\n======================================================================\nFAIL: test_area_negative (__main__.TestSum)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"tests_unittest.py\", line 11, in test_area_negative\n self.assertEqual(sq.area(), -1, f'Area is shown {sq.area()} rather than -1 for negative side length')\nAssertionError: 9 != -1 : Area is shown 9 rather than -1 for negative side length\n\n======================================================================\nFAIL: test_perimeter_negative (__main__.TestSum)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"tests_unittest.py\", line 19, in test_perimeter_negative\n self.assertEqual(sq.perimeter(), -1, f'Perimeter is {sq.perimeter()} rather than -1 for negative side length')\nAssertionError: -24 != -1 : Perimeter is -24 rather than -1 for negative side length\n\n----------------------------------------------------------------------\nRan 4 tests in 0.001s\n\nFAILED (failures=2)" }, { "code": null, "e": 9675, "s": 9623, "text": "A few things to note in the above test report are –" }, { "code": null, "e": 9777, "s": 9675, "text": "The first line represents that test 1 and test 3 executed successfully while test 2 and test 4 failed" }, { "code": null, "e": 9979, "s": 9777, "text": "Each failed test case is described in the report, the first line of the description contains the name of the failed test case and the last line contains the error message we defined for that test case." }, { "code": null, "e": 10089, "s": 9979, "text": "At the end of the report you can see the number of failed tests, if no test fails the report will end with OK" }, { "code": null, "e": 10170, "s": 10089, "text": "Note: For further knowledge you can read the complete documentation of unittest." }, { "code": null, "e": 10375, "s": 10170, "text": "The purpose of nose2 is to extend unittest to make testing easier. nose2 is compatible with tests written using the unittest testing framework and can be used as a replacement of the unittest test runner." }, { "code": null, "e": 10441, "s": 10375, "text": "Installation: nose2 can be installed from PyPI using the command," }, { "code": null, "e": 10459, "s": 10441, "text": "pip install nose2" }, { "code": null, "e": 10781, "s": 10459, "text": "Use: nose2 does not have any testing framework and is merely a test runner which is compatible with the unittest testing framework. Therefore we’ll the run same tests we wrote above (for unittest) using nose2. To run the tests we use the following command in the project source directory (“Software_Testing” in our case)," }, { "code": null, "e": 10787, "s": 10781, "text": "nose2" }, { "code": null, "e": 11062, "s": 10787, "text": "In nose2 terminology all the python modules (.py) with name starting from “test” (i.e. test_file.py, test_1.py) are considered as test files. On execution, nose2 will look for all test files in all the sub-directories which lie under one or more of the following categories," }, { "code": null, "e": 11113, "s": 11062, "text": "which are python packages (contain “__init__.py”)." }, { "code": null, "e": 11190, "s": 11113, "text": "whose name starts with “test” after being lowercased, i.e. TestFiles, tests." }, { "code": null, "e": 11229, "s": 11190, "text": "which are named either “src” or “lib”." }, { "code": null, "e": 11511, "s": 11229, "text": "nose2 first loads all the test files present in the project and then the tests are executed. Thus, with nose2 we get the freedom to split our tests among various test files in different folders and execute them at once, which is very useful when dealing with large number of tests." }, { "code": null, "e": 11629, "s": 11511, "text": "Let’s now learn about different customisation options provided by nose2 which can help us during the testing process." }, { "code": null, "e": 13061, "s": 11629, "text": "Changing the search directory –If we want to change the directory in which nose2 searchs for test files, we can do that using the command line arguments -s or --start-dir as,nose2 -s DIR_ADD DIR_NAMEhere, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time.Running specific test cases –Using nose2 we can also run a specific test at a time by using the command line arguments -s and --start-dir as,nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAMETEST_NAME: name of the test method.TEST_CLASS: class in which the test method is defined.TEST_FILE: name of the test file in which the test case is defined i.e. test.py.DIR_NAME: directory in which the test file exists.DIR_ADD: address of the parent directory of DIR_NAME relative to the project source.Using this feature we can test our software on specific inputs.Running tests in a single module –nose2 can also be used like unittest by calling the function nose2.main() just like we called unittest.main() in previous examples.Apart from above basic customisations nose2 provides advanced features like, loading various plugins and config files or creating your own test runner." }, { "code": null, "e": 13614, "s": 13061, "text": "Changing the search directory –If we want to change the directory in which nose2 searchs for test files, we can do that using the command line arguments -s or --start-dir as,nose2 -s DIR_ADD DIR_NAMEhere, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time." }, { "code": null, "e": 13640, "s": 13614, "text": "nose2 -s DIR_ADD DIR_NAME" }, { "code": null, "e": 13994, "s": 13640, "text": "here, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself).This is extremely useful when you want to test only one feature of your application at a time." }, { "code": null, "e": 14558, "s": 13994, "text": "Running specific test cases –Using nose2 we can also run a specific test at a time by using the command line arguments -s and --start-dir as,nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAMETEST_NAME: name of the test method.TEST_CLASS: class in which the test method is defined.TEST_FILE: name of the test file in which the test case is defined i.e. test.py.DIR_NAME: directory in which the test file exists.DIR_ADD: address of the parent directory of DIR_NAME relative to the project source.Using this feature we can test our software on specific inputs." }, { "code": null, "e": 14615, "s": 14558, "text": "nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAME" }, { "code": null, "e": 14651, "s": 14615, "text": "TEST_NAME: name of the test method." }, { "code": null, "e": 14706, "s": 14651, "text": "TEST_CLASS: class in which the test method is defined." }, { "code": null, "e": 14787, "s": 14706, "text": "TEST_FILE: name of the test file in which the test case is defined i.e. test.py." }, { "code": null, "e": 14838, "s": 14787, "text": "DIR_NAME: directory in which the test file exists." }, { "code": null, "e": 14923, "s": 14838, "text": "DIR_ADD: address of the parent directory of DIR_NAME relative to the project source." }, { "code": null, "e": 14987, "s": 14923, "text": "Using this feature we can test our software on specific inputs." }, { "code": null, "e": 15153, "s": 14987, "text": "Running tests in a single module –nose2 can also be used like unittest by calling the function nose2.main() just like we called unittest.main() in previous examples." }, { "code": null, "e": 15305, "s": 15153, "text": "Apart from above basic customisations nose2 provides advanced features like, loading various plugins and config files or creating your own test runner." }, { "code": null, "e": 15552, "s": 15305, "text": "pytest is the most popular testing framework for python. Using pytest you can test anything from basic python scripts to databases, APIs and UIs. Though pytest is mainly used for API testing, in this article we’ll cover only the basics of pytest." }, { "code": null, "e": 15618, "s": 15552, "text": "Installation: You can install pytest from PyPI using the command," }, { "code": null, "e": 15637, "s": 15618, "text": "pip install pytest" }, { "code": null, "e": 15722, "s": 15637, "text": "Use: The pytest test runner is called using the following command in project source," }, { "code": null, "e": 15730, "s": 15722, "text": "py.test" }, { "code": null, "e": 16016, "s": 15730, "text": "Unlike nose2, pytest looks for test files in all the locations inside the project directory. Any file with name starting with “test_” or ending with “_test” is considered a test file in the pytest terminology. Let’s create a file “test_file1.py” in the folder “tests” as our test file." }, { "code": null, "e": 16251, "s": 16016, "text": "Creating test methods:pytest supports the test methods written in the unittest framework, but the pytest framework provides easier syntax to write tests. See the code below to understand the test method syntax of the pytest framework." }, { "code": "from .. import app def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f\"area for side {sq.side} units is {sq.area()}\" def test_file1_perimeter(): sq = app.Square(-1) assert sq.perimeter() == -1, f'perimeter is shown {sq.perimeter()} rather than -1'", "e": 16544, "s": 16251, "text": null }, { "code": null, "e": 16624, "s": 16544, "text": "Note: similar to unittest, pytest requires all test names to start with “test”." }, { "code": null, "e": 16727, "s": 16624, "text": "Unlike unittest, pytest uses the default python assert statements which make it further easier to use." }, { "code": null, "e": 16920, "s": 16727, "text": "Note that, now the “tests” folder contains two files namely, “tests.py” (written in unittest framework) and “test_file1.py” (written in pytest framework). Now let’s run the pytest test runner." }, { "code": null, "e": 16928, "s": 16920, "text": "py.test" }, { "code": null, "e": 16987, "s": 16928, "text": "You’ll get a similar report as obtained by using unittest." }, { "code": null, "e": 17519, "s": 16987, "text": "============================= test session starts ==============================\nplatform linux -- Python 3.6.7, pytest-4.4.1, py-1.8.0, pluggy-0.9.0\nrootdir: /home/manthan/articles/Software_testing_in_Python\ncollected 6 items \n\ntests/test_file1.py .F [ 33%]\ntests/test_file2.py .F.F [100%]\n\n=================================== FAILURES ===================================" }, { "code": null, "e": 17718, "s": 17519, "text": "The percentages on the right side of the report show the percentage of tests that have been completed at that moment, i.e. 2 out of the 6 test cases were completed at the end of the “test_file1.py”." }, { "code": null, "e": 17782, "s": 17718, "text": "Here are a few more basic customisations that come with pytest." }, { "code": null, "e": 19438, "s": 17782, "text": "Running specific test files: To run only a specific test file, use the command,py.test <filename>Substring matching: Suppose we want to test only the area() method of our Square class, we can do this using substring matching as follows,py.test -k \"area\"With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc.Marking: As a substitute to substring matching, marking is another method using which we can run a specific set of tests. In this method we put a mark on the tests we want to run. Observe the code example given below,# @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f\"area for side {sq.side} units is {sq.area()}\"In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command,py.test -m <tag_name>Parallel Processing: If you have a large number of tests then pytest can be customised to run these test methods in parallel. For that you need to install pytest-xdist which can be installed using the command,pip install pytest-xdistNow you can use the following command to execute your tests faster using multiprocessing,py.test -n 4With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs.If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command,pytest --workers 4" }, { "code": null, "e": 19536, "s": 19438, "text": "Running specific test files: To run only a specific test file, use the command,py.test <filename>" }, { "code": null, "e": 19555, "s": 19536, "text": "py.test <filename>" }, { "code": null, "e": 19856, "s": 19555, "text": "Substring matching: Suppose we want to test only the area() method of our Square class, we can do this using substring matching as follows,py.test -k \"area\"With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc." }, { "code": null, "e": 19874, "s": 19856, "text": "py.test -k \"area\"" }, { "code": null, "e": 20019, "s": 19874, "text": "With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc." }, { "code": null, "e": 20598, "s": 20019, "text": "Marking: As a substitute to substring matching, marking is another method using which we can run a specific set of tests. In this method we put a mark on the tests we want to run. Observe the code example given below,# @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f\"area for side {sq.side} units is {sq.area()}\"In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command,py.test -m <tag_name>" }, { "code": "# @pytest.mark.<tag_name>@pytest.mark.area def test_file1_area(): sq = app.Square(2) assert sq.area() == 4, f\"area for side {sq.side} units is {sq.area()}\"", "e": 20773, "s": 20598, "text": null }, { "code": null, "e": 20940, "s": 20773, "text": "In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command," }, { "code": null, "e": 20962, "s": 20940, "text": "py.test -m <tag_name>" }, { "code": null, "e": 21643, "s": 20962, "text": "Parallel Processing: If you have a large number of tests then pytest can be customised to run these test methods in parallel. For that you need to install pytest-xdist which can be installed using the command,pip install pytest-xdistNow you can use the following command to execute your tests faster using multiprocessing,py.test -n 4With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs.If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command,pytest --workers 4" }, { "code": null, "e": 21668, "s": 21643, "text": "pip install pytest-xdist" }, { "code": null, "e": 21758, "s": 21668, "text": "Now you can use the following command to execute your tests faster using multiprocessing," }, { "code": null, "e": 21771, "s": 21758, "text": "py.test -n 4" }, { "code": null, "e": 21894, "s": 21771, "text": "With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs." }, { "code": null, "e": 22101, "s": 21894, "text": "If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command," }, { "code": null, "e": 22120, "s": 22101, "text": "pytest --workers 4" }, { "code": null, "e": 22140, "s": 22120, "text": "sidhanthnandansaaho" }, { "code": null, "e": 22155, "s": 22140, "text": "python-utility" }, { "code": null, "e": 22162, "s": 22155, "text": "Python" }, { "code": null, "e": 22260, "s": 22162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22278, "s": 22260, "text": "Python Dictionary" }, { "code": null, "e": 22320, "s": 22278, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 22342, "s": 22320, "text": "Enumerate() in Python" }, { "code": null, "e": 22377, "s": 22342, "text": "Read a file line by line in Python" }, { "code": null, "e": 22403, "s": 22377, "text": "Python String | replace()" }, { "code": null, "e": 22435, "s": 22403, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 22464, "s": 22435, "text": "*args and **kwargs in Python" }, { "code": null, "e": 22491, "s": 22464, "text": "Python Classes and Objects" }, { "code": null, "e": 22521, "s": 22491, "text": "Iterate over a list in Python" } ]
Python | Pandas Series.isna()
12 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.isna() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False. Syntax: Series.isna() Parameter : None Returns : boolean Example #1: Use Series.isna() function to detect missing values in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output :Now we will use Series.isna() function to detect all the missing values in the given series object. # detect missing valuesresult = sr.isna() # Print the resultprint(result) Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isna() function to detect missing values in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.isna() function to detect all the missing values in the given series object. # detect missing valuesresult = sr.isna() # Print the resultprint(result) Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All missing values have been mapped to True. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 515, "s": 285, "text": "Pandas Series.isna() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False." }, { "code": null, "e": 537, "s": 515, "text": "Syntax: Series.isna()" }, { "code": null, "e": 554, "s": 537, "text": "Parameter : None" }, { "code": null, "e": 572, "s": 554, "text": "Returns : boolean" }, { "code": null, "e": 664, "s": 572, "text": "Example #1: Use Series.isna() function to detect missing values in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 920, "s": 664, "text": null }, { "code": null, "e": 1028, "s": 920, "text": "Output :Now we will use Series.isna() function to detect all the missing values in the given series object." }, { "code": "# detect missing valuesresult = sr.isna() # Print the resultprint(result)", "e": 1103, "s": 1028, "text": null }, { "code": null, "e": 1409, "s": 1103, "text": "Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isna() function to detect missing values in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1682, "s": 1409, "text": null }, { "code": null, "e": 1691, "s": 1682, "text": "Output :" }, { "code": null, "e": 1791, "s": 1691, "text": "Now we will use Series.isna() function to detect all the missing values in the given series object." }, { "code": "# detect missing valuesresult = sr.isna() # Print the resultprint(result)", "e": 1866, "s": 1791, "text": null }, { "code": null, "e": 2025, "s": 1866, "text": "Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All missing values have been mapped to True." }, { "code": null, "e": 2046, "s": 2025, "text": "Python pandas-series" }, { "code": null, "e": 2075, "s": 2046, "text": "Python pandas-series-methods" }, { "code": null, "e": 2089, "s": 2075, "text": "Python-pandas" }, { "code": null, "e": 2096, "s": 2089, "text": "Python" }, { "code": null, "e": 2194, "s": 2096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2212, "s": 2194, "text": "Python Dictionary" }, { "code": null, "e": 2254, "s": 2212, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2276, "s": 2254, "text": "Enumerate() in Python" }, { "code": null, "e": 2311, "s": 2276, "text": "Read a file line by line in Python" }, { "code": null, "e": 2337, "s": 2311, "text": "Python String | replace()" }, { "code": null, "e": 2369, "s": 2337, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2398, "s": 2369, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2428, "s": 2398, "text": "Iterate over a list in Python" }, { "code": null, "e": 2455, "s": 2428, "text": "Python Classes and Objects" } ]
Singleton Method – Python Design Patterns
08 Jul, 2022 Prerequisite: Singleton Design pattern | Introduction Singleton Method is a type of Creational Design pattern and is one of the simplest design patterns00 available to us. It is a way to provide one and only one object of a particular type. It involves only one class to create methods and specify the objects. Singleton Design Pattern can be understood by a very simple example of Database connectivity. When each object creates a unique Database Connection to the Database, it will highly affect the cost and expenses of the project. So, it is always better to make a single connection rather than making extra irrelevant connections which can be easily done by Singleton Design Pattern. singleton-pattern Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object. Now let’s have a look at the different implementations of the Singleton Design pattern. Singleton behavior can be implemented by Borg’s pattern but instead of having only one instance of the class, there are multiple instances that share the same state. Here we don’t focus on the sharing of the instance identity instead we focus on the sharing state. Python3 # Singleton Borg patternclass Borg: # state shared by each instance __shared_state = dict() # constructor method def __init__(self): self.__dict__ = self.__shared_state self.state = 'GeeksforGeeks' def __str__(self): return self.state # main methodif __name__ == "__main__": person1 = Borg() # object of class Borg person2 = Borg() # object of class Borg person3 = Borg() # object of class Borg person1.state = 'DataStructures' # person1 changed the state person2.state = 'Algorithms' # person2 changed the state print(person1) # output --> Algorithms print(person2) # output --> Algorithms person3.state = 'Geeks' # person3 changed the # the shared state print(person1) # output --> Geeks print(person2) # output --> Geeks print(person3) # output --> Geeks Output: Algorithms Algorithms Geeks Geeks Geeks Singleton-Design-pattern It is easy to notice that once an object is created, the synchronization of the threading is no longer useful because now the object will never be equal to None and any sequence of operations will lead to consistent results. So, when the object will be equal to None, then only we will acquire the Lock on the getInstance method. Python3 # Double Checked Locking singleton patternimport threading class SingletonDoubleChecked(object): # resources shared by each and every # instance __singleton_lock = threading.Lock() __singleton_instance = None # define the classmethod @classmethod def instance(cls): # check for the singleton instance if not cls.__singleton_instance: with cls.__singleton_lock: if not cls.__singleton_instance: cls.__singleton_instance = cls() # return the singleton instance return cls.__singleton_instance # main methodif __name__ == '__main__': # create class X class X(SingletonDoubleChecked): pass # create class Y class Y(SingletonDoubleChecked): pass A1, A2 = X.instance(), X.instance() B1, B2 = Y.instance(), Y.instance() assert A1 is not B1 assert A1 is A2 assert B1 is B2 print('A1 : ', A1) print('A2 : ', A2) print('B1 : ', B1) print('B2 : ', B2) Output: A1 : __main__.X object at 0x02EA2590 A2 : __main__.X object at 0x02EA2590 B1 : __main__.Y object at 0x02EA25B0 B2 : __main__.Y object at 0x02EA25B0 In the classic implementation of the Singleton Design pattern, we simply use the static method for creating the getInstance method which has the ability to return the shared resource. We also make use of the so-called Virtual private Constructor to raise the exception against it although it is not much required. Python3 # classic implementation of Singleton Design patternclass Singleton: __shared_instance = 'GeeksforGeeks' @staticmethod def getInstance(): """Static Access Method""" if Singleton.__shared_instance == 'GeeksforGeeks': Singleton() return Singleton.__shared_instance def __init__(self): """virtual private constructor""" if Singleton.__shared_instance != 'GeeksforGeeks': raise Exception("This class is a singleton class !") else: Singleton.__shared_instance = self # main methodif __name__ == "__main__": # create object of Singleton Class obj = Singleton() print(obj) # pick the instance of the class obj = Singleton.getInstance() print(obj) Output: __main__.Singleton object at 0x014FFE90 __main__.Singleton object at 0x014FFE90 Class Diagram of Singleton Design Pattern singleton-class-diagram Initializations: An object created by the Singleton method is initialized only when it is requested for the first time.Access to the object: We got global access to the instance of the object.Count of instances: In singleton, method classes can’t have more than one instance Initializations: An object created by the Singleton method is initialized only when it is requested for the first time. Access to the object: We got global access to the instance of the object. Count of instances: In singleton, method classes can’t have more than one instance Multithread Environment: It’s not easy to use the singleton method in a multithread environment, because we have to take care that the multithread wouldn’t create a singleton object several times.Single responsibility principle: As the Singleton method is solving two problems at a single time, it doesn’t follow the single responsibility principle.Unit testing process: As they introduce the global state to the application, it makes the unit testing very hard. Multithread Environment: It’s not easy to use the singleton method in a multithread environment, because we have to take care that the multithread wouldn’t create a singleton object several times. Single responsibility principle: As the Singleton method is solving two problems at a single time, it doesn’t follow the single responsibility principle. Unit testing process: As they introduce the global state to the application, it makes the unit testing very hard. Controlling over global variables: In the projects where we specifically need strong control over the global variables, it is highly recommended to use Singleton MethodDaily Developers use: Singleton patterns are generally used in providing the logging, caching, thread pools, and configuration settings and are often used in conjunction with Factory design patterns. Controlling over global variables: In the projects where we specifically need strong control over the global variables, it is highly recommended to use Singleton Method Daily Developers use: Singleton patterns are generally used in providing the logging, caching, thread pools, and configuration settings and are often used in conjunction with Factory design patterns. Further read: Singleton method in Java, Singleton Design Pattern Practices with Examples rajeev0719singh surinderdawra388 surajkumarguptaintern python-design-pattern Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2022" }, { "code": null, "e": 107, "s": 53, "text": "Prerequisite: Singleton Design pattern | Introduction" }, { "code": null, "e": 743, "s": 107, "text": "Singleton Method is a type of Creational Design pattern and is one of the simplest design patterns00 available to us. It is a way to provide one and only one object of a particular type. It involves only one class to create methods and specify the objects. Singleton Design Pattern can be understood by a very simple example of Database connectivity. When each object creates a unique Database Connection to the Database, it will highly affect the cost and expenses of the project. So, it is always better to make a single connection rather than making extra irrelevant connections which can be easily done by Singleton Design Pattern." }, { "code": null, "e": 761, "s": 743, "text": "singleton-pattern" }, { "code": null, "e": 874, "s": 761, "text": "Definition: The singleton pattern is a design pattern that restricts the instantiation of a class to one object." }, { "code": null, "e": 963, "s": 874, "text": "Now let’s have a look at the different implementations of the Singleton Design pattern. " }, { "code": null, "e": 1229, "s": 963, "text": "Singleton behavior can be implemented by Borg’s pattern but instead of having only one instance of the class, there are multiple instances that share the same state. Here we don’t focus on the sharing of the instance identity instead we focus on the sharing state. " }, { "code": null, "e": 1237, "s": 1229, "text": "Python3" }, { "code": "# Singleton Borg patternclass Borg: # state shared by each instance __shared_state = dict() # constructor method def __init__(self): self.__dict__ = self.__shared_state self.state = 'GeeksforGeeks' def __str__(self): return self.state # main methodif __name__ == \"__main__\": person1 = Borg() # object of class Borg person2 = Borg() # object of class Borg person3 = Borg() # object of class Borg person1.state = 'DataStructures' # person1 changed the state person2.state = 'Algorithms' # person2 changed the state print(person1) # output --> Algorithms print(person2) # output --> Algorithms person3.state = 'Geeks' # person3 changed the # the shared state print(person1) # output --> Geeks print(person2) # output --> Geeks print(person3) # output --> Geeks", "e": 2108, "s": 1237, "text": null }, { "code": null, "e": 2117, "s": 2108, "text": "Output: " }, { "code": null, "e": 2157, "s": 2117, "text": "Algorithms\nAlgorithms\nGeeks\nGeeks\nGeeks" }, { "code": null, "e": 2182, "s": 2157, "text": "Singleton-Design-pattern" }, { "code": null, "e": 2512, "s": 2182, "text": "It is easy to notice that once an object is created, the synchronization of the threading is no longer useful because now the object will never be equal to None and any sequence of operations will lead to consistent results. So, when the object will be equal to None, then only we will acquire the Lock on the getInstance method." }, { "code": null, "e": 2520, "s": 2512, "text": "Python3" }, { "code": "# Double Checked Locking singleton patternimport threading class SingletonDoubleChecked(object): # resources shared by each and every # instance __singleton_lock = threading.Lock() __singleton_instance = None # define the classmethod @classmethod def instance(cls): # check for the singleton instance if not cls.__singleton_instance: with cls.__singleton_lock: if not cls.__singleton_instance: cls.__singleton_instance = cls() # return the singleton instance return cls.__singleton_instance # main methodif __name__ == '__main__': # create class X class X(SingletonDoubleChecked): pass # create class Y class Y(SingletonDoubleChecked): pass A1, A2 = X.instance(), X.instance() B1, B2 = Y.instance(), Y.instance() assert A1 is not B1 assert A1 is A2 assert B1 is B2 print('A1 : ', A1) print('A2 : ', A2) print('B1 : ', B1) print('B2 : ', B2)", "e": 3520, "s": 2520, "text": null }, { "code": null, "e": 3530, "s": 3520, "text": "Output: " }, { "code": null, "e": 3682, "s": 3530, "text": "A1 : __main__.X object at 0x02EA2590\nA2 : __main__.X object at 0x02EA2590\nB1 : __main__.Y object at 0x02EA25B0\nB2 : __main__.Y object at 0x02EA25B0" }, { "code": null, "e": 3996, "s": 3682, "text": "In the classic implementation of the Singleton Design pattern, we simply use the static method for creating the getInstance method which has the ability to return the shared resource. We also make use of the so-called Virtual private Constructor to raise the exception against it although it is not much required." }, { "code": null, "e": 4004, "s": 3996, "text": "Python3" }, { "code": "# classic implementation of Singleton Design patternclass Singleton: __shared_instance = 'GeeksforGeeks' @staticmethod def getInstance(): \"\"\"Static Access Method\"\"\" if Singleton.__shared_instance == 'GeeksforGeeks': Singleton() return Singleton.__shared_instance def __init__(self): \"\"\"virtual private constructor\"\"\" if Singleton.__shared_instance != 'GeeksforGeeks': raise Exception(\"This class is a singleton class !\") else: Singleton.__shared_instance = self # main methodif __name__ == \"__main__\": # create object of Singleton Class obj = Singleton() print(obj) # pick the instance of the class obj = Singleton.getInstance() print(obj)", "e": 4755, "s": 4004, "text": null }, { "code": null, "e": 4765, "s": 4755, "text": "Output: " }, { "code": null, "e": 4847, "s": 4765, "text": " __main__.Singleton object at 0x014FFE90\n __main__.Singleton object at 0x014FFE90" }, { "code": null, "e": 4890, "s": 4847, "text": "Class Diagram of Singleton Design Pattern " }, { "code": null, "e": 4914, "s": 4890, "text": "singleton-class-diagram" }, { "code": null, "e": 5189, "s": 4914, "text": "Initializations: An object created by the Singleton method is initialized only when it is requested for the first time.Access to the object: We got global access to the instance of the object.Count of instances: In singleton, method classes can’t have more than one instance" }, { "code": null, "e": 5309, "s": 5189, "text": "Initializations: An object created by the Singleton method is initialized only when it is requested for the first time." }, { "code": null, "e": 5383, "s": 5309, "text": "Access to the object: We got global access to the instance of the object." }, { "code": null, "e": 5466, "s": 5383, "text": "Count of instances: In singleton, method classes can’t have more than one instance" }, { "code": null, "e": 5929, "s": 5466, "text": "Multithread Environment: It’s not easy to use the singleton method in a multithread environment, because we have to take care that the multithread wouldn’t create a singleton object several times.Single responsibility principle: As the Singleton method is solving two problems at a single time, it doesn’t follow the single responsibility principle.Unit testing process: As they introduce the global state to the application, it makes the unit testing very hard." }, { "code": null, "e": 6126, "s": 5929, "text": "Multithread Environment: It’s not easy to use the singleton method in a multithread environment, because we have to take care that the multithread wouldn’t create a singleton object several times." }, { "code": null, "e": 6280, "s": 6126, "text": "Single responsibility principle: As the Singleton method is solving two problems at a single time, it doesn’t follow the single responsibility principle." }, { "code": null, "e": 6394, "s": 6280, "text": "Unit testing process: As they introduce the global state to the application, it makes the unit testing very hard." }, { "code": null, "e": 6762, "s": 6394, "text": "Controlling over global variables: In the projects where we specifically need strong control over the global variables, it is highly recommended to use Singleton MethodDaily Developers use: Singleton patterns are generally used in providing the logging, caching, thread pools, and configuration settings and are often used in conjunction with Factory design patterns." }, { "code": null, "e": 6931, "s": 6762, "text": "Controlling over global variables: In the projects where we specifically need strong control over the global variables, it is highly recommended to use Singleton Method" }, { "code": null, "e": 7131, "s": 6931, "text": "Daily Developers use: Singleton patterns are generally used in providing the logging, caching, thread pools, and configuration settings and are often used in conjunction with Factory design patterns." }, { "code": null, "e": 7220, "s": 7131, "text": "Further read: Singleton method in Java, Singleton Design Pattern Practices with Examples" }, { "code": null, "e": 7236, "s": 7220, "text": "rajeev0719singh" }, { "code": null, "e": 7253, "s": 7236, "text": "surinderdawra388" }, { "code": null, "e": 7275, "s": 7253, "text": "surajkumarguptaintern" }, { "code": null, "e": 7297, "s": 7275, "text": "python-design-pattern" }, { "code": null, "e": 7304, "s": 7297, "text": "Python" }, { "code": null, "e": 7402, "s": 7304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7420, "s": 7402, "text": "Python Dictionary" }, { "code": null, "e": 7462, "s": 7420, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7484, "s": 7462, "text": "Enumerate() in Python" }, { "code": null, "e": 7510, "s": 7484, "text": "Python String | replace()" }, { "code": null, "e": 7542, "s": 7510, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7571, "s": 7542, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7598, "s": 7571, "text": "Python Classes and Objects" }, { "code": null, "e": 7619, "s": 7598, "text": "Python OOPs Concepts" }, { "code": null, "e": 7655, "s": 7619, "text": "Convert integer to string in Python" } ]
How to convert CSV into array in R?
02 Jul, 2021 In this article, we are going to see how to convert CSV into an array in R Programming Language. If we load this file into any environment like python, R language .etc, the data will be displayed in rows and columns format, let us convert CSV file into an array. Each and every column in the CSV will be converted into array of multiple dimensions. Method 1 : Using loop. Here we will use loop to convert all the columns in to the array. R setwd("C:/Users/KRISHNA KARTHIKEYA/Documents") df = read.csv("item.csv") lst1 = list() for(i in 1:ncol(df)) { lst1[[i]] <- df[ , i] } names(lst1) = colnames(df) arr = array(unlist(lst1), dim = c(5, 5, 3))print(arr) Output: Explanation : In the first step we changed the directory using setwd() function to where the csv file is located. In the next step we have imported a CSV file into R environment using read.csv() function. Then created a empty list. Using for loop extracted every element by column wise and passed to list() function. Converted list to array using array() by passing list variable as parameter. In the array() function we have used unlist() function. The unlist() function is used to convert list to vector. So, the unlist() with list variable is passed to array(). Finally, printed the array variable. Method 2: Extract every column into separate variable and pass to array() function. R setwd('C:/Users/KRISHNA KARTHIKEYA/Documents') df = read.csv('item.csv')a = df$idb = df$itemc = df$quantityd = df$pricee = df$boughtf = df$forenoong = df$afternoonarr = array(c(a, b, c, d, e, f, g), dim = c(5, 3 ,2))print(arr) Output: Explanation : In the first step we changed the directory using setwd() function to where the csv file is located. In the next step we have imported a CSV file into R environment using read.csv() function. Using $ operator we have extracted every column into separate variable. Pass all the column variables to array( ) and give dimensions using dim attribute. Finally, printed the array variable. sweetyty R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Printing Output of an R Program Group by function in R using Dplyr How to Replace specific values in column in R DataFrame ? How to filter R DataFrame by values in a column? R Programming Language - Introduction Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Creating a Data Frame from Vectors in R Programming Change Color of Bars in Barchart using ggplot2 in R
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jul, 2021" }, { "code": null, "e": 377, "s": 28, "text": "In this article, we are going to see how to convert CSV into an array in R Programming Language. If we load this file into any environment like python, R language .etc, the data will be displayed in rows and columns format, let us convert CSV file into an array. Each and every column in the CSV will be converted into array of multiple dimensions." }, { "code": null, "e": 400, "s": 377, "text": "Method 1 : Using loop." }, { "code": null, "e": 467, "s": 400, "text": "Here we will use loop to convert all the columns in to the array. " }, { "code": null, "e": 469, "s": 467, "text": "R" }, { "code": "setwd(\"C:/Users/KRISHNA KARTHIKEYA/Documents\") df = read.csv(\"item.csv\") lst1 = list() for(i in 1:ncol(df)) { lst1[[i]] <- df[ , i] } names(lst1) = colnames(df) arr = array(unlist(lst1), dim = c(5, 5, 3))print(arr)", "e": 703, "s": 469, "text": null }, { "code": null, "e": 711, "s": 703, "text": "Output:" }, { "code": null, "e": 725, "s": 711, "text": "Explanation :" }, { "code": null, "e": 825, "s": 725, "text": "In the first step we changed the directory using setwd() function to where the csv file is located." }, { "code": null, "e": 916, "s": 825, "text": "In the next step we have imported a CSV file into R environment using read.csv() function." }, { "code": null, "e": 943, "s": 916, "text": "Then created a empty list." }, { "code": null, "e": 1028, "s": 943, "text": "Using for loop extracted every element by column wise and passed to list() function." }, { "code": null, "e": 1276, "s": 1028, "text": "Converted list to array using array() by passing list variable as parameter. In the array() function we have used unlist() function. The unlist() function is used to convert list to vector. So, the unlist() with list variable is passed to array()." }, { "code": null, "e": 1313, "s": 1276, "text": "Finally, printed the array variable." }, { "code": null, "e": 1397, "s": 1313, "text": "Method 2: Extract every column into separate variable and pass to array() function." }, { "code": null, "e": 1399, "s": 1397, "text": "R" }, { "code": "setwd('C:/Users/KRISHNA KARTHIKEYA/Documents') df = read.csv('item.csv')a = df$idb = df$itemc = df$quantityd = df$pricee = df$boughtf = df$forenoong = df$afternoonarr = array(c(a, b, c, d, e, f, g), dim = c(5, 3 ,2))print(arr)", "e": 1637, "s": 1399, "text": null }, { "code": null, "e": 1645, "s": 1637, "text": "Output:" }, { "code": null, "e": 1659, "s": 1645, "text": "Explanation :" }, { "code": null, "e": 1759, "s": 1659, "text": "In the first step we changed the directory using setwd() function to where the csv file is located." }, { "code": null, "e": 1850, "s": 1759, "text": "In the next step we have imported a CSV file into R environment using read.csv() function." }, { "code": null, "e": 1922, "s": 1850, "text": "Using $ operator we have extracted every column into separate variable." }, { "code": null, "e": 2005, "s": 1922, "text": "Pass all the column variables to array( ) and give dimensions using dim attribute." }, { "code": null, "e": 2042, "s": 2005, "text": "Finally, printed the array variable." }, { "code": null, "e": 2051, "s": 2042, "text": "sweetyty" }, { "code": null, "e": 2057, "s": 2051, "text": "R-CSV" }, { "code": null, "e": 2068, "s": 2057, "text": "R Language" }, { "code": null, "e": 2166, "s": 2068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2218, "s": 2166, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2250, "s": 2218, "text": "Printing Output of an R Program" }, { "code": null, "e": 2285, "s": 2250, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2343, "s": 2285, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2392, "s": 2343, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2430, "s": 2392, "text": "R Programming Language - Introduction" }, { "code": null, "e": 2462, "s": 2430, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2506, "s": 2462, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2558, "s": 2506, "text": "Creating a Data Frame from Vectors in R Programming" } ]
Get Time Zone of a Given Location using Python
17 May, 2022 In this article, we are going to see how to get the time zone from a given location. The Timezonefinder module is able to find the timezone of any point on earth (coordinates) offline. Before starting we need to install this module. timezonefinder: This module does not built in with Python. To install this type the below command in the terminal. timezonefinder: This module does not built in with Python. To install this type the below command in the terminal. pip install timezonefinder Geopy: .geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal. pip install geopy Let’s understand this module with Step by step: Step 1: import TimezoneFinder module Python3 from timezonefinder import TimezoneFinder Step 2: make an object of TimezoneFinder. Python3 # object creationobj = TimezoneFinder() Step 3: Pass the latitude and longitude in a timezone_at() method and it return the time zone of a given location. Python3 # pass the longitude and latitude# in timezone_at and# it return time zone latitude = 25.6093239longitude = 85.1235252obj.timezone_at(lng=latitude, lat=longitude) Output: 'Asia/Kolkata' Now let write a script to get timezone with a specific location. Approach: Import the module Initialize Nominatim API to get location from the input string. Get latitude and longitude with geolocator.geocode() function. Pass the latitude and longitude in a timezone_at() method and it returns the time zone of a given location. Code: Python3 # importing modulefrom geopy.geocoders import Nominatimfrom timezonefinder import TimezoneFinder # initialize Nominatim APIgeolocator = Nominatim(user_agent="geoapiExercises") # input as a geeklad = "Dhaka"print("Location address:", lad) # getting Latitude and Longitudelocation = geolocator.geocode(lad) print("Latitude and Longitude of the said address:")print((location.latitude, location.longitude)) # pass the Latitude and Longitude# into a timezone_at# and it return timezoneobj = TimezoneFinder() # returns 'Europe/Berlin'result = obj.timezone_at(lng=location.longitude, lat=location.latitude)print("Time Zone : ", result) Output: Location address: Dhaka Latitude and Longitude of the said address: (23.810651, 90.4126466) Time Zone : Asia/Dhaka rkbhola5 Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2022" }, { "code": null, "e": 261, "s": 28, "text": "In this article, we are going to see how to get the time zone from a given location. The Timezonefinder module is able to find the timezone of any point on earth (coordinates) offline. Before starting we need to install this module." }, { "code": null, "e": 376, "s": 261, "text": "timezonefinder: This module does not built in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 491, "s": 376, "text": "timezonefinder: This module does not built in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 519, "s": 491, "text": "pip install timezonefinder\n" }, { "code": null, "e": 734, "s": 519, "text": " Geopy: .geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal." }, { "code": null, "e": 753, "s": 734, "text": "pip install geopy\n" }, { "code": null, "e": 801, "s": 753, "text": "Let’s understand this module with Step by step:" }, { "code": null, "e": 838, "s": 801, "text": "Step 1: import TimezoneFinder module" }, { "code": null, "e": 846, "s": 838, "text": "Python3" }, { "code": "from timezonefinder import TimezoneFinder", "e": 888, "s": 846, "text": null }, { "code": null, "e": 931, "s": 888, "text": "Step 2: make an object of TimezoneFinder." }, { "code": null, "e": 939, "s": 931, "text": "Python3" }, { "code": "# object creationobj = TimezoneFinder()", "e": 979, "s": 939, "text": null }, { "code": null, "e": 1094, "s": 979, "text": "Step 3: Pass the latitude and longitude in a timezone_at() method and it return the time zone of a given location." }, { "code": null, "e": 1102, "s": 1094, "text": "Python3" }, { "code": "# pass the longitude and latitude# in timezone_at and# it return time zone latitude = 25.6093239longitude = 85.1235252obj.timezone_at(lng=latitude, lat=longitude)", "e": 1265, "s": 1102, "text": null }, { "code": null, "e": 1273, "s": 1265, "text": "Output:" }, { "code": null, "e": 1289, "s": 1273, "text": "'Asia/Kolkata'\n" }, { "code": null, "e": 1354, "s": 1289, "text": "Now let write a script to get timezone with a specific location." }, { "code": null, "e": 1364, "s": 1354, "text": "Approach:" }, { "code": null, "e": 1382, "s": 1364, "text": "Import the module" }, { "code": null, "e": 1446, "s": 1382, "text": "Initialize Nominatim API to get location from the input string." }, { "code": null, "e": 1510, "s": 1446, "text": "Get latitude and longitude with geolocator.geocode() function." }, { "code": null, "e": 1618, "s": 1510, "text": "Pass the latitude and longitude in a timezone_at() method and it returns the time zone of a given location." }, { "code": null, "e": 1624, "s": 1618, "text": "Code:" }, { "code": null, "e": 1632, "s": 1624, "text": "Python3" }, { "code": "# importing modulefrom geopy.geocoders import Nominatimfrom timezonefinder import TimezoneFinder # initialize Nominatim APIgeolocator = Nominatim(user_agent=\"geoapiExercises\") # input as a geeklad = \"Dhaka\"print(\"Location address:\", lad) # getting Latitude and Longitudelocation = geolocator.geocode(lad) print(\"Latitude and Longitude of the said address:\")print((location.latitude, location.longitude)) # pass the Latitude and Longitude# into a timezone_at# and it return timezoneobj = TimezoneFinder() # returns 'Europe/Berlin'result = obj.timezone_at(lng=location.longitude, lat=location.latitude)print(\"Time Zone : \", result)", "e": 2268, "s": 1632, "text": null }, { "code": null, "e": 2276, "s": 2268, "text": "Output:" }, { "code": null, "e": 2393, "s": 2276, "text": "Location address: Dhaka\nLatitude and Longitude of the said address:\n(23.810651, 90.4126466)\nTime Zone : Asia/Dhaka\n" }, { "code": null, "e": 2402, "s": 2393, "text": "rkbhola5" }, { "code": null, "e": 2418, "s": 2402, "text": "Python-projects" }, { "code": null, "e": 2433, "s": 2418, "text": "python-utility" }, { "code": null, "e": 2440, "s": 2433, "text": "Python" }, { "code": null, "e": 2538, "s": 2440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2570, "s": 2538, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2597, "s": 2570, "text": "Python Classes and Objects" }, { "code": null, "e": 2618, "s": 2597, "text": "Python OOPs Concepts" }, { "code": null, "e": 2641, "s": 2618, "text": "Introduction To PYTHON" }, { "code": null, "e": 2697, "s": 2641, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2728, "s": 2697, "text": "Python | os.path.join() method" }, { "code": null, "e": 2770, "s": 2728, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2812, "s": 2770, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2851, "s": 2812, "text": "Python | datetime.timedelta() function" } ]
Program to check if a matrix is symmetric
30 Apr, 2021 A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row. Examples: Input : 1 2 3 2 1 4 3 4 3 Output : Yes Input : 3 5 8 3 4 7 8 5 3 Output : No A Simple solution is to do following. 1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not, C++ Java Python C# PHP Javascript // Simple c++ code for check a matrix is// symmetric or not.#include <iostream>using namespace std; const int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N]void transpose(int mat[][MAX], int tr[][MAX], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is symmetric, else falsebool isSymmetric(int mat[][MAX], int N){ int tr[N][MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver codeint main(){ int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << "Yes"; else cout << "No"; return 0;} // Simple java code for check a matrix is// symmetric or not. import java.io.*; class GFG { static int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N] static void transpose(int mat[][], int tr[][], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is symmetric, else false static boolean isSymmetric(int mat[][], int N){ int tr[][] = new int[N][MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver code public static void main (String[] args) { int mat[][] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) System.out.println( "Yes"); else System.out.println ( "No"); }} # Simple Python code for check a matrix is# symmetric or not. # Fills transpose of mat[N][N] in tr[N][N]def transpose(mat, tr, N): for i in range(N): for j in range(N): tr[i][j] = mat[j][i] # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N): tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ] transpose(mat, tr, N) for i in range(N): for j in range(N): if (mat[i][j] != tr[i][j]): return False return True # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)): print "Yes"else: print "No" # This code is contributed by Sachin Bisht // Simple C# code for check a matrix is// symmetric or not. using System; class GFG { static int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N] static void transpose(int [,]mat, int [,]tr, int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i,j] = mat[j,i]; } // Returns true if mat[N][N] is symmetric, else false static bool isSymmetric(int [,]mat, int N) { int [,]tr = new int[N,MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i,j] != tr[i,j]) return false; return true; } // Driver code public static void Main () { int [,]mat = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) Console.WriteLine( "Yes"); else Console.WriteLine( "No"); }} // This code is contributed by vt_m. <?php// Simple PHP code for check a matrix is// symmetric or not. // Returns true if mat[N][N] is// symmetric, else falsefunction isSymmetric($mat, $N){ $tr = array(array()); for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $tr[$i][$j] = $mat[$j][$i]; // Fills transpose of // mat[N][N] in tr[N][N] for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if ($mat[$i][$j] != $tr[$i][$j]) return false; return true;} // Driver code $mat= array(array(1, 3, 5), array(3, 2, 4), array(5, 4, 1)); if (isSymmetric($mat, 3)) echo "Yes"; else echo "No"; // This code is contributed by Sam007?> <script> // Simple javascript code for check// a matrix is symmetric or not.let MAX = 100; // Fills transpose of mat[N][N] in tr[N][N]function transpose(mat, tr, N){ for(let i = 0; i < N; i++) for(let j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is// symmetric, else falsefunction isSymmetric(mat, N){ let tr = new Array(N); for(let i = 0; i < N; i++) { tr[i] = new Array(MAX); } transpose(mat, tr, N); for(let i = 0; i < N; i++) for(let j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver codelet mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]; if (isSymmetric(mat, 3)) document.write("Yes");else document.write("No"); // This code is contributed by decode2207 </script> Output : Yes Time Complexity : O(N x N) Auxiliary Space : O(N x N) An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i]. C++ Java Python C# PHP Javascript // Efficient c++ code for check a matrix is// symmetric or not.#include <iostream>using namespace std; const int MAX = 100; // Returns true if mat[N][N] is symmetric, else falsebool isSymmetric(int mat[][MAX], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Driver codeint main(){ int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << "Yes"; else cout << "No"; return 0;} // Efficient Java code for check a matrix is// symmetric or no import java.io.*; class GFG { static int MAX = 100; // Returns true if mat[N][N]// is symmetric, else false static boolean isSymmetric(int mat[][], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Driver code public static void main (String[] args) { int mat[][] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) System.out.println( "Yes"); else System.out.println("NO"); }}// This article is contributed by vt_m. # Efficient Python code for check a matrix is# symmetric or not. # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N): for i in range(N): for j in range(N): if (mat[i][j] != mat[j][i]): return False return True # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)): print "Yes"else: print "No" # This code is contributed by Sachin Bisht // Efficient C# code for check a matrix is// symmetric or no using System; class GFG{ //static int MAX = 100; // Returns true if mat[N][N] // is symmetric, else false static bool isSymmetric(int [,]mat, int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i, j] != mat[j, i]) return false; return true; } // Driver code public static void Main () { int [,]mat = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) Console.WriteLine( "Yes"); else Console.WriteLine("NO"); }} // This code is contributed by vt_m. <?php// Efficient PHP code for// check a matrix is// symmetric or not. $MAX = 100; // Returns true if mat[N][N]// is symmetric, else falsefunction isSymmetric($mat, $N){ for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if ($mat[$i][$j] != $mat[$j][$i]) return false; return true;} // Driver code$mat = array(array(1, 3, 5), array(3, 2, 4), array(5, 4, 1)); if (isSymmetric($mat, 3)) echo("Yes");else echo("No"); // This code is contributed by Ajit.?> <script> // Efficient Javascript code for check a matrix is symmetric or no let MAX = 100; // Returns true if mat[N][N] // is symmetric, else false function isSymmetric(mat, N) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true; } let mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]; if (isSymmetric(mat, 3)) document.write( "Yes"); else document.write("NO"); </script> Output: Yes Time Complexity : O(N x N) Auxiliary Space : O(1) This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. jit_t Sam007 mukesh07 decode2207 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 The Celebrity Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Unique paths in a Grid with Obstacles Maximum size rectangle binary sub-matrix with all 1s Inplace rotate square matrix by 90 degrees | Set 1 Printing all solutions in N-Queen Problem Count all possible paths from top left to bottom right of a mXn matrix Search in a row wise and column wise sorted matrix Gold Mine Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Apr, 2021" }, { "code": null, "e": 235, "s": 52, "text": "A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row." }, { "code": null, "e": 246, "s": 235, "text": "Examples: " }, { "code": null, "e": 356, "s": 246, "text": "Input : 1 2 3\n 2 1 4\n 3 4 3\nOutput : Yes\n\nInput : 3 5 8\n 3 4 7\n 8 5 3\nOutput : No" }, { "code": null, "e": 395, "s": 356, "text": "A Simple solution is to do following. " }, { "code": null, "e": 492, "s": 395, "text": "1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not, " }, { "code": null, "e": 496, "s": 492, "text": "C++" }, { "code": null, "e": 501, "s": 496, "text": "Java" }, { "code": null, "e": 508, "s": 501, "text": "Python" }, { "code": null, "e": 511, "s": 508, "text": "C#" }, { "code": null, "e": 515, "s": 511, "text": "PHP" }, { "code": null, "e": 526, "s": 515, "text": "Javascript" }, { "code": "// Simple c++ code for check a matrix is// symmetric or not.#include <iostream>using namespace std; const int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N]void transpose(int mat[][MAX], int tr[][MAX], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is symmetric, else falsebool isSymmetric(int mat[][MAX], int N){ int tr[N][MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver codeint main(){ int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 1360, "s": 526, "text": null }, { "code": "// Simple java code for check a matrix is// symmetric or not. import java.io.*; class GFG { static int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N] static void transpose(int mat[][], int tr[][], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is symmetric, else false static boolean isSymmetric(int mat[][], int N){ int tr[][] = new int[N][MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver code public static void main (String[] args) { int mat[][] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) System.out.println( \"Yes\"); else System.out.println ( \"No\"); }}", "e": 2281, "s": 1360, "text": null }, { "code": "# Simple Python code for check a matrix is# symmetric or not. # Fills transpose of mat[N][N] in tr[N][N]def transpose(mat, tr, N): for i in range(N): for j in range(N): tr[i][j] = mat[j][i] # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N): tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ] transpose(mat, tr, N) for i in range(N): for j in range(N): if (mat[i][j] != tr[i][j]): return False return True # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)): print \"Yes\"else: print \"No\" # This code is contributed by Sachin Bisht", "e": 2965, "s": 2281, "text": null }, { "code": "// Simple C# code for check a matrix is// symmetric or not. using System; class GFG { static int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N] static void transpose(int [,]mat, int [,]tr, int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i,j] = mat[j,i]; } // Returns true if mat[N][N] is symmetric, else false static bool isSymmetric(int [,]mat, int N) { int [,]tr = new int[N,MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i,j] != tr[i,j]) return false; return true; } // Driver code public static void Main () { int [,]mat = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) Console.WriteLine( \"Yes\"); else Console.WriteLine( \"No\"); }} // This code is contributed by vt_m.", "e": 4015, "s": 2965, "text": null }, { "code": "<?php// Simple PHP code for check a matrix is// symmetric or not. // Returns true if mat[N][N] is// symmetric, else falsefunction isSymmetric($mat, $N){ $tr = array(array()); for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $tr[$i][$j] = $mat[$j][$i]; // Fills transpose of // mat[N][N] in tr[N][N] for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if ($mat[$i][$j] != $tr[$i][$j]) return false; return true;} // Driver code $mat= array(array(1, 3, 5), array(3, 2, 4), array(5, 4, 1)); if (isSymmetric($mat, 3)) echo \"Yes\"; else echo \"No\"; // This code is contributed by Sam007?>", "e": 4756, "s": 4015, "text": null }, { "code": "<script> // Simple javascript code for check// a matrix is symmetric or not.let MAX = 100; // Fills transpose of mat[N][N] in tr[N][N]function transpose(mat, tr, N){ for(let i = 0; i < N; i++) for(let j = 0; j < N; j++) tr[i][j] = mat[j][i];} // Returns true if mat[N][N] is// symmetric, else falsefunction isSymmetric(mat, N){ let tr = new Array(N); for(let i = 0; i < N; i++) { tr[i] = new Array(MAX); } transpose(mat, tr, N); for(let i = 0; i < N; i++) for(let j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true;} // Driver codelet mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]; if (isSymmetric(mat, 3)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by decode2207 </script>", "e": 5624, "s": 4756, "text": null }, { "code": null, "e": 5634, "s": 5624, "text": "Output : " }, { "code": null, "e": 5639, "s": 5634, "text": " Yes" }, { "code": null, "e": 5693, "s": 5639, "text": "Time Complexity : O(N x N) Auxiliary Space : O(N x N)" }, { "code": null, "e": 5870, "s": 5693, "text": "An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i]. " }, { "code": null, "e": 5874, "s": 5870, "text": "C++" }, { "code": null, "e": 5879, "s": 5874, "text": "Java" }, { "code": null, "e": 5886, "s": 5879, "text": "Python" }, { "code": null, "e": 5889, "s": 5886, "text": "C#" }, { "code": null, "e": 5893, "s": 5889, "text": "PHP" }, { "code": null, "e": 5904, "s": 5893, "text": "Javascript" }, { "code": "// Efficient c++ code for check a matrix is// symmetric or not.#include <iostream>using namespace std; const int MAX = 100; // Returns true if mat[N][N] is symmetric, else falsebool isSymmetric(int mat[][MAX], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Driver codeint main(){ int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 6500, "s": 5904, "text": null }, { "code": "// Efficient Java code for check a matrix is// symmetric or no import java.io.*; class GFG { static int MAX = 100; // Returns true if mat[N][N]// is symmetric, else false static boolean isSymmetric(int mat[][], int N){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Driver code public static void main (String[] args) { int mat[][] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) System.out.println( \"Yes\"); else System.out.println(\"NO\"); }}// This article is contributed by vt_m.", "e": 7214, "s": 6500, "text": null }, { "code": "# Efficient Python code for check a matrix is# symmetric or not. # Returns true if mat[N][N] is symmetric, else falsedef isSymmetric(mat, N): for i in range(N): for j in range(N): if (mat[i][j] != mat[j][i]): return False return True # Driver codemat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]if (isSymmetric(mat, 3)): print \"Yes\"else: print \"No\" # This code is contributed by Sachin Bisht", "e": 7651, "s": 7214, "text": null }, { "code": "// Efficient C# code for check a matrix is// symmetric or no using System; class GFG{ //static int MAX = 100; // Returns true if mat[N][N] // is symmetric, else false static bool isSymmetric(int [,]mat, int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i, j] != mat[j, i]) return false; return true; } // Driver code public static void Main () { int [,]mat = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) Console.WriteLine( \"Yes\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by vt_m.", "e": 8401, "s": 7651, "text": null }, { "code": "<?php// Efficient PHP code for// check a matrix is// symmetric or not. $MAX = 100; // Returns true if mat[N][N]// is symmetric, else falsefunction isSymmetric($mat, $N){ for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if ($mat[$i][$j] != $mat[$j][$i]) return false; return true;} // Driver code$mat = array(array(1, 3, 5), array(3, 2, 4), array(5, 4, 1)); if (isSymmetric($mat, 3)) echo(\"Yes\");else echo(\"No\"); // This code is contributed by Ajit.?>", "e": 8928, "s": 8401, "text": null }, { "code": "<script> // Efficient Javascript code for check a matrix is symmetric or no let MAX = 100; // Returns true if mat[N][N] // is symmetric, else false function isSymmetric(mat, N) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true; } let mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]; if (isSymmetric(mat, 3)) document.write( \"Yes\"); else document.write(\"NO\"); </script>", "e": 9518, "s": 8928, "text": null }, { "code": null, "e": 9527, "s": 9518, "text": "Output: " }, { "code": null, "e": 9531, "s": 9527, "text": "Yes" }, { "code": null, "e": 9581, "s": 9531, "text": "Time Complexity : O(N x N) Auxiliary Space : O(1)" }, { "code": null, "e": 10005, "s": 9581, "text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 10011, "s": 10005, "text": "jit_t" }, { "code": null, "e": 10018, "s": 10011, "text": "Sam007" }, { "code": null, "e": 10027, "s": 10018, "text": "mukesh07" }, { "code": null, "e": 10038, "s": 10027, "text": "decode2207" }, { "code": null, "e": 10045, "s": 10038, "text": "Matrix" }, { "code": null, "e": 10052, "s": 10045, "text": "Matrix" }, { "code": null, "e": 10150, "s": 10052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10174, "s": 10150, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 10196, "s": 10174, "text": "The Celebrity Problem" }, { "code": null, "e": 10278, "s": 10196, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 10316, "s": 10278, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 10369, "s": 10316, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 10420, "s": 10369, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 10462, "s": 10420, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 10533, "s": 10462, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 10584, "s": 10533, "text": "Search in a row wise and column wise sorted matrix" } ]
NLP | Chunking and chinking with RegEx
27 Sep, 2021 Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. A ChunkRule class specifies what words or patterns to include and exclude in a chunk. Defining Chunk patterns : Chuck patterns are normal regular expressions which are modified and designed to match the part-of-speech tag designed to match sequences of part-of-speech tags. Angle brackets are used to specify an individual tag for example – to match a noun tag. One can define multiple tags in the same way. Code #1 : Converting chunks to RegEx Pattern. Python3 # Laading Libraryfrom nltk.chunk.regexp import tag_pattern2re_pattern # Chunk Pattern to RegEx Patternprint("Chunk Pattern : ", tag_pattern2re_pattern('<DT>?<NN.*>+')) Output : Chunk Pattern : ()?(<(NN[^\{\}]*)>)+ Curly Braces are used to specify a chunk like {} and to specify the chink pattern one can just flip the braces }{. For a particular phrase type, these rules (chunk and a chink pattern) can be combined into grammar. Code #2 : Parsing the sentence with RegExParser. Python3 from nltk.chunk import RegexpParser # Introducing the Patternchunker = RegexpParser(r'''NP:{<DT><NN.*><.*>*<NN.*>}}<VB.*>{''') chunker.parse([('the', 'DT'), ('book', 'NN'), ( 'has', 'VBZ'), ('many', 'JJ'), ('chapters', 'NNS')]) Output : Tree('S', [Tree('NP', [('the', 'DT'), ('book', 'NN')]), ('has', 'VBZ'), Tree('NP', [('many', 'JJ'), ('chapters', 'NNS')])]) sumitgumber28 anikakapoor Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Search Algorithms in AI Decision Tree Introduction with example Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 450, "s": 28, "text": "Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. A ChunkRule class specifies what words or patterns to include and exclude in a chunk. " }, { "code": null, "e": 773, "s": 450, "text": "Defining Chunk patterns : Chuck patterns are normal regular expressions which are modified and designed to match the part-of-speech tag designed to match sequences of part-of-speech tags. Angle brackets are used to specify an individual tag for example – to match a noun tag. One can define multiple tags in the same way. " }, { "code": null, "e": 820, "s": 773, "text": "Code #1 : Converting chunks to RegEx Pattern. " }, { "code": null, "e": 828, "s": 820, "text": "Python3" }, { "code": "# Laading Libraryfrom nltk.chunk.regexp import tag_pattern2re_pattern # Chunk Pattern to RegEx Patternprint(\"Chunk Pattern : \", tag_pattern2re_pattern('<DT>?<NN.*>+'))", "e": 996, "s": 828, "text": null }, { "code": null, "e": 1006, "s": 996, "text": "Output : " }, { "code": null, "e": 1044, "s": 1006, "text": "Chunk Pattern : ()?(<(NN[^\\{\\}]*)>)+" }, { "code": null, "e": 1259, "s": 1044, "text": "Curly Braces are used to specify a chunk like {} and to specify the chink pattern one can just flip the braces }{. For a particular phrase type, these rules (chunk and a chink pattern) can be combined into grammar." }, { "code": null, "e": 1310, "s": 1259, "text": "Code #2 : Parsing the sentence with RegExParser. " }, { "code": null, "e": 1318, "s": 1310, "text": "Python3" }, { "code": "from nltk.chunk import RegexpParser # Introducing the Patternchunker = RegexpParser(r'''NP:{<DT><NN.*><.*>*<NN.*>}}<VB.*>{''') chunker.parse([('the', 'DT'), ('book', 'NN'), ( 'has', 'VBZ'), ('many', 'JJ'), ('chapters', 'NNS')])", "e": 1549, "s": 1318, "text": null }, { "code": null, "e": 1559, "s": 1549, "text": "Output : " }, { "code": null, "e": 1684, "s": 1559, "text": "Tree('S', [Tree('NP', [('the', 'DT'), ('book', 'NN')]), ('has', 'VBZ'), \nTree('NP', [('many', 'JJ'), ('chapters', 'NNS')])])" }, { "code": null, "e": 1700, "s": 1686, "text": "sumitgumber28" }, { "code": null, "e": 1712, "s": 1700, "text": "anikakapoor" }, { "code": null, "e": 1740, "s": 1712, "text": "Natural-language-processing" }, { "code": null, "e": 1752, "s": 1740, "text": "Python-nltk" }, { "code": null, "e": 1769, "s": 1752, "text": "Machine Learning" }, { "code": null, "e": 1776, "s": 1769, "text": "Python" }, { "code": null, "e": 1793, "s": 1776, "text": "Machine Learning" }, { "code": null, "e": 1891, "s": 1793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1914, "s": 1891, "text": "ML | Linear Regression" }, { "code": null, "e": 1937, "s": 1914, "text": "Reinforcement learning" }, { "code": null, "e": 1974, "s": 1937, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 1998, "s": 1974, "text": "Search Algorithms in AI" }, { "code": null, "e": 2038, "s": 1998, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2066, "s": 2038, "text": "Read JSON file using Python" }, { "code": null, "e": 2116, "s": 2066, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2138, "s": 2116, "text": "Python map() function" } ]
Python | Keys with Maximum value
23 Jan, 2020 Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the maximum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, maximum value is extracted using the max function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with max value. # Python3 code to demonstrate working of# Keys with Maximum value# Using max() + list comprehension + values() # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using max() + list comprehension + values()# Keys with Maximum valuetemp = max(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp] # printing result print("Keys with maximum values are : " + str(res)) The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1} Keys with maximum values are : ['CS', 'Gfg'] Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are smaller than values with keys and return the keys with largest values using list comprehension. # Python3 code to demonstrate working of# Keys with Maximum value# Using all() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using all() + list comprehension# Keys with Maximum valueres = [key for key in test_dict if all(test_dict[temp] <= test_dict[key] for temp in test_dict)] # printing result print("Keys with maximum values are : " + str(res)) The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1} Keys with maximum values are : ['CS', 'Gfg'] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 246, "s": 28, "text": "Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the maximum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 596, "s": 246, "text": "Method #1 : Using max() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, maximum value is extracted using the max function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with max value." }, { "code": "# Python3 code to demonstrate working of# Keys with Maximum value# Using max() + list comprehension + values() # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using max() + list comprehension + values()# Keys with Maximum valuetemp = max(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp] # printing result print(\"Keys with maximum values are : \" + str(res))", "e": 1096, "s": 596, "text": null }, { "code": null, "e": 1201, "s": 1096, "text": "The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1}\nKeys with maximum values are : ['CS', 'Gfg']\n" }, { "code": null, "e": 1488, "s": 1203, "text": "Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are smaller than values with keys and return the keys with largest values using list comprehension." }, { "code": "# Python3 code to demonstrate working of# Keys with Maximum value# Using all() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using all() + list comprehension# Keys with Maximum valueres = [key for key in test_dict if all(test_dict[temp] <= test_dict[key] for temp in test_dict)] # printing result print(\"Keys with maximum values are : \" + str(res))", "e": 1974, "s": 1488, "text": null }, { "code": null, "e": 2079, "s": 1974, "text": "The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1}\nKeys with maximum values are : ['CS', 'Gfg']\n" }, { "code": null, "e": 2106, "s": 2079, "text": "Python dictionary-programs" }, { "code": null, "e": 2113, "s": 2106, "text": "Python" }, { "code": null, "e": 2129, "s": 2113, "text": "Python Programs" }, { "code": null, "e": 2227, "s": 2129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2245, "s": 2227, "text": "Python Dictionary" }, { "code": null, "e": 2287, "s": 2245, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2322, "s": 2287, "text": "Read a file line by line in Python" }, { "code": null, "e": 2348, "s": 2322, "text": "Python String | replace()" }, { "code": null, "e": 2380, "s": 2348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2423, "s": 2380, "text": "Python program to convert a list to string" }, { "code": null, "e": 2445, "s": 2423, "text": "Defaultdict in Python" }, { "code": null, "e": 2484, "s": 2445, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2522, "s": 2484, "text": "Python | Convert a list to dictionary" } ]
How to share data between controllers in AngularJS ?
30 Jan, 2020 The task is to share data variable between two or more controllers by using AngularJS. There are many procedures to achieve this. Here we will discuss the most popular ones. Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller. Share data between controllers without having relation: Here, the sharing of data can be done through a few ways some of them are:By using rootScope variable: We can use the rootScope variable to hold shared data and then can reference it from any controller. Here, at the starting of the Angular app, we initialized the rootScope variable with some value and then refer it from every controller and thus bind scope variables in both controllers to the rootScope variable.Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="firstcontroller"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller="secondcontroller"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> Output:By using factory or service: The $rootscope method is not preferred for data transfer or sharing data because it has a global scope that is available for the entire application. So, we use another method in which we create a factory or service to hold share data. AngularJS factories and services are JS functions that perform a specific task containing both methods & properties and can be injected in other components (e.g. your controllers) using dependency injection. In this way we can define a shared variable in a factory, inject it in both controllers and thus bind scope variables in both controllers to this factory data.Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="FirstController"> <input type="text" ng-model="value.name"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller="SecondController"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> Output:My Personal Notes arrow_drop_upSave By using rootScope variable: We can use the rootScope variable to hold shared data and then can reference it from any controller. Here, at the starting of the Angular app, we initialized the rootScope variable with some value and then refer it from every controller and thus bind scope variables in both controllers to the rootScope variable. Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="firstcontroller"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller="secondcontroller"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> <!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="firstcontroller"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller="secondcontroller"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> Output: By using factory or service: The $rootscope method is not preferred for data transfer or sharing data because it has a global scope that is available for the entire application. So, we use another method in which we create a factory or service to hold share data. AngularJS factories and services are JS functions that perform a specific task containing both methods & properties and can be injected in other components (e.g. your controllers) using dependency injection. In this way we can define a shared variable in a factory, inject it in both controllers and thus bind scope variables in both controllers to this factory data. Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="FirstController"> <input type="text" ng-model="value.name"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller="SecondController"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> <!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <div ng-app="mainApp"> <div ng-controller="FirstController"> <input type="text" ng-model="value.name"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller="SecondController"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module("mainApp", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> Output: AngularJS-Misc Picked Technical Scripter 2019 AngularJS Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 202, "s": 28, "text": "The task is to share data variable between two or more controllers by using AngularJS. There are many procedures to achieve this. Here we will discuss the most popular ones." }, { "code": null, "e": 287, "s": 202, "text": "Approach: To share data between the controllers in AngularJS we have two main cases:" }, { "code": null, "e": 486, "s": 287, "text": "Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller." }, { "code": null, "e": 3919, "s": 486, "text": "Share data between controllers without having relation: Here, the sharing of data can be done through a few ways some of them are:By using rootScope variable: We can use the rootScope variable to hold shared data and then can reference it from any controller. Here, at the starting of the Angular app, we initialized the rootScope variable with some value and then refer it from every controller and thus bind scope variables in both controllers to the rootScope variable.Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"firstcontroller\"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller=\"secondcontroller\"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> Output:By using factory or service: The $rootscope method is not preferred for data transfer or sharing data because it has a global scope that is available for the entire application. So, we use another method in which we create a factory or service to hold share data. AngularJS factories and services are JS functions that perform a specific task containing both methods & properties and can be injected in other components (e.g. your controllers) using dependency injection. In this way we can define a shared variable in a factory, inject it in both controllers and thus bind scope variables in both controllers to this factory data.Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"FirstController\"> <input type=\"text\" ng-model=\"value.name\"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller=\"SecondController\"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 4262, "s": 3919, "text": "By using rootScope variable: We can use the rootScope variable to hold shared data and then can reference it from any controller. Here, at the starting of the Angular app, we initialized the rootScope variable with some value and then refer it from every controller and thus bind scope variables in both controllers to the rootScope variable." }, { "code": null, "e": 5412, "s": 4262, "text": "Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"firstcontroller\"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller=\"secondcontroller\"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> " }, { "code": "<!DOCTYPE html><html> <head> <title> Angular JS sharing data using rootScope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"firstcontroller\"> <h2>First controller</h2> <p>{{firstvalue}}</p> </div> <div ng-controller=\"secondcontroller\"> <h2>Second controller</h2> <p>{{secondvalue}}</p> </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.run(function($rootScope) { $rootScope.value = 'A Computer Science Portal for Geeks'; }); mainApp.controller('firstcontroller', function($scope, $rootScope) { $scope.firstvalue = $rootScope.value; }); mainApp.controller('secondcontroller', function($scope, $rootScope) { $scope.secondvalue = $rootScope.value; }); </script></body> </html> ", "e": 6554, "s": 5412, "text": null }, { "code": null, "e": 6562, "s": 6554, "text": "Output:" }, { "code": null, "e": 7194, "s": 6562, "text": "By using factory or service: The $rootscope method is not preferred for data transfer or sharing data because it has a global scope that is available for the entire application. So, we use another method in which we create a factory or service to hold share data. AngularJS factories and services are JS functions that perform a specific task containing both methods & properties and can be injected in other components (e.g. your controllers) using dependency injection. In this way we can define a shared variable in a factory, inject it in both controllers and thus bind scope variables in both controllers to this factory data." }, { "code": null, "e": 8326, "s": 7194, "text": "Example:<!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"FirstController\"> <input type=\"text\" ng-model=\"value.name\"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller=\"SecondController\"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> " }, { "code": "<!DOCTYPE html><html> <head> <title> Angular JS sharing data using factory </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div ng-app=\"mainApp\"> <div ng-controller=\"FirstController\"> <input type=\"text\" ng-model=\"value.name\"> <br> Input in first controller is : {{value.name}} </div> <hr> <div ng-controller=\"SecondController\"> Input in second controller is : {{value.name}} </div> </div> <script> var mainApp = angular.module(\"mainApp\", []); mainApp.factory('Fact', function() { return { name: '' }; }); mainApp.controller('FirstController', function($scope, Fact) { $scope.value = Fact; }); mainApp.controller('SecondController', function($scope, Fact) { $scope.value = Fact; }); </script></body> </html> ", "e": 9450, "s": 8326, "text": null }, { "code": null, "e": 9458, "s": 9450, "text": "Output:" }, { "code": null, "e": 9473, "s": 9458, "text": "AngularJS-Misc" }, { "code": null, "e": 9480, "s": 9473, "text": "Picked" }, { "code": null, "e": 9504, "s": 9480, "text": "Technical Scripter 2019" }, { "code": null, "e": 9514, "s": 9504, "text": "AngularJS" }, { "code": null, "e": 9533, "s": 9514, "text": "Technical Scripter" }, { "code": null, "e": 9550, "s": 9533, "text": "Web Technologies" }, { "code": null, "e": 9577, "s": 9550, "text": "Web technologies Questions" }, { "code": null, "e": 9675, "s": 9577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9706, "s": 9675, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 9730, "s": 9706, "text": "Routing in Angular 9/10" }, { "code": null, "e": 9772, "s": 9730, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 9807, "s": 9772, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 9881, "s": 9807, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 9943, "s": 9881, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9976, "s": 9943, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 10037, "s": 9976, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 10087, "s": 10037, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | functools.wraps() function
23 Sep, 2021 functools is a standard Python module for higher-order functions (functions that act on or return other functions). wraps() is a decorator that is applied to the wrapper function of a decorator. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __doc__ (the docstring), etc. Syntax: @functools.wraps(wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES)Parameters: wrapped: The function name that is to be decorated by wrapper function. assigned : Tuple to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function. By default set to WRAPPER_ASSIGNMENTS (which assigns to the wrapper function’s __module__, __name__, __qualname__, __annotations__ and __doc__, the documentation string) updated : Tuple to specify which attributes of the wrapper function are updated with the corresponding attributes from the original function. By default set to WRAPPER_UPDATES (which updates the wrapper function’s __dict__, i.e. the instance dictionary). Example 1: Without functools.wraps() Python3 def a_decorator(func): def wrapper(*args, **kwargs): """A wrapper function""" # Extend some capabilities of func func() return wrapper @a_decoratordef first_function(): """This is docstring for first function""" print("first function") @a_decoratordef second_function(a): """This is docstring for second function""" print("second function") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__) wrapper A wrapper function wrapper A wrapper function Now what will happen if we write help(first_function) and help(second_function) Python3 print("First Function")help(first_function) print("\nSecond Function")help(second_function) First Function Help on function wrapper in module __main__: wrapper(*args, **kwargs) A wrapper function Second Function Help on function wrapper in module __main__: wrapper(*args, **kwargs) A wrapper function While the above code will work logically fine, but consider this if you are writing an API or a library and someone want to know what your function does and it’s name or simply type help(yourFunction), it will always show wrapper function’s name and docstring. This gets more confusing if you have used the same wrapper function for different functions, as it will show the same details for each one of them. Ideally it should show the name and docstring of wrapped function instead of wrapping function. Manual solution would be to assign __name__, __doc__ attributes in the wrapping function before returning it. Python3 def a_decorator(func): def wrapper(*args, **kwargs): """A wrapper function""" # Extend some capabilities of func func() wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ return wrapper @a_decoratordef first_function(): """This is docstring for first function""" print("first function") @a_decoratordef second_function(a): """This is docstring for second function""" print("second function") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__) first_function This is docstring for first function second_function This is docstring for second function This solves the problem, but what if we again type help(yourFunction), Python3 print("First Function")help(first_function) print("\nSecond Function")help(second_function) For first_function: help(first_function) First Function Help on function first_function in module __main__: first_function(*args, **kwargs) This is docstring for first function Second Function Help on function second_function in module __main__: second_function(*args, **kwargs) This is docstring for second function As you can see it still has an issue, i.e. the signature of the function, it is showing signature used by wrapper function (here, generic signature) for each of them. Also if you are implementing many decorators, then you have to write these lines for each one of them. So to save time and increase readability, we could use functools.wraps() as decorator to wrapper function.Example (with functools.wraps()) Python3 from functools import wraps def a_decorator(func): @wraps(func) def wrapper(*args, **kwargs): """A wrapper function""" # Extend some capabilities of func func() return wrapper @a_decoratordef first_function(): """This is docstring for first function""" print("first function") @a_decoratordef second_function(a): """This is docstring for second function""" print("second function") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__) first_function This is docstring for first function second_function This is docstring for second function Now, if we type help(first_function) – Python3 print("First Function")help(first_function) print("\nSecond Function")help(second_function) First Function Help on function first_function in module __main__: first_function() This is docstring for first function Second Function Help on function second_function in module __main__: second_function(a) This is docstring for second function gabaa406 Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Sep, 2021" }, { "code": null, "e": 380, "s": 52, "text": "functools is a standard Python module for higher-order functions (functions that act on or return other functions). wraps() is a decorator that is applied to the wrapper function of a decorator. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __doc__ (the docstring), etc. " }, { "code": null, "e": 1127, "s": 380, "text": "Syntax: @functools.wraps(wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES)Parameters: wrapped: The function name that is to be decorated by wrapper function. assigned : Tuple to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function. By default set to WRAPPER_ASSIGNMENTS (which assigns to the wrapper function’s __module__, __name__, __qualname__, __annotations__ and __doc__, the documentation string) updated : Tuple to specify which attributes of the wrapper function are updated with the corresponding attributes from the original function. By default set to WRAPPER_UPDATES (which updates the wrapper function’s __dict__, i.e. the instance dictionary). " }, { "code": null, "e": 1165, "s": 1127, "text": "Example 1: Without functools.wraps() " }, { "code": null, "e": 1173, "s": 1165, "text": "Python3" }, { "code": "def a_decorator(func): def wrapper(*args, **kwargs): \"\"\"A wrapper function\"\"\" # Extend some capabilities of func func() return wrapper @a_decoratordef first_function(): \"\"\"This is docstring for first function\"\"\" print(\"first function\") @a_decoratordef second_function(a): \"\"\"This is docstring for second function\"\"\" print(\"second function\") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__)", "e": 1674, "s": 1173, "text": null }, { "code": null, "e": 1728, "s": 1674, "text": "wrapper\nA wrapper function\nwrapper\nA wrapper function" }, { "code": null, "e": 1811, "s": 1730, "text": "Now what will happen if we write help(first_function) and help(second_function) " }, { "code": null, "e": 1819, "s": 1811, "text": "Python3" }, { "code": "print(\"First Function\")help(first_function) print(\"\\nSecond Function\")help(second_function)", "e": 1911, "s": 1819, "text": null }, { "code": null, "e": 2132, "s": 1911, "text": "First Function\nHelp on function wrapper in module __main__:\n\nwrapper(*args, **kwargs)\n A wrapper function\n\n\nSecond Function\nHelp on function wrapper in module __main__:\n\nwrapper(*args, **kwargs)\n A wrapper function" }, { "code": null, "e": 2750, "s": 2134, "text": "While the above code will work logically fine, but consider this if you are writing an API or a library and someone want to know what your function does and it’s name or simply type help(yourFunction), it will always show wrapper function’s name and docstring. This gets more confusing if you have used the same wrapper function for different functions, as it will show the same details for each one of them. Ideally it should show the name and docstring of wrapped function instead of wrapping function. Manual solution would be to assign __name__, __doc__ attributes in the wrapping function before returning it. " }, { "code": null, "e": 2758, "s": 2750, "text": "Python3" }, { "code": "def a_decorator(func): def wrapper(*args, **kwargs): \"\"\"A wrapper function\"\"\" # Extend some capabilities of func func() wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ return wrapper @a_decoratordef first_function(): \"\"\"This is docstring for first function\"\"\" print(\"first function\") @a_decoratordef second_function(a): \"\"\"This is docstring for second function\"\"\" print(\"second function\") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__)", "e": 3329, "s": 2758, "text": null }, { "code": null, "e": 3435, "s": 3329, "text": "first_function\nThis is docstring for first function\nsecond_function\nThis is docstring for second function" }, { "code": null, "e": 3509, "s": 3437, "text": "This solves the problem, but what if we again type help(yourFunction), " }, { "code": null, "e": 3517, "s": 3509, "text": "Python3" }, { "code": "print(\"First Function\")help(first_function) print(\"\\nSecond Function\")help(second_function)", "e": 3609, "s": 3517, "text": null }, { "code": null, "e": 3652, "s": 3609, "text": "For first_function: help(first_function) " }, { "code": null, "e": 3940, "s": 3652, "text": "First Function\nHelp on function first_function in module __main__:\n\nfirst_function(*args, **kwargs)\n This is docstring for first function\n\n\nSecond Function\nHelp on function second_function in module __main__:\n\nsecond_function(*args, **kwargs)\n This is docstring for second function" }, { "code": null, "e": 4353, "s": 3942, "text": "As you can see it still has an issue, i.e. the signature of the function, it is showing signature used by wrapper function (here, generic signature) for each of them. Also if you are implementing many decorators, then you have to write these lines for each one of them. So to save time and increase readability, we could use functools.wraps() as decorator to wrapper function.Example (with functools.wraps()) " }, { "code": null, "e": 4361, "s": 4353, "text": "Python3" }, { "code": "from functools import wraps def a_decorator(func): @wraps(func) def wrapper(*args, **kwargs): \"\"\"A wrapper function\"\"\" # Extend some capabilities of func func() return wrapper @a_decoratordef first_function(): \"\"\"This is docstring for first function\"\"\" print(\"first function\") @a_decoratordef second_function(a): \"\"\"This is docstring for second function\"\"\" print(\"second function\") print(first_function.__name__)print(first_function.__doc__)print(second_function.__name__)print(second_function.__doc__)", "e": 4907, "s": 4361, "text": null }, { "code": null, "e": 5013, "s": 4907, "text": "first_function\nThis is docstring for first function\nsecond_function\nThis is docstring for second function" }, { "code": null, "e": 5055, "s": 5015, "text": "Now, if we type help(first_function) – " }, { "code": null, "e": 5063, "s": 5055, "text": "Python3" }, { "code": "print(\"First Function\")help(first_function) print(\"\\nSecond Function\")help(second_function)", "e": 5155, "s": 5063, "text": null }, { "code": null, "e": 5414, "s": 5155, "text": "First Function\nHelp on function first_function in module __main__:\n\nfirst_function()\n This is docstring for first function\n\n\nSecond Function\nHelp on function second_function in module __main__:\n\nsecond_function(a)\n This is docstring for second function" }, { "code": null, "e": 5425, "s": 5416, "text": "gabaa406" }, { "code": null, "e": 5443, "s": 5425, "text": "Python Decorators" }, { "code": null, "e": 5450, "s": 5443, "text": "Python" } ]
How to Do a vLookup in Python using pandas
06 Aug, 2021 Vlookup is essentially used for vertically arranged data. Vlookup is an operation used to merge 2 different data tables based on some condition where there must be at least 1 common attribute(column) between the two tables. After performing this operation we get a table consisting of all the data from both the tables for which the data is matched.We can use merge() function to perform Vlookup in pandas. The merge function does the same job as the Join in SQL We can perform the merge operation with respect to table 1 or table 2.There can be different ways of merging the 2 tables. Syntax: dataframe.merge(dataframe1, dataframe2, how, on, copy, indicator, suffixes, validate)Parameters: datafram1: dataframe object to be merged with. dataframe2: dataframe object to be merged. how: {left, right, inner, outer} specifies how merging will be done on: specifies column or index names used for performing join. suffixes: suffix used for overlapping columns.For exception use values (False, False). validate: If specified, checks the kind of merging.The type of merge could be (one-one, one-many, many-one, many-many). Let’s consider 2 tables on which the operation is to be performed. 1st table consists of the information of students and 2nd column consists of the information of the respective Courses they are enrolled in. The below code tells the information contained in both the tables. Python3 # import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') print(df1)print(df2) Output Inner join: Inner join produces an output data frame of only those rows for which the condition is satisfied in both the rows. To perform inner join you may specify inner as a keyword in how.Example: Python3 # import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') inner_join = pd.merge(df1, df2, on ='Name', how ='inner')inner_join Output Left join: Left join operation provides all the rows from 1st dataframe and matching rows from the 2nd dataframe. If the rows are not matched in the 2nd dataframe then they will be replaced by NaN.Example: Python3 # import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Left_join = pd.merge(df1, df2, on ='Name', how ='left')Left_join Output: Right join: Right join is somewhat similar to left join in which the output dataframe will consist of all the rows from the 2nd dataframe and matching rows from the 1st dataframe. If the rows are not matched in 1st row then they will be replaced by NaN Python3 # import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Right_join = pd.merge(df1, df2, on ='Name', how ='right')Right_join Output Outer join: Outer join provides the output dataframe consisting of rows from both the dataframes. Values will be shown if rows are matched otherwise NaN will be shown for rows that do not match.Example: Python3 # import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Outer_join = pd.merge(df1, df2, on ='Name', how ='outer')Outer_join Output Akanksha_Rai simmytarika5 rajeev0719singh Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2021" }, { "code": null, "e": 615, "s": 28, "text": "Vlookup is essentially used for vertically arranged data. Vlookup is an operation used to merge 2 different data tables based on some condition where there must be at least 1 common attribute(column) between the two tables. After performing this operation we get a table consisting of all the data from both the tables for which the data is matched.We can use merge() function to perform Vlookup in pandas. The merge function does the same job as the Join in SQL We can perform the merge operation with respect to table 1 or table 2.There can be different ways of merging the 2 tables. " }, { "code": null, "e": 1149, "s": 615, "text": "Syntax: dataframe.merge(dataframe1, dataframe2, how, on, copy, indicator, suffixes, validate)Parameters: datafram1: dataframe object to be merged with. dataframe2: dataframe object to be merged. how: {left, right, inner, outer} specifies how merging will be done on: specifies column or index names used for performing join. suffixes: suffix used for overlapping columns.For exception use values (False, False). validate: If specified, checks the kind of merging.The type of merge could be (one-one, one-many, many-one, many-many). " }, { "code": null, "e": 1425, "s": 1149, "text": "Let’s consider 2 tables on which the operation is to be performed. 1st table consists of the information of students and 2nd column consists of the information of the respective Courses they are enrolled in. The below code tells the information contained in both the tables. " }, { "code": null, "e": 1433, "s": 1425, "text": "Python3" }, { "code": "# import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') print(df1)print(df2)", "e": 1584, "s": 1433, "text": null }, { "code": null, "e": 1592, "s": 1584, "text": "Output " }, { "code": null, "e": 1797, "s": 1596, "text": "Inner join: Inner join produces an output data frame of only those rows for which the condition is satisfied in both the rows. To perform inner join you may specify inner as a keyword in how.Example: " }, { "code": null, "e": 1805, "s": 1797, "text": "Python3" }, { "code": "# import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') inner_join = pd.merge(df1, df2, on ='Name', how ='inner')inner_join", "e": 2071, "s": 1805, "text": null }, { "code": null, "e": 2078, "s": 2071, "text": "Output" }, { "code": null, "e": 2285, "s": 2078, "text": "Left join: Left join operation provides all the rows from 1st dataframe and matching rows from the 2nd dataframe. If the rows are not matched in the 2nd dataframe then they will be replaced by NaN.Example: " }, { "code": null, "e": 2293, "s": 2285, "text": "Python3" }, { "code": "# import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Left_join = pd.merge(df1, df2, on ='Name', how ='left')Left_join", "e": 2553, "s": 2293, "text": null }, { "code": null, "e": 2561, "s": 2553, "text": "Output:" }, { "code": null, "e": 2815, "s": 2561, "text": "Right join: Right join is somewhat similar to left join in which the output dataframe will consist of all the rows from the 2nd dataframe and matching rows from the 1st dataframe. If the rows are not matched in 1st row then they will be replaced by NaN " }, { "code": null, "e": 2823, "s": 2815, "text": "Python3" }, { "code": "# import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Right_join = pd.merge(df1, df2, on ='Name', how ='right')Right_join", "e": 3088, "s": 2823, "text": null }, { "code": null, "e": 3095, "s": 3088, "text": "Output" }, { "code": null, "e": 3299, "s": 3095, "text": "Outer join: Outer join provides the output dataframe consisting of rows from both the dataframes. Values will be shown if rows are matched otherwise NaN will be shown for rows that do not match.Example: " }, { "code": null, "e": 3307, "s": 3299, "text": "Python3" }, { "code": "# import pandasimport pandas as pd # read csv datadf1 = pd.read_csv('Student_data.csv')df2 = pd.read_csv('Course_enrolled.csv') Outer_join = pd.merge(df1, df2, on ='Name', how ='outer')Outer_join", "e": 3573, "s": 3307, "text": null }, { "code": null, "e": 3580, "s": 3573, "text": "Output" }, { "code": null, "e": 3593, "s": 3580, "text": "Akanksha_Rai" }, { "code": null, "e": 3606, "s": 3593, "text": "simmytarika5" }, { "code": null, "e": 3622, "s": 3606, "text": "rajeev0719singh" }, { "code": null, "e": 3636, "s": 3622, "text": "Python-pandas" }, { "code": null, "e": 3643, "s": 3636, "text": "Python" }, { "code": null, "e": 3741, "s": 3643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3783, "s": 3741, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3805, "s": 3783, "text": "Enumerate() in Python" }, { "code": null, "e": 3837, "s": 3805, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3866, "s": 3837, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3893, "s": 3866, "text": "Python Classes and Objects" }, { "code": null, "e": 3929, "s": 3893, "text": "Convert integer to string in Python" }, { "code": null, "e": 3950, "s": 3929, "text": "Python OOPs Concepts" }, { "code": null, "e": 3973, "s": 3950, "text": "Introduction To PYTHON" }, { "code": null, "e": 4004, "s": 3973, "text": "Python | os.path.join() method" } ]
Find the position of the given Prime Number
21 Nov, 2021 Given a number N which is a prime number, the task is to find the position of the given prime number in the series of Prime Numbers.Examples : Input: N = 11 Output: 5 Explanation: The prime numbers are 2, 3, 5, 7, 11, 13, 17, .... Therefore, the position of 11 in this series is 5.Input: N = 13 Output: 6 Naive Approach: The naive approach for this problem is for the given input, compute the prime numbers which are less than that number and keep a track of the number of primes less than the given N. If the count is K, then K + 1 would be the answer. The time complexity for this approach is quadratic. Efficient Approach: The idea is to use the slight modification of Sieve of Eratosthenes. All the prime numbers up to the maximum value can be computed and stored in an array along with its position. Clearly, when the prime numbers are stored in an array, the index at which the number is stored is the position of the number in the series. After this precomputation, the answer can be calculated in constant time. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the position// of the given prime number #include <bits/stdc++.h>#define limit 10000000using namespace std;int position[limit + 1]; // Function to precompute the position// of every prime number using Sievevoid sieve(){ // 0 and 1 are not prime numbers position[0] = -1, position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codeint main(){ sieve(); int n = 11; cout << position[n]; return 0;} // Java program to find the position// of the given prime numberclass GFG{ static final int limit = 10000000;static int []position = new int[limit + 1]; // Function to precompute the position// of every prime number using Sievestatic void sieve(){ // 0 and 1 are not prime numbers position[0] = -1; position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codepublic static void main(String[] args){ sieve(); int n = 11; System.out.print(position[n]);}} // This code is contributed by Rajput-Ji # Python3 program to find the position# of the given prime numberlimit = 1000000position = [0]*(limit + 1) # Function to precompute the position# of every prime number using Sievedef sieve(): # 0 and 1 are not prime numbers position[0] = -1 position[1] = -1 # Variable to store the position pos = 0 for i in range(2, limit + 1): if (position[i] == 0): # Incrementing the position for # every prime number pos += 1 position[i] = pos for j in range( i * 2, limit + 1 ,i): position[j] = -1 # Driver codeif __name__ == "__main__": sieve() n = 11 print(position[n]) # This code is contributed by chitranayal // C# program to find the position// of the given prime numberusing System; class GFG{ static readonly int limit = 1000000;static int []position = new int[limit + 1]; // Function to precompute the position// of every prime number using Sievestatic void sieve(){ // 0 and 1 are not prime numbers position[0] = -1; position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codepublic static void Main(String[] args){ sieve(); int n = 11; Console.Write(position[n]);}} // This code is contributed by Princi Singh <script> // Javascript program to find the position// of the given prime numbervar limit = 10000000var position = Array(limit+1).fill(0); // Function to precompute the position// of every prime number using Sievefunction sieve(){ // 0 and 1 are not prime numbers position[0] = -1, position[1] = -1; // Variable to store the position var pos = 0; for (var i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (var j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codesieve();var n = 11;document.write( position[n]); // This code is contributed by noob2000.</script> 5 Time Complexity: O(limit2) Auxiliary Space: O(limit) ukasp Rajput-Ji princi singh noob2000 souravmahato348 Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Modulo Operator (%) in C/C++ with Examples Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Nov, 2021" }, { "code": null, "e": 199, "s": 54, "text": "Given a number N which is a prime number, the task is to find the position of the given prime number in the series of Prime Numbers.Examples : " }, { "code": null, "e": 363, "s": 199, "text": "Input: N = 11 Output: 5 Explanation: The prime numbers are 2, 3, 5, 7, 11, 13, 17, .... Therefore, the position of 11 in this series is 5.Input: N = 13 Output: 6 " }, { "code": null, "e": 1132, "s": 365, "text": "Naive Approach: The naive approach for this problem is for the given input, compute the prime numbers which are less than that number and keep a track of the number of primes less than the given N. If the count is K, then K + 1 would be the answer. The time complexity for this approach is quadratic. Efficient Approach: The idea is to use the slight modification of Sieve of Eratosthenes. All the prime numbers up to the maximum value can be computed and stored in an array along with its position. Clearly, when the prime numbers are stored in an array, the index at which the number is stored is the position of the number in the series. After this precomputation, the answer can be calculated in constant time. Below is the implementation of the above approach: " }, { "code": null, "e": 1136, "s": 1132, "text": "C++" }, { "code": null, "e": 1141, "s": 1136, "text": "Java" }, { "code": null, "e": 1149, "s": 1141, "text": "Python3" }, { "code": null, "e": 1152, "s": 1149, "text": "C#" }, { "code": null, "e": 1163, "s": 1152, "text": "Javascript" }, { "code": "// C++ program to find the position// of the given prime number #include <bits/stdc++.h>#define limit 10000000using namespace std;int position[limit + 1]; // Function to precompute the position// of every prime number using Sievevoid sieve(){ // 0 and 1 are not prime numbers position[0] = -1, position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codeint main(){ sieve(); int n = 11; cout << position[n]; return 0;}", "e": 1905, "s": 1163, "text": null }, { "code": "// Java program to find the position// of the given prime numberclass GFG{ static final int limit = 10000000;static int []position = new int[limit + 1]; // Function to precompute the position// of every prime number using Sievestatic void sieve(){ // 0 and 1 are not prime numbers position[0] = -1; position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codepublic static void main(String[] args){ sieve(); int n = 11; System.out.print(position[n]);}} // This code is contributed by Rajput-Ji", "e": 2734, "s": 1905, "text": null }, { "code": "# Python3 program to find the position# of the given prime numberlimit = 1000000position = [0]*(limit + 1) # Function to precompute the position# of every prime number using Sievedef sieve(): # 0 and 1 are not prime numbers position[0] = -1 position[1] = -1 # Variable to store the position pos = 0 for i in range(2, limit + 1): if (position[i] == 0): # Incrementing the position for # every prime number pos += 1 position[i] = pos for j in range( i * 2, limit + 1 ,i): position[j] = -1 # Driver codeif __name__ == \"__main__\": sieve() n = 11 print(position[n]) # This code is contributed by chitranayal", "e": 3454, "s": 2734, "text": null }, { "code": "// C# program to find the position// of the given prime numberusing System; class GFG{ static readonly int limit = 1000000;static int []position = new int[limit + 1]; // Function to precompute the position// of every prime number using Sievestatic void sieve(){ // 0 and 1 are not prime numbers position[0] = -1; position[1] = -1; // Variable to store the position int pos = 0; for (int i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (int j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codepublic static void Main(String[] args){ sieve(); int n = 11; Console.Write(position[n]);}} // This code is contributed by Princi Singh", "e": 4304, "s": 3454, "text": null }, { "code": "<script> // Javascript program to find the position// of the given prime numbervar limit = 10000000var position = Array(limit+1).fill(0); // Function to precompute the position// of every prime number using Sievefunction sieve(){ // 0 and 1 are not prime numbers position[0] = -1, position[1] = -1; // Variable to store the position var pos = 0; for (var i = 2; i <= limit; i++) { if (position[i] == 0) { // Incrementing the position for // every prime number position[i] = ++pos; for (var j = i * 2; j <= limit; j += i) position[j] = -1; } }} // Driver codesieve();var n = 11;document.write( position[n]); // This code is contributed by noob2000.</script>", "e": 5065, "s": 4304, "text": null }, { "code": null, "e": 5067, "s": 5065, "text": "5" }, { "code": null, "e": 5096, "s": 5069, "text": "Time Complexity: O(limit2)" }, { "code": null, "e": 5122, "s": 5096, "text": "Auxiliary Space: O(limit)" }, { "code": null, "e": 5128, "s": 5122, "text": "ukasp" }, { "code": null, "e": 5138, "s": 5128, "text": "Rajput-Ji" }, { "code": null, "e": 5151, "s": 5138, "text": "princi singh" }, { "code": null, "e": 5160, "s": 5151, "text": "noob2000" }, { "code": null, "e": 5176, "s": 5160, "text": "souravmahato348" }, { "code": null, "e": 5189, "s": 5176, "text": "Prime Number" }, { "code": null, "e": 5195, "s": 5189, "text": "sieve" }, { "code": null, "e": 5208, "s": 5195, "text": "Mathematical" }, { "code": null, "e": 5221, "s": 5208, "text": "Mathematical" }, { "code": null, "e": 5234, "s": 5221, "text": "Prime Number" }, { "code": null, "e": 5240, "s": 5234, "text": "sieve" }, { "code": null, "e": 5338, "s": 5240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5362, "s": 5338, "text": "Merge two sorted arrays" }, { "code": null, "e": 5383, "s": 5362, "text": "Operators in C / C++" }, { "code": null, "e": 5397, "s": 5383, "text": "Prime Numbers" }, { "code": null, "e": 5450, "s": 5397, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 5487, "s": 5450, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 5519, "s": 5487, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5562, "s": 5519, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 5603, "s": 5562, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 5646, "s": 5603, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
SQL | Intersect & Except clause
30 Jun, 2022 1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 ...... FROM table 1 WHERE..... INTERSECT SELECT column-1, column-2 ...... FROM table 2 WHERE..... Example : Table 1 containing Employee Details Table 2 containing details of employees who are provided bonus Query : SELECT ID, Name, Bonus FROM table1 LEFT JOIN table2 ON table1.ID = table2.Employee_ID INTERSECT SELECT ID, Name, Bonus FROM table1 RIGHT JOIN table2 ON table1.ID = table2.Employee_ID; Result : 2. EXCEPT clause : contains all the rows that are returned by the first SELECT operation, and not returned by the second SELECT operation. Syntax : SELECT column-1, column-2 ...... FROM table 1 WHERE..... EXCEPT SELECT column-1, column-2 ...... FROM table 2 WHERE..... Example : Table 1 containing Employee Details Table 2 containing details of employees who are provided bonus Query : SELECT ID, Name, Bonus FROM table1 LEFT JOIN table2 ON table1.ID = table2.Employee_ID EXCEPT SELECT ID, Name, Bonus FROM table1 RIGHT JOIN table2 ON table1.ID = table2.Employee_ID; Result : yaraalsham86 SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL Correlated Subqueries MySQL | Regular expressions (Regexp) What is Temporary Table in SQL?
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Jun, 2022" }, { "code": null, "e": 297, "s": 53, "text": "1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax :" }, { "code": null, "e": 425, "s": 297, "text": "SELECT column-1, column-2 ...... \nFROM table 1\nWHERE.....\n\nINTERSECT\n\nSELECT column-1, column-2 ...... \nFROM table 2\nWHERE....." }, { "code": null, "e": 544, "s": 425, "text": "Example : Table 1 containing Employee Details Table 2 containing details of employees who are provided bonus Query :" }, { "code": null, "e": 736, "s": 544, "text": "SELECT ID, Name, Bonus \nFROM\ntable1 \nLEFT JOIN\ntable2\nON table1.ID = table2.Employee_ID\n\nINTERSECT\n\nSELECT ID, Name, Bonus \nFROM\ntable1 \nRIGHT JOIN\ntable2\nON table1.ID = table2.Employee_ID;\n " }, { "code": null, "e": 898, "s": 736, "text": "Result : 2. EXCEPT clause : contains all the rows that are returned by the first SELECT operation, and not returned by the second SELECT operation. Syntax :" }, { "code": null, "e": 1023, "s": 898, "text": "SELECT column-1, column-2 ...... \nFROM table 1\nWHERE.....\n\nEXCEPT\n\nSELECT column-1, column-2 ...... \nFROM table 2\nWHERE....." }, { "code": null, "e": 1142, "s": 1023, "text": "Example : Table 1 containing Employee Details Table 2 containing details of employees who are provided bonus Query :" }, { "code": null, "e": 1329, "s": 1142, "text": "SELECT ID, Name, Bonus \nFROM\ntable1 \nLEFT JOIN\ntable2\nON table1.ID = table2.Employee_ID\n\nEXCEPT\n\nSELECT ID, Name, Bonus \nFROM\ntable1 \nRIGHT JOIN\ntable2\nON table1.ID = table2.Employee_ID;" }, { "code": null, "e": 1339, "s": 1329, "text": "Result : " }, { "code": null, "e": 1352, "s": 1339, "text": "yaraalsham86" }, { "code": null, "e": 1374, "s": 1352, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 1378, "s": 1374, "text": "SQL" }, { "code": null, "e": 1382, "s": 1378, "text": "SQL" }, { "code": null, "e": 1480, "s": 1382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1491, "s": 1480, "text": "CTE in SQL" }, { "code": null, "e": 1557, "s": 1491, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1581, "s": 1557, "text": "SQL Interview Questions" }, { "code": null, "e": 1626, "s": 1581, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1650, "s": 1626, "text": "Window functions in SQL" }, { "code": null, "e": 1682, "s": 1650, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1721, "s": 1682, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1747, "s": 1721, "text": "SQL Correlated Subqueries" }, { "code": null, "e": 1784, "s": 1747, "text": "MySQL | Regular expressions (Regexp)" } ]
C# | Boolean.CompareTo(Boolean) Method
06 Jan, 2022 Boolean.CompareTo(Boolean) Method is used to compare the current instance to a specified Boolean object and returns an indication of their relative values. Syntax: public int CompareTo (bool value); Here, the value is a Boolean object to compare to the current instance. Return Value: This method returns a 32-bit signed integer that indicates the relative order of this instance and value. Less than zero: If this instance is false and value is true. Zero: If this instance and value are equal (either both are true or both are false). Greater than zero: If this instance is true and value is false. Example: C# // C# program to demonstrate// Boolean.CompareTo(Boolean)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring val1 and val2 bool val1, val2; // initializing the val1, // and val2 val1 = true; val2 = false; // using CompareTo method int i = val2.CompareTo(val1); // checking the condition if (i > 0) Console.Write("val2 is greater than val1"); else if (i < 0) Console.Write("val2 is less than val1"); else Console.Write("val1 is equal to val1"); }} val2 is less than val1 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.boolean.compareto?view=netframework-4.8#System_Boolean_CompareTo_System_Boolean_ sweetyty CSharp Boolean Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2022" }, { "code": null, "e": 184, "s": 28, "text": "Boolean.CompareTo(Boolean) Method is used to compare the current instance to a specified Boolean object and returns an indication of their relative values." }, { "code": null, "e": 192, "s": 184, "text": "Syntax:" }, { "code": null, "e": 227, "s": 192, "text": "public int CompareTo (bool value);" }, { "code": null, "e": 299, "s": 227, "text": "Here, the value is a Boolean object to compare to the current instance." }, { "code": null, "e": 420, "s": 299, "text": "Return Value: This method returns a 32-bit signed integer that indicates the relative order of this instance and value. " }, { "code": null, "e": 481, "s": 420, "text": "Less than zero: If this instance is false and value is true." }, { "code": null, "e": 566, "s": 481, "text": "Zero: If this instance and value are equal (either both are true or both are false)." }, { "code": null, "e": 630, "s": 566, "text": "Greater than zero: If this instance is true and value is false." }, { "code": null, "e": 640, "s": 630, "text": "Example: " }, { "code": null, "e": 643, "s": 640, "text": "C#" }, { "code": "// C# program to demonstrate// Boolean.CompareTo(Boolean)// Methodusing System; class GFG { // Main Method public static void Main() { // Declaring val1 and val2 bool val1, val2; // initializing the val1, // and val2 val1 = true; val2 = false; // using CompareTo method int i = val2.CompareTo(val1); // checking the condition if (i > 0) Console.Write(\"val2 is greater than val1\"); else if (i < 0) Console.Write(\"val2 is less than val1\"); else Console.Write(\"val1 is equal to val1\"); }}", "e": 1265, "s": 643, "text": null }, { "code": null, "e": 1288, "s": 1265, "text": "val2 is less than val1" }, { "code": null, "e": 1302, "s": 1290, "text": "Reference: " }, { "code": null, "e": 1434, "s": 1302, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.boolean.compareto?view=netframework-4.8#System_Boolean_CompareTo_System_Boolean_" }, { "code": null, "e": 1445, "s": 1436, "text": "sweetyty" }, { "code": null, "e": 1467, "s": 1445, "text": "CSharp Boolean Struct" }, { "code": null, "e": 1481, "s": 1467, "text": "CSharp-method" }, { "code": null, "e": 1484, "s": 1481, "text": "C#" }, { "code": null, "e": 1582, "s": 1484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1610, "s": 1582, "text": "C# Dictionary with examples" }, { "code": null, "e": 1653, "s": 1610, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1684, "s": 1653, "text": "Introduction to .NET Framework" }, { "code": null, "e": 1699, "s": 1684, "text": "C# | Delegates" }, { "code": null, "e": 1748, "s": 1699, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1764, "s": 1748, "text": "C# | Data Types" }, { "code": null, "e": 1787, "s": 1764, "text": "C# | Method Overriding" }, { "code": null, "e": 1827, "s": 1787, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 1845, "s": 1827, "text": "C# | Constructors" } ]
Python | Select dictionary with condition given key greater than k
29 May, 2019 In Python, sometimes we require to get only some of the dictionary required to solve the problem. This problem is quite common in web development that we require to get only the selective dictionary satisfying some given criteria. Let’s discuss certain ways in which this problem can be solved. Method #1: Using list comprehension # Python3 code to demonstrate# filtering of a list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}] # printing initial list of dictionaryprint ("initial_list", str(ini_list)) # code to filter list# where c is greater than 10res = [d for d in ini_list if d['c'] > 10] # printing resultprint ("resultant_list", str(res)) Output: initial_list [{‘c’: 7, ‘b’: 3, ‘a’: 1}, {‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}, {‘c’: 2, ‘b’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}] Method #2: Using lambda and filter # Python3 code to demonstrate# filtering of list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}] # printing initial list of dictionaryprint ("initial_list", str(ini_list)) # code to filter list# where c is less than 10res = list(filter(lambda x:x["c"] > 10, ini_list )) # printing resultprint ("resultant_list", str(res)) Output: initial_list [{‘b’: 3, ‘c’: 7, ‘a’: 1}, {‘b’: 8, ‘c’: 17, ‘a’: 3}, {‘b’: 12, ‘c’: 13, ‘a’: 78}, {‘b’: 2, ‘c’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}] Method #3: Using dict comprehension and list comprehension # Python3 code to demonstrate# filtering of list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':10}] # printing initial list of dictionaryprint ("initial_list", str(ini_list)) # code to filter list# where c is more than 10 res = [{ k:v for (k, v) in i.items()} for i in ini_list if i.get('c') > 10] # printing resultprint ("resultant_list", str(res)) Output: initial_list [{‘a’: 1, ‘c’: 7, ‘b’: 3}, {‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}, {‘a’: 2, ‘c’: 10, ‘b’: 2}]resultant_list [{‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Defaultdict in Python Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 323, "s": 28, "text": "In Python, sometimes we require to get only some of the dictionary required to solve the problem. This problem is quite common in web development that we require to get only the selective dictionary satisfying some given criteria. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 359, "s": 323, "text": "Method #1: Using list comprehension" }, { "code": "# Python3 code to demonstrate# filtering of a list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}] # printing initial list of dictionaryprint (\"initial_list\", str(ini_list)) # code to filter list# where c is greater than 10res = [d for d in ini_list if d['c'] > 10] # printing resultprint (\"resultant_list\", str(res))", "e": 822, "s": 359, "text": null }, { "code": null, "e": 830, "s": 822, "text": "Output:" }, { "code": null, "e": 1023, "s": 830, "text": "initial_list [{‘c’: 7, ‘b’: 3, ‘a’: 1}, {‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}, {‘c’: 2, ‘b’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}]" }, { "code": null, "e": 1059, "s": 1023, "text": " Method #2: Using lambda and filter" }, { "code": "# Python3 code to demonstrate# filtering of list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}] # printing initial list of dictionaryprint (\"initial_list\", str(ini_list)) # code to filter list# where c is less than 10res = list(filter(lambda x:x[\"c\"] > 10, ini_list )) # printing resultprint (\"resultant_list\", str(res))", "e": 1526, "s": 1059, "text": null }, { "code": null, "e": 1534, "s": 1526, "text": "Output:" }, { "code": null, "e": 1727, "s": 1534, "text": "initial_list [{‘b’: 3, ‘c’: 7, ‘a’: 1}, {‘b’: 8, ‘c’: 17, ‘a’: 3}, {‘b’: 12, ‘c’: 13, ‘a’: 78}, {‘b’: 2, ‘c’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}]" }, { "code": null, "e": 1787, "s": 1727, "text": " Method #3: Using dict comprehension and list comprehension" }, { "code": "# Python3 code to demonstrate# filtering of list of dictionary# on basis of condition # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17}, {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':10}] # printing initial list of dictionaryprint (\"initial_list\", str(ini_list)) # code to filter list# where c is more than 10 res = [{ k:v for (k, v) in i.items()} for i in ini_list if i.get('c') > 10] # printing resultprint (\"resultant_list\", str(res))", "e": 2305, "s": 1787, "text": null }, { "code": null, "e": 2313, "s": 2305, "text": "Output:" }, { "code": null, "e": 2507, "s": 2313, "text": "initial_list [{‘a’: 1, ‘c’: 7, ‘b’: 3}, {‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}, {‘a’: 2, ‘c’: 10, ‘b’: 2}]resultant_list [{‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}]" }, { "code": null, "e": 2534, "s": 2507, "text": "Python dictionary-programs" }, { "code": null, "e": 2541, "s": 2534, "text": "Python" }, { "code": null, "e": 2557, "s": 2541, "text": "Python Programs" }, { "code": null, "e": 2655, "s": 2557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2673, "s": 2655, "text": "Python Dictionary" }, { "code": null, "e": 2715, "s": 2673, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2737, "s": 2715, "text": "Enumerate() in Python" }, { "code": null, "e": 2763, "s": 2737, "text": "Python String | replace()" }, { "code": null, "e": 2795, "s": 2763, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2817, "s": 2795, "text": "Defaultdict in Python" }, { "code": null, "e": 2855, "s": 2817, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2904, "s": 2855, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 2941, "s": 2904, "text": "Python Program for Fibonacci numbers" } ]
askopenfile() function in Python Tkinter
Instead of hard coding the path to a file to be used by a python program, we can allow the user to browse the os folder structure using a GUI and let the user select the file. This is achieved using the tkinter module in which we define a canvas and put a button on it to browse the files. In the below program, we define a file opener function. We only use this function to open a text file as python can read the content of a text file and print it out in a much readable manner. We can read any text based files like .txt or .csv files. from tkinter import * from tkinter import filedialog base = Tk() # Create a canvas base.geometry('150x150') # Function for opening the file def file_opener(): input = filedialog.askopenfile(initialdir="/") print(input) for i in input: print(i) # Button label x = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener()) x.pack() mainloop() The below dialogue box opens to browse a file. Then we choose a file. Running the above code gives us the following result − <_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'> Hello There ! Welcome to Tutorialspoint!
[ { "code": null, "e": 1477, "s": 1187, "text": "Instead of hard coding the path to a file to be used by a python program, we can allow the user to browse the os folder structure using a GUI and let the user select the file. This is achieved using the tkinter module in which we define a canvas and put a button on it to browse the files." }, { "code": null, "e": 1727, "s": 1477, "text": "In the below program, we define a file opener function. We only use this function to open a text file as python can read the content of a text file and print it out in a much readable manner. We can read any text based files like .txt or .csv files." }, { "code": null, "e": 2103, "s": 1727, "text": "from tkinter import *\nfrom tkinter import filedialog\nbase = Tk()\n# Create a canvas\nbase.geometry('150x150')\n# Function for opening the file\ndef file_opener():\n input = filedialog.askopenfile(initialdir=\"/\")\n print(input)\n for i in input:\n print(i)\n# Button label\nx = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener())\nx.pack()\nmainloop()" }, { "code": null, "e": 2150, "s": 2103, "text": "The below dialogue box opens to browse a file." }, { "code": null, "e": 2173, "s": 2150, "text": "Then we choose a file." }, { "code": null, "e": 2228, "s": 2173, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2362, "s": 2228, "text": "<_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'>\nHello There !\nWelcome to Tutorialspoint!" } ]
MFC - Dialog Boxes
In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently communicate with the user through dialog boxes. CDialog class provides an interface for managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes and create their dialog-template resources. Creating a dialog object is a two-phase operation − Construct the dialog object. Create the dialog window. Creating a dialog object is a two-phase operation − Construct the dialog object. Construct the dialog object. Create the dialog window. Create the dialog window. Let us look into a simple example by creating a new Win32 project. Step 1 − Open the Visual studio and click on the File → New → Project menu option. Step 2 − You can now see the New Project dialog box. Step 3 − From the left pane, select Templates → Visual C++ → Win32. Step 4 − In the middle pane, select Win32 Project. Step 5 − Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue. You will see the following dialog. Step 6 − Click Next. Step 7 − Select the options shown in the dialog box given above and click Finish. Step 8 − An empty project is created. Step 9 − To make it a MFC project, right-click on the project and select Properties. Step 10 − In the left section, click Configuration Properties → General. Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK. Step 12 − Add a new source file. Step 13 − Right-click on your Project and select Add → New Item. Step 14 − In the Templates section, click C++ File (.cpp) Step 15 − Set the Name as Example and click Add. Step 16 − To create an application, we need to add a class and derive it from the MFC's CWinApp. #include <afxwin.h> class CExample : public CWinApp { public: BOOL InitInstance(); }; Step 1 − To create a dialog box, right-click on the Resource Files folder in solution explorer and select Add → Resource. Step 2 − In the Add Resource dialog box, select Dialog and click New. Step 3 − A dialog box requires some preparation before actually programmatically creating it. Step 4 − A dialog box can first be manually created as a text file (in a resource file). Step 5 − You can now see the MFCDialogDemo.rc file created under Resource Files. Step 6 − The resource file is open in designer. The same can be opened as a text file. Rightclick on the resource file and select Open With. Step 7 − Select the Source Code (Text) editor and click Add button. Step 8 − Go back to the designer and right-click on the dialog and select Properties. Step 9 − You need to choose out of the many options. Step 10 − Like most other controls, a dialog box must be identified. The identifier (ID) of a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG. A dialog box must be “physically” located on an application. Because a dialog box is usually created as a parent to other controls, its location depends on its relationship to its parent window or to the desktop. If you look and the Properties window, you see two fields, X Pos and Y Pos. X is the distance from the left border of the monitor to the left border of the dialog box. X is the distance from the left border of the monitor to the left border of the dialog box. Y is the distance from the top border of the monitor to the top border of the dialog box. Y is the distance from the top border of the monitor to the top border of the dialog box. By default, these fields are set to zero. You can also change as shown above. If you specify these two dimensions as 0, the left and top borders of the dialog box would be set so the object appears in the center-middle of the screen. The dimensions of a dialog box refer to its width and its height. You can resize the width and height with the help of mouse in designer window. You can see the changes in width and height on the Status Bar. The base class used for displaying dialog boxes on the screen is CDialog class. To create a dialog box, we need to derive a class from CDialog. The CDialog class itself provides three constructors which are as follows − CDialog(); CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL); CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); Let us create another class CExampleDlg and derive it from CDialog. We will implement its default constructor destructor as shown in the following code. class CExampleDlg : public CDialog { public: enum { IDD = IDD_EXAMPLE_DLG }; CExampleDlg(); ~CExampleDlg(); }; CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) { } CExampleDlg::~CExampleDlg() { } We need to instantiate this dialog on CExample::InitInstance() method as shown in the following code. BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; return TRUE; } There are two types of dialog boxes − modeless and modal. Modal and modeless dialog boxes differ by the process used to create and display them. For a modeless dialog box, you must provide your own public constructor in your dialog class. For a modeless dialog box, you must provide your own public constructor in your dialog class. To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource. To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource. You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately. You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately. If not, you must call its ShowWindow member function. If not, you must call its ShowWindow member function. To create a modal dialog box, call either of the two public constructors declared in CDialog. To create a modal dialog box, call either of the two public constructors declared in CDialog. Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel. Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel. This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource. This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource. Step 1 − To display the dialog box as modal, in the CExample::InitInstance() event call the DoModal() method using your dialog variable − BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; myDlg.DoModal(); return TRUE; } Step 2 − Here is the complete implementation of Example.cpp file. #include <afxwin.h> #include "resource.h" class CExample : public CWinApp { public: BOOL InitInstance(); }; class CExampleDlg : public CDialog { public: enum { IDD = IDD_EXAMPLE_DLG }; CExampleDlg(); ~CExampleDlg(); }; CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) { } CExampleDlg::~CExampleDlg() { } BOOL CExample::InitInstance() { CExampleDlg myDlg; m_pMainWnd = &myDlg; myDlg.DoModal(); return TRUE; } CExample MyApp; Step 3 − When the above code is compiled and executed, you will see the following dialog box. Microsoft Visual Studio provides an easier way to create an application that is mainly based on a dialog box. Here are the steps to create a dialog base project using project templates available in Visual Studio − Step 1 − Open the Visual studio and click on the File → New → Project menu option. You can see the New Project dialog box. Step 2 − From the left pane, select Templates → Visual C++ → MFC. Step 3 − In the middle pane, select MFC Application. Step 4 − Enter project name ‘MFCModalDemo’ in the Name field and click OK to continue. You will see the following dialog box. Step 5 − Click Next. Step 6 − Select the options shown in the above dialog box and click Next. Step 7 − Check all the options that you choose to have on your dialog box like Maximize and Minimize Boxes and click Next. Step 8 − Click Next. Step 9 − It will generate these two classes. You can change the name of the classes and click Finish. Step 10 − You can now see that the MFC wizard creates this Dialog Box and the project files by default. Step 11 − When you run this application, you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2379, "s": 2067, "text": "In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently communicate with the user through dialog boxes. CDialog class provides an interface for managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes and create their dialog-template resources." }, { "code": null, "e": 2488, "s": 2379, "text": "Creating a dialog object is a two-phase operation −\n\nConstruct the dialog object.\nCreate the dialog window.\n" }, { "code": null, "e": 2540, "s": 2488, "text": "Creating a dialog object is a two-phase operation −" }, { "code": null, "e": 2569, "s": 2540, "text": "Construct the dialog object." }, { "code": null, "e": 2598, "s": 2569, "text": "Construct the dialog object." }, { "code": null, "e": 2624, "s": 2598, "text": "Create the dialog window." }, { "code": null, "e": 2650, "s": 2624, "text": "Create the dialog window." }, { "code": null, "e": 2717, "s": 2650, "text": "Let us look into a simple example by creating a new Win32 project." }, { "code": null, "e": 2800, "s": 2717, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option." }, { "code": null, "e": 2853, "s": 2800, "text": "Step 2 − You can now see the New Project dialog box." }, { "code": null, "e": 2921, "s": 2853, "text": "Step 3 − From the left pane, select Templates → Visual C++ → Win32." }, { "code": null, "e": 2972, "s": 2921, "text": "Step 4 − In the middle pane, select Win32 Project." }, { "code": null, "e": 3095, "s": 2972, "text": "Step 5 − Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue. You will see the following dialog." }, { "code": null, "e": 3116, "s": 3095, "text": "Step 6 − Click Next." }, { "code": null, "e": 3198, "s": 3116, "text": "Step 7 − Select the options shown in the dialog box given above and click Finish." }, { "code": null, "e": 3236, "s": 3198, "text": "Step 8 − An empty project is created." }, { "code": null, "e": 3321, "s": 3236, "text": "Step 9 − To make it a MFC project, right-click on the project and select Properties." }, { "code": null, "e": 3394, "s": 3321, "text": "Step 10 − In the left section, click Configuration Properties → General." }, { "code": null, "e": 3486, "s": 3394, "text": "Step 11 − Select the Use MFC in Shared DLL option in Project Defaults section and click OK." }, { "code": null, "e": 3519, "s": 3486, "text": "Step 12 − Add a new source file." }, { "code": null, "e": 3584, "s": 3519, "text": "Step 13 − Right-click on your Project and select Add → New Item." }, { "code": null, "e": 3642, "s": 3584, "text": "Step 14 − In the Templates section, click C++ File (.cpp)" }, { "code": null, "e": 3691, "s": 3642, "text": "Step 15 − Set the Name as Example and click Add." }, { "code": null, "e": 3788, "s": 3691, "text": "Step 16 − To create an application, we need to add a class and derive it from the MFC's CWinApp." }, { "code": null, "e": 3884, "s": 3788, "text": "#include <afxwin.h>\n\nclass CExample : public CWinApp {\n public:\n BOOL InitInstance();\n};" }, { "code": null, "e": 4006, "s": 3884, "text": "Step 1 − To create a dialog box, right-click on the Resource Files folder in solution explorer and select Add → Resource." }, { "code": null, "e": 4076, "s": 4006, "text": "Step 2 − In the Add Resource dialog box, select Dialog and click New." }, { "code": null, "e": 4170, "s": 4076, "text": "Step 3 − A dialog box requires some preparation before actually programmatically creating it." }, { "code": null, "e": 4259, "s": 4170, "text": "Step 4 − A dialog box can first be manually created as a text file (in a resource file)." }, { "code": null, "e": 4340, "s": 4259, "text": "Step 5 − You can now see the MFCDialogDemo.rc file created under Resource Files." }, { "code": null, "e": 4481, "s": 4340, "text": "Step 6 − The resource file is open in designer. The same can be opened as a text file. Rightclick on the resource file and select Open With." }, { "code": null, "e": 4549, "s": 4481, "text": "Step 7 − Select the Source Code (Text) editor and click Add button." }, { "code": null, "e": 4635, "s": 4549, "text": "Step 8 − Go back to the designer and right-click on the dialog and select Properties." }, { "code": null, "e": 4688, "s": 4635, "text": "Step 9 − You need to choose out of the many options." }, { "code": null, "e": 4860, "s": 4688, "text": "Step 10 − Like most other controls, a dialog box must be identified. The identifier (ID) of a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG." }, { "code": null, "e": 5073, "s": 4860, "text": "A dialog box must be “physically” located on an application. Because a dialog box is usually created as a parent to other controls, its location depends on its relationship to its parent window or to the desktop." }, { "code": null, "e": 5149, "s": 5073, "text": "If you look and the Properties window, you see two fields, X Pos and Y Pos." }, { "code": null, "e": 5241, "s": 5149, "text": "X is the distance from the left border of the monitor to the left border of the dialog box." }, { "code": null, "e": 5333, "s": 5241, "text": "X is the distance from the left border of the monitor to the left border of the dialog box." }, { "code": null, "e": 5423, "s": 5333, "text": "Y is the distance from the top border of the monitor to the top border of the dialog box." }, { "code": null, "e": 5513, "s": 5423, "text": "Y is the distance from the top border of the monitor to the top border of the dialog box." }, { "code": null, "e": 5591, "s": 5513, "text": "By default, these fields are set to zero. You can also change as shown above." }, { "code": null, "e": 5747, "s": 5591, "text": "If you specify these two dimensions as 0, the left and top borders of the dialog box would be set so the object appears in the center-middle of the screen." }, { "code": null, "e": 5892, "s": 5747, "text": "The dimensions of a dialog box refer to its width and its height. You can resize the width and height with the help of mouse in designer window." }, { "code": null, "e": 5955, "s": 5892, "text": "You can see the changes in width and height on the Status Bar." }, { "code": null, "e": 6175, "s": 5955, "text": "The base class used for displaying dialog boxes on the screen is CDialog class. To create a dialog box, we need to derive a class from CDialog. The CDialog class itself provides three constructors which are as follows −" }, { "code": null, "e": 6298, "s": 6175, "text": "CDialog();\nCDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);\nCDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);" }, { "code": null, "e": 6451, "s": 6298, "text": "Let us create another class CExampleDlg and derive it from CDialog. We will implement its default constructor destructor as shown in the following code." }, { "code": null, "e": 6680, "s": 6451, "text": "class CExampleDlg : public CDialog {\n public:\n enum { IDD = IDD_EXAMPLE_DLG };\n \n CExampleDlg();\n ~CExampleDlg();\n};\n\nCExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) {\n\n}\n\nCExampleDlg::~CExampleDlg() {\n\n}" }, { "code": null, "e": 6782, "s": 6680, "text": "We need to instantiate this dialog on CExample::InitInstance() method as shown in the following code." }, { "code": null, "e": 6882, "s": 6782, "text": "BOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n \n return TRUE;\n}" }, { "code": null, "e": 7027, "s": 6882, "text": "There are two types of dialog boxes − modeless and modal. Modal and modeless dialog boxes differ by the process used to create and display them." }, { "code": null, "e": 7121, "s": 7027, "text": "For a modeless dialog box, you must provide your own public constructor in your dialog class." }, { "code": null, "e": 7215, "s": 7121, "text": "For a modeless dialog box, you must provide your own public constructor in your dialog class." }, { "code": null, "e": 7363, "s": 7215, "text": "To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource." }, { "code": null, "e": 7511, "s": 7363, "text": "To create a modeless dialog box, call your public constructor and then call the dialog object's Create member function to load the dialog resource." }, { "code": null, "e": 7664, "s": 7511, "text": "You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately." }, { "code": null, "e": 7817, "s": 7664, "text": "You can call Create either during or after the constructor call. If the dialog resource has the property WS_VISIBLE, the dialog box appears immediately." }, { "code": null, "e": 7871, "s": 7817, "text": "If not, you must call its ShowWindow member function." }, { "code": null, "e": 7925, "s": 7871, "text": "If not, you must call its ShowWindow member function." }, { "code": null, "e": 8019, "s": 7925, "text": "To create a modal dialog box, call either of the two public constructors declared in CDialog." }, { "code": null, "e": 8113, "s": 8019, "text": "To create a modal dialog box, call either of the two public constructors declared in CDialog." }, { "code": null, "e": 8262, "s": 8113, "text": "Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel." }, { "code": null, "e": 8411, "s": 8262, "text": "Next, call the dialog object's DoModal member function to display the dialog box and manage interaction with it until the user chooses OK or Cancel." }, { "code": null, "e": 8533, "s": 8411, "text": "This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource." }, { "code": null, "e": 8655, "s": 8533, "text": "This management by DoModal is what makes the dialog box modal. For modal dialog boxes, DoModal loads the dialog resource." }, { "code": null, "e": 8794, "s": 8655, "text": "Step 1 − To display the dialog box as modal, in the CExample::InitInstance() event call the DoModal() method using your dialog variable − " }, { "code": null, "e": 8910, "s": 8794, "text": "BOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n myDlg.DoModal();\n return TRUE;\n}" }, { "code": null, "e": 8976, "s": 8910, "text": "Step 2 − Here is the complete implementation of Example.cpp file." }, { "code": null, "e": 9459, "s": 8976, "text": "#include <afxwin.h>\n#include \"resource.h\"\n\nclass CExample : public CWinApp {\n public:\n BOOL InitInstance();\n};\n \nclass CExampleDlg : public CDialog {\n public:\n enum { IDD = IDD_EXAMPLE_DLG };\n \n CExampleDlg();\n ~CExampleDlg();\n};\n\nCExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD) {\n\n}\n\nCExampleDlg::~CExampleDlg() {\n\n}\n\nBOOL CExample::InitInstance() {\n CExampleDlg myDlg;\n m_pMainWnd = &myDlg;\n myDlg.DoModal();\n return TRUE;\n}\nCExample MyApp;" }, { "code": null, "e": 9553, "s": 9459, "text": "Step 3 − When the above code is compiled and executed, you will see the following dialog box." }, { "code": null, "e": 9768, "s": 9553, "text": "Microsoft Visual Studio provides an easier way to create an application that is mainly based on a dialog box. Here are the steps to create a dialog base project using project templates available in Visual Studio − " }, { "code": null, "e": 9891, "s": 9768, "text": "Step 1 − Open the Visual studio and click on the File → New → Project menu option. You can see the New Project dialog box." }, { "code": null, "e": 9957, "s": 9891, "text": "Step 2 − From the left pane, select Templates → Visual C++ → MFC." }, { "code": null, "e": 10010, "s": 9957, "text": "Step 3 − In the middle pane, select MFC Application." }, { "code": null, "e": 10136, "s": 10010, "text": "Step 4 − Enter project name ‘MFCModalDemo’ in the Name field and click OK to continue. You will see the following dialog box." }, { "code": null, "e": 10157, "s": 10136, "text": "Step 5 − Click Next." }, { "code": null, "e": 10231, "s": 10157, "text": "Step 6 − Select the options shown in the above dialog box and click Next." }, { "code": null, "e": 10354, "s": 10231, "text": "Step 7 − Check all the options that you choose to have on your dialog box like Maximize and Minimize Boxes and click Next." }, { "code": null, "e": 10375, "s": 10354, "text": "Step 8 − Click Next." }, { "code": null, "e": 10477, "s": 10375, "text": "Step 9 − It will generate these two classes. You can change the name of the classes and click Finish." }, { "code": null, "e": 10581, "s": 10477, "text": "Step 10 − You can now see that the MFC wizard creates this Dialog Box and the project files by default." }, { "code": null, "e": 10657, "s": 10581, "text": "Step 11 − When you run this application, you will see the following output." }, { "code": null, "e": 10664, "s": 10657, "text": " Print" }, { "code": null, "e": 10675, "s": 10664, "text": " Add Notes" } ]
Difference between Test-Path and Resolve-Path in PowerShell?
Test-Path command checks if the particular path exists or not and returns the Boolean output (True or False) while Resolve-Path command displays the particular directory if exists otherwise throws an exception. For example, For the path to exist, PS C:\> Test-Path C:\Temp\ True PS C:\> Resolve-Path C:\Temp\ Path ---- C:\Temp\ For the path doesn’t exist, PS C:\> Test-Path C:\Temp11\ False PS C:\> Resolve-Path C:\Temp11\ Resolve-Path : Cannot find path 'C:\Temp11\' because it does not exist. At line:1 char:1 + Resolve-Path C:\Temp11\ + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Temp11\:String) [Resolve-Path], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand Resolve-Path is also used to get the file content using the wildcard character. For example, Resolve-Path C:\Temp\* The above command will get all the files and folders inside the C:\temp path. Resolve-Path C:\Temp\web* The above command will get all the files from the C:\temp with the Web starting keyword. Path ---- C:\Temp\WebImages C:\Temp\web.html C:\Temp\web1.html
[ { "code": null, "e": 1286, "s": 1062, "text": "Test-Path command checks if the particular path exists or not and returns the Boolean output (True or False) while Resolve-Path command displays the particular directory if exists otherwise throws an exception. For example," }, { "code": null, "e": 1309, "s": 1286, "text": "For the path to exist," }, { "code": null, "e": 1390, "s": 1309, "text": "PS C:\\> Test-Path C:\\Temp\\\nTrue\nPS C:\\> Resolve-Path C:\\Temp\\\nPath\n----\nC:\\Temp\\" }, { "code": null, "e": 1418, "s": 1390, "text": "For the path doesn’t exist," }, { "code": null, "e": 1805, "s": 1418, "text": "PS C:\\> Test-Path C:\\Temp11\\\nFalse\nPS C:\\> Resolve-Path C:\\Temp11\\\nResolve-Path : Cannot find path 'C:\\Temp11\\' because it does not exist.\nAt line:1 char:1\n+ Resolve-Path C:\\Temp11\\\n+ ~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : ObjectNotFound: (C:\\Temp11\\:String) [Resolve-Path], ItemNotFoundException\n+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand" }, { "code": null, "e": 1898, "s": 1805, "text": "Resolve-Path is also used to get the file content using the wildcard character. For example," }, { "code": null, "e": 1921, "s": 1898, "text": "Resolve-Path C:\\Temp\\*" }, { "code": null, "e": 1999, "s": 1921, "text": "The above command will get all the files and folders inside the C:\\temp path." }, { "code": null, "e": 2025, "s": 1999, "text": "Resolve-Path C:\\Temp\\web*" }, { "code": null, "e": 2114, "s": 2025, "text": "The above command will get all the files from the C:\\temp with the Web starting keyword." }, { "code": null, "e": 2177, "s": 2114, "text": "Path\n----\nC:\\Temp\\WebImages\nC:\\Temp\\web.html\nC:\\Temp\\web1.html" } ]
How to get file last modified time in Java?
He class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method. Following Java program gets the last modified time of a directory − import java.io.File; import java.util.Date; public class GettingLastmodifiedTime { public static void main(String args[]) { String filePath = "D://ExampleDirectory//"; //Creating the File object File file = new File(filePath); //Getting the last modified time long lastModified = file.lastModified(); Date date = new Date(lastModified); System.out.println("Given file was last modified at: "); System.out.println(date); } } Given file was last modified at: Wed Jul 03 19:20:50 IST 2019
[ { "code": null, "e": 1252, "s": 1062, "text": "He class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories." }, { "code": null, "e": 1464, "s": 1252, "text": "The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method." }, { "code": null, "e": 1532, "s": 1464, "text": "Following Java program gets the last modified time of a directory −" }, { "code": null, "e": 2010, "s": 1532, "text": "import java.io.File;\nimport java.util.Date;\npublic class GettingLastmodifiedTime {\n public static void main(String args[]) {\n String filePath = \"D://ExampleDirectory//\";\n //Creating the File object\n File file = new File(filePath);\n //Getting the last modified time\n long lastModified = file.lastModified();\n Date date = new Date(lastModified);\n System.out.println(\"Given file was last modified at: \");\n System.out.println(date);\n }\n}" }, { "code": null, "e": 2072, "s": 2010, "text": "Given file was last modified at:\nWed Jul 03 19:20:50 IST 2019" } ]
Early and late binding in C# - GeeksforGeeks
23 Jan, 2019 When an object is assigned to an object variable of the specific type, then the C# compiler performs the binding with the help of .NET Framework. C# performs two different types of bindings which are: Early Binding or Static Binding Late Binding or Dynamic Binding It recognizes and checks the methods, or properties during compile time. In this binding, the compiler already knows about what kind of object it is and what are the methods or properties it holds, here the objects are static objects. The performance of early binding is fast and it is easy to code. It decreases the number of run-time errors. Example: // C# program to illustrate the// concept of early bindingusing System; class Geeks { // data members public string name; public string subject; // public method public void details(string name, string subject) { this.name = name; this.subject = subject; Console.WriteLine("Myself: " + name); Console.WriteLine("My Favorite Subject is: " + subject); }} // Driver classclass GFG { // Main Method static void Main(string[] args) { // creating object of Geeks class Geeks g = new Geeks(); // Calling the method of Geeks class g.details("Ankita", "C#"); // Calling "mymethod()" gives error // because this method does not // belong to class Geeks or compiler // does not know mymethod() at compile time g.mymethod(); }} Compile-Time error: prog.cs(34, 5): error CS1061: Type `Geeks’ does not contain a definition for `mymethod’ and no extension method `mymethod’ of type `Geeks’ could be found. Are you missing an assembly reference?prog.cs(5, 7): (Location of the symbol related to previous error) Explanation: In the above example, we have a class named as Geeks. This class contains details() method. Here, the compiler already knows about the properties and methods present in Geeks. But when we try to call mymethod() then it will throw an error because this method is not known by the compiler. In late binding, the compiler does not know about what kind of object it is and what are the methods or properties it holds, here the objects are dynamic objects. The type of the object is decided on the bases of the data it holds on the right-hand side during run-time. Basically, late binding is achieved by using virtual methods. The performance of late binding is slower than early binding because it requires lookups at run-time. Example: In the below, program the obj holds integer type data and obj1 holds double type data. But the compiler doesn’t resolve these at compile-time. At the runtime, these dynamic objects get detected and converted into System.Int32 and System.Double respectively. Thats why the run-time resolving process is termed as late binding. // C# program to illustrate the// concept of late bindingusing System; class GFG { static void Main() { // Dynamic objects dynamic obj = 4; dynamic obj1 = 5.678; // Display the type of objects Console.WriteLine("The type of the objects are :"); // GetType() method is // used to get the type Console.WriteLine(obj.GetType()); Console.WriteLine(obj1.GetType()); }} Output : The type of the objects are : System.Int32 System.Double CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Abstract Classes C# | Data Types Destructors in C# HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 24342, "s": 24314, "text": "\n23 Jan, 2019" }, { "code": null, "e": 24543, "s": 24342, "text": "When an object is assigned to an object variable of the specific type, then the C# compiler performs the binding with the help of .NET Framework. C# performs two different types of bindings which are:" }, { "code": null, "e": 24575, "s": 24543, "text": "Early Binding or Static Binding" }, { "code": null, "e": 24607, "s": 24575, "text": "Late Binding or Dynamic Binding" }, { "code": null, "e": 24951, "s": 24607, "text": "It recognizes and checks the methods, or properties during compile time. In this binding, the compiler already knows about what kind of object it is and what are the methods or properties it holds, here the objects are static objects. The performance of early binding is fast and it is easy to code. It decreases the number of run-time errors." }, { "code": null, "e": 24960, "s": 24951, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of early bindingusing System; class Geeks { // data members public string name; public string subject; // public method public void details(string name, string subject) { this.name = name; this.subject = subject; Console.WriteLine(\"Myself: \" + name); Console.WriteLine(\"My Favorite Subject is: \" + subject); }} // Driver classclass GFG { // Main Method static void Main(string[] args) { // creating object of Geeks class Geeks g = new Geeks(); // Calling the method of Geeks class g.details(\"Ankita\", \"C#\"); // Calling \"mymethod()\" gives error // because this method does not // belong to class Geeks or compiler // does not know mymethod() at compile time g.mymethod(); }}", "e": 25816, "s": 24960, "text": null }, { "code": null, "e": 25836, "s": 25816, "text": "Compile-Time error:" }, { "code": null, "e": 26095, "s": 25836, "text": "prog.cs(34, 5): error CS1061: Type `Geeks’ does not contain a definition for `mymethod’ and no extension method `mymethod’ of type `Geeks’ could be found. Are you missing an assembly reference?prog.cs(5, 7): (Location of the symbol related to previous error)" }, { "code": null, "e": 26397, "s": 26095, "text": "Explanation: In the above example, we have a class named as Geeks. This class contains details() method. Here, the compiler already knows about the properties and methods present in Geeks. But when we try to call mymethod() then it will throw an error because this method is not known by the compiler." }, { "code": null, "e": 26832, "s": 26397, "text": "In late binding, the compiler does not know about what kind of object it is and what are the methods or properties it holds, here the objects are dynamic objects. The type of the object is decided on the bases of the data it holds on the right-hand side during run-time. Basically, late binding is achieved by using virtual methods. The performance of late binding is slower than early binding because it requires lookups at run-time." }, { "code": null, "e": 27167, "s": 26832, "text": "Example: In the below, program the obj holds integer type data and obj1 holds double type data. But the compiler doesn’t resolve these at compile-time. At the runtime, these dynamic objects get detected and converted into System.Int32 and System.Double respectively. Thats why the run-time resolving process is termed as late binding." }, { "code": "// C# program to illustrate the// concept of late bindingusing System; class GFG { static void Main() { // Dynamic objects dynamic obj = 4; dynamic obj1 = 5.678; // Display the type of objects Console.WriteLine(\"The type of the objects are :\"); // GetType() method is // used to get the type Console.WriteLine(obj.GetType()); Console.WriteLine(obj1.GetType()); }}", "e": 27609, "s": 27167, "text": null }, { "code": null, "e": 27618, "s": 27609, "text": "Output :" }, { "code": null, "e": 27676, "s": 27618, "text": "The type of the objects are :\nSystem.Int32\nSystem.Double\n" }, { "code": null, "e": 27687, "s": 27676, "text": "CSharp-OOP" }, { "code": null, "e": 27690, "s": 27687, "text": "C#" }, { "code": null, "e": 27788, "s": 27690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27816, "s": 27788, "text": "C# Dictionary with examples" }, { "code": null, "e": 27831, "s": 27816, "text": "C# | Delegates" }, { "code": null, "e": 27862, "s": 27831, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27902, "s": 27862, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27925, "s": 27902, "text": "Extension Method in C#" }, { "code": null, "e": 27947, "s": 27925, "text": "C# | Abstract Classes" }, { "code": null, "e": 27963, "s": 27947, "text": "C# | Data Types" }, { "code": null, "e": 27981, "s": 27963, "text": "Destructors in C#" }, { "code": null, "e": 28009, "s": 27981, "text": "HashSet in C# with Examples" } ]
How to limit the values in a Number JSpinner Component with Java?
To limit the values in a number JSpinner component, use the SpinnerNumberModel that allows to set the min, max, step size and even the initial value − value − current value of the model min − first number in the sequence max − last number in the sequence stepSize − difference between elements of the sequence Let us set the above values − int min = 0; int max = 10; int step = 1; int i = 1; SpinnerModel value = new SpinnerNumberModel(i, min, max, step); Now, we will set these values to our JSpinner − JSpinner spinner = new JSpinner(value); The following is an example to limit the values in a number JSpinner component − package my; import java.awt.GridBagLayout; import javax.swing.*; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Spinner Demo"); JPanel panel = new JPanel(); JLabel label = new JLabel("Rank − "); panel.setLayout(new GridBagLayout()); int min = 0; int max = 10; int step = 1; int i = 1; SpinnerModel value = new SpinnerNumberModel(i, min, max, step); JSpinner spinner = new JSpinner(value); spinner.setBounds(50, 80, 70, 100); panel.add(label); panel.add(spinner); frame.add(panel); frame.setSize(550,300); frame.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1213, "s": 1062, "text": "To limit the values in a number JSpinner component, use the SpinnerNumberModel that allows to set the min, max, step size and even the initial value −" }, { "code": null, "e": 1372, "s": 1213, "text": "value − current value of the model\nmin − first number in the sequence\nmax − last number in the sequence\nstepSize − difference between elements of the sequence" }, { "code": null, "e": 1402, "s": 1372, "text": "Let us set the above values −" }, { "code": null, "e": 1518, "s": 1402, "text": "int min = 0;\nint max = 10;\nint step = 1;\nint i = 1;\nSpinnerModel value = new SpinnerNumberModel(i, min, max, step);" }, { "code": null, "e": 1566, "s": 1518, "text": "Now, we will set these values to our JSpinner −" }, { "code": null, "e": 1606, "s": 1566, "text": "JSpinner spinner = new JSpinner(value);" }, { "code": null, "e": 1687, "s": 1606, "text": "The following is an example to limit the values in a number JSpinner component −" }, { "code": null, "e": 2368, "s": 1687, "text": "package my;\nimport java.awt.GridBagLayout;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Spinner Demo\");\n JPanel panel = new JPanel();\n JLabel label = new JLabel(\"Rank − \");\n panel.setLayout(new GridBagLayout());\n int min = 0;\n int max = 10;\n int step = 1;\n int i = 1;\n SpinnerModel value = new SpinnerNumberModel(i, min, max, step);\n JSpinner spinner = new JSpinner(value);\n spinner.setBounds(50, 80, 70, 100);\n panel.add(label);\n panel.add(spinner);\n frame.add(panel);\n frame.setSize(550,300);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2409, "s": 2368, "text": "This will produce the following output −" } ]
Rearrange Array Alternately | Practice | GeeksforGeeks
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on. Example 1: Input: N = 6 arr[] = {1,2,3,4,5,6} Output: 6 1 5 2 4 3 Explanation: Max element = 6, min = 1, second max = 5, second min = 2, and so on... Modified array is : 6 1 5 2 4 3. Example 2: Input: N = 11 arr[]={10,20,30,40,50,60,70,80,90,100,110} Output:110 10 100 20 90 30 80 40 70 50 60 Explanation: Max element = 110, min = 10, second max = 100, second min = 20, and so on... Modified array is : 110 10 100 20 90 30 80 40 70 50 60. Your Task: The task is to complete the function rearrange() which rearranges elements as explained above. Printing of the modified array will be handled by driver code. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 <= N <= 106 1 <= arr[i] <= 107 0 mihirdhabe1 day ago Easy C++ Solution void rearrange(long long *arr, int n) { // Your code here vector<int>v; for(int i=0;i<n;i++) { v.push_back(arr[i]); } int i=0; int j=1; while(i<n) { arr[i]=v[v.size()-j]; i+=2; j++; } i=1; j=0; while(i<n) { arr[i]=v[j]; i+=2; j++; } } 0 bhavikkasundra551 week ago if(n==1)return ; vector<long long>v; long long left=0,right=n-1; int count=0; while(left<=right){ // cout<<arr[right]<<" "; v.push_back(arr[right]); right--; // cout<<arr[left]<<" "; v.push_back(arr[left]); left++; } for(long long i=0;i<n;i++){ arr[i] = v[i]; } 0 rishabh21cse1 week ago best c++ sol --------------------- void rearrange(long long *arr, int n) { // Your code here int i=0; int j = n-1; vector<int> v; while(i<=j){ if(i==j){ v.push_back(arr[j]); } v.push_back(arr[j]); v.push_back(arr[i]); i++; j--; } for(int i=0;i<v.size();i++){ arr[i]=v[i]; } } +1 daniilb2 weeks ago void rearrange(long long *arr, int n) { // this approach is based on calculating the destination position // for a given element, moving it there, and repeating this // procedure for the just replaced element until all elements // are placed in their required positions. // To track that an element has been moved we change its sign //find mid point that will go to the end int mid = (n-1)/2; for (int i = 0; i < n; ++i) { if (arr[i] > 0) { int i_curr = i; int saved = arr[i_curr]; while (1) { // compute destination of the current element int i_next; if (i_curr == mid) { i_next = n-1; } else if (i_curr < mid) { i_next = 2*i_curr+1; } else { i_next = 2*(n-1-i_curr); } if (arr[i_next] < 0) { // found a loop break; } else { // move the current element to its destination // but save value at the destination beforehand int tmp = arr[i_next]; arr[i_next] = -saved; saved = tmp; i_curr = i_next; } } } } // flip all numbers back to being positive for (int i = 0; i < n; ++i) { arr[i] = -arr[i]; } } -1 sachinsharma291112 weeks ago class Solution: ##Complete this function #Function to rearrange the array elements alternately. def rearrange(self,arr, n): ##Your code here max_index=n-1 min_index=0 maximum=arr[n-1]+1 for i in range(n): if (i%2==0): arr[i]=(arr[max_index]%maximum)*maximum+arr[i] max_index=max_index-1 else: arr[i]=(arr[min_index]%maximum)*maximum+arr[i] min_index=min_index+1 for i in range(n): arr[i]=arr[i]//maximum 0 mayank180919992 weeks ago void rearrange(long long *arr, int n) { // Your code here int i=0; int j=n-1; vector<int>nums; while(i<=j){ if(i==j){ nums.push_back(arr[j]); } nums.push_back(arr[j]); nums.push_back(arr[i]); i++; j--; } for(int i=0;i<nums.size();i++){ arr[i]=nums[i]; } } 0 user_990i2 weeks ago void rearrange(long long *arr, int n) { long long prime=1000000007; //prime*rearranged+original long long high=n-1,low=0; for(int i=0;i<n;i++){ long long l=(arr[low]%prime); long long h=(arr[high]%prime); if(i%2==0){ arr[i]=h*prime+arr[i]; high--; } else{ arr[i]=l*prime+arr[i]; low++; } } for(int i=0;i<n;i++){ arr[i]=arr[i]/prime; } }}; 0 itskiran This comment was deleted. 0 souvik404d This comment was deleted. 0 hk63017359392 weeks ago JAVA SOLUTION.............. public static void rearrange(long arr[], int n){ ArrayList<Long> o1 = new ArrayList<>(); for(int i=0;i<n;i++){ o1.add(arr[n-1-i]); o1.add(arr[i]); } for(int i=0;i<n;i++){ arr[i]=o1.get(i); } } 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": 527, "s": 290, "text": "Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on." }, { "code": null, "e": 538, "s": 527, "text": "Example 1:" }, { "code": null, "e": 712, "s": 538, "text": "Input:\nN = 6\narr[] = {1,2,3,4,5,6}\nOutput: 6 1 5 2 4 3\nExplanation: Max element = 6, min = 1, \nsecond max = 5, second min = 2, and \nso on... Modified array is : 6 1 5 2 4 3." }, { "code": null, "e": 723, "s": 712, "text": "Example 2:" }, { "code": null, "e": 972, "s": 723, "text": "Input:\nN = 11\narr[]={10,20,30,40,50,60,70,80,90,100,110}\nOutput:110 10 100 20 90 30 80 40 70 50 60\nExplanation: Max element = 110, min = 10, \nsecond max = 100, second min = 20, and \nso on... Modified array is : \n110 10 100 20 90 30 80 40 70 50 60.\n" }, { "code": null, "e": 1141, "s": 972, "text": "Your Task:\nThe task is to complete the function rearrange() which rearranges elements as explained above. Printing of the modified array will be handled by driver code." }, { "code": null, "e": 1205, "s": 1141, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1251, "s": 1205, "text": "Constraints:\n1 <= N <= 106\n1 <= arr[i] <= 107" }, { "code": null, "e": 1253, "s": 1251, "text": "0" }, { "code": null, "e": 1273, "s": 1253, "text": "mihirdhabe1 day ago" }, { "code": null, "e": 1291, "s": 1273, "text": "Easy C++ Solution" }, { "code": null, "e": 1677, "s": 1291, "text": "void rearrange(long long *arr, int n) { // Your code here vector<int>v; for(int i=0;i<n;i++) { v.push_back(arr[i]); } int i=0; int j=1; while(i<n) { arr[i]=v[v.size()-j]; i+=2; j++; } i=1; j=0; while(i<n) { arr[i]=v[j]; i+=2; j++; } }" }, { "code": null, "e": 1679, "s": 1677, "text": "0" }, { "code": null, "e": 1706, "s": 1679, "text": "bhavikkasundra551 week ago" }, { "code": null, "e": 2033, "s": 1706, "text": "if(n==1)return ; vector<long long>v; long long left=0,right=n-1; int count=0; while(left<=right){ // cout<<arr[right]<<\" \"; v.push_back(arr[right]); right--; // cout<<arr[left]<<\" \"; v.push_back(arr[left]); left++; } for(long long i=0;i<n;i++){ arr[i] = v[i]; }" }, { "code": null, "e": 2035, "s": 2033, "text": "0" }, { "code": null, "e": 2058, "s": 2035, "text": "rishabh21cse1 week ago" }, { "code": null, "e": 2093, "s": 2058, "text": "best c++ sol ---------------------" }, { "code": null, "e": 2449, "s": 2093, "text": " void rearrange(long long *arr, int n) { // Your code here int i=0; int j = n-1; vector<int> v; while(i<=j){ if(i==j){ v.push_back(arr[j]); } v.push_back(arr[j]); v.push_back(arr[i]); i++; j--; } for(int i=0;i<v.size();i++){ arr[i]=v[i]; } }" }, { "code": null, "e": 2452, "s": 2449, "text": "+1" }, { "code": null, "e": 2471, "s": 2452, "text": "daniilb2 weeks ago" }, { "code": null, "e": 4011, "s": 2471, "text": " void rearrange(long long *arr, int n) { // this approach is based on calculating the destination position // for a given element, moving it there, and repeating this // procedure for the just replaced element until all elements // are placed in their required positions. // To track that an element has been moved we change its sign //find mid point that will go to the end int mid = (n-1)/2; for (int i = 0; i < n; ++i) { if (arr[i] > 0) { int i_curr = i; int saved = arr[i_curr]; while (1) { // compute destination of the current element int i_next; if (i_curr == mid) { i_next = n-1; } else if (i_curr < mid) { i_next = 2*i_curr+1; } else { i_next = 2*(n-1-i_curr); } if (arr[i_next] < 0) { // found a loop break; } else { // move the current element to its destination // but save value at the destination beforehand int tmp = arr[i_next]; arr[i_next] = -saved; saved = tmp; i_curr = i_next; } } } } // flip all numbers back to being positive for (int i = 0; i < n; ++i) { arr[i] = -arr[i]; } }" }, { "code": null, "e": 4014, "s": 4011, "text": "-1" }, { "code": null, "e": 4043, "s": 4014, "text": "sachinsharma291112 weeks ago" }, { "code": null, "e": 4577, "s": 4043, "text": "class Solution: ##Complete this function #Function to rearrange the array elements alternately. def rearrange(self,arr, n): ##Your code here max_index=n-1 min_index=0 maximum=arr[n-1]+1 for i in range(n): if (i%2==0): arr[i]=(arr[max_index]%maximum)*maximum+arr[i] max_index=max_index-1 else: arr[i]=(arr[min_index]%maximum)*maximum+arr[i] min_index=min_index+1 for i in range(n): arr[i]=arr[i]//maximum" }, { "code": null, "e": 4579, "s": 4577, "text": "0" }, { "code": null, "e": 4605, "s": 4579, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 5000, "s": 4605, "text": " void rearrange(long long *arr, int n) \n { \n \t\n \t// Your code here\n \tint i=0;\n \tint j=n-1;\n \tvector<int>nums;\n \twhile(i<=j){\n \t if(i==j){\n \t nums.push_back(arr[j]);\n \t }\n \t nums.push_back(arr[j]);\n \t nums.push_back(arr[i]);\n \t i++;\n \t j--;\n \t}\n \tfor(int i=0;i<nums.size();i++){\n \t arr[i]=nums[i];\n \t}\n \t \n }" }, { "code": null, "e": 5002, "s": 5000, "text": "0" }, { "code": null, "e": 5023, "s": 5002, "text": "user_990i2 weeks ago" }, { "code": null, "e": 5586, "s": 5023, "text": "void rearrange(long long *arr, int n) { long long prime=1000000007; //prime*rearranged+original long long high=n-1,low=0; for(int i=0;i<n;i++){ long long l=(arr[low]%prime); long long h=(arr[high]%prime); if(i%2==0){ arr[i]=h*prime+arr[i]; high--; } else{ arr[i]=l*prime+arr[i]; low++; } } for(int i=0;i<n;i++){ arr[i]=arr[i]/prime; } }};" }, { "code": null, "e": 5588, "s": 5586, "text": "0" }, { "code": null, "e": 5597, "s": 5588, "text": "itskiran" }, { "code": null, "e": 5623, "s": 5597, "text": "This comment was deleted." }, { "code": null, "e": 5625, "s": 5623, "text": "0" }, { "code": null, "e": 5636, "s": 5625, "text": "souvik404d" }, { "code": null, "e": 5662, "s": 5636, "text": "This comment was deleted." }, { "code": null, "e": 5664, "s": 5662, "text": "0" }, { "code": null, "e": 5688, "s": 5664, "text": "hk63017359392 weeks ago" }, { "code": null, "e": 5718, "s": 5688, "text": "JAVA SOLUTION.............. " }, { "code": null, "e": 5987, "s": 5718, "text": "public static void rearrange(long arr[], int n){ ArrayList<Long> o1 = new ArrayList<>(); for(int i=0;i<n;i++){ o1.add(arr[n-1-i]); o1.add(arr[i]); } for(int i=0;i<n;i++){ arr[i]=o1.get(i); } }" }, { "code": null, "e": 6133, "s": 5987, "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": 6169, "s": 6133, "text": " Login to access your submissions. " }, { "code": null, "e": 6179, "s": 6169, "text": "\nProblem\n" }, { "code": null, "e": 6189, "s": 6179, "text": "\nContest\n" }, { "code": null, "e": 6252, "s": 6189, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6400, "s": 6252, "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": 6608, "s": 6400, "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": 6714, "s": 6608, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Jump Search
Jump search technique also works for ordered lists. It creates a block and tries to find the element in that block. If the item is not in the block, it shifts the entire block. The block size is based on the size of the list. If the size of the list is n then block size will be √n. After finding a correct block it finds the item using a linear search technique. The jump search lies between linear search and binary search according to its performance. Time Complexity: O(√n) Space Complexity: O(1) Input: A sorted list of data: 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995 The search key 356 Output: Item found at location: 11 jumpSearch(array, size, key) Input: An sorted array, size of the array and the search key Output − location of the key (if found), otherwise wrong location. Begin blockSize := √size start := 0 end := blockSize while array[end] <= key AND end < size do start := end end := end + blockSize if end > size – 1 then end := size done for i := start to end -1 do if array[i] = key then return i done return invalid location End #include<iostream> #include<cmath> using namespace std; int jumpSearch(int array[], int size, int key) { int start = 0; int end = sqrt(size); //the square root of array length while(array[end] <= key && end < size) { start = end; //it it is not correct block then shift block end += sqrt(size); if(end > size - 1) end = size; //if right exceeds then bound the range } for(int i = start; i<end; i++) { //perform linear search in selected block if(array[i] == key) return i; //the correct position of the key } return -1; } int main() { int n, searchKey, loc; cout << "Enter number of items: "; cin >> n; int arr[n]; //create an array of size n cout << "Enter items: " << endl; for(int i = 0; i< n; i++) { cin >> arr[i]; } cout << "Enter search key to search in the list: "; cin >> searchKey; if((loc = jumpSearch(arr, n, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "Item is not found in the list." << endl; } Enter number of items: 20 Enter items: 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995 Enter search key to search in the list: 356 Item found at location: 11
[ { "code": null, "e": 1517, "s": 1062, "text": "Jump search technique also works for ordered lists. It creates a block and tries to find the element in that block. If the item is not in the block, it shifts the entire block. The block size is based on the size of the list. If the size of the list is n then block size will be √n. After finding a correct block it finds the item using a linear search technique. The jump search lies between linear search and binary search according to its performance." }, { "code": null, "e": 1540, "s": 1517, "text": "Time Complexity: O(√n)" }, { "code": null, "e": 1563, "s": 1540, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1718, "s": 1563, "text": "Input:\nA sorted list of data:\n10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995\nThe search key 356\nOutput:\nItem found at location: 11" }, { "code": null, "e": 1747, "s": 1718, "text": "jumpSearch(array, size, key)" }, { "code": null, "e": 1808, "s": 1747, "text": "Input: An sorted array, size of the array and the search key" }, { "code": null, "e": 1875, "s": 1808, "text": "Output − location of the key (if found), otherwise wrong location." }, { "code": null, "e": 2205, "s": 1875, "text": "Begin\n blockSize := √size\n start := 0\n end := blockSize\n while array[end] <= key AND end < size do\n start := end\n end := end + blockSize\n if end > size – 1 then\n end := size\n done\n for i := start to end -1 do\n if array[i] = key then\n return i\n done\n return invalid location\nEnd" }, { "code": null, "e": 3271, "s": 2205, "text": "#include<iostream>\n#include<cmath>\n\nusing namespace std;\nint jumpSearch(int array[], int size, int key) {\n int start = 0;\n int end = sqrt(size); //the square root of array length\n\n while(array[end] <= key && end < size) {\n start = end; //it it is not correct block then shift block\n end += sqrt(size);\n if(end > size - 1)\n end = size; //if right exceeds then bound the range\n }\n\n for(int i = start; i<end; i++) { //perform linear search in selected block\n if(array[i] == key)\n return i; //the correct position of the key\n }\n return -1;\n}\n\nint main() {\n int n, searchKey, loc;\n cout << \"Enter number of items: \";\n cin >> n;\n int arr[n]; //create an array of size n\n cout << \"Enter items: \" << endl;\n\n for(int i = 0; i< n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Enter search key to search in the list: \";\n cin >> searchKey;\n if((loc = jumpSearch(arr, n, searchKey)) >= 0)\n cout << \"Item found at location: \" << loc << endl;\n else\n cout << \"Item is not found in the list.\" << endl;\n}" }, { "code": null, "e": 3452, "s": 3271, "text": "Enter number of items: 20\nEnter items:\n10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995\nEnter search key to search in the list: 356\nItem found at location: 11" } ]
R - Packages
R packages are a collection of R functions, complied code and sample data. They are stored under a directory called "library" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them. All the packages available in R language are listed at R Packages. Below is a list of commands to be used to check, verify and use the R packages. Get library locations containing R packages .libPaths() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. [2] "C:/Program Files/R/R-3.2.2/library" library() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. Packages in library ‘C:/Program Files/R/R-3.2.2/library’: base The R Base Package boot Bootstrap Functions (Originally by Angelo Canty for S) class Functions for Classification cluster "Finding Groups in Data": Cluster Analysis Extended Rousseeuw et al. codetools Code Analysis Tools for R compiler The R Compiler Package datasets The R Datasets Package foreign Read Data Stored by 'Minitab', 'S', 'SAS', 'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ... graphics The R Graphics Package grDevices The R Graphics Devices and Support for Colours and Fonts grid The Grid Graphics Package KernSmooth Functions for Kernel Smoothing Supporting Wand & Jones (1995) lattice Trellis Graphics for R MASS Support Functions and Datasets for Venables and Ripley's MASS Matrix Sparse and Dense Matrix Classes and Methods methods Formal Methods and Classes mgcv Mixed GAM Computation Vehicle with GCV/AIC/REML Smoothness Estimation nlme Linear and Nonlinear Mixed Effects Models nnet Feed-Forward Neural Networks and Multinomial Log-Linear Models parallel Support for Parallel computation in R rpart Recursive Partitioning and Regression Trees spatial Functions for Kriging and Point Pattern Analysis splines Regression Spline Functions and Classes stats The R Stats Package stats4 Statistical Functions using S4 Classes survival Survival Analysis tcltk Tcl/Tk Interface tools Tools for Package Development utils The R Utils Package Get all packages currently loaded in the R environment search() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. [1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" "package:datasets" [7] "package:methods" "Autoloads" "package:base" There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually. The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location. install.packages("Package Name") # Install the package named "XML". install.packages("XML") Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system. Now you can run the following command to install this package in the R environment. install.packages(file_name_with_path, repos = NULL, type = "source") # Install the package named "XML" install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source") Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment. A package is loaded using the following command − library("package Name", lib.loc = "path to library") # Load the package named "XML" install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source") 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2899, "s": 2402, "text": "R packages are a collection of R functions, complied code and sample data. They are stored under a directory called \"library\" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them." }, { "code": null, "e": 2966, "s": 2899, "text": "All the packages available in R language are listed at R Packages." }, { "code": null, "e": 3046, "s": 2966, "text": "Below is a list of commands to be used to check, verify and use the R packages." }, { "code": null, "e": 3090, "s": 3046, "text": "Get library locations containing R packages" }, { "code": null, "e": 3102, "s": 3090, "text": ".libPaths()" }, { "code": null, "e": 3224, "s": 3102, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 3266, "s": 3224, "text": "[2] \"C:/Program Files/R/R-3.2.2/library\"\n" }, { "code": null, "e": 3276, "s": 3266, "text": "library()" }, { "code": null, "e": 3398, "s": 3276, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 5519, "s": 3398, "text": "Packages in library ‘C:/Program Files/R/R-3.2.2/library’:\n\nbase The R Base Package\nboot Bootstrap Functions (Originally by Angelo Canty\n for S)\nclass Functions for Classification\ncluster \"Finding Groups in Data\": Cluster Analysis\n Extended Rousseeuw et al.\ncodetools Code Analysis Tools for R\ncompiler The R Compiler Package\ndatasets The R Datasets Package\nforeign Read Data Stored by 'Minitab', 'S', 'SAS',\n 'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ...\ngraphics The R Graphics Package\ngrDevices The R Graphics Devices and Support for Colours\n and Fonts\ngrid The Grid Graphics Package\nKernSmooth Functions for Kernel Smoothing Supporting Wand\n & Jones (1995)\nlattice Trellis Graphics for R\nMASS Support Functions and Datasets for Venables and\n Ripley's MASS\nMatrix Sparse and Dense Matrix Classes and Methods\nmethods Formal Methods and Classes\nmgcv Mixed GAM Computation Vehicle with GCV/AIC/REML\n Smoothness Estimation\nnlme Linear and Nonlinear Mixed Effects Models\nnnet Feed-Forward Neural Networks and Multinomial\n Log-Linear Models\nparallel Support for Parallel computation in R\nrpart Recursive Partitioning and Regression Trees\nspatial Functions for Kriging and Point Pattern\n Analysis\nsplines Regression Spline Functions and Classes\nstats The R Stats Package\nstats4 Statistical Functions using S4 Classes\nsurvival Survival Analysis\ntcltk Tcl/Tk Interface\ntools Tools for Package Development\nutils The R Utils Package\n" }, { "code": null, "e": 5574, "s": 5519, "text": "Get all packages currently loaded in the R environment" }, { "code": null, "e": 5583, "s": 5574, "text": "search()" }, { "code": null, "e": 5705, "s": 5583, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 5894, "s": 5705, "text": "[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n" }, { "code": null, "e": 6075, "s": 5894, "text": "There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually." }, { "code": null, "e": 6282, "s": 6075, "text": "The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location." }, { "code": null, "e": 6379, "s": 6282, "text": " install.packages(\"Package Name\")\n \n# Install the package named \"XML\".\n install.packages(\"XML\")\n" }, { "code": null, "e": 6513, "s": 6379, "text": "Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system." }, { "code": null, "e": 6597, "s": 6513, "text": "Now you can run the following command to install this package in the R environment." }, { "code": null, "e": 6772, "s": 6597, "text": "install.packages(file_name_with_path, repos = NULL, type = \"source\")\n\n# Install the package named \"XML\"\ninstall.packages(\"E:/XML_3.98-1.3.zip\", repos = NULL, type = \"source\")" }, { "code": null, "e": 6977, "s": 6772, "text": "Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment." }, { "code": null, "e": 7027, "s": 6977, "text": "A package is loaded using the following command −" }, { "code": null, "e": 7184, "s": 7027, "text": "library(\"package Name\", lib.loc = \"path to library\")\n\n# Load the package named \"XML\"\ninstall.packages(\"E:/XML_3.98-1.3.zip\", repos = NULL, type = \"source\")\n" }, { "code": null, "e": 7217, "s": 7184, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 7232, "s": 7217, "text": " Nishant Malik" }, { "code": null, "e": 7267, "s": 7232, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7282, "s": 7267, "text": " Nishant Malik" }, { "code": null, "e": 7317, "s": 7282, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7332, "s": 7317, "text": " Nishant Malik" }, { "code": null, "e": 7365, "s": 7332, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7379, "s": 7365, "text": " Asif Hussain" }, { "code": null, "e": 7414, "s": 7379, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7429, "s": 7414, "text": " Nishant Malik" }, { "code": null, "e": 7464, "s": 7429, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7478, "s": 7464, "text": " Asif Hussain" }, { "code": null, "e": 7485, "s": 7478, "text": " Print" }, { "code": null, "e": 7496, "s": 7485, "text": " Add Notes" } ]
Draw Color Filled Shapes in Turtle - Python - GeeksforGeeks
10 Feb, 2020 Prerequisite: Python Turtle Basics turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc. To fill the colors in the shapes drawn by turtle, turtle provides three functions – fillcolor(): This helps to choose the color for filling the shape. It takes the input parameter as the color name or hex value of the color and fills the upcoming closed geographical objects with the chosen color. Color names are basic color names i.e. red, blue, green, orange.The hex value of color is a string(starting with ‘#’) of hexadecimal numbers i.e. #RRGGBB. R, G, and B are the hexadecimal numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F). begin_fill(): This function tells turtle that all upcoming closed graphical objects needed to be filled by the chosen color. end_fill(): this function tells turtle to stop the filling upcoming closed graphical objects. # draw color-filled square in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the squares = int(input("Enter the length of the side of the square: ")) # taking the input for the colorcol = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the square of side sfor _ in range(4): t.forward(s) t.right(90) # ending the filling of the colort.end_fill() Input : 200 green Output : # draw color filled triangle in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the triangles = int(input("Enter the length of the side of the triangle: ")) # taking the input for the colorcol = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the triangle of side sfor _ in range(3): t.forward(s) t.right(-120) # ending the filling of the colort.end_fill() Input : 200 red Output : # draw color-filled hexagon in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the hexagons = int(input("Enter the length of the side of the hexagon: ")) # taking the input for the colorcol = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the hexagon of side sfor _ in range(6): t.forward(s) t.right(-60) # ending the filling of the colort.end_fill() Input : 100 #113300 Output : # draw color filled star in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the stars = int(input("Enter the length of the side of the star: ")) # taking the input for the colorcol = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the star of side sfor _ in range(5): t.forward(s) t.right(144) # ending the filling of colort.end_fill() Input : 200 #551122 Output : # draw color filled circle in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the radius of the circler = int(input("Enter the radius of the circle: ")) # taking the input for the colorcol = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the circle of radius rt.circle(r) # ending the filling of the colort.end_fill() Input : 100 blue Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24526, "s": 24498, "text": "\n10 Feb, 2020" }, { "code": null, "e": 24561, "s": 24526, "text": "Prerequisite: Python Turtle Basics" }, { "code": null, "e": 24799, "s": 24561, "text": "turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 24883, "s": 24799, "text": "To fill the colors in the shapes drawn by turtle, turtle provides three functions –" }, { "code": null, "e": 25342, "s": 24883, "text": "fillcolor(): This helps to choose the color for filling the shape. It takes the input parameter as the color name or hex value of the color and fills the upcoming closed geographical objects with the chosen color. Color names are basic color names i.e. red, blue, green, orange.The hex value of color is a string(starting with ‘#’) of hexadecimal numbers i.e. #RRGGBB. R, G, and B are the hexadecimal numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)." }, { "code": null, "e": 25467, "s": 25342, "text": "begin_fill(): This function tells turtle that all upcoming closed graphical objects needed to be filled by the chosen color." }, { "code": null, "e": 25561, "s": 25467, "text": "end_fill(): this function tells turtle to stop the filling upcoming closed graphical objects." }, { "code": "# draw color-filled square in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the squares = int(input(\"Enter the length of the side of the square: \")) # taking the input for the colorcol = input(\"Enter the color name or hex value of color(# RRGGBB): \") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the square of side sfor _ in range(4): t.forward(s) t.right(90) # ending the filling of the colort.end_fill()", "e": 26065, "s": 25561, "text": null }, { "code": null, "e": 26073, "s": 26065, "text": "Input :" }, { "code": null, "e": 26083, "s": 26073, "text": "200\ngreen" }, { "code": null, "e": 26092, "s": 26083, "text": "Output :" }, { "code": "# draw color filled triangle in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the triangles = int(input(\"Enter the length of the side of the triangle: \")) # taking the input for the colorcol = input(\"Enter the color name or hex value of color(# RRGGBB): \") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the triangle of side sfor _ in range(3): t.forward(s) t.right(-120) # ending the filling of the colort.end_fill()", "e": 26606, "s": 26092, "text": null }, { "code": null, "e": 26614, "s": 26606, "text": "Input :" }, { "code": null, "e": 26622, "s": 26614, "text": "200\nred" }, { "code": null, "e": 26631, "s": 26622, "text": "Output :" }, { "code": "# draw color-filled hexagon in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the hexagons = int(input(\"Enter the length of the side of the hexagon: \")) # taking the input for the colorcol = input(\"Enter the color name or hex value of color(# RRGGBB): \") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the hexagon of side sfor _ in range(6): t.forward(s) t.right(-60) # ending the filling of the colort.end_fill()", "e": 27140, "s": 26631, "text": null }, { "code": null, "e": 27148, "s": 27140, "text": "Input :" }, { "code": null, "e": 27160, "s": 27148, "text": "100\n#113300" }, { "code": null, "e": 27169, "s": 27160, "text": "Output :" }, { "code": "# draw color filled star in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the side of the stars = int(input(\"Enter the length of the side of the star: \")) # taking the input for the colorcol = input(\"Enter the color name or hex value of color(# RRGGBB): \") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the star of side sfor _ in range(5): t.forward(s) t.right(144) # ending the filling of colort.end_fill()", "e": 27662, "s": 27169, "text": null }, { "code": null, "e": 27670, "s": 27662, "text": "Input :" }, { "code": null, "e": 27682, "s": 27670, "text": "200\n#551122" }, { "code": null, "e": 27691, "s": 27682, "text": "Output :" }, { "code": "# draw color filled circle in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the radius of the circler = int(input(\"Enter the radius of the circle: \")) # taking the input for the colorcol = input(\"Enter the color name or hex value of color(# RRGGBB): \") # set the fillcolort.fillcolor(col) # start the filling colort.begin_fill() # drawing the circle of radius rt.circle(r) # ending the filling of the colort.end_fill()", "e": 28153, "s": 27691, "text": null }, { "code": null, "e": 28161, "s": 28153, "text": "Input :" }, { "code": null, "e": 28170, "s": 28161, "text": "100\nblue" }, { "code": null, "e": 28179, "s": 28170, "text": "Output :" }, { "code": null, "e": 28193, "s": 28179, "text": "Python-turtle" }, { "code": null, "e": 28200, "s": 28193, "text": "Python" }, { "code": null, "e": 28298, "s": 28200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28307, "s": 28298, "text": "Comments" }, { "code": null, "e": 28320, "s": 28307, "text": "Old Comments" }, { "code": null, "e": 28338, "s": 28320, "text": "Python Dictionary" }, { "code": null, "e": 28373, "s": 28338, "text": "Read a file line by line in Python" }, { "code": null, "e": 28395, "s": 28373, "text": "Enumerate() in Python" }, { "code": null, "e": 28427, "s": 28395, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28457, "s": 28427, "text": "Iterate over a list in Python" }, { "code": null, "e": 28499, "s": 28457, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28525, "s": 28499, "text": "Python String | replace()" }, { "code": null, "e": 28562, "s": 28525, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28605, "s": 28562, "text": "Python program to convert a list to string" } ]
How to display the app version in Angular? - GeeksforGeeks
02 Nov, 2020 Angular is a client-side TypeScript based, front-end web framework by Google. Angular 8 is a great, reusable UI (User Interface) framework for the developers which help in building Single Page Applications. Generally, all the angular 2+ projects or applications are referred to as Angular applications. The earlier version is called Angular.js and angular is a complete re-write of Angular.js which comes with rich and useful features. Approach: In order to know the version, first, we need to import ‘VERSION’ from ‘@angular/core’. The reason for importing this is that it is an object which contains properties that we can use to know the version. After importing it now access the version using the ‘full’ key from the imported Version. After retrieving the value assign it to a variable and then using a string interpolation display in the HTML file. Once you are done with the above implementation, start the project. Code Implementation: app.component.ts:JavascriptJavascriptimport { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;}app.component.html:HTMLHTML<h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p>app.module.ts:JavascriptJavascriptimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } app.component.ts:JavascriptJavascriptimport { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;} app.component.ts: Javascript import { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;} app.component.html:HTMLHTML<h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p> app.component.html: HTML <h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p> app.module.ts:JavascriptJavascriptimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { } Output: Note: My version number is 6 and hence it is displaying as 6. AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers Introduction to AngularJS AngularJS | ng-src Directive ng-content in Angular How to force redirect to a particular route in angular? Express.js express.Router() Function How to set input type date in dd-mm-yyyy format using HTML ? Installation of Node.js on Linux Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24718, "s": 24690, "text": "\n02 Nov, 2020" }, { "code": null, "e": 25154, "s": 24718, "text": "Angular is a client-side TypeScript based, front-end web framework by Google. Angular 8 is a great, reusable UI (User Interface) framework for the developers which help in building Single Page Applications. Generally, all the angular 2+ projects or applications are referred to as Angular applications. The earlier version is called Angular.js and angular is a complete re-write of Angular.js which comes with rich and useful features." }, { "code": null, "e": 25164, "s": 25154, "text": "Approach:" }, { "code": null, "e": 25251, "s": 25164, "text": "In order to know the version, first, we need to import ‘VERSION’ from ‘@angular/core’." }, { "code": null, "e": 25368, "s": 25251, "text": "The reason for importing this is that it is an object which contains properties that we can use to know the version." }, { "code": null, "e": 25458, "s": 25368, "text": "After importing it now access the version using the ‘full’ key from the imported Version." }, { "code": null, "e": 25573, "s": 25458, "text": "After retrieving the value assign it to a variable and then using a string interpolation display in the HTML file." }, { "code": null, "e": 25641, "s": 25573, "text": "Once you are done with the above implementation, start the project." }, { "code": null, "e": 25662, "s": 25641, "text": "Code Implementation:" }, { "code": null, "e": 26356, "s": 25662, "text": "app.component.ts:JavascriptJavascriptimport { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;}app.component.html:HTMLHTML<h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p>app.module.ts:JavascriptJavascriptimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }" }, { "code": null, "e": 26616, "s": 26356, "text": "app.component.ts:JavascriptJavascriptimport { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;}" }, { "code": null, "e": 26634, "s": 26616, "text": "app.component.ts:" }, { "code": null, "e": 26645, "s": 26634, "text": "Javascript" }, { "code": "import { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]}) export class AppComponent { version = VERSION.full;}", "e": 26868, "s": 26645, "text": null }, { "code": null, "e": 26983, "s": 26868, "text": "app.component.html:HTMLHTML<h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p>" }, { "code": null, "e": 27003, "s": 26983, "text": "app.component.html:" }, { "code": null, "e": 27008, "s": 27003, "text": "HTML" }, { "code": "<h2> Welcome to GeeksforGeeks </h2> <p> The version of the App is : {{ version }} </p>", "e": 27096, "s": 27008, "text": null }, { "code": null, "e": 27417, "s": 27096, "text": "app.module.ts:JavascriptJavascriptimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }" }, { "code": null, "e": 27432, "s": 27417, "text": "app.module.ts:" }, { "code": null, "e": 27443, "s": 27432, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 27730, "s": 27443, "text": null }, { "code": null, "e": 27739, "s": 27730, "text": "Output: " }, { "code": null, "e": 27803, "s": 27741, "text": "Note: My version number is 6 and hence it is displaying as 6." }, { "code": null, "e": 27818, "s": 27803, "text": "AngularJS-Misc" }, { "code": null, "e": 27828, "s": 27818, "text": "AngularJS" }, { "code": null, "e": 27845, "s": 27828, "text": "Web Technologies" }, { "code": null, "e": 27943, "s": 27845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27952, "s": 27943, "text": "Comments" }, { "code": null, "e": 27965, "s": 27952, "text": "Old Comments" }, { "code": null, "e": 28009, "s": 27965, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28035, "s": 28009, "text": "Introduction to AngularJS" }, { "code": null, "e": 28064, "s": 28035, "text": "AngularJS | ng-src Directive" }, { "code": null, "e": 28086, "s": 28064, "text": "ng-content in Angular" }, { "code": null, "e": 28142, "s": 28086, "text": "How to force redirect to a particular route in angular?" }, { "code": null, "e": 28179, "s": 28142, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28240, "s": 28179, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28273, "s": 28240, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28345, "s": 28273, "text": "Differences between Functional Components and Class Components in React" } ]
Python Program to Count number of binary strings without consecutive 1’
In this article, we will learn about the solution to the problem statement given below. Problem statement − We are given a positive integer N, we need to count all possible distinct binary strings available with length N such that no consecutive 1’s exist in the string. Now let’s observe the solution in the implementation below − Live Demo # count the number of strings def countStrings(n): a=[0 for i in range(n)] b=[0 for i in range(n)] a[0] = b[0] = 1 for i in range(1,n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] # main n=5 print("The number of strings: ",countStrings(n)) The number of strings: 13 All the variables are declared in the local scope and their references are seen in the figure above. In this article, we have learned about how we can make a Python Program to Count number of binary strings without consecutive 1’
[ { "code": null, "e": 1150, "s": 1062, "text": "In this article, we will learn about the solution to the problem statement given below." }, { "code": null, "e": 1333, "s": 1150, "text": "Problem statement − We are given a positive integer N, we need to count all possible distinct binary strings available with length N such that no consecutive 1’s exist in the string." }, { "code": null, "e": 1394, "s": 1333, "text": "Now let’s observe the solution in the implementation below −" }, { "code": null, "e": 1405, "s": 1394, "text": " Live Demo" }, { "code": null, "e": 1688, "s": 1405, "text": "# count the number of strings\ndef countStrings(n):\n a=[0 for i in range(n)]\n b=[0 for i in range(n)]\n a[0] = b[0] = 1\n for i in range(1,n):\n a[i] = a[i-1] + b[i-1]\n b[i] = a[i-1]\n return a[n-1] + b[n-1]\n# main\nn=5\nprint(\"The number of strings: \",countStrings(n))" }, { "code": null, "e": 1714, "s": 1688, "text": "The number of strings: 13" }, { "code": null, "e": 1815, "s": 1714, "text": "All the variables are declared in the local scope and their references are seen in the figure above." }, { "code": null, "e": 1944, "s": 1815, "text": "In this article, we have learned about how we can make a Python Program to Count number of binary strings without consecutive 1’" } ]
How I Write Meaningful Tests for AWS Lambda Functions | by Paul Singman | Towards Data Science
If you are going to write meaningless unit tests that are more likely to mask errors than expose them, you are better off skipping the exercise altogether. There, I said it. Your time is precious and could be spent on better things than achieving a hollow coverage percentage. Effective testing of code has long been a challenging problem in programming, and newer tools like AWS Lambda seem to bring out the worst in developers when it comes to writing tests. I think the main reason for this is that it’s more difficult (or at least less intuitive) to mirror the Lambda production environment locally. And as a result, some developers abstain from testing entirely. I know because I’ve done it myself, even for projects in production. Instead, testing was done integration-style only after code was already deployed to the cloud. This is extremely manual and wastes time in the long run. Another approach I’ve seen results in tests that look something like this: This is the unmistakeable sign of an engineering team with a test coverage requirement but a lack of accountability. And no explanation is needed that the above is a no-no. So, how do we go about transforming the sad test_lambda_function.py file above into something meaningful? Before we can dive right into testing our Lambda code, there are a couple hurdles in the way. We’ll cover each of these individually and determine how to best handle them. Once dealt with, we are then free to test Lambdas to our heart’s content! Note: I’ll be including small snippets of code throughout the article for clarity. But at the end there will be a full working code example to reference. Every Lambda function gets invoked in response to a pre-defined trigger that passes specific event data into the default lambda_handler() method. And your first task for effectively testing a Lambda function is to create a realistic input event to test with. The format of this event depends on the type of trigger. As of the time of writing there are 16 distinct AWS services that can act as the invocation trigger for Lambda. Below is a code snippet with several examples of inputs that I most commonly use: The full list of sample input events can be found in the AWS documentation. Alternatively, you can also print the event variable in your lambda_handler code after deploying and view the payload in CloudWatch Logs: Once you have that example, simply hardcode it in your test file as shown above and we’re off to a fantastic start! Next up... Almost inevitably, a Lambda function interacts with other AWS services. Maybe you are writing data to a DynamoDB table. Or posting a message to an SNS topic. Or simply sending a metric to CloudWatch. Or a combination of all three! When testing it is not a good idea to send data or alter actual AWS resources used in production. To get around this problem, one approach is to set up and later tear down separate test resources. A cleaner approach though, is to mock interactions with AWS services. And since this is a common problem, a package has been developed to solve this specific problem. And what’s better is it does so in a super elegant way. It’s name is moto (a portmanteau of mock & boto) and its elegance is derived from two main features: It patches and mocks boto clients in tests automatically.It maintains the state of pseudo AWS resources. It patches and mocks boto clients in tests automatically. It maintains the state of pseudo AWS resources. What does this look like? All that’s needed is some decorator magic and a little set up! Say we read data from S3 in our Lambda. Instead of creating and populating a test bucket in S3, we can use moto to create a fake S3 bucket — one that looks and behaves exactly like a real one — without actually touching AWS. And the best part is we can do this using standard boto3 syntax, as seen in the example below when calling the create_bucket and put_object methods: Similarly, if we write data to DynamoDB, we could set up our test by creating a fake Dynamo table first: It requires a bit of trust, but if the test passes, you can be confident your code will work in production, too. Yes, it is true that moto doesn’t maintain parity with every AWS API. For example, if your Lambda function interacts with AWS Glue, odds are moto will leave you high and dry since it is only 5% implemented for the Glue service. This is where we need to roll up our sleeves and do the dirty work of mocking calls ourselves by monkeypatching. This is true whether we’re talking about AWS-related calls or any external service your Lambda may touch, like when posting a message to Slack, for example. Admittedly the terminology and concepts around this get dense, so it is best explained via an example. Let’s stick with AWS Glue and say we have a burning desire to list our account’s Glue crawlers with the following code: session = boto3.session.Session()glue_client = session.client("glue", region_name='us-east-1')glue_client.list_crawlers()['CrawlerNames']# {“CrawlerNames”: [“crawler1”, "crawler2",...]} If we don’t want the success or failure of our illustrious test to depend on the list_crawlers() response, we can hardcode a return value like so: By leveraging the setattr method of the pytest monkeypatch fixture, we allow glue client code in a lambda_handler to dynamically at runtime access the hardcoded list_clusters response from the MockBotoSession class. What’s nice about this solution is that is it flexible enough to work for any boto client. We’ve already covered how to deal with event inputs and external dependencies in Lambda tests. Another tip I’d like to share involves the use of pytest fixtures to maintain an organized testing file. The code examples thus far have shown set up code directly in the test_lambda_handler method itself. A better pattern, however, is to create a separate set_up function as a pytest fixture that gets passed into any test method that needs to use it. For the final code snippet, let’s show an example of this fixture structure using the @pytest.fixture decorator and combine everything covered: We’ve come a long way from the empty test file at the beginning of the article, no? As a reminder, this code tests a Lambda function that: Triggers off an sqs message eventWrites the message to a Dynamo TableLists available Glue CrawlersAnd finally reads back the data written to Dynamo and asserts that the final values match the input. Triggers off an sqs message event Writes the message to a Dynamo Table Lists available Glue Crawlers And finally reads back the data written to Dynamo and asserts that the final values match the input. By employing these strategies though, you should feel confident testing a Lambda triggered from any event type, and one that interacts with any AWS service. If you’ve been struggling to test your Lambda functions, my hope is this article showed you a few tips to help you do so in a useful way. While we spent a lot of time on common issues and how you shouldn’t test a Lambda, we didn’t get a chance to cover the opposite, yet equally important aspect of this topic— namely what should you test, and how can you structure your Lambda function’s code to make it easier to do so. I look forward to hearing from you and discussing how you test Lambda functions! Thank you to Vamshi Rapolu for inspiration and feedback on this article.
[ { "code": null, "e": 328, "s": 172, "text": "If you are going to write meaningless unit tests that are more likely to mask errors than expose them, you are better off skipping the exercise altogether." }, { "code": null, "e": 346, "s": 328, "text": "There, I said it." }, { "code": null, "e": 449, "s": 346, "text": "Your time is precious and could be spent on better things than achieving a hollow coverage percentage." }, { "code": null, "e": 633, "s": 449, "text": "Effective testing of code has long been a challenging problem in programming, and newer tools like AWS Lambda seem to bring out the worst in developers when it comes to writing tests." }, { "code": null, "e": 840, "s": 633, "text": "I think the main reason for this is that it’s more difficult (or at least less intuitive) to mirror the Lambda production environment locally. And as a result, some developers abstain from testing entirely." }, { "code": null, "e": 1004, "s": 840, "text": "I know because I’ve done it myself, even for projects in production. Instead, testing was done integration-style only after code was already deployed to the cloud." }, { "code": null, "e": 1062, "s": 1004, "text": "This is extremely manual and wastes time in the long run." }, { "code": null, "e": 1137, "s": 1062, "text": "Another approach I’ve seen results in tests that look something like this:" }, { "code": null, "e": 1310, "s": 1137, "text": "This is the unmistakeable sign of an engineering team with a test coverage requirement but a lack of accountability. And no explanation is needed that the above is a no-no." }, { "code": null, "e": 1416, "s": 1310, "text": "So, how do we go about transforming the sad test_lambda_function.py file above into something meaningful?" }, { "code": null, "e": 1662, "s": 1416, "text": "Before we can dive right into testing our Lambda code, there are a couple hurdles in the way. We’ll cover each of these individually and determine how to best handle them. Once dealt with, we are then free to test Lambdas to our heart’s content!" }, { "code": null, "e": 1816, "s": 1662, "text": "Note: I’ll be including small snippets of code throughout the article for clarity. But at the end there will be a full working code example to reference." }, { "code": null, "e": 2075, "s": 1816, "text": "Every Lambda function gets invoked in response to a pre-defined trigger that passes specific event data into the default lambda_handler() method. And your first task for effectively testing a Lambda function is to create a realistic input event to test with." }, { "code": null, "e": 2244, "s": 2075, "text": "The format of this event depends on the type of trigger. As of the time of writing there are 16 distinct AWS services that can act as the invocation trigger for Lambda." }, { "code": null, "e": 2326, "s": 2244, "text": "Below is a code snippet with several examples of inputs that I most commonly use:" }, { "code": null, "e": 2540, "s": 2326, "text": "The full list of sample input events can be found in the AWS documentation. Alternatively, you can also print the event variable in your lambda_handler code after deploying and view the payload in CloudWatch Logs:" }, { "code": null, "e": 2656, "s": 2540, "text": "Once you have that example, simply hardcode it in your test file as shown above and we’re off to a fantastic start!" }, { "code": null, "e": 2667, "s": 2656, "text": "Next up..." }, { "code": null, "e": 2898, "s": 2667, "text": "Almost inevitably, a Lambda function interacts with other AWS services. Maybe you are writing data to a DynamoDB table. Or posting a message to an SNS topic. Or simply sending a metric to CloudWatch. Or a combination of all three!" }, { "code": null, "e": 3095, "s": 2898, "text": "When testing it is not a good idea to send data or alter actual AWS resources used in production. To get around this problem, one approach is to set up and later tear down separate test resources." }, { "code": null, "e": 3318, "s": 3095, "text": "A cleaner approach though, is to mock interactions with AWS services. And since this is a common problem, a package has been developed to solve this specific problem. And what’s better is it does so in a super elegant way." }, { "code": null, "e": 3419, "s": 3318, "text": "It’s name is moto (a portmanteau of mock & boto) and its elegance is derived from two main features:" }, { "code": null, "e": 3524, "s": 3419, "text": "It patches and mocks boto clients in tests automatically.It maintains the state of pseudo AWS resources." }, { "code": null, "e": 3582, "s": 3524, "text": "It patches and mocks boto clients in tests automatically." }, { "code": null, "e": 3630, "s": 3582, "text": "It maintains the state of pseudo AWS resources." }, { "code": null, "e": 3719, "s": 3630, "text": "What does this look like? All that’s needed is some decorator magic and a little set up!" }, { "code": null, "e": 3944, "s": 3719, "text": "Say we read data from S3 in our Lambda. Instead of creating and populating a test bucket in S3, we can use moto to create a fake S3 bucket — one that looks and behaves exactly like a real one — without actually touching AWS." }, { "code": null, "e": 4093, "s": 3944, "text": "And the best part is we can do this using standard boto3 syntax, as seen in the example below when calling the create_bucket and put_object methods:" }, { "code": null, "e": 4198, "s": 4093, "text": "Similarly, if we write data to DynamoDB, we could set up our test by creating a fake Dynamo table first:" }, { "code": null, "e": 4311, "s": 4198, "text": "It requires a bit of trust, but if the test passes, you can be confident your code will work in production, too." }, { "code": null, "e": 4539, "s": 4311, "text": "Yes, it is true that moto doesn’t maintain parity with every AWS API. For example, if your Lambda function interacts with AWS Glue, odds are moto will leave you high and dry since it is only 5% implemented for the Glue service." }, { "code": null, "e": 4809, "s": 4539, "text": "This is where we need to roll up our sleeves and do the dirty work of mocking calls ourselves by monkeypatching. This is true whether we’re talking about AWS-related calls or any external service your Lambda may touch, like when posting a message to Slack, for example." }, { "code": null, "e": 5032, "s": 4809, "text": "Admittedly the terminology and concepts around this get dense, so it is best explained via an example. Let’s stick with AWS Glue and say we have a burning desire to list our account’s Glue crawlers with the following code:" }, { "code": null, "e": 5218, "s": 5032, "text": "session = boto3.session.Session()glue_client = session.client(\"glue\", region_name='us-east-1')glue_client.list_crawlers()['CrawlerNames']# {“CrawlerNames”: [“crawler1”, \"crawler2\",...]}" }, { "code": null, "e": 5365, "s": 5218, "text": "If we don’t want the success or failure of our illustrious test to depend on the list_crawlers() response, we can hardcode a return value like so:" }, { "code": null, "e": 5581, "s": 5365, "text": "By leveraging the setattr method of the pytest monkeypatch fixture, we allow glue client code in a lambda_handler to dynamically at runtime access the hardcoded list_clusters response from the MockBotoSession class." }, { "code": null, "e": 5672, "s": 5581, "text": "What’s nice about this solution is that is it flexible enough to work for any boto client." }, { "code": null, "e": 5872, "s": 5672, "text": "We’ve already covered how to deal with event inputs and external dependencies in Lambda tests. Another tip I’d like to share involves the use of pytest fixtures to maintain an organized testing file." }, { "code": null, "e": 6120, "s": 5872, "text": "The code examples thus far have shown set up code directly in the test_lambda_handler method itself. A better pattern, however, is to create a separate set_up function as a pytest fixture that gets passed into any test method that needs to use it." }, { "code": null, "e": 6264, "s": 6120, "text": "For the final code snippet, let’s show an example of this fixture structure using the @pytest.fixture decorator and combine everything covered:" }, { "code": null, "e": 6348, "s": 6264, "text": "We’ve come a long way from the empty test file at the beginning of the article, no?" }, { "code": null, "e": 6403, "s": 6348, "text": "As a reminder, this code tests a Lambda function that:" }, { "code": null, "e": 6602, "s": 6403, "text": "Triggers off an sqs message eventWrites the message to a Dynamo TableLists available Glue CrawlersAnd finally reads back the data written to Dynamo and asserts that the final values match the input." }, { "code": null, "e": 6636, "s": 6602, "text": "Triggers off an sqs message event" }, { "code": null, "e": 6673, "s": 6636, "text": "Writes the message to a Dynamo Table" }, { "code": null, "e": 6703, "s": 6673, "text": "Lists available Glue Crawlers" }, { "code": null, "e": 6804, "s": 6703, "text": "And finally reads back the data written to Dynamo and asserts that the final values match the input." }, { "code": null, "e": 6961, "s": 6804, "text": "By employing these strategies though, you should feel confident testing a Lambda triggered from any event type, and one that interacts with any AWS service." }, { "code": null, "e": 7099, "s": 6961, "text": "If you’ve been struggling to test your Lambda functions, my hope is this article showed you a few tips to help you do so in a useful way." }, { "code": null, "e": 7383, "s": 7099, "text": "While we spent a lot of time on common issues and how you shouldn’t test a Lambda, we didn’t get a chance to cover the opposite, yet equally important aspect of this topic— namely what should you test, and how can you structure your Lambda function’s code to make it easier to do so." }, { "code": null, "e": 7464, "s": 7383, "text": "I look forward to hearing from you and discussing how you test Lambda functions!" } ]
Disconnecting Inactive SSH Connections in Linux - GeeksforGeeks
19 Feb, 2021 SSH or Secure Shell is a cryptographic network protocol that establishes a secure connection between systems remotely. Any user can use this protocol to manage the system remotely but mainly system administrators use it because it transmits data over encrypted channels, which increases its security at a high level. SSH can be used to manage the system, move between files and folders, etc. To disconnect inactive or idle SSH connections we have to set the timeout period for an SSH within which if a server does not receive any request from the client then it will disconnect the connection. Follow the steps to set the timeout period for an SSH connection: Step 1: On the server, head over to the /etc/ssh/sshd_config configuration file. $ sudo vi /etc/ssh/sshd_config Step 2: Scroll and locate the following parameters and remove the ‘#’ symbol to uncomment it: #ClientAliveInterval #ClientAliveCountMax Here, ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd will send a message through the encrypted channel to request a response from the client. In simple ways, the number of seconds that the server waits before sending a null packet to the client. ClientAliveCountMax: Sets the number of client alive messages which may be sent without sshd receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. The timeout value is given by the product of the above parameters i.e. Timeout value = ClientAliveInterval * ClientAliveCountMax For example let’s define our parameter ClientAliveInterval = 30 ClientAliveCountMax = 3 The Timeout value will be 30 seconds * 3 = 90 seconds. This is an equivalent of 1 minute and 30 seconds, which implies that your ssh session will remain alive for idle time of 1 minute 30 seconds without dropping. Step 3: Once done, reload the “sshd” for the changes to come into effect. $ sudo systemctl reload sshd Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ nohup Command in Linux with Examples mv command in Linux with examples scp command in Linux with Examples 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": "\n19 Feb, 2021" }, { "code": null, "e": 24609, "s": 24015, "text": "SSH or Secure Shell is a cryptographic network protocol that establishes a secure connection between systems remotely. Any user can use this protocol to manage the system remotely but mainly system administrators use it because it transmits data over encrypted channels, which increases its security at a high level. SSH can be used to manage the system, move between files and folders, etc. To disconnect inactive or idle SSH connections we have to set the timeout period for an SSH within which if a server does not receive any request from the client then it will disconnect the connection." }, { "code": null, "e": 24675, "s": 24609, "text": "Follow the steps to set the timeout period for an SSH connection:" }, { "code": null, "e": 24756, "s": 24675, "text": "Step 1: On the server, head over to the /etc/ssh/sshd_config configuration file." }, { "code": null, "e": 24788, "s": 24756, "text": "$ sudo vi /etc/ssh/sshd_config " }, { "code": null, "e": 24882, "s": 24788, "text": "Step 2: Scroll and locate the following parameters and remove the ‘#’ symbol to uncomment it:" }, { "code": null, "e": 24924, "s": 24882, "text": "#ClientAliveInterval\n#ClientAliveCountMax" }, { "code": null, "e": 24930, "s": 24924, "text": "Here," }, { "code": null, "e": 25242, "s": 24930, "text": "ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd will send a message through the encrypted channel to request a response from the client. In simple ways, the number of seconds that the server waits before sending a null packet to the client." }, { "code": null, "e": 25511, "s": 25242, "text": "ClientAliveCountMax: Sets the number of client alive messages which may be sent without sshd receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session." }, { "code": null, "e": 25582, "s": 25511, "text": "The timeout value is given by the product of the above parameters i.e." }, { "code": null, "e": 25640, "s": 25582, "text": "Timeout value = ClientAliveInterval * ClientAliveCountMax" }, { "code": null, "e": 25680, "s": 25640, "text": "For example let’s define our parameter " }, { "code": null, "e": 25705, "s": 25680, "text": "ClientAliveInterval = 30" }, { "code": null, "e": 25729, "s": 25705, "text": "ClientAliveCountMax = 3" }, { "code": null, "e": 25943, "s": 25729, "text": "The Timeout value will be 30 seconds * 3 = 90 seconds. This is an equivalent of 1 minute and 30 seconds, which implies that your ssh session will remain alive for idle time of 1 minute 30 seconds without dropping." }, { "code": null, "e": 26017, "s": 25943, "text": "Step 3: Once done, reload the “sshd” for the changes to come into effect." }, { "code": null, "e": 26046, "s": 26017, "text": "$ sudo systemctl reload sshd" }, { "code": null, "e": 26053, "s": 26046, "text": "Picked" }, { "code": null, "e": 26064, "s": 26053, "text": "Linux-Unix" }, { "code": null, "e": 26162, "s": 26064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26171, "s": 26162, "text": "Comments" }, { "code": null, "e": 26184, "s": 26171, "text": "Old Comments" }, { "code": null, "e": 26210, "s": 26184, "text": "Thread functions in C/C++" }, { "code": null, "e": 26247, "s": 26210, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26281, "s": 26247, "text": "mv command in Linux with examples" }, { "code": null, "e": 26316, "s": 26281, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26342, "s": 26316, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26379, "s": 26342, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26419, "s": 26379, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26448, "s": 26419, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26490, "s": 26448, "text": "Named Pipe or FIFO with example C program" } ]
Circular array - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON Events WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Circular array Circular Queue | Set 1 (Introduction and Array Implementation) Circular Queue | Set 2 (Circular Linked List Implementation) Queue | Set 1 (Introduction and Array Implementation) Queue – Linked List Implementation Implement a stack using singly linked list Stack Data Structure (Introduction and Program) Finding sum of digits of a number until sum becomes single digit Program for Sum of the digits of a given number Compute sum of digits in all numbers from 1 to n Count possible ways to construct buildings Maximum profit by buying and selling a share at most twice Maximum profit by buying and selling a share at most k times Stock Buy Sell to Maximize Profit Maximum difference between two elements such that larger element appears after the smaller number Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Sliding Window Maximum (Maximum of all subarrays of size k) Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time Next Greater Element Next greater element in same order as input Next Greater Frequency Element Number of NGEs to the right Maximum product of indexes of next greater on left and right The Celebrity Problem Expression Evaluation Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Circular array Circular Queue | Set 1 (Introduction and Array Implementation) Circular Queue | Set 2 (Circular Linked List Implementation) Queue | Set 1 (Introduction and Array Implementation) Queue – Linked List Implementation Implement a stack using singly linked list Stack Data Structure (Introduction and Program) Finding sum of digits of a number until sum becomes single digit Program for Sum of the digits of a given number Compute sum of digits in all numbers from 1 to n Count possible ways to construct buildings Maximum profit by buying and selling a share at most twice Maximum profit by buying and selling a share at most k times Stock Buy Sell to Maximize Profit Maximum difference between two elements such that larger element appears after the smaller number Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Sliding Window Maximum (Maximum of all subarrays of size k) Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time Next Greater Element Next greater element in same order as input Next Greater Frequency Element Number of NGEs to the right Maximum product of indexes of next greater on left and right The Celebrity Problem Expression Evaluation Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Difficulty Level : Medium An array is called circular if we consider the first element as next of the last element. Circular arrays are used to implement queue (Refer to this and this).An example problem : Suppose n people are sitting at a circular table with names A, B, C, D, ... Given a name, we need to print all n people (in order) starting from the given name. For example, consider 6 people A B C D E F and given name as ‘D’. People sitting in a circular manner starting from D are D E F A B C.A simple solution is to create an auxiliary array of size 2*n and store it in another array. For example for 6 people, we create below the auxiliary array. A B C D E F A B C D E F Now for any given index, we simply print n elements starting from it. For example, we print the following 6. A B C D E F A B C D E F Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to demonstrate use of circular// array using extra memory space#include <bits/stdc++.h>using namespace std;void print(char a[], int n, int ind){ // Create an auxiliary array of twice size. char b[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to (n+i)th index. for (int i = ind; i < n + ind; i++) cout << b[i] << " ";} // Driver codeint main(){ char a[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = sizeof(a) / sizeof(a[0]); print(a, n, 3); return 0;} // Java program to demonstrate use of circular// array using extra memory spaceimport java.util.*;import java.lang.*; public class GfG{ public static void print(char a[], int n, int ind){ // Create an auxiliary array // of twice size. char[] b = new char[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) System.out.print(b[i]+" "); } // Driver code public static void main(String argc[]){ char[] a = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by Sagar Shukla */ # Python3 program to demonstrate use of# circular array using extra memory space def prints(a, n, ind): # Create an auxiliary array of twice size. b = [None]*2*n i = 0 # Copy a[] to b[] two times while i < n: b[i] = b[n + i] = a[i] i = i + 1 i = ind # print from ind-th index to (n+i)th index. while i < n + ind : print(b[i], end = " "); i = i + 1 # Driver Codea = ['A', 'B', 'C', 'D', 'E', 'F']n = len(a);prints(a, n, 3); #This code is contributed by rishabh_jain // C# program to demonstrate use of circular// array using extra memory spaceusing System; public class GfG { public static void print(char[] a, int n, int ind) { // Create an auxiliary array // of twice size. char[] b = new char[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) Console.Write(b[i] + " "); } // Driver code public static void Main() { char[] a = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by vt_m*/ <script>// javascript program to demonstrate use of circular// array using extra memory space function print( a , n , ind) { // Create an auxiliary array // of twice size. var b = Array(2 * n); // Copy a to b two times for (i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (i = ind; i < n + ind; i++) document.write(b[i] + " "); } // Driver code var a = [ 'A', 'B', 'C', 'D', 'E', 'F' ]; var n = 6; print(a, n, 3); // This code is contributed by todaysgaurav</script> Output: D E F A B C This approach takes of O(n) time but takes extra space of order O(n) An efficient solution is to deal with circular arrays using the same array. If a careful observation is run through the array, then after n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index. and apply mod we can do the traversal in a circular array within the given array without using any extra space. C++ Java Python3 C# PHP Javascript // CPP program to demonstrate the use of circular// array without using extra memory space#include <bits/stdc++.h>using namespace std; // function to print circular list starting// from given index ind.void print(char a[], int n, int ind){ // print from ind-th index to (n+i)th index. for (int i = ind; i < n + ind; i++) cout << a[(i % n)] << " ";} // Driver codeint main(){ char a[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = sizeof(a) / sizeof(a[0]); print(a, n, 3); return 0;} // Java program to demonstrate use of circular// array using extra memory spaceimport java.util.*;import java.lang.*; public class GfG{ // function to print circular list // starting from given index ind. public static void print(char a[], int n, int ind){ // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) System.out.print(a[(i % n)] + " "); } // driver code public static void main(String argc[]){ char[] a = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by Sagar Shukla */ # Python3 program to demonstrate the use of# circular array without using extra memory space # function to print circular list starting# from given index ind.def prints(a, n, ind): i = ind # print from ind-th index to (n+i)th index. while i < n + ind : print(a[(i % n)], end = " ") i = i + 1 # Driver Codea = ['A', 'B', 'C', 'D', 'E', 'F']n = len(a);prints(a, n, 3); # This code is contributed by rishabh_jain // C# program to demonstrate use of circular// array without using extra memory spaceusing System; public class GfG { // function to print circular list // starting from given index ind. public static void print(char[] a, int n, int ind) { // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) Console.Write(a[(i % n)] + " "); } // driver code public static void Main() { char[] a = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by vt_m */ <?php// PHP program to demonstrate use// of circular array without using// extra memory space // function to print circular list// starting from given index ind.function print($a, $n, $ind){ // print from ind-th index // to (n+i)th index. for ($i = $ind; $i < $n + $ind; $i++) echo $a[($i % $n)] . " ";} // Driver Code$a = array( 'A', 'B', 'C', 'D', 'E', 'F' );$n = count($a);print($a, $n, 3); // This code is contributed by Sam007?> <script>// javascript program to demonstrate use of circular// array using extra memory space // function to print circular list // starting from given index ind. function print(a, n, ind) { // print from ind-th index to // (n+i)th index. for (var i = ind; i < n + ind; i++) document.write(a[parseInt(i % n)] + " "); } // Driver code var a =[ 'A', 'B', 'C', 'D', 'E', 'F' ]; var n = 6; print(a, n, 3); // This code is contributed by Rajput-Ji</script> Output : D E F A B C This approach takes O(n) time and O(1) extra space.More problems based on circular array : Maximum circular subarray sum Maximize sum of consecutive differences in a circular array Implementation of Deque using circular array Circular Queue | Set 1 (Introduction and Array Implementation) Circular Queue | Set 2 (Circular Linked List Implementation) Find the Longest Increasing Subsequence in Circular manner Minimum absolute difference of adjacent elements in a circular array Recent articles on circular array. Sam007 tushar1247 todaysgaurav Rajput-Ji surindertarika1234 sweetyty circular-array Arrays Technical Scripter Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 4036, "s": 1469, "text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 4103, "s": 4036, "text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise" }, { "code": null, "e": 4121, "s": 4103, "text": "Must Do Questions" }, { "code": null, "e": 4136, "s": 4121, "text": "DSA Topic-wise" }, { "code": null, "e": 4153, "s": 4136, "text": "DSA Company-wise" }, { "code": null, "e": 4734, "s": 4153, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 5067, "s": 4734, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 5087, "s": 5067, "text": "Asymptotic Analysis" }, { "code": null, "e": 5117, "s": 5087, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 5138, "s": 5117, "text": "Asymptotic Notations" }, { "code": null, "e": 5174, "s": 5138, "text": "Little o and little omega notations" }, { "code": null, "e": 5203, "s": 5174, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5221, "s": 5203, "text": "Analysis of Loops" }, { "code": null, "e": 5241, "s": 5221, "text": "Solving Recurrences" }, { "code": null, "e": 5260, "s": 5241, "text": "Amortized Analysis" }, { "code": null, "e": 5296, "s": 5260, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5325, "s": 5296, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5362, "s": 5325, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5389, "s": 5362, "text": "A Time Complexity Question" }, { "code": null, "e": 5410, "s": 5389, "text": "Searching Algorithms" }, { "code": null, "e": 5429, "s": 5410, "text": "Sorting Algorithms" }, { "code": null, "e": 5446, "s": 5429, "text": "Graph Algorithms" }, { "code": null, "e": 5464, "s": 5446, "text": "Pattern Searching" }, { "code": null, "e": 5485, "s": 5464, "text": "Geometric Algorithms" }, { "code": null, "e": 5498, "s": 5485, "text": "Mathematical" }, { "code": null, "e": 5517, "s": 5498, "text": "Bitwise Algorithms" }, { "code": null, "e": 5539, "s": 5517, "text": "Randomized Algorithms" }, { "code": null, "e": 5557, "s": 5539, "text": "Greedy Algorithms" }, { "code": null, "e": 5577, "s": 5557, "text": "Dynamic Programming" }, { "code": null, "e": 5596, "s": 5577, "text": "Divide and Conquer" }, { "code": null, "e": 5609, "s": 5596, "text": "Backtracking" }, { "code": null, "e": 5626, "s": 5609, "text": "Branch and Bound" }, { "code": null, "e": 5641, "s": 5626, "text": "All Algorithms" }, { "code": null, "e": 5784, "s": 5641, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5791, "s": 5784, "text": "Arrays" }, { "code": null, "e": 5803, "s": 5791, "text": "Linked List" }, { "code": null, "e": 5809, "s": 5803, "text": "Stack" }, { "code": null, "e": 5815, "s": 5809, "text": "Queue" }, { "code": null, "e": 5827, "s": 5815, "text": "Binary Tree" }, { "code": null, "e": 5846, "s": 5827, "text": "Binary Search Tree" }, { "code": null, "e": 5851, "s": 5846, "text": "Heap" }, { "code": null, "e": 5859, "s": 5851, "text": "Hashing" }, { "code": null, "e": 5865, "s": 5859, "text": "Graph" }, { "code": null, "e": 5889, "s": 5865, "text": "Advanced Data Structure" }, { "code": null, "e": 5896, "s": 5889, "text": "Matrix" }, { "code": null, "e": 5904, "s": 5896, "text": "Strings" }, { "code": null, "e": 5924, "s": 5904, "text": "All Data Structures" }, { "code": null, "e": 6144, "s": 5924, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 6164, "s": 6144, "text": "Company Preparation" }, { "code": null, "e": 6175, "s": 6164, "text": "Top Topics" }, { "code": null, "e": 6202, "s": 6175, "text": "Practice Company Questions" }, { "code": null, "e": 6224, "s": 6202, "text": "Interview Experiences" }, { "code": null, "e": 6247, "s": 6224, "text": "Experienced Interviews" }, { "code": null, "e": 6269, "s": 6247, "text": "Internship Interviews" }, { "code": null, "e": 6294, "s": 6269, "text": "Competititve Programming" }, { "code": null, "e": 6310, "s": 6294, "text": "Design Patterns" }, { "code": null, "e": 6333, "s": 6310, "text": "System Design Tutorial" }, { "code": null, "e": 6357, "s": 6333, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6438, "s": 6357, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6440, "s": 6438, "text": "C" }, { "code": null, "e": 6444, "s": 6440, "text": "C++" }, { "code": null, "e": 6449, "s": 6444, "text": "Java" }, { "code": null, "e": 6456, "s": 6449, "text": "Python" }, { "code": null, "e": 6459, "s": 6456, "text": "C#" }, { "code": null, "e": 6470, "s": 6459, "text": "JavaScript" }, { "code": null, "e": 6477, "s": 6470, "text": "jQuery" }, { "code": null, "e": 6481, "s": 6477, "text": "SQL" }, { "code": null, "e": 6485, "s": 6481, "text": "PHP" }, { "code": null, "e": 6491, "s": 6485, "text": "Scala" }, { "code": null, "e": 6496, "s": 6491, "text": "Perl" }, { "code": null, "e": 6508, "s": 6496, "text": "Go Language" }, { "code": null, "e": 6513, "s": 6508, "text": "HTML" }, { "code": null, "e": 6517, "s": 6513, "text": "CSS" }, { "code": null, "e": 6524, "s": 6517, "text": "Kotlin" }, { "code": null, "e": 6570, "s": 6524, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6587, "s": 6570, "text": "Machine Learning" }, { "code": null, "e": 6600, "s": 6587, "text": "Data Science" }, { "code": null, "e": 6767, "s": 6600, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6779, "s": 6767, "text": "Mathematics" }, { "code": null, "e": 6796, "s": 6779, "text": "Operating System" }, { "code": null, "e": 6801, "s": 6796, "text": "DBMS" }, { "code": null, "e": 6819, "s": 6801, "text": "Computer Networks" }, { "code": null, "e": 6858, "s": 6819, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6880, "s": 6858, "text": "Theory of Computation" }, { "code": null, "e": 6896, "s": 6880, "text": "Compiler Design" }, { "code": null, "e": 6910, "s": 6896, "text": "Digital Logic" }, { "code": null, "e": 6931, "s": 6910, "text": "Software Engineering" }, { "code": null, "e": 7106, "s": 6931, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 7134, "s": 7106, "text": "GATE Computer Science Notes" }, { "code": null, "e": 7152, "s": 7134, "text": "Last Minute Notes" }, { "code": null, "e": 7174, "s": 7152, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7216, "s": 7174, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7232, "s": 7216, "text": "GATE 2021 Dates" }, { "code": null, "e": 7254, "s": 7232, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7283, "s": 7254, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7357, "s": 7283, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7362, "s": 7357, "text": "HTML" }, { "code": null, "e": 7366, "s": 7362, "text": "CSS" }, { "code": null, "e": 7377, "s": 7366, "text": "JavaScript" }, { "code": null, "e": 7387, "s": 7377, "text": "AngularJS" }, { "code": null, "e": 7395, "s": 7387, "text": "ReactJS" }, { "code": null, "e": 7402, "s": 7395, "text": "NodeJS" }, { "code": null, "e": 7412, "s": 7402, "text": "Bootstrap" }, { "code": null, "e": 7419, "s": 7412, "text": "jQuery" }, { "code": null, "e": 7423, "s": 7419, "text": "PHP" }, { "code": null, "e": 7486, "s": 7423, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7511, "s": 7486, "text": "Software Design Patterns" }, { "code": null, "e": 7534, "s": 7511, "text": "System Design Tutorial" }, { "code": null, "e": 8091, "s": 7534, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8110, "s": 8091, "text": "School Programming" }, { "code": null, "e": 8202, "s": 8110, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8216, "s": 8202, "text": "Number System" }, { "code": null, "e": 8224, "s": 8216, "text": "Algebra" }, { "code": null, "e": 8237, "s": 8224, "text": "Trigonometry" }, { "code": null, "e": 8248, "s": 8237, "text": "Statistics" }, { "code": null, "e": 8260, "s": 8248, "text": "Probability" }, { "code": null, "e": 8269, "s": 8260, "text": "Geometry" }, { "code": null, "e": 8281, "s": 8269, "text": "Mensuration" }, { "code": null, "e": 8290, "s": 8281, "text": "Calculus" }, { "code": null, "e": 8383, "s": 8290, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8397, "s": 8383, "text": "Class 8 Notes" }, { "code": null, "e": 8411, "s": 8397, "text": "Class 9 Notes" }, { "code": null, "e": 8426, "s": 8411, "text": "Class 10 Notes" }, { "code": null, "e": 8441, "s": 8426, "text": "Class 11 Notes" }, { "code": null, "e": 8456, "s": 8441, "text": "Class 12 Notes" }, { "code": null, "e": 8585, "s": 8456, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8608, "s": 8585, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8631, "s": 8608, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8655, "s": 8631, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8679, "s": 8655, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8703, "s": 8679, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8836, "s": 8703, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8859, "s": 8836, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8882, "s": 8859, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8906, "s": 8882, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8930, "s": 8906, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8954, "s": 8930, "text": "Class 12 Maths Solution" }, { "code": null, "e": 9035, "s": 8954, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 9049, "s": 9035, "text": "Class 8 Notes" }, { "code": null, "e": 9063, "s": 9049, "text": "Class 9 Notes" }, { "code": null, "e": 9078, "s": 9063, "text": "Class 10 Notes" }, { "code": null, "e": 9093, "s": 9078, "text": "Class 11 Notes" }, { "code": null, "e": 9299, "s": 9093, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9410, "s": 9299, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9452, "s": 9410, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9474, "s": 9452, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9519, "s": 9474, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9602, "s": 9519, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9628, "s": 9602, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9655, "s": 9628, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9680, "s": 9655, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9870, "s": 9680, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 9896, "s": 9870, "text": "Campus Ambassador Program" }, { "code": null, "e": 9922, "s": 9896, "text": "School Ambassador Program" }, { "code": null, "e": 9930, "s": 9922, "text": "Project" }, { "code": null, "e": 9948, "s": 9930, "text": "Geek of the Month" }, { "code": null, "e": 9973, "s": 9948, "text": "Campus Geek of the Month" }, { "code": null, "e": 9990, "s": 9973, "text": "Placement Course" }, { "code": null, "e": 10015, "s": 9990, "text": "Competititve Programming" }, { "code": null, "e": 10028, "s": 10015, "text": "Testimonials" }, { "code": null, "e": 10044, "s": 10028, "text": "Geek on the Top" }, { "code": null, "e": 10052, "s": 10044, "text": "Careers" }, { "code": null, "e": 10063, "s": 10052, "text": "Internship" }, { "code": null, "e": 10102, "s": 10063, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 10117, "s": 10102, "text": "Apply for Jobs" }, { "code": null, "e": 10128, "s": 10117, "text": "Post a Job" }, { "code": null, "e": 10139, "s": 10128, "text": "JOB-A-THON" }, { "code": null, "e": 10146, "s": 10139, "text": "Events" }, { "code": null, "e": 10417, "s": 10150, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10430, "s": 10417, "text": "Geeks Digest" }, { "code": null, "e": 10438, "s": 10430, "text": "Quizzes" }, { "code": null, "e": 10451, "s": 10438, "text": "Geeks Campus" }, { "code": null, "e": 10466, "s": 10451, "text": "Gblog Articles" }, { "code": null, "e": 10470, "s": 10466, "text": "IDE" }, { "code": null, "e": 10484, "s": 10470, "text": "Campus Mantri" }, { "code": null, "e": 10492, "s": 10484, "text": "Sign In" }, { "code": null, "e": 10500, "s": 10492, "text": "Sign In" }, { "code": null, "e": 10505, "s": 10500, "text": "Home" }, { "code": null, "e": 10518, "s": 10505, "text": "Saved Videos" }, { "code": null, "e": 10526, "s": 10518, "text": "Courses" }, { "code": null, "e": 14731, "s": 10526, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 14785, "s": 14731, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 14908, "s": 14785, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 14927, "s": 14908, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 14943, "s": 14927, "text": "\nSystem Design\n" }, { "code": null, "e": 14970, "s": 14943, "text": "\nJava Backend Development\n" }, { "code": null, "e": 14988, "s": 14970, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15003, "s": 14988, "text": "\nExplore More\n" }, { "code": null, "e": 15111, "s": 15003, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15129, "s": 15111, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15142, "s": 15129, "text": "\nSDE Theory\n" }, { "code": null, "e": 15169, "s": 15142, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15184, "s": 15169, "text": "\nExplore More\n" }, { "code": null, "e": 15225, "s": 15184, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 15337, "s": 15225, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 15363, "s": 15337, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 15390, "s": 15363, "text": "\nData Structures with C++\n" }, { "code": null, "e": 15405, "s": 15390, "text": "\nData Science\n" }, { "code": null, "e": 15420, "s": 15405, "text": "\nExplore More\n" }, { "code": null, "e": 15516, "s": 15420, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 15534, "s": 15516, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15540, "s": 15534, "text": "\nCIP\n" }, { "code": null, "e": 15562, "s": 15540, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 15577, "s": 15562, "text": "\nExplore More\n" }, { "code": null, "e": 15688, "s": 15577, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 15703, "s": 15688, "text": "\nSchool Guide\n" }, { "code": null, "e": 15724, "s": 15703, "text": "\nPython Programming\n" }, { "code": null, "e": 15745, "s": 15724, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 15760, "s": 15745, "text": "\nExplore more\n" }, { "code": null, "e": 15861, "s": 15760, "text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n" }, { "code": null, "e": 15881, "s": 15861, "text": "\nMust Do Questions\n" }, { "code": null, "e": 15898, "s": 15881, "text": "\nDSA Topic-wise\n" }, { "code": null, "e": 15917, "s": 15898, "text": "\nDSA Company-wise\n" }, { "code": null, "e": 16222, "s": 15917, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16245, "s": 16222, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16266, "s": 16245, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16285, "s": 16266, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16305, "s": 16285, "text": "\nPattern Searching\n" }, { "code": null, "e": 16328, "s": 16305, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16343, "s": 16328, "text": "\nMathematical\n" }, { "code": null, "e": 16364, "s": 16343, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16388, "s": 16364, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 16408, "s": 16388, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 16430, "s": 16408, "text": "\nDynamic Programming\n" }, { "code": null, "e": 16451, "s": 16430, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 16466, "s": 16451, "text": "\nBacktracking\n" }, { "code": null, "e": 16485, "s": 16466, "text": "\nBranch and Bound\n" }, { "code": null, "e": 16502, "s": 16485, "text": "\nAll Algorithms\n" }, { "code": null, "e": 16887, "s": 16502, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 16909, "s": 16887, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 16941, "s": 16909, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 16964, "s": 16941, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17002, "s": 16964, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17033, "s": 17002, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17053, "s": 17033, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17075, "s": 17053, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17096, "s": 17075, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17134, "s": 17096, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17165, "s": 17134, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17204, "s": 17165, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17233, "s": 17204, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 17430, "s": 17233, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 17439, "s": 17430, "text": "\nArrays\n" }, { "code": null, "e": 17453, "s": 17439, "text": "\nLinked List\n" }, { "code": null, "e": 17461, "s": 17453, "text": "\nStack\n" }, { "code": null, "e": 17469, "s": 17461, "text": "\nQueue\n" }, { "code": null, "e": 17483, "s": 17469, "text": "\nBinary Tree\n" }, { "code": null, "e": 17504, "s": 17483, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 17511, "s": 17504, "text": "\nHeap\n" }, { "code": null, "e": 17521, "s": 17511, "text": "\nHashing\n" }, { "code": null, "e": 17529, "s": 17521, "text": "\nGraph\n" }, { "code": null, "e": 17555, "s": 17529, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 17564, "s": 17555, "text": "\nMatrix\n" }, { "code": null, "e": 17574, "s": 17564, "text": "\nStrings\n" }, { "code": null, "e": 17596, "s": 17574, "text": "\nAll Data Structures\n" }, { "code": null, "e": 17864, "s": 17596, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 17886, "s": 17864, "text": "\nCompany Preparation\n" }, { "code": null, "e": 17899, "s": 17886, "text": "\nTop Topics\n" }, { "code": null, "e": 17928, "s": 17899, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 17952, "s": 17928, "text": "\nInterview Experiences\n" }, { "code": null, "e": 17977, "s": 17952, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18001, "s": 17977, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18028, "s": 18001, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18046, "s": 18028, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18071, "s": 18046, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18097, "s": 18071, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18236, "s": 18097, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18240, "s": 18236, "text": "\nC\n" }, { "code": null, "e": 18246, "s": 18240, "text": "\nC++\n" }, { "code": null, "e": 18253, "s": 18246, "text": "\nJava\n" }, { "code": null, "e": 18262, "s": 18253, "text": "\nPython\n" }, { "code": null, "e": 18267, "s": 18262, "text": "\nC#\n" }, { "code": null, "e": 18280, "s": 18267, "text": "\nJavaScript\n" }, { "code": null, "e": 18289, "s": 18280, "text": "\njQuery\n" }, { "code": null, "e": 18295, "s": 18289, "text": "\nSQL\n" }, { "code": null, "e": 18301, "s": 18295, "text": "\nPHP\n" }, { "code": null, "e": 18309, "s": 18301, "text": "\nScala\n" }, { "code": null, "e": 18316, "s": 18309, "text": "\nPerl\n" }, { "code": null, "e": 18330, "s": 18316, "text": "\nGo Language\n" }, { "code": null, "e": 18337, "s": 18330, "text": "\nHTML\n" }, { "code": null, "e": 18343, "s": 18337, "text": "\nCSS\n" }, { "code": null, "e": 18352, "s": 18343, "text": "\nKotlin\n" }, { "code": null, "e": 18430, "s": 18352, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 18449, "s": 18430, "text": "\nMachine Learning\n" }, { "code": null, "e": 18464, "s": 18449, "text": "\nData Science\n" }, { "code": null, "e": 18677, "s": 18464, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 18691, "s": 18677, "text": "\nMathematics\n" }, { "code": null, "e": 18710, "s": 18691, "text": "\nOperating System\n" }, { "code": null, "e": 18717, "s": 18710, "text": "\nDBMS\n" }, { "code": null, "e": 18737, "s": 18717, "text": "\nComputer Networks\n" }, { "code": null, "e": 18778, "s": 18737, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 18802, "s": 18778, "text": "\nTheory of Computation\n" }, { "code": null, "e": 18820, "s": 18802, "text": "\nCompiler Design\n" }, { "code": null, "e": 18836, "s": 18820, "text": "\nDigital Logic\n" }, { "code": null, "e": 18859, "s": 18836, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19076, "s": 18859, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19106, "s": 19076, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19126, "s": 19106, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19150, "s": 19126, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19194, "s": 19150, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19212, "s": 19194, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19236, "s": 19212, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19267, "s": 19236, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19387, "s": 19267, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19394, "s": 19387, "text": "\nHTML\n" }, { "code": null, "e": 19400, "s": 19394, "text": "\nCSS\n" }, { "code": null, "e": 19413, "s": 19400, "text": "\nJavaScript\n" }, { "code": null, "e": 19425, "s": 19413, "text": "\nAngularJS\n" }, { "code": null, "e": 19435, "s": 19425, "text": "\nReactJS\n" }, { "code": null, "e": 19444, "s": 19435, "text": "\nNodeJS\n" }, { "code": null, "e": 19456, "s": 19444, "text": "\nBootstrap\n" }, { "code": null, "e": 19465, "s": 19456, "text": "\njQuery\n" }, { "code": null, "e": 19471, "s": 19465, "text": "\nPHP\n" }, { "code": null, "e": 19566, "s": 19471, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 19593, "s": 19566, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 19618, "s": 19593, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 19682, "s": 19618, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 19703, "s": 19682, "text": "\nSchool Programming\n" }, { "code": null, "e": 19839, "s": 19703, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 19855, "s": 19839, "text": "\nNumber System\n" }, { "code": null, "e": 19865, "s": 19855, "text": "\nAlgebra\n" }, { "code": null, "e": 19880, "s": 19865, "text": "\nTrigonometry\n" }, { "code": null, "e": 19893, "s": 19880, "text": "\nStatistics\n" }, { "code": null, "e": 19907, "s": 19893, "text": "\nProbability\n" }, { "code": null, "e": 19918, "s": 19907, "text": "\nGeometry\n" }, { "code": null, "e": 19932, "s": 19918, "text": "\nMensuration\n" }, { "code": null, "e": 19943, "s": 19932, "text": "\nCalculus\n" }, { "code": null, "e": 20074, "s": 19943, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20090, "s": 20074, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20106, "s": 20090, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20123, "s": 20106, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20140, "s": 20123, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20157, "s": 20140, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20324, "s": 20157, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20349, "s": 20324, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20374, "s": 20349, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20400, "s": 20374, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20426, "s": 20400, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20452, "s": 20426, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20623, "s": 20452, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20648, "s": 20623, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20673, "s": 20648, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20699, "s": 20673, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20725, "s": 20699, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20751, "s": 20725, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20868, "s": 20751, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 20884, "s": 20868, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20900, "s": 20884, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20917, "s": 20900, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20934, "s": 20917, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20976, "s": 20934, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21121, "s": 20976, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21165, "s": 21121, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21189, "s": 21165, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21236, "s": 21189, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21353, "s": 21236, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21381, "s": 21353, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 21410, "s": 21381, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 21437, "s": 21410, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21677, "s": 21437, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n" }, { "code": null, "e": 21705, "s": 21677, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 21733, "s": 21705, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 21743, "s": 21733, "text": "\nProject\n" }, { "code": null, "e": 21763, "s": 21743, "text": "\nGeek of the Month\n" }, { "code": null, "e": 21790, "s": 21763, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 21809, "s": 21790, "text": "\nPlacement Course\n" }, { "code": null, "e": 21836, "s": 21809, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 21851, "s": 21836, "text": "\nTestimonials\n" }, { "code": null, "e": 21869, "s": 21851, "text": "\nGeek on the Top\n" }, { "code": null, "e": 21879, "s": 21869, "text": "\nCareers\n" }, { "code": null, "e": 21892, "s": 21879, "text": "\nInternship\n" }, { "code": null, "e": 21930, "s": 21892, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22003, "s": 21930, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22020, "s": 22003, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22033, "s": 22020, "text": "\nPost a Job\n" }, { "code": null, "e": 22046, "s": 22033, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 22052, "s": 22046, "text": "GBlog" }, { "code": null, "e": 22060, "s": 22052, "text": "Puzzles" }, { "code": null, "e": 22073, "s": 22060, "text": "What's New ?" }, { "code": null, "e": 22079, "s": 22073, "text": "Array" }, { "code": null, "e": 22086, "s": 22079, "text": "Matrix" }, { "code": null, "e": 22094, "s": 22086, "text": "Strings" }, { "code": null, "e": 22102, "s": 22094, "text": "Hashing" }, { "code": null, "e": 22114, "s": 22102, "text": "Linked List" }, { "code": null, "e": 22120, "s": 22114, "text": "Stack" }, { "code": null, "e": 22126, "s": 22120, "text": "Queue" }, { "code": null, "e": 22138, "s": 22126, "text": "Binary Tree" }, { "code": null, "e": 22157, "s": 22138, "text": "Binary Search Tree" }, { "code": null, "e": 22162, "s": 22157, "text": "Heap" }, { "code": null, "e": 22168, "s": 22162, "text": "Graph" }, { "code": null, "e": 22178, "s": 22168, "text": "Searching" }, { "code": null, "e": 22186, "s": 22178, "text": "Sorting" }, { "code": null, "e": 22203, "s": 22186, "text": "Divide & Conquer" }, { "code": null, "e": 22216, "s": 22203, "text": "Mathematical" }, { "code": null, "e": 22226, "s": 22216, "text": "Geometric" }, { "code": null, "e": 22234, "s": 22226, "text": "Bitwise" }, { "code": null, "e": 22241, "s": 22234, "text": "Greedy" }, { "code": null, "e": 22254, "s": 22241, "text": "Backtracking" }, { "code": null, "e": 22271, "s": 22254, "text": "Branch and Bound" }, { "code": null, "e": 22291, "s": 22271, "text": "Dynamic Programming" }, { "code": null, "e": 22309, "s": 22291, "text": "Pattern Searching" }, { "code": null, "e": 22320, "s": 22309, "text": "Randomized" }, { "code": null, "e": 22335, "s": 22320, "text": "Circular array" }, { "code": null, "e": 22398, "s": 22335, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 22459, "s": 22398, "text": "Circular Queue | Set 2 (Circular Linked List Implementation)" }, { "code": null, "e": 22513, "s": 22459, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 22548, "s": 22513, "text": "Queue – Linked List Implementation" }, { "code": null, "e": 22591, "s": 22548, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 22639, "s": 22591, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 22704, "s": 22639, "text": "Finding sum of digits of a number until sum becomes single digit" }, { "code": null, "e": 22752, "s": 22704, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 22801, "s": 22752, "text": "Compute sum of digits in all numbers from 1 to n" }, { "code": null, "e": 22844, "s": 22801, "text": "Count possible ways to construct buildings" }, { "code": null, "e": 22903, "s": 22844, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 22964, "s": 22903, "text": "Maximum profit by buying and selling a share at most k times" }, { "code": null, "e": 22998, "s": 22964, "text": "Stock Buy Sell to Maximize Profit" }, { "code": null, "e": 23096, "s": 22998, "text": "Maximum difference between two elements such that larger element appears after the smaller number" }, { "code": null, "e": 23167, "s": 23096, "text": "Given an array arr[], find the maximum j – i such that arr[j] > arr[i]" }, { "code": null, "e": 23227, "s": 23167, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 23312, "s": 23227, "text": "Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time" }, { "code": null, "e": 23333, "s": 23312, "text": "Next Greater Element" }, { "code": null, "e": 23377, "s": 23333, "text": "Next greater element in same order as input" }, { "code": null, "e": 23408, "s": 23377, "text": "Next Greater Frequency Element" }, { "code": null, "e": 23436, "s": 23408, "text": "Number of NGEs to the right" }, { "code": null, "e": 23497, "s": 23436, "text": "Maximum product of indexes of next greater on left and right" }, { "code": null, "e": 23519, "s": 23497, "text": "The Celebrity Problem" }, { "code": null, "e": 23541, "s": 23519, "text": "Expression Evaluation" }, { "code": null, "e": 23556, "s": 23541, "text": "Arrays in Java" }, { "code": null, "e": 23602, "s": 23556, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23634, "s": 23602, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 23661, "s": 23634, "text": "Program for array rotation" }, { "code": null, "e": 23677, "s": 23661, "text": "Arrays in C/C++" }, { "code": null, "e": 23692, "s": 23677, "text": "Circular array" }, { "code": null, "e": 23755, "s": 23692, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 23816, "s": 23755, "text": "Circular Queue | Set 2 (Circular Linked List Implementation)" }, { "code": null, "e": 23870, "s": 23816, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 23905, "s": 23870, "text": "Queue – Linked List Implementation" }, { "code": null, "e": 23948, "s": 23905, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 23996, "s": 23948, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 24061, "s": 23996, "text": "Finding sum of digits of a number until sum becomes single digit" }, { "code": null, "e": 24109, "s": 24061, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 24158, "s": 24109, "text": "Compute sum of digits in all numbers from 1 to n" }, { "code": null, "e": 24201, "s": 24158, "text": "Count possible ways to construct buildings" }, { "code": null, "e": 24260, "s": 24201, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 24321, "s": 24260, "text": "Maximum profit by buying and selling a share at most k times" }, { "code": null, "e": 24355, "s": 24321, "text": "Stock Buy Sell to Maximize Profit" }, { "code": null, "e": 24453, "s": 24355, "text": "Maximum difference between two elements such that larger element appears after the smaller number" }, { "code": null, "e": 24524, "s": 24453, "text": "Given an array arr[], find the maximum j – i such that arr[j] > arr[i]" }, { "code": null, "e": 24584, "s": 24524, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 24669, "s": 24584, "text": "Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time" }, { "code": null, "e": 24690, "s": 24669, "text": "Next Greater Element" }, { "code": null, "e": 24734, "s": 24690, "text": "Next greater element in same order as input" }, { "code": null, "e": 24765, "s": 24734, "text": "Next Greater Frequency Element" }, { "code": null, "e": 24793, "s": 24765, "text": "Number of NGEs to the right" }, { "code": null, "e": 24854, "s": 24793, "text": "Maximum product of indexes of next greater on left and right" }, { "code": null, "e": 24876, "s": 24854, "text": "The Celebrity Problem" }, { "code": null, "e": 24898, "s": 24876, "text": "Expression Evaluation" }, { "code": null, "e": 24913, "s": 24898, "text": "Arrays in Java" }, { "code": null, "e": 24959, "s": 24913, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24991, "s": 24959, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 25018, "s": 24991, "text": "Program for array rotation" }, { "code": null, "e": 25034, "s": 25018, "text": "Arrays in C/C++" }, { "code": null, "e": 25060, "s": 25034, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 25440, "s": 25060, "text": "An array is called circular if we consider the first element as next of the last element. Circular arrays are used to implement queue (Refer to this and this).An example problem : Suppose n people are sitting at a circular table with names A, B, C, D, ... Given a name, we need to print all n people (in order) starting from the given name. " }, { "code": null, "e": 25889, "s": 25440, "text": " For example, consider 6 people A B C D E F and given name as ‘D’. People sitting in a circular manner starting from D are D E F A B C.A simple solution is to create an auxiliary array of size 2*n and store it in another array. For example for 6 people, we create below the auxiliary array. A B C D E F A B C D E F Now for any given index, we simply print n elements starting from it. For example, we print the following 6. A B C D E F A B C D E F " }, { "code": null, "e": 25941, "s": 25889, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25945, "s": 25941, "text": "C++" }, { "code": null, "e": 25950, "s": 25945, "text": "Java" }, { "code": null, "e": 25958, "s": 25950, "text": "Python3" }, { "code": null, "e": 25961, "s": 25958, "text": "C#" }, { "code": null, "e": 25972, "s": 25961, "text": "Javascript" }, { "code": "// CPP program to demonstrate use of circular// array using extra memory space#include <bits/stdc++.h>using namespace std;void print(char a[], int n, int ind){ // Create an auxiliary array of twice size. char b[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to (n+i)th index. for (int i = ind; i < n + ind; i++) cout << b[i] << \" \";} // Driver codeint main(){ char a[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = sizeof(a) / sizeof(a[0]); print(a, n, 3); return 0;}", "e": 26555, "s": 25972, "text": null }, { "code": "// Java program to demonstrate use of circular// array using extra memory spaceimport java.util.*;import java.lang.*; public class GfG{ public static void print(char a[], int n, int ind){ // Create an auxiliary array // of twice size. char[] b = new char[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) System.out.print(b[i]+\" \"); } // Driver code public static void main(String argc[]){ char[] a = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by Sagar Shukla */", "e": 27394, "s": 26555, "text": null }, { "code": "# Python3 program to demonstrate use of# circular array using extra memory space def prints(a, n, ind): # Create an auxiliary array of twice size. b = [None]*2*n i = 0 # Copy a[] to b[] two times while i < n: b[i] = b[n + i] = a[i] i = i + 1 i = ind # print from ind-th index to (n+i)th index. while i < n + ind : print(b[i], end = \" \"); i = i + 1 # Driver Codea = ['A', 'B', 'C', 'D', 'E', 'F']n = len(a);prints(a, n, 3); #This code is contributed by rishabh_jain", "e": 27927, "s": 27394, "text": null }, { "code": "// C# program to demonstrate use of circular// array using extra memory spaceusing System; public class GfG { public static void print(char[] a, int n, int ind) { // Create an auxiliary array // of twice size. char[] b = new char[(2 * n)]; // Copy a[] to b[] two times for (int i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) Console.Write(b[i] + \" \"); } // Driver code public static void Main() { char[] a = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by vt_m*/", "e": 28719, "s": 27927, "text": null }, { "code": "<script>// javascript program to demonstrate use of circular// array using extra memory space function print( a , n , ind) { // Create an auxiliary array // of twice size. var b = Array(2 * n); // Copy a to b two times for (i = 0; i < n; i++) b[i] = b[n + i] = a[i]; // print from ind-th index to // (n+i)th index. for (i = ind; i < n + ind; i++) document.write(b[i] + \" \"); } // Driver code var a = [ 'A', 'B', 'C', 'D', 'E', 'F' ]; var n = 6; print(a, n, 3); // This code is contributed by todaysgaurav</script>", "e": 29352, "s": 28719, "text": null }, { "code": null, "e": 29362, "s": 29352, "text": "Output: " }, { "code": null, "e": 29375, "s": 29362, "text": "D E F A B C " }, { "code": null, "e": 29444, "s": 29375, "text": "This approach takes of O(n) time but takes extra space of order O(n)" }, { "code": null, "e": 29892, "s": 29444, "text": "An efficient solution is to deal with circular arrays using the same array. If a careful observation is run through the array, then after n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index. and apply mod we can do the traversal in a circular array within the given array without using any extra space. " }, { "code": null, "e": 29896, "s": 29892, "text": "C++" }, { "code": null, "e": 29901, "s": 29896, "text": "Java" }, { "code": null, "e": 29909, "s": 29901, "text": "Python3" }, { "code": null, "e": 29912, "s": 29909, "text": "C#" }, { "code": null, "e": 29916, "s": 29912, "text": "PHP" }, { "code": null, "e": 29927, "s": 29916, "text": "Javascript" }, { "code": "// CPP program to demonstrate the use of circular// array without using extra memory space#include <bits/stdc++.h>using namespace std; // function to print circular list starting// from given index ind.void print(char a[], int n, int ind){ // print from ind-th index to (n+i)th index. for (int i = ind; i < n + ind; i++) cout << a[(i % n)] << \" \";} // Driver codeint main(){ char a[] = { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = sizeof(a) / sizeof(a[0]); print(a, n, 3); return 0;}", "e": 30433, "s": 29927, "text": null }, { "code": "// Java program to demonstrate use of circular// array using extra memory spaceimport java.util.*;import java.lang.*; public class GfG{ // function to print circular list // starting from given index ind. public static void print(char a[], int n, int ind){ // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) System.out.print(a[(i % n)] + \" \"); } // driver code public static void main(String argc[]){ char[] a = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by Sagar Shukla */", "e": 31154, "s": 30433, "text": null }, { "code": "# Python3 program to demonstrate the use of# circular array without using extra memory space # function to print circular list starting# from given index ind.def prints(a, n, ind): i = ind # print from ind-th index to (n+i)th index. while i < n + ind : print(a[(i % n)], end = \" \") i = i + 1 # Driver Codea = ['A', 'B', 'C', 'D', 'E', 'F']n = len(a);prints(a, n, 3); # This code is contributed by rishabh_jain", "e": 31592, "s": 31154, "text": null }, { "code": "// C# program to demonstrate use of circular// array without using extra memory spaceusing System; public class GfG { // function to print circular list // starting from given index ind. public static void print(char[] a, int n, int ind) { // print from ind-th index to // (n+i)th index. for (int i = ind; i < n + ind; i++) Console.Write(a[(i % n)] + \" \"); } // driver code public static void Main() { char[] a = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' }; int n = 6; print(a, n, 3); }} /* This code is contributed by vt_m */", "e": 32268, "s": 31592, "text": null }, { "code": "<?php// PHP program to demonstrate use// of circular array without using// extra memory space // function to print circular list// starting from given index ind.function print($a, $n, $ind){ // print from ind-th index // to (n+i)th index. for ($i = $ind; $i < $n + $ind; $i++) echo $a[($i % $n)] . \" \";} // Driver Code$a = array( 'A', 'B', 'C', 'D', 'E', 'F' );$n = count($a);print($a, $n, 3); // This code is contributed by Sam007?>", "e": 32729, "s": 32268, "text": null }, { "code": "<script>// javascript program to demonstrate use of circular// array using extra memory space // function to print circular list // starting from given index ind. function print(a, n, ind) { // print from ind-th index to // (n+i)th index. for (var i = ind; i < n + ind; i++) document.write(a[parseInt(i % n)] + \" \"); } // Driver code var a =[ 'A', 'B', 'C', 'D', 'E', 'F' ]; var n = 6; print(a, n, 3); // This code is contributed by Rajput-Ji</script>", "e": 33255, "s": 32729, "text": null }, { "code": null, "e": 33266, "s": 33255, "text": "Output : " }, { "code": null, "e": 33279, "s": 33266, "text": "D E F A B C " }, { "code": null, "e": 33371, "s": 33279, "text": "This approach takes O(n) time and O(1) extra space.More problems based on circular array : " }, { "code": null, "e": 33401, "s": 33371, "text": "Maximum circular subarray sum" }, { "code": null, "e": 33461, "s": 33401, "text": "Maximize sum of consecutive differences in a circular array" }, { "code": null, "e": 33506, "s": 33461, "text": "Implementation of Deque using circular array" }, { "code": null, "e": 33569, "s": 33506, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 33630, "s": 33569, "text": "Circular Queue | Set 2 (Circular Linked List Implementation)" }, { "code": null, "e": 33689, "s": 33630, "text": "Find the Longest Increasing Subsequence in Circular manner" }, { "code": null, "e": 33758, "s": 33689, "text": "Minimum absolute difference of adjacent elements in a circular array" }, { "code": null, "e": 33793, "s": 33758, "text": "Recent articles on circular array." }, { "code": null, "e": 33800, "s": 33793, "text": "Sam007" }, { "code": null, "e": 33811, "s": 33800, "text": "tushar1247" }, { "code": null, "e": 33824, "s": 33811, "text": "todaysgaurav" }, { "code": null, "e": 33834, "s": 33824, "text": "Rajput-Ji" }, { "code": null, "e": 33853, "s": 33834, "text": "surindertarika1234" }, { "code": null, "e": 33862, "s": 33853, "text": "sweetyty" }, { "code": null, "e": 33877, "s": 33862, "text": "circular-array" }, { "code": null, "e": 33884, "s": 33877, "text": "Arrays" }, { "code": null, "e": 33903, "s": 33884, "text": "Technical Scripter" }, { "code": null, "e": 33910, "s": 33903, "text": "Arrays" }, { "code": null, "e": 34008, "s": 33910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34052, "s": 34008, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34084, "s": 34052, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34107, "s": 34084, "text": "Introduction to Arrays" }, { "code": null, "e": 34121, "s": 34107, "text": "Linear Search" }, { "code": null, "e": 34189, "s": 34121, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34234, "s": 34189, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 34255, "s": 34234, "text": "Linked List vs Array" }, { "code": null, "e": 34340, "s": 34255, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34364, "s": 34340, "text": "Find the Missing Number" } ]
SWING - Component Class
The class Component is the abstract base class for the non menu user-interface controls of AWT. Component represents an object with graphical representation. Following is the declaration for java.awt.Component class − public abstract class Component extends Object implements ImageObserver, MenuContainer, Serializable Following are the fields for java.awt.Component class − static float BOTTOM_ALIGNMENT − Ease-of-use constant for getAlignmentY. static float BOTTOM_ALIGNMENT − Ease-of-use constant for getAlignmentY. static float CENTER_ALIGNMENT − Ease-of-use constant for getAlignmentY and getAlignmentX. static float CENTER_ALIGNMENT − Ease-of-use constant for getAlignmentY and getAlignmentX. static float LEFT_ALIGNMENT − Ease-of-use constant for getAlignmentX. static float LEFT_ALIGNMENT − Ease-of-use constant for getAlignmentX. static float RIGHT_ALIGNMENT − Ease-of-use constant for getAlignmentX. static float RIGHT_ALIGNMENT − Ease-of-use constant for getAlignmentX. static float TOP_ALIGNMENT − Ease-of-use constant for getAlignmentY(). static float TOP_ALIGNMENT − Ease-of-use constant for getAlignmentY(). protected Component() This creates a new Component. boolean action(Event evt, Object what) Deprecated. As of JDK version 1.1, should register this component as ActionListener on the component which fires action events. void add(PopupMenu popup) Adds the specified popup menu to the component. void addComponentListener(ComponentListener l) Adds the specified component listener to receive the component events from this component. void addFocusListener(FocusListener l) Adds the specified focus listener to receive focus events from this component, when this component gains input focus. void addHierarchyBoundsListener(HierarchyBoundsListener l) Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component, when the hierarchy to which this container belongs changes. void addHierarchyListener(HierarchyListener l) Adds the specified hierarchy listener to receive hierarchy changed events from this component, when the hierarchy to which this container belongs changes. void addInputMethodListener(InputMethodListener l) Adds the specified input method listener to receive input method events from this component. void addKeyListener(KeyListener l) Adds the specified key listener to receive key events from this component. void addMouseListener(MouseListener l) Adds the specified mouse listener to receive mouse events from this component. void addMouseMotionListener(MouseMotionListener l) Adds the specified mouse motion listener to receive mouse motion events from this component. void addMouseWheelListener(MouseWheelListener l) Adds the specified mouse wheel listener to receive mouse wheel events from this component. void addNotify() Makes this Component displayable by connecting it to a native screen resource. void addPropertyChangeListener(PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list. void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list for a specific property. void applyComponentOrientation(ComponentOrientation orientation) Sets the ComponentOrientation property of this component and all components contained within it. boolean areFocusTraversalKeysSet(int id) Returns whether the set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Component. int checkImage(Image image, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image. int checkImage(Image image,int width,int height, ImageObserver observer) Returns the status of the construction of a screen representation of the specified image. boolean contains(int x,int y) Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component. boolean contains(Point p) Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component. Image createImage(ImageProducer producer) Creates an image from the specified image producer. Image createImage(int width,int height) Creates an off-screen drawable image to be used for double buffering. VolatileImage createVolatileImage(int width,int height) Creates a volatile off-screen drawable image to be used for double buffering. VolatileImage createVolatileImage(int width,int height, ImageCapabilities caps) Creates a volatile off-screen drawable image, with the given capabilities. void deliverEvent(Event e) Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e). void disable() Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). protected void disableEvents(long eventsToDisable) Disables the events defined by the specified event mask parameter from being delivered to this component. void dispatchEvent(AWTEvent e) Dispatches an event to this component or one of its sub components. void doLayout() Prompts the layout manager to lay out this component. void enable() Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). void enable(boolean b) Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean). protected void enableEvents(long eventsToEnable) Enables the events defined by the specified event mask parameter to be delivered to this component. void enableInputMethods(boolean enable) Enables or disables input method support for this component. protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) Supports reporting bound property changes for boolean properties. void firePropertyChange(String propertyName, byte oldValue, byte newValue) Reports a bound property change. void firePropertyChange(String propertyName, char oldValue, char newValue) Reports a bound property change. void firePropertyChange(String propertyName, double oldValue, double newValue) Reports a bound property change. void firePropertyChange(String propertyName, float oldValue, float newValue) Reports a bound property change. void firePropertyChange(String propertyName, long oldValue, long newValue) Reports a bound property change. protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) Supports reporting bound property changes for Object properties. void firePropertyChange(String propertyName, short oldValue, short newValue) Reports a bound property change. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Component. float getAlignmentX() Returns the alignment along the x axis. float getAlignmentY() Returns the alignment along the y axis. Color getBackground() Gets the background color of this component. int getBaseline(int width,int height) Returns the baseline. Component.BaselineResizeBehavior getBaselineResizeBehavior() Returns an enum indicating how the baseline of the component changes as the size changes. Rectangle getBounds() Gets the bounds of this component in the form of a Rectangle object. Rectangle getBounds(Rectangle rv) Stores the bounds of this component into "return value" rv and returns rv. ColorModel getColorModel() Gets the instance of ColorModel used to display the component on the output device. Component getComponentAt(int x,int y) Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component. Component getComponentAt(Point p) Returns the component or subcomponent that contains the specified point. ComponentListener[] getComponentListeners() Returns an array of all the component listeners registered on this component. ComponentOrientation getComponentOrientation() Retrieves the language-sensitive orientation that is to be used to order the elements or the text within this component. Cursor getCursor() Gets the cursor set in the component. DropTarget getDropTarget() Gets the DropTarget associated with this Component. Container getFocusCycleRootAncestor() Returns the Container which is the focus cycle root of this Component's focus traversal cycle. FocusListener[] getFocusListeners() Returns an array of all the focus listeners registered on this component. Set<AWTKeyStroke> getFocusTraversalKeys(int id) Returns the Set of focus traversal keys for a given traversal operation for this Component. boolean getFocusTraversalKeysEnabled() Returns whether focus traversal keys are enabled for this Component. Font getFont() Gets the font of this component. FontMetrics getFontMetrics(Font font) Gets the font metrics for the specified font. Color getForeground() Gets the foreground color of this component. Graphics getGraphics() Creates a graphics context for this component. GraphicsConfiguration getGraphicsConfiguration() Gets the GraphicsConfiguration associated with this Component. int getHeight() Returns the current height of this component. HierarchyBoundsListener[] getHierarchyBoundsListeners() Returns an array of all the hierarchy bounds listeners registered on this component. HierarchyListener[] getHierarchyListeners() Returns an array of all the hierarchy listeners registered on this component. boolean getIgnoreRepaint() InputContext getInputContext() Gets the input context used by this component for handling the communication with input methods, when the text is entered in this component. InputMethodListener[] getInputMethodListeners() Returns an array of all the input method listeners registered on this component. InputMethodRequests getInputMethodRequests() Gets the input method request handler which supports requests from input methods for this component. KeyListener[] getKeyListeners() Returns an array of all the key listeners registered on this component. <T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Component. Locale getLocale() Gets the locale of this component. Point getLocation() Gets the location of this component in the form of a point specifying the component's top-left corner. Point getLocation(Point rv) Stores the x,y origin of this component into "return value" rv and returns rv. Point getLocationOnScreen() Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space. Dimension getMaximumSize() Gets the maximum size of this component. Dimension getMinimumSize() Gets the mininimum size of this component. MouseListener[] getMouseListeners() Returns an array of all the mouse listeners registered on this component. MouseMotionListener[] getMouseMotionListeners() Returns an array of all the mouse motion listeners registered on this component. Point getMousePosition() Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null. MouseWheelListener[] getMouseWheelListeners() Returns an array of all the mouse wheel listeners registered on this component. String getName() Gets the name of the component. Container getParent() Gets the parent of this component. java.awt.peer.ComponentPeer getPeer() Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable(). Dimension getPreferredSize() Gets the preferred size of this component. PropertyChangeListener[] getPropertyChangeListeners() Returns an array of all the property change listeners registered on this component. PropertyChangeListener[] getPropertyChangeListeners(String propertyName) Returns an array of all the listeners which have been associated with the named property. Dimension getSize() Returns the size of this component in the form of a Dimension object. Dimension getSize(Dimension rv) Stores the width/height of this component into "return value: rv and returns rv. Toolkit getToolkit() Gets the toolkit of this component. Object getTreeLock() Gets this component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations. int getWidth() Returns the current width of this component. int getX() Returns the current x coordinate of the components origin. int getY() Returns the current y coordinate of the components origin. boolean gotFocus(Event evt, Object what) Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent). boolean handleEvent(Event evt) Deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent). boolean hasFocus() Returns true if this Component is the focus owner. void hide() Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). boolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h) Repaints the component when the image has changed. boolean inside(int x,int y) Deprecated. As of JDK version 1.1, replaced by contains(int, int). void invalidate() Invalidates this component. boolean isBackgroundSet() Returns whether the background color has been explicitly set for this Component. boolean isCursorSet() Returns whether the cursor has been explicitly set for this Component. boolean isDisplayable() Determines whether this component is displayable. boolean isDoubleBuffered() Returns true if this component is painted to an offscreen image (buffer)that's copied to the screen later. boolean isEnabled() Determines whether this component is enabled. boolean isFocusable() Returns whether this Component can be focused. boolean isFocusCycleRoot(Container container) Returns whether the specified Container is the focus cycle root of this Component's focus traversal cycle. boolean isFocusOwner() Returns true if this Component is the focus owner. boolean isFocusTraversable() Deprecated. As of 1.4, replaced by isFocusable(). boolean isFontSet() Returns whether the font has been explicitly set for this Component. boolean isForegroundSet() Returns whether the foreground color has been explicitly set for this Component. boolean isLightweight() A lightweight component doesn't have a native toolkit peer. boolean isMaximumSizeSet() Returns true if the maximum size has been set to a non-null value otherwise returns false. boolean isMinimumSizeSet() Returns whether or not setMinimumSize has been invoked with a non-null value. boolean isOpaque() Returns true if this component is completely opaque, returns false by default. boolean isPreferredSizeSet() Returns true if the preferred size has been set to a non-null value otherwise returns false. boolean isShowing() Determines whether this component is showing on screen. boolean isValid() Determines whether this component is valid. boolean isVisible() Determines whether this component should be visible when its parent is visible. boolean keyDown(Event evt,int key) Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent). boolean keyUp(Event evt,int key) Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent). void layout() Deprecated. As of JDK version 1.1, replaced by doLayout(). void list() Prints a listing of this component to the standard system output stream System.out. void list(PrintStream out) Prints a listing of this component to the specified output stream. void list(PrintStream out,int indent) Prints out a list, starting at the specified indentation, to the specified print stream. void list(PrintWriter out) Prints a listing to the specified print writer. void list(PrintWriter out,int indent) Prints out a list, starting at the specified indentation, to the specified print writer. Component locate(int x,int y) Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int). Point location() Deprecated. As of JDK version 1.1, replaced by getLocation(). boolean lostFocus(Event evt, Object what) Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent). boolean mouseDown(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). boolean mouseDrag(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent). boolean mouseEnter(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). boolean mouseExit(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). boolean mouseMove(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent). boolean mouseUp(Event evt,int x,int y) Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent). void move(int x,int y) Deprecated. As of JDK version 1.1, replaced by setLocation(int, int). void nextFocus() Deprecated. As of JDK version 1.1, replaced by transferFocus(). void paint(Graphics g) Paints this component. void paintAll(Graphics g) Paints this component and all of its subcomponents. boolean postEvent(Event e) Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent). boolean prepareImage(Image image,int width,int height, ImageObserver observer) Prepares an image for rendering on this component at the specified width and height. void print(Graphics g) Prints this component. void printAll(Graphics g) Prints this component and all of its subcomponents. protectedvoid processComponentEvent(ComponentEvent e) Processes component events occurring on this component by dispatching them to any registered ComponentListener objects. protected void processEvent(AWTEvent e) Processes events occurring on this component. protected void processFocusEvent(FocusEvent e) Processes focus events occurring on this component by dispatching them to any registered FocusListener objects. protected void processHierarchyBoundsEvent(HierarchyEvent e) Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects. protected void processHierarchyEvent(HierarchyEvent e) Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects. protectedvoid processInputMethodEvent(InputMethodEvent e) Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects. protected void processKeyEvent(KeyEvent e) Processes key events occurring on this component by dispatching them to any registered KeyListener objects. protected void processMouseEvent(MouseEvent e) Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects. protected void processMouseMotionEvent(MouseEvent e) Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects. protected void processMouseWheelEvent(MouseWheelEvent e) Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects. void remove(MenuComponent popup) Removes the specified popup menu from the component. void removeComponentListener(ComponentListener l) Removes the specified component listener so that it no longer receives component events from this component. void removeFocusListener(FocusListener l) Removes the specified focus listener so that it no longer receives focus events from this component. void removeHierarchyBoundsListener(HierarchyBoundsListener l) Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component. void removeHierarchyListener(HierarchyListener l) Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component. void removeInputMethodListener(InputMethodListener l) Removes the specified input method listener so that it no longer receives input method events from this component. void removeKeyListener(KeyListener l) Removes the specified key listener so that it no longer receives key events from this component. void removeMouseListener(MouseListener l) Removes the specified mouse listener so that it no longer receives mouse events from this component. void removeMouseMotionListener(MouseMotionListener l) Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component. void removeMouseWheelListener(MouseWheelListener l) Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component. void removeNotify() Makes this component undisplayable by destroying its native screen resource. void removePropertyChangeListener(PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list. void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) Removes a PropertyChangeListener from the listener list for a specific property. void repaint() Repaints this component. void repaint(int x,int y,int width,int height) Repaints the specified rectangle of this component. void repaint(long tm) Repaints the component. void repaint(long tm,int x,int y,int width,int height) Repaints the specified rectangle of this component within tm milliseconds. void requestFocus() Requests that this component get the input focus, and that this component's top-level ancestor become the focused Window. protected boolean requestFocus(boolean temporary) Requests that this component get the input focus, and that this component's top-level ancestor become the focused Window. boolean requestFocusInWindow() Requests that this component get the input focus, if this component's top-level ancestor is already the focused Window. protected boolean requestFocusInWindow(boolean temporary) Requests that this component get the input focus, if this component's top-level ancestor is already the focused Window. void reshape(int x,int y,int width,int height) Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int). void resize(Dimension d) Deprecated. As of JDK version 1.1, replaced by setSize(Dimension). void resize(int width,int height) Deprecated. As of JDK version 1.1, replaced by setSize(int, int). void setBackground(Color c) Sets the background color of this component. void setBounds(int x,int y,int width,int height) Moves and resizes this component. void setBounds(Rectangle r) Moves and resizes this component to conform to the new bounding rectangle r. void setComponentOrientation(ComponentOrientation o) Sets the language-sensitive orientation that is to be used to order the elements or text within this component. void setCursor(Cursor cursor) Sets the cursor image to the specified cursor. void setDropTarget(DropTarget dt) Associate a DropTarget with this component. void setEnabled(boolean b) Enables or disables this component, depending on the value of the parameter b. void setFocusable(boolean focusable) Sets the focusable state of this Component to the specified value. void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) Sets the focus traversal keys for a given traversal operation for this Component. void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled) Sets whether focus traversal keys are enabled for this component. void setFont(Font f) Sets the font of this component. void setForeground(Color c) Sets the foreground color of this component. void setIgnoreRepaint(boolean ignoreRepaint) Sets whether or not paint messages received from the operating system should be ignored. void setLocale(Locale l) Sets the locale of this component. void setLocation(int x,int y) Moves this component to a new location. void setLocation(Point p) Moves this component to a new location. void setMaximumSize(Dimension maximumSize) Sets the maximum size of this component to a constant value. void setMinimumSize(Dimension minimumSize) Sets the minimum size of this component to a constant value. void setName(String name) Sets the name of the component to the specified string. void setPreferredSize(Dimension preferredSize) Sets the preferred size of this component to a constant value. void setSize(Dimension d) Resizes this component so that it has width d.width and height d.height. void setSize(int width,int height) Resizes this component so that it has width width and height height. void setVisible(boolean b) Shows or hides this component depending on the value of parameter b. void show() Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). void show(boolean b) Deprecated. As of JDK version 1.1, replaced by setVisible(boolean). Dimension size() Deprecated. As of JDK version 1.1, replaced by getSize(). String toString() Returns a string representation of this component and its values. void transferFocus() Transfers the focus to the next component, as though this Component were the focus owner. void transferFocusBackward() Transfers the focus to the previous component, as though this Component were the focus owner. void transferFocusUpCycle() Transfers the focus up one focus traversal cycle. void update(Graphics g) Updates this component. void validate() Ensures that this component has a valid layout. Rectangle bounds() Deprecated. As of JDK version 1.1, replaced by getBounds(). protected AWTEvent coalesceEvents(AWTEvent existingEvent, AWTEvent newEvent) Potentially coalesce an event being posted with an existing event. protected String paramString() Returns a string representing the state of this component. protected void firePropertyChange(String propertyName,int oldValue,int newValue) Supports reporting bound property changes for integer properties. Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). boolean prepareImage(Image image, ImageObserver observer) Prepares an image for rendering on this component. Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). This class inherits methods from the following class − java.lang.Object 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1921, "s": 1763, "text": "The class Component is the abstract base class for the non menu user-interface controls of AWT. Component represents an object with graphical representation." }, { "code": null, "e": 1981, "s": 1921, "text": "Following is the declaration for java.awt.Component class −" }, { "code": null, "e": 2092, "s": 1981, "text": "public abstract class Component\n extends Object\n implements ImageObserver, MenuContainer, Serializable\n" }, { "code": null, "e": 2148, "s": 2092, "text": "Following are the fields for java.awt.Component class −" }, { "code": null, "e": 2220, "s": 2148, "text": "static float BOTTOM_ALIGNMENT − Ease-of-use constant for getAlignmentY." }, { "code": null, "e": 2292, "s": 2220, "text": "static float BOTTOM_ALIGNMENT − Ease-of-use constant for getAlignmentY." }, { "code": null, "e": 2382, "s": 2292, "text": "static float CENTER_ALIGNMENT − Ease-of-use constant for getAlignmentY and getAlignmentX." }, { "code": null, "e": 2472, "s": 2382, "text": "static float CENTER_ALIGNMENT − Ease-of-use constant for getAlignmentY and getAlignmentX." }, { "code": null, "e": 2542, "s": 2472, "text": "static float LEFT_ALIGNMENT − Ease-of-use constant for getAlignmentX." }, { "code": null, "e": 2612, "s": 2542, "text": "static float LEFT_ALIGNMENT − Ease-of-use constant for getAlignmentX." }, { "code": null, "e": 2683, "s": 2612, "text": "static float RIGHT_ALIGNMENT − Ease-of-use constant for getAlignmentX." }, { "code": null, "e": 2754, "s": 2683, "text": "static float RIGHT_ALIGNMENT − Ease-of-use constant for getAlignmentX." }, { "code": null, "e": 2825, "s": 2754, "text": "static float TOP_ALIGNMENT − Ease-of-use constant for getAlignmentY()." }, { "code": null, "e": 2896, "s": 2825, "text": "static float TOP_ALIGNMENT − Ease-of-use constant for getAlignmentY()." }, { "code": null, "e": 2918, "s": 2896, "text": "protected Component()" }, { "code": null, "e": 2948, "s": 2918, "text": "This creates a new Component." }, { "code": null, "e": 2987, "s": 2948, "text": "boolean action(Event evt, Object what)" }, { "code": null, "e": 3115, "s": 2987, "text": "Deprecated. As of JDK version 1.1, should register this component as ActionListener on the component which fires action events." }, { "code": null, "e": 3141, "s": 3115, "text": "void add(PopupMenu popup)" }, { "code": null, "e": 3189, "s": 3141, "text": "Adds the specified popup menu to the component." }, { "code": null, "e": 3236, "s": 3189, "text": "void addComponentListener(ComponentListener l)" }, { "code": null, "e": 3327, "s": 3236, "text": "Adds the specified component listener to receive the component events from this component." }, { "code": null, "e": 3366, "s": 3327, "text": "void addFocusListener(FocusListener l)" }, { "code": null, "e": 3484, "s": 3366, "text": "Adds the specified focus listener to receive focus events from this component, when this component gains input focus." }, { "code": null, "e": 3543, "s": 3484, "text": "void addHierarchyBoundsListener(HierarchyBoundsListener l)" }, { "code": null, "e": 3704, "s": 3543, "text": "Adds the specified hierarchy bounds listener to receive hierarchy bounds events from this component, when the hierarchy to which this container belongs changes." }, { "code": null, "e": 3751, "s": 3704, "text": "void addHierarchyListener(HierarchyListener l)" }, { "code": null, "e": 3906, "s": 3751, "text": "Adds the specified hierarchy listener to receive hierarchy changed events from this component, when the hierarchy to which this container belongs changes." }, { "code": null, "e": 3957, "s": 3906, "text": "void addInputMethodListener(InputMethodListener l)" }, { "code": null, "e": 4050, "s": 3957, "text": "Adds the specified input method listener to receive input method events from this component." }, { "code": null, "e": 4085, "s": 4050, "text": "void addKeyListener(KeyListener l)" }, { "code": null, "e": 4160, "s": 4085, "text": "Adds the specified key listener to receive key events from this component." }, { "code": null, "e": 4199, "s": 4160, "text": "void addMouseListener(MouseListener l)" }, { "code": null, "e": 4278, "s": 4199, "text": "Adds the specified mouse listener to receive mouse events from this component." }, { "code": null, "e": 4329, "s": 4278, "text": "void addMouseMotionListener(MouseMotionListener l)" }, { "code": null, "e": 4422, "s": 4329, "text": "Adds the specified mouse motion listener to receive mouse motion events from this component." }, { "code": null, "e": 4471, "s": 4422, "text": "void addMouseWheelListener(MouseWheelListener l)" }, { "code": null, "e": 4562, "s": 4471, "text": "Adds the specified mouse wheel listener to receive mouse wheel events from this component." }, { "code": null, "e": 4579, "s": 4562, "text": "void addNotify()" }, { "code": null, "e": 4658, "s": 4579, "text": "Makes this Component displayable by connecting it to a native screen resource." }, { "code": null, "e": 4722, "s": 4658, "text": "void addPropertyChangeListener(PropertyChangeListener listener)" }, { "code": null, "e": 4774, "s": 4722, "text": "Adds a PropertyChangeListener to the listener list." }, { "code": null, "e": 4859, "s": 4774, "text": "void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)" }, { "code": null, "e": 4935, "s": 4859, "text": "Adds a PropertyChangeListener to the listener list for a specific property." }, { "code": null, "e": 5000, "s": 4935, "text": "void applyComponentOrientation(ComponentOrientation orientation)" }, { "code": null, "e": 5097, "s": 5000, "text": "Sets the ComponentOrientation property of this component and all components contained within it." }, { "code": null, "e": 5138, "s": 5097, "text": "boolean areFocusTraversalKeysSet(int id)" }, { "code": null, "e": 5274, "s": 5138, "text": "Returns whether the set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Component." }, { "code": null, "e": 5326, "s": 5274, "text": "int checkImage(Image image, ImageObserver observer)" }, { "code": null, "e": 5416, "s": 5326, "text": "Returns the status of the construction of a screen representation of the specified image." }, { "code": null, "e": 5490, "s": 5416, "text": "int checkImage(Image image,int width,int height, ImageObserver observer)" }, { "code": null, "e": 5580, "s": 5490, "text": "Returns the status of the construction of a screen representation of the specified image." }, { "code": null, "e": 5610, "s": 5580, "text": "boolean contains(int x,int y)" }, { "code": null, "e": 5757, "s": 5610, "text": "Checks whether this component \"contains\" the specified point, where x and y are defined to be relative to the coordinate system of this component." }, { "code": null, "e": 5783, "s": 5757, "text": "boolean contains(Point p)" }, { "code": null, "e": 5954, "s": 5783, "text": "Checks whether this component \"contains\" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component." }, { "code": null, "e": 5996, "s": 5954, "text": "Image createImage(ImageProducer producer)" }, { "code": null, "e": 6048, "s": 5996, "text": "Creates an image from the specified image producer." }, { "code": null, "e": 6088, "s": 6048, "text": "Image createImage(int width,int height)" }, { "code": null, "e": 6158, "s": 6088, "text": "Creates an off-screen drawable image to be used for double buffering." }, { "code": null, "e": 6215, "s": 6158, "text": "VolatileImage createVolatileImage(int width,int height)" }, { "code": null, "e": 6293, "s": 6215, "text": "Creates a volatile off-screen drawable image to be used for double buffering." }, { "code": null, "e": 6374, "s": 6293, "text": "VolatileImage createVolatileImage(int width,int height, ImageCapabilities caps)" }, { "code": null, "e": 6449, "s": 6374, "text": "Creates a volatile off-screen drawable image, with the given capabilities." }, { "code": null, "e": 6476, "s": 6449, "text": "void deliverEvent(Event e)" }, { "code": null, "e": 6550, "s": 6476, "text": "Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)." }, { "code": null, "e": 6565, "s": 6550, "text": "void disable()" }, { "code": null, "e": 6633, "s": 6565, "text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)." }, { "code": null, "e": 6684, "s": 6633, "text": "protected void disableEvents(long eventsToDisable)" }, { "code": null, "e": 6790, "s": 6684, "text": "Disables the events defined by the specified event mask parameter from being delivered to this component." }, { "code": null, "e": 6821, "s": 6790, "text": "void dispatchEvent(AWTEvent e)" }, { "code": null, "e": 6889, "s": 6821, "text": "Dispatches an event to this component or one of its sub components." }, { "code": null, "e": 6905, "s": 6889, "text": "void doLayout()" }, { "code": null, "e": 6959, "s": 6905, "text": "Prompts the layout manager to lay out this component." }, { "code": null, "e": 6973, "s": 6959, "text": "void enable()" }, { "code": null, "e": 7041, "s": 6973, "text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)." }, { "code": null, "e": 7064, "s": 7041, "text": "void enable(boolean b)" }, { "code": null, "e": 7132, "s": 7064, "text": "Deprecated. As of JDK version 1.1, replaced by setEnabled(boolean)." }, { "code": null, "e": 7181, "s": 7132, "text": "protected void\tenableEvents(long eventsToEnable)" }, { "code": null, "e": 7281, "s": 7181, "text": "Enables the events defined by the specified event mask parameter to be delivered to this component." }, { "code": null, "e": 7321, "s": 7281, "text": "void enableInputMethods(boolean enable)" }, { "code": null, "e": 7382, "s": 7321, "text": "Enables or disables input method support for this component." }, { "code": null, "e": 7473, "s": 7382, "text": "protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)" }, { "code": null, "e": 7539, "s": 7473, "text": "Supports reporting bound property changes for boolean properties." }, { "code": null, "e": 7614, "s": 7539, "text": "void firePropertyChange(String propertyName, byte oldValue, byte newValue)" }, { "code": null, "e": 7647, "s": 7614, "text": "Reports a bound property change." }, { "code": null, "e": 7722, "s": 7647, "text": "void firePropertyChange(String propertyName, char oldValue, char newValue)" }, { "code": null, "e": 7755, "s": 7722, "text": "Reports a bound property change." }, { "code": null, "e": 7834, "s": 7755, "text": "void firePropertyChange(String propertyName, double oldValue, double newValue)" }, { "code": null, "e": 7867, "s": 7834, "text": "Reports a bound property change." }, { "code": null, "e": 7944, "s": 7867, "text": "void firePropertyChange(String propertyName, float oldValue, float newValue)" }, { "code": null, "e": 7977, "s": 7944, "text": "Reports a bound property change." }, { "code": null, "e": 8052, "s": 7977, "text": "void firePropertyChange(String propertyName, long oldValue, long newValue)" }, { "code": null, "e": 8085, "s": 8052, "text": "Reports a bound property change." }, { "code": null, "e": 8174, "s": 8085, "text": "protected void firePropertyChange(String propertyName, Object oldValue, Object newValue)" }, { "code": null, "e": 8239, "s": 8174, "text": "Supports reporting bound property changes for Object properties." }, { "code": null, "e": 8316, "s": 8239, "text": "void firePropertyChange(String propertyName, short oldValue, short newValue)" }, { "code": null, "e": 8349, "s": 8316, "text": "Reports a bound property change." }, { "code": null, "e": 8390, "s": 8349, "text": "AccessibleContext getAccessibleContext()" }, { "code": null, "e": 8449, "s": 8390, "text": "Gets the AccessibleContext associated with this Component." }, { "code": null, "e": 8471, "s": 8449, "text": "float getAlignmentX()" }, { "code": null, "e": 8511, "s": 8471, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 8533, "s": 8511, "text": "float getAlignmentY()" }, { "code": null, "e": 8573, "s": 8533, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 8595, "s": 8573, "text": "Color getBackground()" }, { "code": null, "e": 8640, "s": 8595, "text": "Gets the background color of this component." }, { "code": null, "e": 8679, "s": 8640, "text": "int getBaseline(int width,int height)" }, { "code": null, "e": 8701, "s": 8679, "text": "Returns the baseline." }, { "code": null, "e": 8762, "s": 8701, "text": "Component.BaselineResizeBehavior getBaselineResizeBehavior()" }, { "code": null, "e": 8852, "s": 8762, "text": "Returns an enum indicating how the baseline of the component changes as the size changes." }, { "code": null, "e": 8874, "s": 8852, "text": "Rectangle getBounds()" }, { "code": null, "e": 8943, "s": 8874, "text": "Gets the bounds of this component in the form of a Rectangle object." }, { "code": null, "e": 8977, "s": 8943, "text": "Rectangle getBounds(Rectangle rv)" }, { "code": null, "e": 9052, "s": 8977, "text": "Stores the bounds of this component into \"return value\" rv and returns rv." }, { "code": null, "e": 9079, "s": 9052, "text": "ColorModel getColorModel()" }, { "code": null, "e": 9163, "s": 9079, "text": "Gets the instance of ColorModel used to display the component on the output device." }, { "code": null, "e": 9201, "s": 9163, "text": "Component getComponentAt(int x,int y)" }, { "code": null, "e": 9343, "s": 9201, "text": "Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component." }, { "code": null, "e": 9377, "s": 9343, "text": "Component getComponentAt(Point p)" }, { "code": null, "e": 9450, "s": 9377, "text": "Returns the component or subcomponent that contains the specified point." }, { "code": null, "e": 9494, "s": 9450, "text": "ComponentListener[] getComponentListeners()" }, { "code": null, "e": 9572, "s": 9494, "text": "Returns an array of all the component listeners registered on this component." }, { "code": null, "e": 9619, "s": 9572, "text": "ComponentOrientation getComponentOrientation()" }, { "code": null, "e": 9740, "s": 9619, "text": "Retrieves the language-sensitive orientation that is to be used to order the elements or the text within this component." }, { "code": null, "e": 9759, "s": 9740, "text": "Cursor getCursor()" }, { "code": null, "e": 9797, "s": 9759, "text": "Gets the cursor set in the component." }, { "code": null, "e": 9824, "s": 9797, "text": "DropTarget getDropTarget()" }, { "code": null, "e": 9876, "s": 9824, "text": "Gets the DropTarget associated with this Component." }, { "code": null, "e": 9914, "s": 9876, "text": "Container getFocusCycleRootAncestor()" }, { "code": null, "e": 10009, "s": 9914, "text": "Returns the Container which is the focus cycle root of this Component's focus traversal cycle." }, { "code": null, "e": 10045, "s": 10009, "text": "FocusListener[] getFocusListeners()" }, { "code": null, "e": 10119, "s": 10045, "text": "Returns an array of all the focus listeners registered on this component." }, { "code": null, "e": 10167, "s": 10119, "text": "Set<AWTKeyStroke> getFocusTraversalKeys(int id)" }, { "code": null, "e": 10259, "s": 10167, "text": "Returns the Set of focus traversal keys for a given traversal operation for this Component." }, { "code": null, "e": 10298, "s": 10259, "text": "boolean getFocusTraversalKeysEnabled()" }, { "code": null, "e": 10367, "s": 10298, "text": "Returns whether focus traversal keys are enabled for this Component." }, { "code": null, "e": 10382, "s": 10367, "text": "Font getFont()" }, { "code": null, "e": 10415, "s": 10382, "text": "Gets the font of this component." }, { "code": null, "e": 10453, "s": 10415, "text": "FontMetrics getFontMetrics(Font font)" }, { "code": null, "e": 10499, "s": 10453, "text": "Gets the font metrics for the specified font." }, { "code": null, "e": 10521, "s": 10499, "text": "Color getForeground()" }, { "code": null, "e": 10566, "s": 10521, "text": "Gets the foreground color of this component." }, { "code": null, "e": 10589, "s": 10566, "text": "Graphics getGraphics()" }, { "code": null, "e": 10636, "s": 10589, "text": "Creates a graphics context for this component." }, { "code": null, "e": 10685, "s": 10636, "text": "GraphicsConfiguration getGraphicsConfiguration()" }, { "code": null, "e": 10748, "s": 10685, "text": "Gets the GraphicsConfiguration associated with this Component." }, { "code": null, "e": 10765, "s": 10748, "text": "int getHeight()" }, { "code": null, "e": 10811, "s": 10765, "text": "Returns the current height of this component." }, { "code": null, "e": 10867, "s": 10811, "text": "HierarchyBoundsListener[] getHierarchyBoundsListeners()" }, { "code": null, "e": 10952, "s": 10867, "text": "Returns an array of all the hierarchy bounds listeners registered on this component." }, { "code": null, "e": 10996, "s": 10952, "text": "HierarchyListener[] getHierarchyListeners()" }, { "code": null, "e": 11074, "s": 10996, "text": "Returns an array of all the hierarchy listeners registered on this component." }, { "code": null, "e": 11101, "s": 11074, "text": "boolean getIgnoreRepaint()" }, { "code": null, "e": 11132, "s": 11101, "text": "InputContext getInputContext()" }, { "code": null, "e": 11273, "s": 11132, "text": "Gets the input context used by this component for handling the communication with input methods, when the text is entered in this component." }, { "code": null, "e": 11321, "s": 11273, "text": "InputMethodListener[] getInputMethodListeners()" }, { "code": null, "e": 11402, "s": 11321, "text": "Returns an array of all the input method listeners registered on this component." }, { "code": null, "e": 11447, "s": 11402, "text": "InputMethodRequests getInputMethodRequests()" }, { "code": null, "e": 11548, "s": 11447, "text": "Gets the input method request handler which supports requests from input methods for this component." }, { "code": null, "e": 11580, "s": 11548, "text": "KeyListener[] getKeyListeners()" }, { "code": null, "e": 11652, "s": 11580, "text": "Returns an array of all the key listeners registered on this component." }, { "code": null, "e": 11718, "s": 11652, "text": "<T extends EventListener> T[] getListeners(Class<T> listenerType)" }, { "code": null, "e": 11812, "s": 11718, "text": "Returns an array of all the objects currently registered as FooListeners upon this Component." }, { "code": null, "e": 11831, "s": 11812, "text": "Locale getLocale()" }, { "code": null, "e": 11866, "s": 11831, "text": "Gets the locale of this component." }, { "code": null, "e": 11886, "s": 11866, "text": "Point getLocation()" }, { "code": null, "e": 11989, "s": 11886, "text": "Gets the location of this component in the form of a point specifying the component's top-left corner." }, { "code": null, "e": 12017, "s": 11989, "text": "Point getLocation(Point rv)" }, { "code": null, "e": 12096, "s": 12017, "text": "Stores the x,y origin of this component into \"return value\" rv and returns rv." }, { "code": null, "e": 12124, "s": 12096, "text": "Point getLocationOnScreen()" }, { "code": null, "e": 12260, "s": 12124, "text": "Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space." }, { "code": null, "e": 12287, "s": 12260, "text": "Dimension getMaximumSize()" }, { "code": null, "e": 12328, "s": 12287, "text": "Gets the maximum size of this component." }, { "code": null, "e": 12355, "s": 12328, "text": "Dimension getMinimumSize()" }, { "code": null, "e": 12398, "s": 12355, "text": "Gets the mininimum size of this component." }, { "code": null, "e": 12434, "s": 12398, "text": "MouseListener[] getMouseListeners()" }, { "code": null, "e": 12508, "s": 12434, "text": "Returns an array of all the mouse listeners registered on this component." }, { "code": null, "e": 12556, "s": 12508, "text": "MouseMotionListener[] getMouseMotionListeners()" }, { "code": null, "e": 12637, "s": 12556, "text": "Returns an array of all the mouse motion listeners registered on this component." }, { "code": null, "e": 12662, "s": 12637, "text": "Point getMousePosition()" }, { "code": null, "e": 12819, "s": 12662, "text": "Returns the position of the mouse pointer in this Component's coordinate space if the Component is directly under the mouse pointer, otherwise returns null." }, { "code": null, "e": 12865, "s": 12819, "text": "MouseWheelListener[] getMouseWheelListeners()" }, { "code": null, "e": 12945, "s": 12865, "text": "Returns an array of all the mouse wheel listeners registered on this component." }, { "code": null, "e": 12962, "s": 12945, "text": "String getName()" }, { "code": null, "e": 12994, "s": 12962, "text": "Gets the name of the component." }, { "code": null, "e": 13016, "s": 12994, "text": "Container getParent()" }, { "code": null, "e": 13051, "s": 13016, "text": "Gets the parent of this component." }, { "code": null, "e": 13089, "s": 13051, "text": "java.awt.peer.ComponentPeer getPeer()" }, { "code": null, "e": 13208, "s": 13089, "text": "Deprecated. As of JDK version 1.1, programs should not directly manipulate peers; replaced by boolean isDisplayable()." }, { "code": null, "e": 13237, "s": 13208, "text": "Dimension getPreferredSize()" }, { "code": null, "e": 13280, "s": 13237, "text": "Gets the preferred size of this component." }, { "code": null, "e": 13334, "s": 13280, "text": "PropertyChangeListener[] getPropertyChangeListeners()" }, { "code": null, "e": 13418, "s": 13334, "text": "Returns an array of all the property change listeners registered on this component." }, { "code": null, "e": 13491, "s": 13418, "text": "PropertyChangeListener[] getPropertyChangeListeners(String propertyName)" }, { "code": null, "e": 13581, "s": 13491, "text": "Returns an array of all the listeners which have been associated with the named property." }, { "code": null, "e": 13601, "s": 13581, "text": "Dimension getSize()" }, { "code": null, "e": 13671, "s": 13601, "text": "Returns the size of this component in the form of a Dimension object." }, { "code": null, "e": 13703, "s": 13671, "text": "Dimension getSize(Dimension rv)" }, { "code": null, "e": 13784, "s": 13703, "text": "Stores the width/height of this component into \"return value: rv and returns rv." }, { "code": null, "e": 13805, "s": 13784, "text": "Toolkit getToolkit()" }, { "code": null, "e": 13841, "s": 13805, "text": "Gets the toolkit of this component." }, { "code": null, "e": 13862, "s": 13841, "text": "Object getTreeLock()" }, { "code": null, "e": 14002, "s": 13862, "text": "Gets this component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations." }, { "code": null, "e": 14017, "s": 14002, "text": "int getWidth()" }, { "code": null, "e": 14062, "s": 14017, "text": "Returns the current width of this component." }, { "code": null, "e": 14073, "s": 14062, "text": "int getX()" }, { "code": null, "e": 14132, "s": 14073, "text": "Returns the current x coordinate of the components origin." }, { "code": null, "e": 14143, "s": 14132, "text": "int getY()" }, { "code": null, "e": 14202, "s": 14143, "text": "Returns the current y coordinate of the components origin." }, { "code": null, "e": 14243, "s": 14202, "text": "boolean gotFocus(Event evt, Object what)" }, { "code": null, "e": 14321, "s": 14243, "text": "Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent)." }, { "code": null, "e": 14352, "s": 14321, "text": "boolean handleEvent(Event evt)" }, { "code": null, "e": 14422, "s": 14352, "text": "Deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent)." }, { "code": null, "e": 14441, "s": 14422, "text": "boolean hasFocus()" }, { "code": null, "e": 14492, "s": 14441, "text": "Returns true if this Component is the focus owner." }, { "code": null, "e": 14504, "s": 14492, "text": "void hide()" }, { "code": null, "e": 14572, "s": 14504, "text": "Deprecated. As of JDK version 1.1, replaced by setVisible(boolean)." }, { "code": null, "e": 14645, "s": 14572, "text": "boolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h)" }, { "code": null, "e": 14696, "s": 14645, "text": "Repaints the component when the image has changed." }, { "code": null, "e": 14724, "s": 14696, "text": "boolean inside(int x,int y)" }, { "code": null, "e": 14791, "s": 14724, "text": "Deprecated. As of JDK version 1.1, replaced by contains(int, int)." }, { "code": null, "e": 14809, "s": 14791, "text": "void invalidate()" }, { "code": null, "e": 14837, "s": 14809, "text": "Invalidates this component." }, { "code": null, "e": 14863, "s": 14837, "text": "boolean isBackgroundSet()" }, { "code": null, "e": 14944, "s": 14863, "text": "Returns whether the background color has been explicitly set for this Component." }, { "code": null, "e": 14966, "s": 14944, "text": "boolean isCursorSet()" }, { "code": null, "e": 15037, "s": 14966, "text": "Returns whether the cursor has been explicitly set for this Component." }, { "code": null, "e": 15061, "s": 15037, "text": "boolean isDisplayable()" }, { "code": null, "e": 15111, "s": 15061, "text": "Determines whether this component is displayable." }, { "code": null, "e": 15138, "s": 15111, "text": "boolean isDoubleBuffered()" }, { "code": null, "e": 15245, "s": 15138, "text": "Returns true if this component is painted to an offscreen image (buffer)that's copied to the screen later." }, { "code": null, "e": 15265, "s": 15245, "text": "boolean isEnabled()" }, { "code": null, "e": 15311, "s": 15265, "text": "Determines whether this component is enabled." }, { "code": null, "e": 15333, "s": 15311, "text": "boolean isFocusable()" }, { "code": null, "e": 15380, "s": 15333, "text": "Returns whether this Component can be focused." }, { "code": null, "e": 15426, "s": 15380, "text": "boolean isFocusCycleRoot(Container container)" }, { "code": null, "e": 15533, "s": 15426, "text": "Returns whether the specified Container is the focus cycle root of this Component's focus traversal cycle." }, { "code": null, "e": 15556, "s": 15533, "text": "boolean isFocusOwner()" }, { "code": null, "e": 15607, "s": 15556, "text": "Returns true if this Component is the focus owner." }, { "code": null, "e": 15636, "s": 15607, "text": "boolean isFocusTraversable()" }, { "code": null, "e": 15686, "s": 15636, "text": "Deprecated. As of 1.4, replaced by isFocusable()." }, { "code": null, "e": 15706, "s": 15686, "text": "boolean isFontSet()" }, { "code": null, "e": 15775, "s": 15706, "text": "Returns whether the font has been explicitly set for this Component." }, { "code": null, "e": 15801, "s": 15775, "text": "boolean isForegroundSet()" }, { "code": null, "e": 15882, "s": 15801, "text": "Returns whether the foreground color has been explicitly set for this Component." }, { "code": null, "e": 15906, "s": 15882, "text": "boolean isLightweight()" }, { "code": null, "e": 15966, "s": 15906, "text": "A lightweight component doesn't have a native toolkit peer." }, { "code": null, "e": 15993, "s": 15966, "text": "boolean isMaximumSizeSet()" }, { "code": null, "e": 16084, "s": 15993, "text": "Returns true if the maximum size has been set to a non-null value otherwise returns false." }, { "code": null, "e": 16111, "s": 16084, "text": "boolean isMinimumSizeSet()" }, { "code": null, "e": 16189, "s": 16111, "text": "Returns whether or not setMinimumSize has been invoked with a non-null value." }, { "code": null, "e": 16208, "s": 16189, "text": "boolean isOpaque()" }, { "code": null, "e": 16287, "s": 16208, "text": "Returns true if this component is completely opaque, returns false by default." }, { "code": null, "e": 16316, "s": 16287, "text": "boolean isPreferredSizeSet()" }, { "code": null, "e": 16409, "s": 16316, "text": "Returns true if the preferred size has been set to a non-null value otherwise returns false." }, { "code": null, "e": 16429, "s": 16409, "text": "boolean isShowing()" }, { "code": null, "e": 16485, "s": 16429, "text": "Determines whether this component is showing on screen." }, { "code": null, "e": 16503, "s": 16485, "text": "boolean isValid()" }, { "code": null, "e": 16547, "s": 16503, "text": "Determines whether this component is valid." }, { "code": null, "e": 16567, "s": 16547, "text": "boolean isVisible()" }, { "code": null, "e": 16647, "s": 16567, "text": "Determines whether this component should be visible when its parent is visible." }, { "code": null, "e": 16682, "s": 16647, "text": "boolean keyDown(Event evt,int key)" }, { "code": null, "e": 16756, "s": 16682, "text": "Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent)." }, { "code": null, "e": 16790, "s": 16756, "text": "boolean keyUp(Event evt,int key)" }, { "code": null, "e": 16864, "s": 16790, "text": "Deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent)." }, { "code": null, "e": 16878, "s": 16864, "text": "void layout()" }, { "code": null, "e": 16937, "s": 16878, "text": "Deprecated. As of JDK version 1.1, replaced by doLayout()." }, { "code": null, "e": 16949, "s": 16937, "text": "void list()" }, { "code": null, "e": 17033, "s": 16949, "text": "Prints a listing of this component to the standard system output stream System.out." }, { "code": null, "e": 17060, "s": 17033, "text": "void list(PrintStream out)" }, { "code": null, "e": 17127, "s": 17060, "text": "Prints a listing of this component to the specified output stream." }, { "code": null, "e": 17166, "s": 17127, "text": "void list(PrintStream out,int indent)" }, { "code": null, "e": 17255, "s": 17166, "text": "Prints out a list, starting at the specified indentation, to the specified print stream." }, { "code": null, "e": 17282, "s": 17255, "text": "void list(PrintWriter out)" }, { "code": null, "e": 17330, "s": 17282, "text": "Prints a listing to the specified print writer." }, { "code": null, "e": 17369, "s": 17330, "text": "void list(PrintWriter out,int indent)" }, { "code": null, "e": 17458, "s": 17369, "text": "Prints out a list, starting at the specified indentation, to the specified print writer." }, { "code": null, "e": 17488, "s": 17458, "text": "Component locate(int x,int y)" }, { "code": null, "e": 17561, "s": 17488, "text": "Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int)." }, { "code": null, "e": 17578, "s": 17561, "text": "Point location()" }, { "code": null, "e": 17640, "s": 17578, "text": "Deprecated. As of JDK version 1.1, replaced by getLocation()." }, { "code": null, "e": 17682, "s": 17640, "text": "boolean lostFocus(Event evt, Object what)" }, { "code": null, "e": 17760, "s": 17682, "text": "Deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent)." }, { "code": null, "e": 17802, "s": 17760, "text": "boolean mouseDown(Event evt,int x,int y)" }, { "code": null, "e": 17880, "s": 17802, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent)." }, { "code": null, "e": 17922, "s": 17880, "text": "boolean mouseDrag(Event evt,int x,int y)" }, { "code": null, "e": 18006, "s": 17922, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent)." }, { "code": null, "e": 18049, "s": 18006, "text": "boolean mouseEnter(Event evt,int x,int y)" }, { "code": null, "e": 18127, "s": 18049, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent)." }, { "code": null, "e": 18169, "s": 18127, "text": "boolean mouseExit(Event evt,int x,int y)" }, { "code": null, "e": 18247, "s": 18169, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent)." }, { "code": null, "e": 18289, "s": 18247, "text": "boolean mouseMove(Event evt,int x,int y)" }, { "code": null, "e": 18373, "s": 18289, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent)." }, { "code": null, "e": 18413, "s": 18373, "text": "boolean mouseUp(Event evt,int x,int y)" }, { "code": null, "e": 18491, "s": 18413, "text": "Deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent)." }, { "code": null, "e": 18514, "s": 18491, "text": "void move(int x,int y)" }, { "code": null, "e": 18584, "s": 18514, "text": "Deprecated. As of JDK version 1.1, replaced by setLocation(int, int)." }, { "code": null, "e": 18601, "s": 18584, "text": "void nextFocus()" }, { "code": null, "e": 18665, "s": 18601, "text": "Deprecated. As of JDK version 1.1, replaced by transferFocus()." }, { "code": null, "e": 18688, "s": 18665, "text": "void paint(Graphics g)" }, { "code": null, "e": 18711, "s": 18688, "text": "Paints this component." }, { "code": null, "e": 18737, "s": 18711, "text": "void paintAll(Graphics g)" }, { "code": null, "e": 18789, "s": 18737, "text": "Paints this component and all of its subcomponents." }, { "code": null, "e": 18816, "s": 18789, "text": "boolean postEvent(Event e)" }, { "code": null, "e": 18888, "s": 18816, "text": "Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent)." }, { "code": null, "e": 18967, "s": 18888, "text": "boolean prepareImage(Image image,int width,int height, ImageObserver observer)" }, { "code": null, "e": 19052, "s": 18967, "text": "Prepares an image for rendering on this component at the specified width and height." }, { "code": null, "e": 19075, "s": 19052, "text": "void print(Graphics g)" }, { "code": null, "e": 19098, "s": 19075, "text": "Prints this component." }, { "code": null, "e": 19124, "s": 19098, "text": "void printAll(Graphics g)" }, { "code": null, "e": 19176, "s": 19124, "text": "Prints this component and all of its subcomponents." }, { "code": null, "e": 19230, "s": 19176, "text": "protectedvoid processComponentEvent(ComponentEvent e)" }, { "code": null, "e": 19350, "s": 19230, "text": "Processes component events occurring on this component by dispatching them to any registered ComponentListener objects." }, { "code": null, "e": 19390, "s": 19350, "text": "protected void processEvent(AWTEvent e)" }, { "code": null, "e": 19436, "s": 19390, "text": "Processes events occurring on this component." }, { "code": null, "e": 19483, "s": 19436, "text": "protected void processFocusEvent(FocusEvent e)" }, { "code": null, "e": 19595, "s": 19483, "text": "Processes focus events occurring on this component by dispatching them to any registered FocusListener objects." }, { "code": null, "e": 19656, "s": 19595, "text": "protected void processHierarchyBoundsEvent(HierarchyEvent e)" }, { "code": null, "e": 19789, "s": 19656, "text": "Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects." }, { "code": null, "e": 19844, "s": 19789, "text": "protected void processHierarchyEvent(HierarchyEvent e)" }, { "code": null, "e": 19964, "s": 19844, "text": "Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects." }, { "code": null, "e": 20022, "s": 19964, "text": "protectedvoid processInputMethodEvent(InputMethodEvent e)" }, { "code": null, "e": 20147, "s": 20022, "text": "Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects." }, { "code": null, "e": 20190, "s": 20147, "text": "protected void processKeyEvent(KeyEvent e)" }, { "code": null, "e": 20298, "s": 20190, "text": "Processes key events occurring on this component by dispatching them to any registered KeyListener objects." }, { "code": null, "e": 20345, "s": 20298, "text": "protected void processMouseEvent(MouseEvent e)" }, { "code": null, "e": 20457, "s": 20345, "text": "Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects." }, { "code": null, "e": 20510, "s": 20457, "text": "protected void processMouseMotionEvent(MouseEvent e)" }, { "code": null, "e": 20635, "s": 20510, "text": "Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects." }, { "code": null, "e": 20692, "s": 20635, "text": "protected void processMouseWheelEvent(MouseWheelEvent e)" }, { "code": null, "e": 20815, "s": 20692, "text": "Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects." }, { "code": null, "e": 20848, "s": 20815, "text": "void remove(MenuComponent popup)" }, { "code": null, "e": 20901, "s": 20848, "text": "Removes the specified popup menu from the component." }, { "code": null, "e": 20951, "s": 20901, "text": "void removeComponentListener(ComponentListener l)" }, { "code": null, "e": 21060, "s": 20951, "text": "Removes the specified component listener so that it no longer receives component events from this component." }, { "code": null, "e": 21102, "s": 21060, "text": "void removeFocusListener(FocusListener l)" }, { "code": null, "e": 21203, "s": 21102, "text": "Removes the specified focus listener so that it no longer receives focus events from this component." }, { "code": null, "e": 21265, "s": 21203, "text": "void removeHierarchyBoundsListener(HierarchyBoundsListener l)" }, { "code": null, "e": 21388, "s": 21265, "text": "Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component." }, { "code": null, "e": 21438, "s": 21388, "text": "void removeHierarchyListener(HierarchyListener l)" }, { "code": null, "e": 21555, "s": 21438, "text": "Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component." }, { "code": null, "e": 21609, "s": 21555, "text": "void removeInputMethodListener(InputMethodListener l)" }, { "code": null, "e": 21724, "s": 21609, "text": "Removes the specified input method listener so that it no longer receives input method events from this component." }, { "code": null, "e": 21762, "s": 21724, "text": "void removeKeyListener(KeyListener l)" }, { "code": null, "e": 21859, "s": 21762, "text": "Removes the specified key listener so that it no longer receives key events from this component." }, { "code": null, "e": 21901, "s": 21859, "text": "void removeMouseListener(MouseListener l)" }, { "code": null, "e": 22002, "s": 21901, "text": "Removes the specified mouse listener so that it no longer receives mouse events from this component." }, { "code": null, "e": 22056, "s": 22002, "text": "void removeMouseMotionListener(MouseMotionListener l)" }, { "code": null, "e": 22171, "s": 22056, "text": "Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component." }, { "code": null, "e": 22223, "s": 22171, "text": "void removeMouseWheelListener(MouseWheelListener l)" }, { "code": null, "e": 22336, "s": 22223, "text": "Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component." }, { "code": null, "e": 22356, "s": 22336, "text": "void removeNotify()" }, { "code": null, "e": 22433, "s": 22356, "text": "Makes this component undisplayable by destroying its native screen resource." }, { "code": null, "e": 22500, "s": 22433, "text": "void removePropertyChangeListener(PropertyChangeListener listener)" }, { "code": null, "e": 22557, "s": 22500, "text": "Removes a PropertyChangeListener from the listener list." }, { "code": null, "e": 22645, "s": 22557, "text": "void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)" }, { "code": null, "e": 22726, "s": 22645, "text": "Removes a PropertyChangeListener from the listener list for a specific property." }, { "code": null, "e": 22741, "s": 22726, "text": "void repaint()" }, { "code": null, "e": 22766, "s": 22741, "text": "Repaints this component." }, { "code": null, "e": 22815, "s": 22766, "text": "void repaint(int x,int y,int width,int height)" }, { "code": null, "e": 22867, "s": 22815, "text": "Repaints the specified rectangle of this component." }, { "code": null, "e": 22889, "s": 22867, "text": "void repaint(long tm)" }, { "code": null, "e": 22913, "s": 22889, "text": "Repaints the component." }, { "code": null, "e": 22971, "s": 22913, "text": "void repaint(long tm,int x,int y,int width,int height)" }, { "code": null, "e": 23046, "s": 22971, "text": "Repaints the specified rectangle of this component within tm milliseconds." }, { "code": null, "e": 23066, "s": 23046, "text": "void requestFocus()" }, { "code": null, "e": 23188, "s": 23066, "text": "Requests that this component get the input focus, and that this component's top-level ancestor become the focused Window." }, { "code": null, "e": 23238, "s": 23188, "text": "protected boolean requestFocus(boolean temporary)" }, { "code": null, "e": 23360, "s": 23238, "text": "Requests that this component get the input focus, and that this component's top-level ancestor become the focused Window." }, { "code": null, "e": 23391, "s": 23360, "text": "boolean requestFocusInWindow()" }, { "code": null, "e": 23511, "s": 23391, "text": "Requests that this component get the input focus, if this component's top-level ancestor is already the focused Window." }, { "code": null, "e": 23569, "s": 23511, "text": "protected boolean requestFocusInWindow(boolean temporary)" }, { "code": null, "e": 23689, "s": 23569, "text": "Requests that this component get the input focus, if this component's top-level ancestor is already the focused Window." }, { "code": null, "e": 23738, "s": 23689, "text": "void reshape(int x,int y,int width,int height)" }, { "code": null, "e": 23816, "s": 23738, "text": "Deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int)." }, { "code": null, "e": 23841, "s": 23816, "text": "void resize(Dimension d)" }, { "code": null, "e": 23908, "s": 23841, "text": "Deprecated. As of JDK version 1.1, replaced by setSize(Dimension)." }, { "code": null, "e": 23943, "s": 23908, "text": "void resize(int width,int height)" }, { "code": null, "e": 24009, "s": 23943, "text": "Deprecated. As of JDK version 1.1, replaced by setSize(int, int)." }, { "code": null, "e": 24037, "s": 24009, "text": "void setBackground(Color c)" }, { "code": null, "e": 24082, "s": 24037, "text": "Sets the background color of this component." }, { "code": null, "e": 24132, "s": 24082, "text": "void setBounds(int x,int y,int width,int height)" }, { "code": null, "e": 24166, "s": 24132, "text": "Moves and resizes this component." }, { "code": null, "e": 24194, "s": 24166, "text": "void setBounds(Rectangle r)" }, { "code": null, "e": 24271, "s": 24194, "text": "Moves and resizes this component to conform to the new bounding rectangle r." }, { "code": null, "e": 24324, "s": 24271, "text": "void setComponentOrientation(ComponentOrientation o)" }, { "code": null, "e": 24436, "s": 24324, "text": "Sets the language-sensitive orientation that is to be used to order the elements or text within this component." }, { "code": null, "e": 24466, "s": 24436, "text": "void setCursor(Cursor cursor)" }, { "code": null, "e": 24513, "s": 24466, "text": "Sets the cursor image to the specified cursor." }, { "code": null, "e": 24547, "s": 24513, "text": "void setDropTarget(DropTarget dt)" }, { "code": null, "e": 24591, "s": 24547, "text": "Associate a DropTarget with this component." }, { "code": null, "e": 24618, "s": 24591, "text": "void setEnabled(boolean b)" }, { "code": null, "e": 24697, "s": 24618, "text": "Enables or disables this component, depending on the value of the parameter b." }, { "code": null, "e": 24734, "s": 24697, "text": "void setFocusable(boolean focusable)" }, { "code": null, "e": 24801, "s": 24734, "text": "Sets the focusable state of this Component to the specified value." }, { "code": null, "e": 24876, "s": 24801, "text": "void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)" }, { "code": null, "e": 24958, "s": 24876, "text": "Sets the focus traversal keys for a given traversal operation for this Component." }, { "code": null, "e": 25027, "s": 24958, "text": "void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled)" }, { "code": null, "e": 25093, "s": 25027, "text": "Sets whether focus traversal keys are enabled for this component." }, { "code": null, "e": 25114, "s": 25093, "text": "void setFont(Font f)" }, { "code": null, "e": 25147, "s": 25114, "text": "Sets the font of this component." }, { "code": null, "e": 25175, "s": 25147, "text": "void setForeground(Color c)" }, { "code": null, "e": 25220, "s": 25175, "text": "Sets the foreground color of this component." }, { "code": null, "e": 25265, "s": 25220, "text": "void setIgnoreRepaint(boolean ignoreRepaint)" }, { "code": null, "e": 25354, "s": 25265, "text": "Sets whether or not paint messages received from the operating system should be ignored." }, { "code": null, "e": 25379, "s": 25354, "text": "void setLocale(Locale l)" }, { "code": null, "e": 25414, "s": 25379, "text": "Sets the locale of this component." }, { "code": null, "e": 25444, "s": 25414, "text": "void setLocation(int x,int y)" }, { "code": null, "e": 25484, "s": 25444, "text": "Moves this component to a new location." }, { "code": null, "e": 25510, "s": 25484, "text": "void setLocation(Point p)" }, { "code": null, "e": 25550, "s": 25510, "text": "Moves this component to a new location." }, { "code": null, "e": 25593, "s": 25550, "text": "void setMaximumSize(Dimension maximumSize)" }, { "code": null, "e": 25654, "s": 25593, "text": "Sets the maximum size of this component to a constant value." }, { "code": null, "e": 25697, "s": 25654, "text": "void setMinimumSize(Dimension minimumSize)" }, { "code": null, "e": 25758, "s": 25697, "text": "Sets the minimum size of this component to a constant value." }, { "code": null, "e": 25784, "s": 25758, "text": "void setName(String name)" }, { "code": null, "e": 25840, "s": 25784, "text": "Sets the name of the component to the specified string." }, { "code": null, "e": 25887, "s": 25840, "text": "void setPreferredSize(Dimension preferredSize)" }, { "code": null, "e": 25950, "s": 25887, "text": "Sets the preferred size of this component to a constant value." }, { "code": null, "e": 25976, "s": 25950, "text": "void setSize(Dimension d)" }, { "code": null, "e": 26049, "s": 25976, "text": "Resizes this component so that it has width d.width and height d.height." }, { "code": null, "e": 26085, "s": 26049, "text": "void setSize(int width,int height)" }, { "code": null, "e": 26154, "s": 26085, "text": "Resizes this component so that it has width width and height height." }, { "code": null, "e": 26181, "s": 26154, "text": "void setVisible(boolean b)" }, { "code": null, "e": 26250, "s": 26181, "text": "Shows or hides this component depending on the value of parameter b." }, { "code": null, "e": 26262, "s": 26250, "text": "void show()" }, { "code": null, "e": 26330, "s": 26262, "text": "Deprecated. As of JDK version 1.1, replaced by setVisible(boolean)." }, { "code": null, "e": 26351, "s": 26330, "text": "void show(boolean b)" }, { "code": null, "e": 26419, "s": 26351, "text": "Deprecated. As of JDK version 1.1, replaced by setVisible(boolean)." }, { "code": null, "e": 26436, "s": 26419, "text": "Dimension size()" }, { "code": null, "e": 26494, "s": 26436, "text": "Deprecated. As of JDK version 1.1, replaced by getSize()." }, { "code": null, "e": 26512, "s": 26494, "text": "String toString()" }, { "code": null, "e": 26578, "s": 26512, "text": "Returns a string representation of this component and its values." }, { "code": null, "e": 26599, "s": 26578, "text": "void transferFocus()" }, { "code": null, "e": 26689, "s": 26599, "text": "Transfers the focus to the next component, as though this Component were the focus owner." }, { "code": null, "e": 26718, "s": 26689, "text": "void transferFocusBackward()" }, { "code": null, "e": 26812, "s": 26718, "text": "Transfers the focus to the previous component, as though this Component were the focus owner." }, { "code": null, "e": 26840, "s": 26812, "text": "void transferFocusUpCycle()" }, { "code": null, "e": 26890, "s": 26840, "text": "Transfers the focus up one focus traversal cycle." }, { "code": null, "e": 26914, "s": 26890, "text": "void update(Graphics g)" }, { "code": null, "e": 26938, "s": 26914, "text": "Updates this component." }, { "code": null, "e": 26954, "s": 26938, "text": "void validate()" }, { "code": null, "e": 27002, "s": 26954, "text": "Ensures that this component has a valid layout." }, { "code": null, "e": 27021, "s": 27002, "text": "Rectangle bounds()" }, { "code": null, "e": 27081, "s": 27021, "text": "Deprecated. As of JDK version 1.1, replaced by getBounds()." }, { "code": null, "e": 27159, "s": 27081, "text": "protected AWTEvent\tcoalesceEvents(AWTEvent existingEvent, AWTEvent newEvent)" }, { "code": null, "e": 27226, "s": 27159, "text": "Potentially coalesce an event being posted with an existing event." }, { "code": null, "e": 27257, "s": 27226, "text": "protected String paramString()" }, { "code": null, "e": 27316, "s": 27257, "text": "Returns a string representing the state of this component." }, { "code": null, "e": 27399, "s": 27316, "text": "protected void firePropertyChange(String propertyName,int oldValue,int newValue)" }, { "code": null, "e": 27465, "s": 27399, "text": "Supports reporting bound property changes for integer properties." }, { "code": null, "e": 27491, "s": 27465, "text": "Dimension preferredSize()" }, { "code": null, "e": 27558, "s": 27491, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()." }, { "code": null, "e": 27616, "s": 27558, "text": "boolean prepareImage(Image image, ImageObserver observer)" }, { "code": null, "e": 27667, "s": 27616, "text": "Prepares an image for rendering on this component." }, { "code": null, "e": 27691, "s": 27667, "text": "Dimension minimumSize()" }, { "code": null, "e": 27756, "s": 27691, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize()." }, { "code": null, "e": 27811, "s": 27756, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 27828, "s": 27811, "text": "java.lang.Object" }, { "code": null, "e": 27863, "s": 27828, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 27883, "s": 27863, "text": " Pranjal Srivastava" }, { "code": null, "e": 27916, "s": 27883, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 27936, "s": 27916, "text": " Pranjal Srivastava" }, { "code": null, "e": 27971, "s": 27936, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 28007, "s": 27971, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 28042, "s": 28007, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 28055, "s": 28042, "text": " Travis Rose" }, { "code": null, "e": 28088, "s": 28055, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 28101, "s": 28088, "text": " Travis Rose" }, { "code": null, "e": 28108, "s": 28101, "text": " Print" }, { "code": null, "e": 28119, "s": 28108, "text": " Add Notes" } ]
How to loop through an array in Java?
To process array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known. Suppose we have an array of 5 elements we can print all the elements of this array as − Live Demo public class ProcessingArrays { public static void main(String args[]) { int myArray[] = {22, 23, 25, 27, 30}; for(int i=0; i<myArray.length; i++) { System.out.println(myArray[i]); } } } 22 23 25 27 30
[ { "code": null, "e": 1320, "s": 1062, "text": "To process array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known. Suppose we have an array of 5 elements we can print all the elements of this array as −" }, { "code": null, "e": 1330, "s": 1320, "text": "Live Demo" }, { "code": null, "e": 1556, "s": 1330, "text": "public class ProcessingArrays {\n public static void main(String args[]) {\n int myArray[] = {22, 23, 25, 27, 30};\n \n for(int i=0; i<myArray.length; i++) {\n System.out.println(myArray[i]);\n }\n }\n}" }, { "code": null, "e": 1571, "s": 1556, "text": "22\n23\n25\n27\n30" } ]
Generating random numbers in C#
To generate random numbers, use Random class. Create an object − Random r = new Random(); Now, use the Next() method to get random numbers in between a range − r.Next(10,50); The following is the complete code − Live Demo using System; public class Program { public static void Main() { Random r = new Random(); int genRand= r.Next(10,50); Console.WriteLine("Random Number = "+genRand); } } Random Number = 24
[ { "code": null, "e": 1108, "s": 1062, "text": "To generate random numbers, use Random class." }, { "code": null, "e": 1127, "s": 1108, "text": "Create an object −" }, { "code": null, "e": 1152, "s": 1127, "text": "Random r = new Random();" }, { "code": null, "e": 1222, "s": 1152, "text": "Now, use the Next() method to get random numbers in between a range −" }, { "code": null, "e": 1237, "s": 1222, "text": "r.Next(10,50);" }, { "code": null, "e": 1274, "s": 1237, "text": "The following is the complete code −" }, { "code": null, "e": 1285, "s": 1274, "text": " Live Demo" }, { "code": null, "e": 1478, "s": 1285, "text": "using System;\npublic class Program {\n public static void Main() {\n Random r = new Random();\n int genRand= r.Next(10,50);\n Console.WriteLine(\"Random Number = \"+genRand);\n }\n}" }, { "code": null, "e": 1497, "s": 1478, "text": "Random Number = 24" } ]
Fuzzy String Match With Python on Large Datasets and Why You Should Not Use FuzzyWuzzy | by Alina Zhang | Towards Data Science
Languages are ambiguous. The text referring to the same thing could be written slightly differently, or even misspelled. Assuming that you are trying to join two tables by the column of addresses, the same location shows in table A as “520 Xavier Ave, California City” while “520 Xavier Avenue, CA” in table B. How would you handle this issue? There are a few more examples demonstrating the same content written in different ways: The Queen’s Gambit vs Netflix The Queen’s Gambit (miniseries) Toronto Raptors vs Raptors Los Angeles Lakers vs Lakers helloworld@gmail.com vs helloworld@gmail.con Tesla, Inc. vs TSLA We want to treat them as the same thing before we feed the data to machine learning models or apply any other data analysis methods. When it comes to fuzzy string match, the first solution data scientists typically take is FuzzyWuzzy. FuzzyWuzzy package is a Levenshtein distance based method which widely used in computing similarity scores of strings. But why we should not use it? The answer is simple: it is way too slow. The estimated time of computing similarity scores for a 406,000-entity dataset of addresses is 337 hours. It only took 21 minutes on the same dataset with another solution FuzzyCouple which we will introduce soon. FYI, my box is MacBook Pro 2019 with an Intel Core i7 processor. 337 hours vs 21 minutes on large datasets — is it a strong enough argument that convinces you to try FuzzyCouple? If you say that it is the first time you heard about FuzzyCouple, you are absolutely right. Because I created the term that this method can be introduced as “I applied FuzzyCouple” instead of “I used TF-IDF as vectorizer then computed similarity scores with cosine similarity.” The ARXIV dataset used in this project contains about 41,000 research papers related to machine learning, NER, and computer vision published between 1992 and 2018. replace symbols: \n “ ‘ / ( ) { } | @ , ; # with space remove multiple spaces to lower case remove stop words import retext = 'Supporting "Temporal \'Reasoning by Mapping #@{ Calendar Expressions to Minimal\n Periodic Sets'REPLACE_BY_SPACE_RE = re.compile('[\n\"\'/(){}\[\]\|@,;#]')text = re.sub(REPLACE_BY_SPACE_RE, ' ', text)text = re.sub(' +', ' ', text)text = text.lower()print(text) As illustrated above, the column TITLE has removed stopwords, symbols, extra spaces, and been converted to lower cases. from wordcloud import WordCloudwordcloud = WordCloud().generate(' '.join(df['TITLE']))# plot the WordCloud imageplt.figure(figsize = (10, 8), facecolor = None)plt.imshow(wordcloud)plt.axis("off")plt.tight_layout(pad = 0)plt.show() As shown in the plot, the most common words used in research paper titles are neural, network, learning, analysis, classification, model, using, based, algorithm. from sklearn.feature_extraction.text import TfidfVectorizertfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2), max_df=0.9, min_df=5, token_pattern='(\S+)')tf_idf_matrix = tfidf_vectorizer.fit_transform(df['TITLE']) Column TITLE is the strings we remove stopwords and symbols from original paper titles. Column SIMILAR_TITLE is similar to TITLE. similarity_score indicates how similar they are which ranges from 0 to 1. As shown in the above example, the TITLE ‘unsupervised learning disentangled representations video’ is similar to ‘inferencing based unsupervised learning disentangled representations’ with a high score of 0.94. Let’s check the corresponding titles in the original papers: As we have seen, they are both research papers about disentangled representations with unsupervised learning algorithms. In this article, we introduced FuzzyCouple which is a super-fast solution for fuzzy string matching at scale. As mentioned at the beginning, text or languages can be ambiguous. FuzzyCouple is an efficient and practical method for identifying the “same thing” in unstructured data. Reference: Super Fast String Matching in Python by Ven Dan
[ { "code": null, "e": 516, "s": 172, "text": "Languages are ambiguous. The text referring to the same thing could be written slightly differently, or even misspelled. Assuming that you are trying to join two tables by the column of addresses, the same location shows in table A as “520 Xavier Ave, California City” while “520 Xavier Avenue, CA” in table B. How would you handle this issue?" }, { "code": null, "e": 604, "s": 516, "text": "There are a few more examples demonstrating the same content written in different ways:" }, { "code": null, "e": 666, "s": 604, "text": "The Queen’s Gambit vs Netflix The Queen’s Gambit (miniseries)" }, { "code": null, "e": 693, "s": 666, "text": "Toronto Raptors vs Raptors" }, { "code": null, "e": 722, "s": 693, "text": "Los Angeles Lakers vs Lakers" }, { "code": null, "e": 767, "s": 722, "text": "helloworld@gmail.com vs helloworld@gmail.con" }, { "code": null, "e": 787, "s": 767, "text": "Tesla, Inc. vs TSLA" }, { "code": null, "e": 920, "s": 787, "text": "We want to treat them as the same thing before we feed the data to machine learning models or apply any other data analysis methods." }, { "code": null, "e": 1213, "s": 920, "text": "When it comes to fuzzy string match, the first solution data scientists typically take is FuzzyWuzzy. FuzzyWuzzy package is a Levenshtein distance based method which widely used in computing similarity scores of strings. But why we should not use it? The answer is simple: it is way too slow." }, { "code": null, "e": 1492, "s": 1213, "text": "The estimated time of computing similarity scores for a 406,000-entity dataset of addresses is 337 hours. It only took 21 minutes on the same dataset with another solution FuzzyCouple which we will introduce soon. FYI, my box is MacBook Pro 2019 with an Intel Core i7 processor." }, { "code": null, "e": 1606, "s": 1492, "text": "337 hours vs 21 minutes on large datasets — is it a strong enough argument that convinces you to try FuzzyCouple?" }, { "code": null, "e": 1884, "s": 1606, "text": "If you say that it is the first time you heard about FuzzyCouple, you are absolutely right. Because I created the term that this method can be introduced as “I applied FuzzyCouple” instead of “I used TF-IDF as vectorizer then computed similarity scores with cosine similarity.”" }, { "code": null, "e": 2048, "s": 1884, "text": "The ARXIV dataset used in this project contains about 41,000 research papers related to machine learning, NER, and computer vision published between 1992 and 2018." }, { "code": null, "e": 2103, "s": 2048, "text": "replace symbols: \\n “ ‘ / ( ) { } | @ , ; # with space" }, { "code": null, "e": 2126, "s": 2103, "text": "remove multiple spaces" }, { "code": null, "e": 2140, "s": 2126, "text": "to lower case" }, { "code": null, "e": 2158, "s": 2140, "text": "remove stop words" }, { "code": null, "e": 2436, "s": 2158, "text": "import retext = 'Supporting \"Temporal \\'Reasoning by Mapping #@{ Calendar Expressions to Minimal\\n Periodic Sets'REPLACE_BY_SPACE_RE = re.compile('[\\n\\\"\\'/(){}\\[\\]\\|@,;#]')text = re.sub(REPLACE_BY_SPACE_RE, ' ', text)text = re.sub(' +', ' ', text)text = text.lower()print(text)" }, { "code": null, "e": 2556, "s": 2436, "text": "As illustrated above, the column TITLE has removed stopwords, symbols, extra spaces, and been converted to lower cases." }, { "code": null, "e": 2787, "s": 2556, "text": "from wordcloud import WordCloudwordcloud = WordCloud().generate(' '.join(df['TITLE']))# plot the WordCloud imageplt.figure(figsize = (10, 8), facecolor = None)plt.imshow(wordcloud)plt.axis(\"off\")plt.tight_layout(pad = 0)plt.show()" }, { "code": null, "e": 2950, "s": 2787, "text": "As shown in the plot, the most common words used in research paper titles are neural, network, learning, analysis, classification, model, using, based, algorithm." }, { "code": null, "e": 3167, "s": 2950, "text": "from sklearn.feature_extraction.text import TfidfVectorizertfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2), max_df=0.9, min_df=5, token_pattern='(\\S+)')tf_idf_matrix = tfidf_vectorizer.fit_transform(df['TITLE'])" }, { "code": null, "e": 3371, "s": 3167, "text": "Column TITLE is the strings we remove stopwords and symbols from original paper titles. Column SIMILAR_TITLE is similar to TITLE. similarity_score indicates how similar they are which ranges from 0 to 1." }, { "code": null, "e": 3583, "s": 3371, "text": "As shown in the above example, the TITLE ‘unsupervised learning disentangled representations video’ is similar to ‘inferencing based unsupervised learning disentangled representations’ with a high score of 0.94." }, { "code": null, "e": 3644, "s": 3583, "text": "Let’s check the corresponding titles in the original papers:" }, { "code": null, "e": 3765, "s": 3644, "text": "As we have seen, they are both research papers about disentangled representations with unsupervised learning algorithms." }, { "code": null, "e": 4046, "s": 3765, "text": "In this article, we introduced FuzzyCouple which is a super-fast solution for fuzzy string matching at scale. As mentioned at the beginning, text or languages can be ambiguous. FuzzyCouple is an efficient and practical method for identifying the “same thing” in unstructured data." }, { "code": null, "e": 4057, "s": 4046, "text": "Reference:" } ]
Angular 8 - Web Workers
Web workers enables JavaScript application to run the CPU-intensive in the background so that the application main thread concentrate on the smooth operation of UI. Angular provides support for including Web workers in the application. Let us write a simple Angular application and try to use web workers. Create a new Angular application using below command − cd /go/to/workspace ng new web-worker-sample Run the application using below command − cd web-worker-sample npm run start Add new web worker using below command − ng generate web-worker app The output of the above command is as follows − CREATE tsconfig.worker.json (212 bytes) CREATE src/app/app.worker.ts (157 bytes) UPDATE tsconfig.app.json (296 bytes) UPDATE angular.json (3776 bytes) UPDATE src/app/app.component.ts (605 bytes) Here, app refers the location of the web worker to be created. Angular CLI will generate two new files, tsconfig.worker.json and src/app/app.worker.ts and update three files, tsconfig.app.json, angular.json and src/app/app.component.ts file. Let us check the changes − // tsconfig.worker.json { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/worker", "lib": [ "es2018", "webworker" ], "types": [] }, "include": [ "src/**/*.worker.ts" ] } Here, tsconfig.worker.json extends tsconfig.json and includes options to compile web workers. // tsconfig.app.json [only a snippet] "exclude": [ "src/test.ts", "src/**/*.spec.ts", "src/**/*.worker.ts" ] Here, Basically, it excludes all the worker from compiling as it has separate configuration. // angular.json (only a snippet) "webWorkerTsConfig": "tsconfig.worker.json" Here, angular.json includes the web worker configuration file, tsconfig.worker.json. // src/app/app.worker.ts addEventListener('message', ({ data }) => { const response = `worker response to ${data}`; postMessage(response); }); Here, A web worker is created. Web worker is basically a function, which will be called when a message event is fired. The web worker will receive the data send by the caller, process it and then send the response back to the caller. // src/app/app.component.ts [only a snippet] if (typeof Worker !== 'undefined') { // Create a new const worker = new Worker('./app.worker', { type: 'module' }); worker.onmessage = ({ data }) => { console.log(`page got message: ${data}`); }; worker.postMessage('hello'); } else { // Web Workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } Here, AppComponent create a new worker instance, create a callback function to receive the response and then post the message to the worker. Restart the application. Since the angular.json file is changed, which is not watched by Angular runner, it is necessary to restart the application. Otherwise, Angular does not identify the new web worker and does not compile it. Let us create Typescript class, src/app/app.prime.ts to find nth prime numbers. export class PrimeCalculator { static isPrimeNumber(num : number) : boolean { if(num == 1) return true; let idx : number = 2; for(idx = 2; idx < num / 2; idx++) { if(num % idx == 0) return false; } return true; } static findNthPrimeNumber(num : number) : number { let idx : number = 1; let count = 0; while(count < num) { if(this.isPrimeNumber(idx)) count++; idx++; console.log(idx); } return idx - 1; } } Here, isPrimeNumber check whether the given number is prime or not. findNthPrimeNumber finds the nth prime number. Import the new created prime number class into src/app/app.worker.ts and change the logic of the web worker to find nth prime number. /// <reference lib="webworker" /> import { PrimeCalculator } from './app.prime'; addEventListener('message', ({ data }) => { // const response = `worker response to ${data}`; const response = PrimeCalculator.findNthPrimeNumber(parseInt(data)); postMessage(response); }); Change AppComponent and include two function, find10thPrimeNumber and find10000thPrimeNumber. import { Component } from '@angular/core'; import { PrimeCalculator } from './app.prime'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Web worker sample'; prime10 : number = 0; prime10000 : number = 0; find10thPrimeNumber() { this.prime10 = PrimeCalculator.findNthPrimeNumber(10); } find10000thPrimeNumber() { if (typeof Worker !== 'undefined') { // Create a new const worker = new Worker('./app.worker', { type: 'module' }); worker.onmessage = ({ data }) => { this.prime10000 = data; }; worker.postMessage(10000); } else { // Web Workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } } } Here, find10thPrimeNumber is directly using the PrimeCalculator. But, find10000thPrimeNumber is delegating the calculation to web worker, which in turn uses PrimeCalculator. Change the AppComponent template, src/app/app.commands.html and include two option, one to find 10th prime number and another to find the 10000th prime number. <h1>{{ title }}</h1> <div> <a href="#" (click)="find10thPrimeNumber()">Click here</a> to find 10th prime number <div>The 10<sup>th</sup> prime number is {{ prime10 }}</div> <br/> <a href="#" (click)="find10000thPrimeNumber()">Click here</a> to find 10000th prime number <div>The 10000<sup>th</sup> prime number is {{ prime10000 }}</div> </div> Here, Finding 10000th prime number will take few seconds, but it will not affect other process as it is uses web workers. Just try to find the 10000th prime number first and then, the 10th prime number. Since, the web worker is calculating 10000th prime number, the UI does not freeze. We can check 10th prime number in the meantime. If we have not used web worker, we could not do anything in the browser as it is actively processing the 10000th prime number. The result of the application is as follows − Initial state of the application. Click and try to find the 10000th prime number and then try to find the 10th prime number. The application finds the 10th prime number quite fast and shows it. The application is still processing in the background to find the 10000th prime number. Both processes are completed. Web worker enhances the user experience of web application by doing the complex operation in the background and it is quite easy to do it in Angular Application as well. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2694, "s": 2388, "text": "Web workers enables JavaScript application to run the CPU-intensive in the background so that the application main thread concentrate on the smooth operation of UI. Angular provides support for including Web workers in the application. Let us write a simple Angular application and try to use web workers." }, { "code": null, "e": 2749, "s": 2694, "text": "Create a new Angular application using below command −" }, { "code": null, "e": 2794, "s": 2749, "text": "cd /go/to/workspace\nng new web-worker-sample" }, { "code": null, "e": 2836, "s": 2794, "text": "Run the application using below command −" }, { "code": null, "e": 2871, "s": 2836, "text": "cd web-worker-sample\nnpm run start" }, { "code": null, "e": 2912, "s": 2871, "text": "Add new web worker using below command −" }, { "code": null, "e": 2939, "s": 2912, "text": "ng generate web-worker app" }, { "code": null, "e": 2987, "s": 2939, "text": "The output of the above command is as follows −" }, { "code": null, "e": 3182, "s": 2987, "text": "CREATE tsconfig.worker.json (212 bytes)\nCREATE src/app/app.worker.ts (157 bytes)\nUPDATE tsconfig.app.json (296 bytes)\nUPDATE angular.json (3776 bytes)\nUPDATE src/app/app.component.ts (605 bytes)" }, { "code": null, "e": 3188, "s": 3182, "text": "Here," }, { "code": null, "e": 3245, "s": 3188, "text": "app refers the location of the web worker to be created." }, { "code": null, "e": 3424, "s": 3245, "text": "Angular CLI will generate two new files, tsconfig.worker.json and src/app/app.worker.ts and update three files, tsconfig.app.json, angular.json and src/app/app.component.ts file." }, { "code": null, "e": 3451, "s": 3424, "text": "Let us check the changes −" }, { "code": null, "e": 3710, "s": 3451, "text": "// tsconfig.worker.json\n{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"./out-tsc/worker\",\n \"lib\": [\n \"es2018\",\n \"webworker\"\n ],\n\n\n \"types\": []\n },\n \"include\": [\n \"src/**/*.worker.ts\"\n ]\n}" }, { "code": null, "e": 3716, "s": 3710, "text": "Here," }, { "code": null, "e": 3804, "s": 3716, "text": "tsconfig.worker.json extends tsconfig.json and includes options to compile web workers." }, { "code": null, "e": 3922, "s": 3804, "text": "// tsconfig.app.json [only a snippet]\n\"exclude\": [\n \"src/test.ts\",\n \"src/**/*.spec.ts\",\n \"src/**/*.worker.ts\"\n]" }, { "code": null, "e": 3928, "s": 3922, "text": "Here," }, { "code": null, "e": 4015, "s": 3928, "text": "Basically, it excludes all the worker from compiling as it has separate configuration." }, { "code": null, "e": 4092, "s": 4015, "text": "// angular.json (only a snippet) \"webWorkerTsConfig\": \"tsconfig.worker.json\"" }, { "code": null, "e": 4098, "s": 4092, "text": "Here," }, { "code": null, "e": 4177, "s": 4098, "text": "angular.json includes the web worker configuration file, tsconfig.worker.json." }, { "code": null, "e": 4326, "s": 4177, "text": "// src/app/app.worker.ts\naddEventListener('message', ({ data }) => {\n const response = `worker response to ${data}`;\n postMessage(response);\n});" }, { "code": null, "e": 4332, "s": 4326, "text": "Here," }, { "code": null, "e": 4560, "s": 4332, "text": "A web worker is created. Web worker is basically a function, which will be called when a message event is fired. The web worker will receive the data send by the caller, process it and then send the response back to the caller." }, { "code": null, "e": 4999, "s": 4560, "text": "// src/app/app.component.ts [only a snippet]\nif (typeof Worker !== 'undefined') {\n // Create a new\n const worker = new Worker('./app.worker', { type: 'module' });\n worker.onmessage = ({ data }) => {\n console.log(`page got message: ${data}`);\n };\n worker.postMessage('hello');\n} else {\n\n // Web Workers are not supported in this environment.\n // You should add a fallback so that your program still executes correctly.\n}" }, { "code": null, "e": 5005, "s": 4999, "text": "Here," }, { "code": null, "e": 5140, "s": 5005, "text": "AppComponent create a new worker instance, create a callback function to receive the response and then post the message to the worker." }, { "code": null, "e": 5370, "s": 5140, "text": "Restart the application. Since the angular.json file is changed, which is not watched by Angular runner, it is necessary to restart the application. Otherwise, Angular does not identify the new web worker and does not compile it." }, { "code": null, "e": 5450, "s": 5370, "text": "Let us create Typescript class, src/app/app.prime.ts to find nth prime numbers." }, { "code": null, "e": 6000, "s": 5450, "text": "export class PrimeCalculator\n{\n static isPrimeNumber(num : number) : boolean {\n if(num == 1) return true;\n\n let idx : number = 2;\n for(idx = 2; idx < num / 2; idx++)\n {\n if(num % idx == 0)\n return false;\n }\n\n return true;\n }\n\n static findNthPrimeNumber(num : number) : number {\n let idx : number = 1;\n let count = 0;\n\n while(count < num) {\n if(this.isPrimeNumber(idx))\n count++;\n\n idx++;\n console.log(idx);\n }\n\n return idx - 1;\n }\n}" }, { "code": null, "e": 6006, "s": 6000, "text": "Here," }, { "code": null, "e": 6068, "s": 6006, "text": "isPrimeNumber check whether the given number is prime or not." }, { "code": null, "e": 6115, "s": 6068, "text": "findNthPrimeNumber finds the nth prime number." }, { "code": null, "e": 6249, "s": 6115, "text": "Import the new created prime number class into src/app/app.worker.ts and change the logic of the web worker to find nth prime number." }, { "code": null, "e": 6531, "s": 6249, "text": "/// <reference lib=\"webworker\" />\n\nimport { PrimeCalculator } from './app.prime';\n\naddEventListener('message', ({ data }) => {\n // const response = `worker response to ${data}`;\n const response = PrimeCalculator.findNthPrimeNumber(parseInt(data));\n postMessage(response);\n});" }, { "code": null, "e": 6625, "s": 6531, "text": "Change AppComponent and include two function, find10thPrimeNumber and find10000thPrimeNumber." }, { "code": null, "e": 7516, "s": 6625, "text": "import { Component } from '@angular/core';\nimport { PrimeCalculator } from './app.prime';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Web worker sample';\n prime10 : number = 0;\n prime10000 : number = 0;\n\n find10thPrimeNumber() {\n this.prime10 = PrimeCalculator.findNthPrimeNumber(10);\n }\n\n find10000thPrimeNumber() {\n if (typeof Worker !== 'undefined') {\n // Create a new\n const worker = new Worker('./app.worker', { type: 'module' });\n worker.onmessage = ({ data }) => {\n this.prime10000 = data;\n };\n worker.postMessage(10000);\n } else {\n // Web Workers are not supported in this environment.\n // You should add a fallback so that your program still executes correctly.\n }\n }\n}" }, { "code": null, "e": 7522, "s": 7516, "text": "Here," }, { "code": null, "e": 7690, "s": 7522, "text": "find10thPrimeNumber is directly using the PrimeCalculator. But, find10000thPrimeNumber is delegating the calculation to web worker, which in turn uses PrimeCalculator." }, { "code": null, "e": 7850, "s": 7690, "text": "Change the AppComponent template, src/app/app.commands.html and include two option, one to find 10th prime number and another to find the 10000th prime number." }, { "code": null, "e": 8207, "s": 7850, "text": "<h1>{{ title }}</h1>\n\n<div>\n <a href=\"#\" (click)=\"find10thPrimeNumber()\">Click here</a> to find 10th prime number\n <div>The 10<sup>th</sup> prime number is {{ prime10 }}</div> <br/>\n <a href=\"#\" (click)=\"find10000thPrimeNumber()\">Click here</a> to find 10000th prime number\n <div>The 10000<sup>th</sup> prime number is {{ prime10000 }}</div>\n</div>" }, { "code": null, "e": 8213, "s": 8207, "text": "Here," }, { "code": null, "e": 8410, "s": 8213, "text": "Finding 10000th prime number will take few seconds, but it will not affect other process as it is uses web workers. Just try to find the 10000th prime number first and then, the 10th prime number." }, { "code": null, "e": 8668, "s": 8410, "text": "Since, the web worker is calculating 10000th prime number, the UI does not freeze. We can check 10th prime number in the meantime. If we have not used web worker, we could not do anything in the browser as it is actively processing the 10000th prime number." }, { "code": null, "e": 8714, "s": 8668, "text": "The result of the application is as follows −" }, { "code": null, "e": 8748, "s": 8714, "text": "Initial state of the application." }, { "code": null, "e": 8996, "s": 8748, "text": "Click and try to find the 10000th prime number and then try to find the 10th prime number. The application finds the 10th prime number quite fast and shows it. The application is still processing in the background to find the 10000th prime number." }, { "code": null, "e": 9026, "s": 8996, "text": "Both processes are completed." }, { "code": null, "e": 9196, "s": 9026, "text": "Web worker enhances the user experience of web application by doing the complex operation in the background and it is quite easy to do it in Angular Application as well." }, { "code": null, "e": 9231, "s": 9196, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9245, "s": 9231, "text": " Anadi Sharma" }, { "code": null, "e": 9280, "s": 9245, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9294, "s": 9280, "text": " Anadi Sharma" }, { "code": null, "e": 9329, "s": 9294, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9349, "s": 9329, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9384, "s": 9349, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9401, "s": 9384, "text": " Frahaan Hussain" }, { "code": null, "e": 9434, "s": 9401, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 9446, "s": 9434, "text": " Senol Atac" }, { "code": null, "e": 9481, "s": 9446, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9493, "s": 9481, "text": " Senol Atac" }, { "code": null, "e": 9500, "s": 9493, "text": " Print" }, { "code": null, "e": 9511, "s": 9500, "text": " Add Notes" } ]
Selecting Optimal Parameters for XGBoost Model Training | by Andrej Baranovskij | Towards Data Science
There is always a bit of luck involved when selecting parameters for Machine Learning model training. Lately, I work with gradient boosted trees and XGBoost in particular. We are using XGBoost in the enterprise to automate repetitive human tasks. While training ML models with XGBoost, I created a pattern to choose parameters, which helps me to build new models quicker. I will share it in this post, hopefully you will find it useful too. I’m using Pima Indians Diabetes Database for the training, CSV data can be downloaded from here. This is the Python code which runs XGBoost training step and builds a model. Training is executed by passing pairs of train/test data, this helps to evaluate training quality ad-hoc during model construction: %%time model = xgb.XGBClassifier(max_depth=12, subsample=0.33, objective='binary:logistic', n_estimators=300, learning_rate = 0.01) eval_set = [(train_X, train_Y), (test_X, test_Y)] model.fit(train_X, train_Y.values.ravel(), early_stopping_rounds=15, eval_metric=["error", "logloss"], eval_set=eval_set, verbose=True) [0] validation_0-error:0.231518 validation_0-logloss:0.688982 validation_1-error:0.30315 validation_1-logloss:0.689593 Multiple eval metrics have been passed: 'validation_1-logloss' will be used for early stopping. Will train until validation_1-logloss hasn't improved in 15 rounds. [1] validation_0-error:0.206226 validation_0-logloss:0.685218 validation_1-error:0.216535 validation_1-logloss:0.686122 [2] validation_0-error:0.196498 validation_0-logloss:0.681505 validation_1-error:0.220472 validation_1-logloss:0.682881 [3] validation_0-error:0.196498 validation_0-logloss:0.67797 validation_1-error:0.220472 validation_1-logloss:0.679601 [4] validation_0-error:0.180934 validation_0-logloss:0.674278 validation_1-error:0.208661 validation_1-logloss:0.676067 [5] validation_0-error:0.177043 validation_0-logloss:0.670627 validation_1-error:0.212598 validation_1-logloss:0.673761 [6] validation_0-error:0.175097 validation_0-logloss:0.667069 validation_1-error:0.216535 validation_1-logloss:0.671441 [7] validation_0-error:0.18677 validation_0-logloss:0.663582 validation_1-error:0.212598 validation_1-logloss:0.668586 [8] validation_0-error:0.180934 validation_0-logloss:0.660353 validation_1-error:0.23622 validation_1-logloss:0.665983 [9] validation_0-error:0.161479 validation_0-logloss:0.656739 validation_1-error:0.228346 validation_1-logloss:0.662987 [10] validation_0-error:0.167315 validation_0-logloss:0.653582 validation_1-error:0.228346 validation_1-logloss:0.660091 [259] validation_0-error:0.122568 validation_0-logloss:0.34313 validation_1-error:0.220472 validation_1-logloss:0.475866 [260] validation_0-error:0.124514 validation_0-logloss:0.34261 validation_1-error:0.220472 validation_1-logloss:0.476068 [261] validation_0-error:0.120623 validation_0-logloss:0.342156 validation_1-error:0.216535 validation_1-logloss:0.476165 [262] validation_0-error:0.120623 validation_0-logloss:0.341714 validation_1-error:0.216535 validation_1-logloss:0.476143 [263] validation_0-error:0.124514 validation_0-logloss:0.341209 validation_1-error:0.216535 validation_1-logloss:0.476063 [264] validation_0-error:0.120623 validation_0-logloss:0.340779 validation_1-error:0.220472 validation_1-logloss:0.47595 [265] validation_0-error:0.120623 validation_0-logloss:0.340297 validation_1-error:0.212598 validation_1-logloss:0.475858 [266] validation_0-error:0.120623 validation_0-logloss:0.339908 validation_1-error:0.212598 validation_1-logloss:0.476057 [267] validation_0-error:0.120623 validation_0-logloss:0.339312 validation_1-error:0.220472 validation_1-logloss:0.476228 [268] validation_0-error:0.120623 validation_0-logloss:0.338874 validation_1-error:0.216535 validation_1-logloss:0.476266 [269] validation_0-error:0.120623 validation_0-logloss:0.338543 validation_1-error:0.216535 validation_1-logloss:0.476202 [270] validation_0-error:0.120623 validation_0-logloss:0.33821 validation_1-error:0.216535 validation_1-logloss:0.47607 [271] validation_0-error:0.120623 validation_0-logloss:0.337716 validation_1-error:0.212598 validation_1-logloss:0.476229 [272] validation_0-error:0.118677 validation_0-logloss:0.337295 validation_1-error:0.212598 validation_1-logloss:0.47612 [273] validation_0-error:0.118677 validation_0-logloss:0.336927 validation_1-error:0.212598 validation_1-logloss:0.476152 [274] validation_0-error:0.118677 validation_0-logloss:0.33651 validation_1-error:0.212598 validation_1-logloss:0.476127 [275] validation_0-error:0.120623 validation_0-logloss:0.336017 validation_1-error:0.216535 validation_1-logloss:0.476117 [276] validation_0-error:0.120623 validation_0-logloss:0.335497 validation_1-error:0.212598 validation_1-logloss:0.476063 [277] validation_0-error:0.116732 validation_0-logloss:0.335159 validation_1-error:0.216535 validation_1-logloss:0.476113 [278] validation_0-error:0.114786 validation_0-logloss:0.334812 validation_1-error:0.216535 validation_1-logloss:0.476143 [279] validation_0-error:0.114786 validation_0-logloss:0.334481 validation_1-error:0.216535 validation_1-logloss:0.476163 [280] validation_0-error:0.116732 validation_0-logloss:0.333843 validation_1-error:0.216535 validation_1-logloss:0.476359 Stopping. Best iteration: [265] validation_0-error:0.120623 validation_0-logloss:0.340297 validation_1-error:0.212598 validation_1-logloss:0.475858 CPU times: user 690 ms, sys: 310 ms, total: 1 s Wall time: 799 ms Key parameters in XGBoost(the ones which would affect model quality greatly), assuming you already selected max_depth (more complex classification task, deeper the tree), subsample (equal to evaluation data percentage), objective (classification algorithm): n_estimators — the number of runs XGBoost will try to learn learning_rate — learning speed early_stopping_rounds — overfitting prevention, stop early if no improvement in learning When model.fit is executed with verbose=True, you will see each training run evaluation quality printed out. At the end of the log, you should see which iteration was selected as the best one. It might be the number of training rounds is not enough to detect the best iteration, then XGBoost will select the last iteration to build the model. With matpotlib library we can plot training results for each run (from XGBoost output). This helps to understand if iteration which was chosen to build the model was the best one possible. Here we are using sklearn library to evaluate model accuracy and then plotting training results with matpotlib: # make predictions for test data y_pred = model.predict(test_X) predictions = [round(value) for value in y_pred] # evaluate predictions accuracy = accuracy_score(test_Y, predictions) print("Accuracy: %.2f%%" % (accuracy * 100.0)) Accuracy: 78.74% # retrieve performance metrics results = model.evals_result() epochs = len(results['validation_0']['error']) x_axis = range(0, epochs) # plot log loss fig, ax = pyplot.subplots() ax.plot(x_axis, results['validation_0']['logloss'], label='Train') ax.plot(x_axis, results['validation_1']['logloss'], label='Test') ax.legend() pyplot.ylabel('Log Loss') pyplot.title('XGBoost Log Loss') pyplot.show() # plot classification error fig, ax = pyplot.subplots() ax.plot(x_axis, results['validation_0']['error'], label='Train') ax.plot(x_axis, results['validation_1']['error'], label='Test') ax.legend() pyplot.ylabel('Classification Error') pyplot.title('XGBoost Classification Error') pyplot.show() Let’s describe my approach to select parameters (n_estimators, learning_rate, early_stopping_rounds) for XGBoost training. Step 1. Start with what you feel works best based on your experience or what makes sense n_estimators = 300 learning_rate = 0.01 early_stopping_rounds = 10 Results: Stop iteration = 237 Accuracy = 78.35% Results plot: With the first attempt, we already get good results for Pima Indians Diabetes dataset. Training was stopped at iteration 237. Classification error plot shows a lower error rate around iteration 237. This means learning rate 0.01 is suitable for this dataset and early stopping of 10 iterations (if the result doesn’t improve in the next 10 iterations) works. Step 2. Experiment with learning rate, try to set a smaller learning rate parameter and increase number of learning iterations n_estimators = 500 learning_rate = 0.001 early_stopping_rounds = 10 Results: Stop iteration = didn’t stop, spent all 500 iterations Accuracy = 77.56% Results plot: Smaller learning rate wasn’t working for this dataset. Classification error almost doesn’t change and XGBoost log loss doesn’t stabilize even with 500 iterations. Step 3. Try to increase the learning rate. n_estimators = 300 learning_rate = 0.1 early_stopping_rounds = 10 Results: Stop iteration = 27 Accuracy = 76.77% Results plot: With increased learning rate, the algorithm learns quicker, it stops already at iteration Nr. 27. XGBoost log loss error is stabilizing, but the overall classification accuracy is not ideal. Step 4. Select optimal learning rate from the first step and increase early stopping (to give the algorithm more chances to find a better result). n_estimators = 300 learning_rate = 0.01 early_stopping_rounds = 15 Results: Stop iteration = 265 Accuracy = 78.74% Results plot: A slightly better result is produced with 78.74% accuracy — this is visible in the classification error plot. Resources: Jupyter notebook on GitHub Blog post — Jupyter Notebook — Forget CSV, fetch data from DB with Python Blog post — Avoid Overfitting By Early Stopping With XGBoost In Python
[ { "code": null, "e": 613, "s": 172, "text": "There is always a bit of luck involved when selecting parameters for Machine Learning model training. Lately, I work with gradient boosted trees and XGBoost in particular. We are using XGBoost in the enterprise to automate repetitive human tasks. While training ML models with XGBoost, I created a pattern to choose parameters, which helps me to build new models quicker. I will share it in this post, hopefully you will find it useful too." }, { "code": null, "e": 710, "s": 613, "text": "I’m using Pima Indians Diabetes Database for the training, CSV data can be downloaded from here." }, { "code": null, "e": 919, "s": 710, "text": "This is the Python code which runs XGBoost training step and builds a model. Training is executed by passing pairs of train/test data, this helps to evaluate training quality ad-hoc during model construction:" }, { "code": null, "e": 1335, "s": 919, "text": "%%time\n\nmodel = xgb.XGBClassifier(max_depth=12,\n subsample=0.33,\n objective='binary:logistic',\n n_estimators=300,\n learning_rate = 0.01)\neval_set = [(train_X, train_Y), (test_X, test_Y)]\nmodel.fit(train_X, train_Y.values.ravel(), early_stopping_rounds=15, eval_metric=[\"error\", \"logloss\"], eval_set=eval_set, verbose=True)\n" }, { "code": null, "e": 5710, "s": 1335, "text": "[0]\tvalidation_0-error:0.231518\tvalidation_0-logloss:0.688982\tvalidation_1-error:0.30315\tvalidation_1-logloss:0.689593\nMultiple eval metrics have been passed: 'validation_1-logloss' will be used for early stopping.\n\nWill train until validation_1-logloss hasn't improved in 15 rounds.\n[1]\tvalidation_0-error:0.206226\tvalidation_0-logloss:0.685218\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.686122\n[2]\tvalidation_0-error:0.196498\tvalidation_0-logloss:0.681505\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.682881\n[3]\tvalidation_0-error:0.196498\tvalidation_0-logloss:0.67797\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.679601\n[4]\tvalidation_0-error:0.180934\tvalidation_0-logloss:0.674278\tvalidation_1-error:0.208661\tvalidation_1-logloss:0.676067\n[5]\tvalidation_0-error:0.177043\tvalidation_0-logloss:0.670627\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.673761\n[6]\tvalidation_0-error:0.175097\tvalidation_0-logloss:0.667069\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.671441\n[7]\tvalidation_0-error:0.18677\tvalidation_0-logloss:0.663582\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.668586\n[8]\tvalidation_0-error:0.180934\tvalidation_0-logloss:0.660353\tvalidation_1-error:0.23622\tvalidation_1-logloss:0.665983\n[9]\tvalidation_0-error:0.161479\tvalidation_0-logloss:0.656739\tvalidation_1-error:0.228346\tvalidation_1-logloss:0.662987\n[10]\tvalidation_0-error:0.167315\tvalidation_0-logloss:0.653582\tvalidation_1-error:0.228346\tvalidation_1-logloss:0.660091\n[259]\tvalidation_0-error:0.122568\tvalidation_0-logloss:0.34313\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.475866\n[260]\tvalidation_0-error:0.124514\tvalidation_0-logloss:0.34261\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.476068\n[261]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.342156\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476165\n[262]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.341714\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476143\n[263]\tvalidation_0-error:0.124514\tvalidation_0-logloss:0.341209\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476063\n[264]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.340779\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.47595\n[265]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.340297\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.475858\n[266]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.339908\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.476057\n[267]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.339312\tvalidation_1-error:0.220472\tvalidation_1-logloss:0.476228\n[268]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.338874\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476266\n[269]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.338543\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476202\n[270]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.33821\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.47607\n[271]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.337716\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.476229\n[272]\tvalidation_0-error:0.118677\tvalidation_0-logloss:0.337295\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.47612\n[273]\tvalidation_0-error:0.118677\tvalidation_0-logloss:0.336927\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.476152\n[274]\tvalidation_0-error:0.118677\tvalidation_0-logloss:0.33651\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.476127\n[275]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.336017\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476117\n[276]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.335497\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.476063\n[277]\tvalidation_0-error:0.116732\tvalidation_0-logloss:0.335159\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476113\n[278]\tvalidation_0-error:0.114786\tvalidation_0-logloss:0.334812\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476143\n[279]\tvalidation_0-error:0.114786\tvalidation_0-logloss:0.334481\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476163\n[280]\tvalidation_0-error:0.116732\tvalidation_0-logloss:0.333843\tvalidation_1-error:0.216535\tvalidation_1-logloss:0.476359\nStopping. Best iteration:\n[265]\tvalidation_0-error:0.120623\tvalidation_0-logloss:0.340297\tvalidation_1-error:0.212598\tvalidation_1-logloss:0.475858\n\nCPU times: user 690 ms, sys: 310 ms, total: 1 s\nWall time: 799 ms\n" }, { "code": null, "e": 5971, "s": 5713, "text": "Key parameters in XGBoost(the ones which would affect model quality greatly), assuming you already selected max_depth (more complex classification task, deeper the tree), subsample (equal to evaluation data percentage), objective (classification algorithm):" }, { "code": null, "e": 6031, "s": 5971, "text": "n_estimators — the number of runs XGBoost will try to learn" }, { "code": null, "e": 6062, "s": 6031, "text": "learning_rate — learning speed" }, { "code": null, "e": 6151, "s": 6062, "text": "early_stopping_rounds — overfitting prevention, stop early if no improvement in learning" }, { "code": null, "e": 6494, "s": 6151, "text": "When model.fit is executed with verbose=True, you will see each training run evaluation quality printed out. At the end of the log, you should see which iteration was selected as the best one. It might be the number of training rounds is not enough to detect the best iteration, then XGBoost will select the last iteration to build the model." }, { "code": null, "e": 6795, "s": 6494, "text": "With matpotlib library we can plot training results for each run (from XGBoost output). This helps to understand if iteration which was chosen to build the model was the best one possible. Here we are using sklearn library to evaluate model accuracy and then plotting training results with matpotlib:" }, { "code": null, "e": 6909, "s": 6795, "text": "# make predictions for test data\ny_pred = model.predict(test_X)\npredictions = [round(value) for value in y_pred]\n" }, { "code": null, "e": 7027, "s": 6909, "text": "# evaluate predictions\naccuracy = accuracy_score(test_Y, predictions)\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n" }, { "code": null, "e": 7045, "s": 7027, "text": "Accuracy: 78.74%\n" }, { "code": null, "e": 7737, "s": 7045, "text": "# retrieve performance metrics\nresults = model.evals_result()\nepochs = len(results['validation_0']['error'])\nx_axis = range(0, epochs)\n# plot log loss\nfig, ax = pyplot.subplots()\nax.plot(x_axis, results['validation_0']['logloss'], label='Train')\nax.plot(x_axis, results['validation_1']['logloss'], label='Test')\nax.legend()\npyplot.ylabel('Log Loss')\npyplot.title('XGBoost Log Loss')\npyplot.show()\n# plot classification error\nfig, ax = pyplot.subplots()\nax.plot(x_axis, results['validation_0']['error'], label='Train')\nax.plot(x_axis, results['validation_1']['error'], label='Test')\nax.legend()\npyplot.ylabel('Classification Error')\npyplot.title('XGBoost Classification Error')\npyplot.show()\n" }, { "code": null, "e": 7863, "s": 7740, "text": "Let’s describe my approach to select parameters (n_estimators, learning_rate, early_stopping_rounds) for XGBoost training." }, { "code": null, "e": 7952, "s": 7863, "text": "Step 1. Start with what you feel works best based on your experience or what makes sense" }, { "code": null, "e": 7971, "s": 7952, "text": "n_estimators = 300" }, { "code": null, "e": 7992, "s": 7971, "text": "learning_rate = 0.01" }, { "code": null, "e": 8019, "s": 7992, "text": "early_stopping_rounds = 10" }, { "code": null, "e": 8028, "s": 8019, "text": "Results:" }, { "code": null, "e": 8049, "s": 8028, "text": "Stop iteration = 237" }, { "code": null, "e": 8067, "s": 8049, "text": "Accuracy = 78.35%" }, { "code": null, "e": 8081, "s": 8067, "text": "Results plot:" }, { "code": null, "e": 8440, "s": 8081, "text": "With the first attempt, we already get good results for Pima Indians Diabetes dataset. Training was stopped at iteration 237. Classification error plot shows a lower error rate around iteration 237. This means learning rate 0.01 is suitable for this dataset and early stopping of 10 iterations (if the result doesn’t improve in the next 10 iterations) works." }, { "code": null, "e": 8567, "s": 8440, "text": "Step 2. Experiment with learning rate, try to set a smaller learning rate parameter and increase number of learning iterations" }, { "code": null, "e": 8586, "s": 8567, "text": "n_estimators = 500" }, { "code": null, "e": 8608, "s": 8586, "text": "learning_rate = 0.001" }, { "code": null, "e": 8635, "s": 8608, "text": "early_stopping_rounds = 10" }, { "code": null, "e": 8644, "s": 8635, "text": "Results:" }, { "code": null, "e": 8699, "s": 8644, "text": "Stop iteration = didn’t stop, spent all 500 iterations" }, { "code": null, "e": 8717, "s": 8699, "text": "Accuracy = 77.56%" }, { "code": null, "e": 8731, "s": 8717, "text": "Results plot:" }, { "code": null, "e": 8894, "s": 8731, "text": "Smaller learning rate wasn’t working for this dataset. Classification error almost doesn’t change and XGBoost log loss doesn’t stabilize even with 500 iterations." }, { "code": null, "e": 8937, "s": 8894, "text": "Step 3. Try to increase the learning rate." }, { "code": null, "e": 8956, "s": 8937, "text": "n_estimators = 300" }, { "code": null, "e": 8976, "s": 8956, "text": "learning_rate = 0.1" }, { "code": null, "e": 9003, "s": 8976, "text": "early_stopping_rounds = 10" }, { "code": null, "e": 9012, "s": 9003, "text": "Results:" }, { "code": null, "e": 9032, "s": 9012, "text": "Stop iteration = 27" }, { "code": null, "e": 9050, "s": 9032, "text": "Accuracy = 76.77%" }, { "code": null, "e": 9064, "s": 9050, "text": "Results plot:" }, { "code": null, "e": 9255, "s": 9064, "text": "With increased learning rate, the algorithm learns quicker, it stops already at iteration Nr. 27. XGBoost log loss error is stabilizing, but the overall classification accuracy is not ideal." }, { "code": null, "e": 9402, "s": 9255, "text": "Step 4. Select optimal learning rate from the first step and increase early stopping (to give the algorithm more chances to find a better result)." }, { "code": null, "e": 9421, "s": 9402, "text": "n_estimators = 300" }, { "code": null, "e": 9442, "s": 9421, "text": "learning_rate = 0.01" }, { "code": null, "e": 9469, "s": 9442, "text": "early_stopping_rounds = 15" }, { "code": null, "e": 9478, "s": 9469, "text": "Results:" }, { "code": null, "e": 9499, "s": 9478, "text": "Stop iteration = 265" }, { "code": null, "e": 9517, "s": 9499, "text": "Accuracy = 78.74%" }, { "code": null, "e": 9531, "s": 9517, "text": "Results plot:" }, { "code": null, "e": 9641, "s": 9531, "text": "A slightly better result is produced with 78.74% accuracy — this is visible in the classification error plot." }, { "code": null, "e": 9652, "s": 9641, "text": "Resources:" }, { "code": null, "e": 9679, "s": 9652, "text": "Jupyter notebook on GitHub" }, { "code": null, "e": 9753, "s": 9679, "text": "Blog post — Jupyter Notebook — Forget CSV, fetch data from DB with Python" } ]
D3.js count() method - GeeksforGeeks
14 Sep, 2020 With the help of d3.count() method, we can get the count of valid values in the specified iterable data structure. Syntax: d3.count(iterable[, accessor]) Return value: It returns the count of valid values. Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command. npm install d3 Example 1: In this example we can see that by using d3.count() method, we are able to get the count of valid values in the specified iterables. Javascript // Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", date: "11/12/2015"}, {name: "DEF", amount: "120.11", date: "11/12/2015"}, {name: "MNO", amount: "12.01", date: "01/04/2016"}, {name: "ABC", amount: "34.05", date: "01/04/2016"}] var gfg = d3.count(data, d => d.amount);console.log(gfg); Output: 4 Example 2: Javascript // Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", age: 20}, {name: "DEF", amount: "120.11", age: NaN}, {name: "MNO", amount: "12.01", age: 23}, {name: "DEF", amount: "34.05", age: 24}] var gfg = d3.count(data, d => d.age);console.log(gfg); Output : 3 D3.js JavaScript Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method How to update NPM ?
[ { "code": null, "e": 25169, "s": 25141, "text": "\n14 Sep, 2020" }, { "code": null, "e": 25284, "s": 25169, "text": "With the help of d3.count() method, we can get the count of valid values in the specified iterable data structure." }, { "code": null, "e": 25292, "s": 25284, "text": "Syntax:" }, { "code": null, "e": 25324, "s": 25292, "text": "d3.count(iterable[, accessor])\n" }, { "code": null, "e": 25376, "s": 25324, "text": "Return value: It returns the count of valid values." }, { "code": null, "e": 25502, "s": 25376, "text": "Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command." }, { "code": null, "e": 25518, "s": 25502, "text": "npm install d3\n" }, { "code": null, "e": 25662, "s": 25518, "text": "Example 1: In this example we can see that by using d3.count() method, we are able to get the count of valid values in the specified iterables." }, { "code": null, "e": 25673, "s": 25662, "text": "Javascript" }, { "code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", date: \"11/12/2015\"}, {name: \"DEF\", amount: \"120.11\", date: \"11/12/2015\"}, {name: \"MNO\", amount: \"12.01\", date: \"01/04/2016\"}, {name: \"ABC\", amount: \"34.05\", date: \"01/04/2016\"}] var gfg = d3.count(data, d => d.amount);console.log(gfg);", "e": 26018, "s": 25673, "text": null }, { "code": null, "e": 26026, "s": 26018, "text": "Output:" }, { "code": null, "e": 26029, "s": 26026, "text": "4\n" }, { "code": null, "e": 26040, "s": 26029, "text": "Example 2:" }, { "code": null, "e": 26051, "s": 26040, "text": "Javascript" }, { "code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", age: 20}, {name: \"DEF\", amount: \"120.11\", age: NaN}, {name: \"MNO\", amount: \"12.01\", age: 23}, {name: \"DEF\", amount: \"34.05\", age: 24}] var gfg = d3.count(data, d => d.age);console.log(gfg);", "e": 26350, "s": 26051, "text": null }, { "code": null, "e": 26359, "s": 26350, "text": "Output :" }, { "code": null, "e": 26362, "s": 26359, "text": "3\n" }, { "code": null, "e": 26368, "s": 26362, "text": "D3.js" }, { "code": null, "e": 26379, "s": 26368, "text": "JavaScript" }, { "code": null, "e": 26387, "s": 26379, "text": "Node.js" }, { "code": null, "e": 26485, "s": 26387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26494, "s": 26485, "text": "Comments" }, { "code": null, "e": 26507, "s": 26494, "text": "Old Comments" }, { "code": null, "e": 26568, "s": 26507, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26609, "s": 26568, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26663, "s": 26609, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26703, "s": 26663, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26765, "s": 26703, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 26798, "s": 26765, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26846, "s": 26798, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26879, "s": 26846, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 26908, "s": 26879, "text": "Node.js fs.readFile() Method" } ]
Enumeration of Binary Trees
26 Oct, 2021 A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binary Trees can be there with n nodes? For n = 1, there is only one tree o For n = 2, there are two trees o o / \ o o For n = 3, there are five trees o o o o o / \ / \ / \ o o o o o o / \ \ / o o o o The idea is to consider all possible pairs of counts for nodes in left and right subtrees and multiply the counts for a particular pair. Finally, add the results of all pairs. For example, let T(n) be count for n nodes. T(0) = 1 [There is only 1 empty tree] T(1) = 1 T(2) = 2 T(3) = T(0)*T(2) + T(1)*T(1) + T(2)*T(0) = 1*2 + 1*1 + 2*1 = 5 T(4) = T(0)*T(3) + T(1)*T(2) + T(2)*T(1) + T(3)*T(0) = 1*5 + 1*2 + 2*1 + 5*1 = 14 The above pattern basically represents n’th Catalan Numbers. First few Catalan numbers are 1 1 2 5 14 42 132 429 1430 4862,... Here, T(i-1) represents the number of nodes on the left-sub-tree T(n−i-1) represents the number of nodes on the right-sub-tree n’th Catalan Number can also be evaluated using the direct formula. T(n) = (2n)! / (n+1)!n! The number of Binary Search Trees (BST) with n nodes is also the same as the number of unlabelled trees. The reason for this is simple, in BST also we can make any key a root, If the root is i’th key in sorted order, then i-1 keys can go on one side, and (n-i) keys can go on another side. How many labeled Binary Trees can be there with n nodes? To count labeled trees, we can use the above count for unlabelled trees. The idea is simple, every unlabelled tree with n nodes can create n! different labeled trees by assigning different permutations of labels to all nodes. Therefore, Number of Labelled Trees = (Number of unlabelled trees) * n! = [(2n)! / (n+1)!n!] × n! For example for n = 3, there are 5 * 3! = 5*6 = 30 different labelled trees Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above satyajitmahunta98 anikaseth98 reenadevi98412200 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2021" }, { "code": null, "e": 183, "s": 54, "text": "A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. " }, { "code": null, "e": 438, "s": 185, "text": "Below two are considered same unlabelled trees\n o o\n / \\ / \\ \n o o o o \n\nBelow two are considered different labelled trees\n A C\n / \\ / \\ \n B C A B " }, { "code": null, "e": 510, "s": 438, "text": "How many different Unlabelled Binary Trees can be there with n nodes? " }, { "code": null, "e": 876, "s": 510, "text": "For n = 1, there is only one tree\n o\n\nFor n = 2, there are two trees\n o o\n / \\ \n o o\n\nFor n = 3, there are five trees\n o o o o o\n / \\ / \\ / \\\n o o o o o o\n / \\ \\ /\no o o o" }, { "code": null, "e": 1053, "s": 876, "text": "The idea is to consider all possible pairs of counts for nodes in left and right subtrees and multiply the counts for a particular pair. Finally, add the results of all pairs. " }, { "code": null, "e": 1319, "s": 1055, "text": "For example, let T(n) be count for n nodes.\nT(0) = 1 [There is only 1 empty tree]\nT(1) = 1\nT(2) = 2\n\nT(3) = T(0)*T(2) + T(1)*T(1) + T(2)*T(0) = 1*2 + 1*1 + 2*1 = 5\n\nT(4) = T(0)*T(3) + T(1)*T(2) + T(2)*T(1) + T(3)*T(0)\n = 1*5 + 1*2 + 2*1 + 5*1 \n = 14 " }, { "code": null, "e": 1574, "s": 1319, "text": "The above pattern basically represents n’th Catalan Numbers. First few Catalan numbers are 1 1 2 5 14 42 132 429 1430 4862,... Here, T(i-1) represents the number of nodes on the left-sub-tree T(n−i-1) represents the number of nodes on the right-sub-tree " }, { "code": null, "e": 1643, "s": 1574, "text": "n’th Catalan Number can also be evaluated using the direct formula. " }, { "code": null, "e": 1670, "s": 1643, "text": " T(n) = (2n)! / (n+1)!n!" }, { "code": null, "e": 1961, "s": 1670, "text": "The number of Binary Search Trees (BST) with n nodes is also the same as the number of unlabelled trees. The reason for this is simple, in BST also we can make any key a root, If the root is i’th key in sorted order, then i-1 keys can go on one side, and (n-i) keys can go on another side. " }, { "code": null, "e": 2245, "s": 1961, "text": "How many labeled Binary Trees can be there with n nodes? To count labeled trees, we can use the above count for unlabelled trees. The idea is simple, every unlabelled tree with n nodes can create n! different labeled trees by assigning different permutations of labels to all nodes. " }, { "code": null, "e": 2257, "s": 2245, "text": "Therefore, " }, { "code": null, "e": 2368, "s": 2257, "text": "Number of Labelled Trees = (Number of unlabelled trees) * n!\n = [(2n)! / (n+1)!n!] × n!" }, { "code": null, "e": 2445, "s": 2368, "text": "For example for n = 3, there are 5 * 3! = 5*6 = 30 different labelled trees " }, { "code": null, "e": 2570, "s": 2445, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 2588, "s": 2570, "text": "satyajitmahunta98" }, { "code": null, "e": 2600, "s": 2588, "text": "anikaseth98" }, { "code": null, "e": 2618, "s": 2600, "text": "reenadevi98412200" }, { "code": null, "e": 2623, "s": 2618, "text": "Tree" }, { "code": null, "e": 2628, "s": 2623, "text": "Tree" } ]
JavaScript Program to print Fibonacci Series
09 Jul, 2022 Suppose in a Class, the Teacher asked students of roll number 1 to write 0 and roll number 2 to write 1 on the blackboard and asked for the rest of the students, to write the summation of your previous two students’. The series written on the board will look like 0,1,1,2,3,5,8,.......... The teacher then told the students, this series is known as the Fibonacci series. It can be represented by the below equation Fn = Fn-1 + Fn-2 Where F0=1 and F1=1. The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1 Examples: Input : 5 Output : 8 Input :8 Output :34 As the first Fibonacci number is 0 and the second is 1. Also, we know that the nth Fibonacci number is the summation of n-1 and n-2 term.So, to get the nth Fibonacci term we can followfib(1)=0fib(2)=1fib(3)=fib(2)+fib(1)fib(4)=fib(3)+fib(2)....fib(n)=fib(n-1)+fib(n-2) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Example: By using for loop javascript <script type = "text/javascript">function fibonacci(num){ var num1=0; var num2=1; var sum; var i=0; for (i = 0; i < num; i++) { sum=num1+num2; num1=num2; num2=sum; } return num2;} document.write("Fibonacci(5): "+fibonacci(5)+"<br>");document.write("Fibonacci(8): "+fibonacci(8)+"<br>");</script> Output: Fibonacci(5): 3 Fibonacci(8): 13 Example: By using while loop javascript <script type = "text/javascript">function fibonacci(num) { if(num==1) return 0; if(num==2) return 1; var num1=0; var num2=1; var sum; var i=2; while (i<num) { sum=num1+num2; num1=num2; num2=sum; i+=1; } return num2; } document.write("Fibonacci(5): "+fibonacci(5)+"<br>");document.write("Fibonacci(8): "+fibonacci(8)+"<br>");</script> Output: Fibonacci(5): 3 Fibonacci(8): 13 By using recursion: As we know that the nth Fibonacci number is the summation of n-1 and n-2 term and the n-1 term is the summation of n-2 and n-3 term.So, to get the nth Fibonacci term we can followfib(n)=fib(n-1)+fib(n-2)fib(n)=fib(n-2)+fib(n-3)+fib(n-3)+fib(n-4)....fib(n)=fib(1)+fib(0)+fib(1)+fib(0)+fib(1)+fib(0)....fib(1)+fib(0) [terms containing sum of fib(1) and fib(0)fib(1)=0fib(2)=1 Example: javascript <script type = "text/javascript">function fibonacci(num) { if(num==1) return 0; if (num == 2) return 1; return fibonacci(num - 1) + fibonacci(num - 2); }document.write("Fibonacci(5): "+fibonacci(5)+"<br>");document.write("Fibonacci(8): "+fibonacci(8)+"<br>");</script> Output: Fibonacci(5): 3 Fibonacci(8): 13 JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2022" }, { "code": null, "e": 317, "s": 28, "text": "Suppose in a Class, the Teacher asked students of roll number 1 to write 0 and roll number 2 to write 1 on the blackboard and asked for the rest of the students, to write the summation of your previous two students’. The series written on the board will look like 0,1,1,2,3,5,8,.........." }, { "code": null, "e": 443, "s": 317, "text": "The teacher then told the students, this series is known as the Fibonacci series. It can be represented by the below equation" }, { "code": null, "e": 461, "s": 443, "text": " Fn = Fn-1 + Fn-2" }, { "code": null, "e": 706, "s": 461, "text": "Where F0=1 and F1=1. The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation" }, { "code": null, "e": 758, "s": 706, "text": "Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1" }, { "code": null, "e": 769, "s": 758, "text": "Examples: " }, { "code": null, "e": 813, "s": 769, "text": "Input : 5 \nOutput : 8\n\nInput :8\nOutput :34\n" }, { "code": null, "e": 1082, "s": 813, "text": "As the first Fibonacci number is 0 and the second is 1. Also, we know that the nth Fibonacci number is the summation of n-1 and n-2 term.So, to get the nth Fibonacci term we can followfib(1)=0fib(2)=1fib(3)=fib(2)+fib(1)fib(4)=fib(3)+fib(2)....fib(n)=fib(n-1)+fib(n-2)" }, { "code": null, "e": 1091, "s": 1082, "text": "Chapters" }, { "code": null, "e": 1118, "s": 1091, "text": "descriptions off, selected" }, { "code": null, "e": 1168, "s": 1118, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1191, "s": 1168, "text": "captions off, selected" }, { "code": null, "e": 1199, "s": 1191, "text": "English" }, { "code": null, "e": 1223, "s": 1199, "text": "This is a modal window." }, { "code": null, "e": 1292, "s": 1223, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1314, "s": 1292, "text": "End of dialog window." }, { "code": null, "e": 1341, "s": 1314, "text": "Example: By using for loop" }, { "code": null, "e": 1352, "s": 1341, "text": "javascript" }, { "code": "<script type = \"text/javascript\">function fibonacci(num){ var num1=0; var num2=1; var sum; var i=0; for (i = 0; i < num; i++) { sum=num1+num2; num1=num2; num2=sum; } return num2;} document.write(\"Fibonacci(5): \"+fibonacci(5)+\"<br>\");document.write(\"Fibonacci(8): \"+fibonacci(8)+\"<br>\");</script>", "e": 1695, "s": 1352, "text": null }, { "code": null, "e": 1703, "s": 1695, "text": "Output:" }, { "code": null, "e": 1736, "s": 1703, "text": "Fibonacci(5): 3\nFibonacci(8): 13" }, { "code": null, "e": 1766, "s": 1736, "text": "Example: By using while loop " }, { "code": null, "e": 1777, "s": 1766, "text": "javascript" }, { "code": "<script type = \"text/javascript\">function fibonacci(num) { if(num==1) return 0; if(num==2) return 1; var num1=0; var num2=1; var sum; var i=2; while (i<num) { sum=num1+num2; num1=num2; num2=sum; i+=1; } return num2; } document.write(\"Fibonacci(5): \"+fibonacci(5)+\"<br>\");document.write(\"Fibonacci(8): \"+fibonacci(8)+\"<br>\");</script>", "e": 2256, "s": 1777, "text": null }, { "code": null, "e": 2264, "s": 2256, "text": "Output:" }, { "code": null, "e": 2297, "s": 2264, "text": "Fibonacci(5): 3\nFibonacci(8): 13" }, { "code": null, "e": 2691, "s": 2297, "text": "By using recursion: As we know that the nth Fibonacci number is the summation of n-1 and n-2 term and the n-1 term is the summation of n-2 and n-3 term.So, to get the nth Fibonacci term we can followfib(n)=fib(n-1)+fib(n-2)fib(n)=fib(n-2)+fib(n-3)+fib(n-3)+fib(n-4)....fib(n)=fib(1)+fib(0)+fib(1)+fib(0)+fib(1)+fib(0)....fib(1)+fib(0) [terms containing sum of fib(1) and fib(0)fib(1)=0fib(2)=1" }, { "code": null, "e": 2700, "s": 2691, "text": "Example:" }, { "code": null, "e": 2711, "s": 2700, "text": "javascript" }, { "code": "<script type = \"text/javascript\">function fibonacci(num) { if(num==1) return 0; if (num == 2) return 1; return fibonacci(num - 1) + fibonacci(num - 2); }document.write(\"Fibonacci(5): \"+fibonacci(5)+\"<br>\");document.write(\"Fibonacci(8): \"+fibonacci(8)+\"<br>\");</script>", "e": 3032, "s": 2711, "text": null }, { "code": null, "e": 3040, "s": 3032, "text": "Output:" }, { "code": null, "e": 3073, "s": 3040, "text": "Fibonacci(5): 3\nFibonacci(8): 13" }, { "code": null, "e": 3089, "s": 3073, "text": "JavaScript-Misc" }, { "code": null, "e": 3100, "s": 3089, "text": "JavaScript" }, { "code": null, "e": 3117, "s": 3100, "text": "Web Technologies" } ]
Triplet Sum in Array | Practice | GeeksforGeeks
Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X. Example 1: Input: n = 6, X = 13 arr[] = [1 4 45 6 10 8] Output: 1 Explanation: The triplet {1, 4, 8} in the array sums up to 13. Example 2: Input: n = 5, X = 10 arr[] = [1 2 4 3 6] Output: 1 Explanation: The triplet {1, 3, 6} in the array sums up to 10. Your Task: You don't need to read input or print anything. Your task is to complete the function find3Numbers() which takes the array arr[], the size of the array (n) and the sum (X) as inputs and returns True if there exists a triplet in the array arr[] which sums up to X and False otherwise. Expected Time Complexity: O(n2) Expected Auxiliary Space: O(1) Constraints: 1 ≤ n ≤ 103 1 ≤ A[i] ≤ 105 0 sy9924554 days ago //Sort the array Arrays.sort(arr); for(int i = 0;i <= n-3; i++){ int target = x - arr[i]; int j = i + 1; int k = n -1; while(j < k){ int sum = arr[j] + arr[k]; if(target == sum) return true; else if(target > sum) j++; else k--; } } return false; } 0 janvijindal055 days ago sort(A,A+n); for(int i=0;i<n;i++){ int y=X-A[i]; int low=i+1; int high=n-1; while(low<high){ if(A[low]+A[high]==y){ return 1; } else if(A[low]+A[high]>y){ high--; } else if(A[low]+A[high]<y){ low++; } } } return 0; } 0 mayurxxivk5 days ago CorrectAnswer. 🍁 Total Time Taken:0.2/1.2 Do not use extra space just sort it first and apply two pointer /three pointer approach public static boolean find3Numbers(int arr[], int n, int k) { Arrays.sort(arr); int cv = 0; // current value while(cv < n-2) { int l = cv+1 ; int h = n-1; while(l<h) { if(arr[l] + arr[h] + arr[cv] == k) return true; if(arr[l] + arr[h] + arr[cv] > k) h--; if(arr[l] + arr[h] + arr[cv] < k) l++; } cv++; } return false; } 0 pratiksehjpal20006 days ago class Solution { //Function to find if there exists a triplet in the //array A[] which sums up to X. public static boolean find3Numbers(int A[], int n, int X) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { map.put(A[i],1); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { int sum = A[i]+A[j]; if(map.containsKey(X-sum)&&X-sum!=A[i]&&X-sum!=A[j]) { return true; } } } return false; } } 0 sowmyadevineni6001 week ago input: 8 45 6 10 1 4 output : 1 expected output : 0 why?? i did'nt get why i am getting wrong output even after solving it correctly int sum; set<int> mp; for(int i=0;i<n;i++) { mp.insert(A[i]); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n-1;j++) { sum=A[i]+A[j]; if(sum<X) { if(mp.find(X-sum)!=mp.end()) { return true; } } else continue; } } return false; } +1 spideyy1 week ago bool find3Numbers(int A[], int n, int X) { unordered_set<int>s; for(int i=0;i<n;i++) s.insert(A[i]); for(int i=0;i<n;i++){ for(int j=i+1;j<n-1;j++){ int ans = A[i]+A[j]; if(s.find(X-ans)!=s.end()){ return 1; } } } return 0; } 0 ajay7yadav951 week ago // Hello JavaScript lovers -------------------→ A7 for(let i=0; i<arr.length; i++){ let k = i; let l = i+1; let r = arr.length-1; while(l<r){ if(arr[k]+arr[l]+arr[r]==key){ return key; } if(arr[k]+arr[l]+arr[r]<key){ l++; }else{ r--; } } } +2 hharshit81181 week ago bool find3Numbers(int arr[], int n, int X) { sort(arr, arr+n); for(int i=0; i< n; i++){ int low=i+1, high=n-1; while(low<high){ int sum = arr[low]+arr[high]+arr[i]; if(sum == X){ return true; } if(sum < X){ low++; } else{ high--; } } } 0 ashutos17sharma89891 week ago JAVA SOLUTION class Solution { //Function to find if there exists a triplet in the //array A[] which sums up to X. public static boolean find3Numbers(int A[], int n, int X) { // Your code Here Arrays.sort(A); for(int i =0;i<n-2;i++){ int a= A[i]; int newX=X-a; int l=i+1; int h=n-1; while(l<h){ if(A[l]+A[h]==newX){ return true; }else if(A[l]+A[h]>newX){ h--; }else{ l++; } } } return false; } } +1 2019sushilkumarkori1 week ago bool find3Numbers(int A[], int n, int X) { //Your Code Here sort(A,A+n); for(int i=0;i<n-1;i++){ int j=i+1,k=n-1; while(k>j){ int sum=A[i]+A[j]+A[k]; if(sum == X){ return true; } else if(sum>X){ k--; } else{ j++; } } } return false; } }; 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": 363, "s": 238, "text": "Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X. " }, { "code": null, "e": 375, "s": 363, "text": "\nExample 1:" }, { "code": null, "e": 494, "s": 375, "text": "Input:\nn = 6, X = 13\narr[] = [1 4 45 6 10 8]\nOutput:\n1\nExplanation:\nThe triplet {1, 4, 8} in \nthe array sums up to 13." }, { "code": null, "e": 505, "s": 494, "text": "Example 2:" }, { "code": null, "e": 621, "s": 505, "text": "Input:\nn = 5, X = 10\narr[] = [1 2 4 3 6]\nOutput:\n1\nExplanation:\nThe triplet {1, 3, 6} in \nthe array sums up to 10.\n" }, { "code": null, "e": 917, "s": 621, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function find3Numbers() which takes the array arr[], the size of the array (n) and the sum (X) as inputs and returns True if there exists a triplet in the array arr[] which sums up to X and False otherwise." }, { "code": null, "e": 981, "s": 917, "text": "\nExpected Time Complexity: O(n2)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1022, "s": 981, "text": "\nConstraints:\n1 ≤ n ≤ 103\n1 ≤ A[i] ≤ 105" }, { "code": null, "e": 1024, "s": 1022, "text": "0" }, { "code": null, "e": 1043, "s": 1024, "text": "sy9924554 days ago" }, { "code": null, "e": 1471, "s": 1043, "text": " //Sort the array\n Arrays.sort(arr);\n for(int i = 0;i <= n-3; i++){\n int target = x - arr[i];\n int j = i + 1;\n int k = n -1;\n \n while(j < k){\n int sum = arr[j] + arr[k];\n if(target == sum) return true;\n else if(target > sum) j++;\n else k--;\n }\n }\n return false;\n }" }, { "code": null, "e": 1473, "s": 1471, "text": "0" }, { "code": null, "e": 1497, "s": 1473, "text": "janvijindal055 days ago" }, { "code": null, "e": 1851, "s": 1497, "text": " sort(A,A+n); for(int i=0;i<n;i++){ int y=X-A[i]; int low=i+1; int high=n-1; while(low<high){ if(A[low]+A[high]==y){ return 1; } else if(A[low]+A[high]>y){ high--; } else if(A[low]+A[high]<y){ low++; } } } return 0; } " }, { "code": null, "e": 1853, "s": 1851, "text": "0" }, { "code": null, "e": 1874, "s": 1853, "text": "mayurxxivk5 days ago" }, { "code": null, "e": 1891, "s": 1874, "text": "CorrectAnswer. 🍁" }, { "code": null, "e": 1916, "s": 1891, "text": "Total Time Taken:0.2/1.2" }, { "code": null, "e": 2006, "s": 1918, "text": "Do not use extra space just sort it first and apply two pointer /three pointer approach" }, { "code": null, "e": 2605, "s": 2006, "text": " public static boolean find3Numbers(int arr[], int n, int k) { \n \n Arrays.sort(arr);\n int cv = 0; // current value\n while(cv < n-2)\n {\n int l = cv+1 ;\n int h = n-1;\n \n while(l<h)\n {\n \n if(arr[l] + arr[h] + arr[cv] == k)\n return true;\n \n if(arr[l] + arr[h] + arr[cv] > k)\n h--;\n \n if(arr[l] + arr[h] + arr[cv] < k)\n l++;\n \n }\n cv++;\n } \n return false;\n \n }\n " }, { "code": null, "e": 2607, "s": 2605, "text": "0" }, { "code": null, "e": 2635, "s": 2607, "text": "pratiksehjpal20006 days ago" }, { "code": null, "e": 3242, "s": 2635, "text": "class Solution\n{\n //Function to find if there exists a triplet in the \n //array A[] which sums up to X.\n public static boolean find3Numbers(int A[], int n, int X) { \n HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();\n for(int i=0;i<n;i++)\n {\n map.put(A[i],1);\n }\n for(int i=0;i<n-1;i++)\n {\n for(int j=i+1;j<n;j++)\n {\n int sum = A[i]+A[j];\n if(map.containsKey(X-sum)&&X-sum!=A[i]&&X-sum!=A[j])\n {\n return true;\n }\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 3244, "s": 3242, "text": "0" }, { "code": null, "e": 3272, "s": 3244, "text": "sowmyadevineni6001 week ago" }, { "code": null, "e": 3293, "s": 3272, "text": "input: 8 45 6 10 1 4" }, { "code": null, "e": 3304, "s": 3293, "text": "output : 1" }, { "code": null, "e": 3324, "s": 3304, "text": "expected output : 0" }, { "code": null, "e": 3330, "s": 3324, "text": "why??" }, { "code": null, "e": 3405, "s": 3330, "text": "i did'nt get why i am getting wrong output even after solving it correctly" }, { "code": null, "e": 3884, "s": 3405, "text": "int sum; set<int> mp; for(int i=0;i<n;i++) { mp.insert(A[i]); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n-1;j++) { sum=A[i]+A[j]; if(sum<X) { if(mp.find(X-sum)!=mp.end()) { return true; } } else continue; } } return false; }" }, { "code": null, "e": 3887, "s": 3884, "text": "+1" }, { "code": null, "e": 3905, "s": 3887, "text": "spideyy1 week ago" }, { "code": null, "e": 4245, "s": 3905, "text": "bool find3Numbers(int A[], int n, int X) { unordered_set<int>s; for(int i=0;i<n;i++) s.insert(A[i]); for(int i=0;i<n;i++){ for(int j=i+1;j<n-1;j++){ int ans = A[i]+A[j]; if(s.find(X-ans)!=s.end()){ return 1; } } } return 0; }" }, { "code": null, "e": 4247, "s": 4245, "text": "0" }, { "code": null, "e": 4270, "s": 4247, "text": "ajay7yadav951 week ago" }, { "code": null, "e": 4321, "s": 4270, "text": "// Hello JavaScript lovers -------------------→ A7" }, { "code": null, "e": 4354, "s": 4321, "text": "for(let i=0; i<arr.length; i++){" }, { "code": null, "e": 4369, "s": 4354, "text": " let k = i;" }, { "code": null, "e": 4386, "s": 4369, "text": " let l = i+1;" }, { "code": null, "e": 4412, "s": 4386, "text": " let r = arr.length-1;" }, { "code": null, "e": 4432, "s": 4416, "text": " while(l<r){" }, { "code": null, "e": 4471, "s": 4432, "text": " if(arr[k]+arr[l]+arr[r]==key){" }, { "code": null, "e": 4500, "s": 4471, "text": " return key;" }, { "code": null, "e": 4510, "s": 4500, "text": " }" }, { "code": null, "e": 4548, "s": 4510, "text": " if(arr[k]+arr[l]+arr[r]<key){" }, { "code": null, "e": 4565, "s": 4548, "text": " l++;" }, { "code": null, "e": 4580, "s": 4565, "text": " }else{" }, { "code": null, "e": 4597, "s": 4580, "text": " r--;" }, { "code": null, "e": 4607, "s": 4597, "text": " }" }, { "code": null, "e": 4613, "s": 4607, "text": " }" }, { "code": null, "e": 4615, "s": 4613, "text": "}" }, { "code": null, "e": 4620, "s": 4617, "text": "+2" }, { "code": null, "e": 4643, "s": 4620, "text": "hharshit81181 week ago" }, { "code": null, "e": 5031, "s": 4643, "text": " bool find3Numbers(int arr[], int n, int X) { sort(arr, arr+n); for(int i=0; i< n; i++){ int low=i+1, high=n-1; while(low<high){ int sum = arr[low]+arr[high]+arr[i]; if(sum == X){ return true; } if(sum < X){ low++; } else{ high--; } } }" }, { "code": null, "e": 5033, "s": 5031, "text": "0" }, { "code": null, "e": 5063, "s": 5033, "text": "ashutos17sharma89891 week ago" }, { "code": null, "e": 5077, "s": 5063, "text": "JAVA SOLUTION" }, { "code": null, "e": 5705, "s": 5077, "text": "class Solution\n{\n //Function to find if there exists a triplet in the \n //array A[] which sums up to X.\n public static boolean find3Numbers(int A[], int n, int X) { \n \n // Your code Here\n Arrays.sort(A);\n for(int i =0;i<n-2;i++){\n int a= A[i];\n int newX=X-a;\n int l=i+1;\n int h=n-1;\n while(l<h){\n if(A[l]+A[h]==newX){\n return true;\n }else if(A[l]+A[h]>newX){\n h--;\n }else{\n l++;\n }\n }\n }\n return false;\n \n }\n}" }, { "code": null, "e": 5710, "s": 5707, "text": "+1" }, { "code": null, "e": 5740, "s": 5710, "text": "2019sushilkumarkori1 week ago" }, { "code": null, "e": 6235, "s": 5740, "text": "bool find3Numbers(int A[], int n, int X)\n {\n //Your Code Here\n sort(A,A+n);\n for(int i=0;i<n-1;i++){\n int j=i+1,k=n-1;\n while(k>j){\n int sum=A[i]+A[j]+A[k];\n if(sum == X){\n return true;\n }\n else if(sum>X){\n k--;\n }\n else{\n j++;\n }\n }\n }\n return false;\n }\n\n};" }, { "code": null, "e": 6381, "s": 6235, "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": 6417, "s": 6381, "text": " Login to access your submissions. " }, { "code": null, "e": 6427, "s": 6417, "text": "\nProblem\n" }, { "code": null, "e": 6437, "s": 6427, "text": "\nContest\n" }, { "code": null, "e": 6500, "s": 6437, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6648, "s": 6500, "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": 6856, "s": 6648, "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": 6962, "s": 6856, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Program to implement Logic Gates - GeeksforGeeks
31 Oct, 2019 A Logic gate is an elementary building block of any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are implemented using diodes or transistors. It can also be constructed using vacuum tubes, electromagnetic elements like optics, molecule etc. In a computer, most of the electronic circuits are made up logic gates. Logic gates are used to create a circuit that performs calculations, data storage or shows off object-oriented programming especially the power of inheritance. There are seven basic logic gates defined, these are: AND gate,OR gate,NOT gate,NAND gate,NOR gate,XOR gate andXNOR gate. AND gate, OR gate, NOT gate, NAND gate, NOR gate, XOR gate and XNOR gate. Below are the brief details about them along with their implementation: AND GateThe AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using product method.Using if else condition.Using “and (&)” operator.Product Method& OperatorIf-ElseProduct Method// C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf("\n %d AND %d = %d", a[i], b[i], product); }}& Operator// C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf("\n %d AND %d = %d", a[i], b[i], and_ans); }}If-Else// C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf("\n %d AND %d = %d", a[i], b[i], ans); }}Output:1 AND 0 = 0 0 AND 1 = 0 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 0 OR GateThe OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using + operator.Using | operator.Using || operator.Using if else.+ Operator| Operator|| OperatorIf-Else+ Operator// C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}| Operator// C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}|| Operator// C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}If-Else// C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}Output:1 AND 0 = 1 0 AND 1 = 1 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 1 NAND GateThe NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.Below are the programs to implement NAND gate using various methods:Using if else.Using Complement of the product.If-ElseComplement of the productIf-Else// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf("\n %d NAND %d = %d", a[i], b[i], ans); }}Complement of the product// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf("\n %d NAND %d = %d", a[i], b[i], ans); }}Output:1 NAND 0 = 1 0 NAND 1 = 1 1 NAND 1 = 0 0 NAND 0 = 1 1 NAND 0 = 1 NOR GateThe NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 1 otherwise.Below are the programs to implement NOR gate using various methods:Using + Operator.Using if else.+ OperatorIf-Else+ Operator// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf("\n %d NOR %d = %d", a[i], b[i], ans); }}If-Else// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf("\n %d NOR %d = %d", a[i], b[i], ans); }}Output:1 NOR 0 = 0 0 NOR 1 = 0 1 NOR 1 = 0 0 NOR 0 = 1 1 NOR 0 = 0 NOT GateIt acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.Below are the programs to implement NOT gate using various methods:Using ! Operator.Using if else.If-Else! OperatorIf-Else// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf("\n NOT %d = %d", a[i], ans); }}! Operator// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf("\n NOT %d = %d", a[i], ans); }}Output:NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 AND GateThe AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using product method.Using if else condition.Using “and (&)” operator.Product Method& OperatorIf-ElseProduct Method// C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf("\n %d AND %d = %d", a[i], b[i], product); }}& Operator// C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf("\n %d AND %d = %d", a[i], b[i], and_ans); }}If-Else// C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf("\n %d AND %d = %d", a[i], b[i], ans); }}Output:1 AND 0 = 0 0 AND 1 = 0 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 0 Below are the programs to implement AND gate using various methods: Using product method.Using if else condition.Using “and (&)” operator. Using product method. Using if else condition. Using “and (&)” operator. Product Method & Operator If-Else // C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf("\n %d AND %d = %d", a[i], b[i], product); }} // C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf("\n %d AND %d = %d", a[i], b[i], and_ans); }} // C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf("\n %d AND %d = %d", a[i], b[i], ans); }} 1 AND 0 = 0 0 AND 1 = 0 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 0 OR GateThe OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using + operator.Using | operator.Using || operator.Using if else.+ Operator| Operator|| OperatorIf-Else+ Operator// C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}| Operator// C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}|| Operator// C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}If-Else// C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }}Output:1 AND 0 = 1 0 AND 1 = 1 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 1 Below are the programs to implement AND gate using various methods: Using + operator.Using | operator.Using || operator.Using if else. Using + operator. Using | operator. Using || operator. Using if else. + Operator | Operator || Operator If-Else // C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }} // C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }} // C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }} // C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf("\n %d AND %d = %d", a[i], b[i], or_ans); }} 1 AND 0 = 1 0 AND 1 = 1 1 AND 1 = 1 0 AND 0 = 0 1 AND 0 = 1 NAND GateThe NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.Below are the programs to implement NAND gate using various methods:Using if else.Using Complement of the product.If-ElseComplement of the productIf-Else// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf("\n %d NAND %d = %d", a[i], b[i], ans); }}Complement of the product// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf("\n %d NAND %d = %d", a[i], b[i], ans); }}Output:1 NAND 0 = 1 0 NAND 1 = 1 1 NAND 1 = 0 0 NAND 0 = 1 1 NAND 0 = 1 Below are the programs to implement NAND gate using various methods: Using if else.Using Complement of the product. Using if else. Using Complement of the product. If-Else Complement of the product // C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf("\n %d NAND %d = %d", a[i], b[i], ans); }} // C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf("\n %d NAND %d = %d", a[i], b[i], ans); }} 1 NAND 0 = 1 0 NAND 1 = 1 1 NAND 1 = 0 0 NAND 0 = 1 1 NAND 0 = 1 NOR GateThe NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 1 otherwise.Below are the programs to implement NOR gate using various methods:Using + Operator.Using if else.+ OperatorIf-Else+ Operator// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf("\n %d NOR %d = %d", a[i], b[i], ans); }}If-Else// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf("\n %d NOR %d = %d", a[i], b[i], ans); }}Output:1 NOR 0 = 0 0 NOR 1 = 0 1 NOR 1 = 0 0 NOR 0 = 1 1 NOR 0 = 0 Below are the programs to implement NOR gate using various methods: Using + Operator.Using if else. Using + Operator. Using if else. + Operator If-Else // C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf("\n %d NOR %d = %d", a[i], b[i], ans); }} // C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf("\n %d NOR %d = %d", a[i], b[i], ans); }} 1 NOR 0 = 0 0 NOR 1 = 0 1 NOR 1 = 0 0 NOR 0 = 1 1 NOR 0 = 0 NOT GateIt acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.Below are the programs to implement NOT gate using various methods:Using ! Operator.Using if else.If-Else! OperatorIf-Else// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf("\n NOT %d = %d", a[i], ans); }}! Operator// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf("\n NOT %d = %d", a[i], ans); }}Output:NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa. Below are the programs to implement NOT gate using various methods: Using ! Operator.Using if else. Using ! Operator. Using if else. If-Else ! Operator // C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf("\n NOT %d = %d", a[i], ans); }} // C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf("\n NOT %d = %d", a[i], ans); }} NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 NOT 0 = 1 NOT 1 = 0 Digital Electronics & Logic Design Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Shift Registers in Digital Logic IEEE Standard 754 Floating Point Numbers 4-bit binary Adder-Subtractor Multiplexers in Digital Logic Magnitude Comparator in Digital Logic Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Differences between Procedural and Object Oriented Programming Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 24423, "s": 24395, "text": "\n31 Oct, 2019" }, { "code": null, "e": 24987, "s": 24423, "text": "A Logic gate is an elementary building block of any digital circuits. It takes one or two inputs and produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are implemented using diodes or transistors. It can also be constructed using vacuum tubes, electromagnetic elements like optics, molecule etc. In a computer, most of the electronic circuits are made up logic gates. Logic gates are used to create a circuit that performs calculations, data storage or shows off object-oriented programming especially the power of inheritance." }, { "code": null, "e": 25041, "s": 24987, "text": "There are seven basic logic gates defined, these are:" }, { "code": null, "e": 25109, "s": 25041, "text": "AND gate,OR gate,NOT gate,NAND gate,NOR gate,XOR gate andXNOR gate." }, { "code": null, "e": 25119, "s": 25109, "text": "AND gate," }, { "code": null, "e": 25128, "s": 25119, "text": "OR gate," }, { "code": null, "e": 25138, "s": 25128, "text": "NOT gate," }, { "code": null, "e": 25149, "s": 25138, "text": "NAND gate," }, { "code": null, "e": 25159, "s": 25149, "text": "NOR gate," }, { "code": null, "e": 25172, "s": 25159, "text": "XOR gate and" }, { "code": null, "e": 25183, "s": 25172, "text": "XNOR gate." }, { "code": null, "e": 25255, "s": 25183, "text": "Below are the brief details about them along with their implementation:" }, { "code": null, "e": 31703, "s": 25255, "text": "AND GateThe AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using product method.Using if else condition.Using “and (&)” operator.Product Method& OperatorIf-ElseProduct Method// C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], product); }}& Operator// C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], and_ans); }}If-Else// C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], ans); }}Output:1 AND 0 = 0\n 0 AND 1 = 0\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 0\nOR GateThe OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using + operator.Using | operator.Using || operator.Using if else.+ Operator| Operator|| OperatorIf-Else+ Operator// C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}| Operator// C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}|| Operator// C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}If-Else// C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}Output:1 AND 0 = 1\n 0 AND 1 = 1\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 1\nNAND GateThe NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.Below are the programs to implement NAND gate using various methods:Using if else.Using Complement of the product.If-ElseComplement of the productIf-Else// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}Complement of the product// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}Output:1 NAND 0 = 1\n 0 NAND 1 = 1\n 1 NAND 1 = 0\n 0 NAND 0 = 1\n 1 NAND 0 = 1\nNOR GateThe NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 1 otherwise.Below are the programs to implement NOR gate using various methods:Using + Operator.Using if else.+ OperatorIf-Else+ Operator// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}If-Else// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}Output:1 NOR 0 = 0\n 0 NOR 1 = 0\n 1 NOR 1 = 0\n 0 NOR 0 = 1\n 1 NOR 0 = 0\nNOT GateIt acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.Below are the programs to implement NOT gate using various methods:Using ! Operator.Using if else.If-Else! OperatorIf-Else// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf(\"\\n NOT %d = %d\", a[i], ans); }}! Operator// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf(\"\\n NOT %d = %d\", a[i], ans); }}Output:NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n" }, { "code": null, "e": 33326, "s": 31703, "text": "AND GateThe AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using product method.Using if else condition.Using “and (&)” operator.Product Method& OperatorIf-ElseProduct Method// C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], product); }}& Operator// C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], and_ans); }}If-Else// C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], ans); }}Output:1 AND 0 = 0\n 0 AND 1 = 0\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 0\n" }, { "code": null, "e": 33394, "s": 33326, "text": "Below are the programs to implement AND gate using various methods:" }, { "code": null, "e": 33465, "s": 33394, "text": "Using product method.Using if else condition.Using “and (&)” operator." }, { "code": null, "e": 33487, "s": 33465, "text": "Using product method." }, { "code": null, "e": 33512, "s": 33487, "text": "Using if else condition." }, { "code": null, "e": 33538, "s": 33512, "text": "Using “and (&)” operator." }, { "code": null, "e": 33553, "s": 33538, "text": "Product Method" }, { "code": null, "e": 33564, "s": 33553, "text": "& Operator" }, { "code": null, "e": 33572, "s": 33564, "text": "If-Else" }, { "code": "// C program implementing the AND gate// through product method. #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, product; for (i = 0; i < 5; i++) { // using product method product = a[i] * b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], product); }}", "e": 33947, "s": 33572, "text": null }, { "code": "// C program implementing the AND gate// using & operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, and_ans; for (i = 0; i < 5; i++) { // using the & operator and_ans = a[i] & b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], and_ans); }}", "e": 34315, "s": 33947, "text": null }, { "code": "// C program implementing the AND gate// using if and else condition #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 0; else if (a[i] == 0 && b[i] == 1) ans = 0; else if (a[i] == 1 && b[i] == 0) ans = 0; else ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], ans); }}", "e": 34834, "s": 34315, "text": null }, { "code": null, "e": 34899, "s": 34834, "text": "1 AND 0 = 0\n 0 AND 1 = 0\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 0\n" }, { "code": null, "e": 36857, "s": 34899, "text": "OR GateThe OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.Below are the programs to implement AND gate using various methods:Using + operator.Using | operator.Using || operator.Using if else.+ Operator| Operator|| OperatorIf-Else+ Operator// C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}| Operator// C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}|| Operator// C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}If-Else// C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}Output:1 AND 0 = 1\n 0 AND 1 = 1\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 1\n" }, { "code": null, "e": 36925, "s": 36857, "text": "Below are the programs to implement AND gate using various methods:" }, { "code": null, "e": 36992, "s": 36925, "text": "Using + operator.Using | operator.Using || operator.Using if else." }, { "code": null, "e": 37010, "s": 36992, "text": "Using + operator." }, { "code": null, "e": 37028, "s": 37010, "text": "Using | operator." }, { "code": null, "e": 37047, "s": 37028, "text": "Using || operator." }, { "code": null, "e": 37062, "s": 37047, "text": "Using if else." }, { "code": null, "e": 37073, "s": 37062, "text": "+ Operator" }, { "code": null, "e": 37084, "s": 37073, "text": "| Operator" }, { "code": null, "e": 37096, "s": 37084, "text": "|| Operator" }, { "code": null, "e": 37104, "s": 37096, "text": "If-Else" }, { "code": "// C program implementing the OR gate// using + operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the + operator if (a[i] + b[i] > 0) or_ans = 1; else or_ans = 0; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}", "e": 37525, "s": 37104, "text": null }, { "code": "// C program implementing the OR gate// using | operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the | operator or_ans = a[i] | b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}", "e": 37889, "s": 37525, "text": null }, { "code": "// C program implementing the OR gate// using || operator #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the || operator or_ans = a[i] || b[i]; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}", "e": 38256, "s": 37889, "text": null }, { "code": "// C program implementing the OR gate// using if else #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, or_ans; for (i = 0; i < 5; i++) { // using the if-else conditions if (a[i] == 0 && b[i] == 0) or_ans = 0; else or_ans = 1; printf(\"\\n %d AND %d = %d\", a[i], b[i], or_ans); }}", "e": 38689, "s": 38256, "text": null }, { "code": null, "e": 38754, "s": 38689, "text": "1 AND 0 = 1\n 0 AND 1 = 1\n 1 AND 1 = 1\n 0 AND 0 = 0\n 1 AND 0 = 1\n" }, { "code": null, "e": 39784, "s": 38754, "text": "NAND GateThe NAND gate (negated AND) gives an output of 0 if both inputs are 1, it gives 1 otherwise.Below are the programs to implement NAND gate using various methods:Using if else.Using Complement of the product.If-ElseComplement of the productIf-Else// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}Complement of the product// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}Output:1 NAND 0 = 1\n 0 NAND 1 = 1\n 1 NAND 1 = 0\n 0 NAND 0 = 1\n 1 NAND 0 = 1\n" }, { "code": null, "e": 39853, "s": 39784, "text": "Below are the programs to implement NAND gate using various methods:" }, { "code": null, "e": 39900, "s": 39853, "text": "Using if else.Using Complement of the product." }, { "code": null, "e": 39915, "s": 39900, "text": "Using if else." }, { "code": null, "e": 39948, "s": 39915, "text": "Using Complement of the product." }, { "code": null, "e": 39956, "s": 39948, "text": "If-Else" }, { "code": null, "e": 39982, "s": 39956, "text": "Complement of the product" }, { "code": "// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 1 && b[i] == 1) ans = 0; else ans = 1; printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}", "e": 40349, "s": 39982, "text": null }, { "code": "// C program implementing the NAND gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] * b[i]); printf(\"\\n %d NAND %d = %d\", a[i], b[i], ans); }}", "e": 40658, "s": 40349, "text": null }, { "code": null, "e": 40728, "s": 40658, "text": "1 NAND 0 = 1\n 0 NAND 1 = 1\n 1 NAND 1 = 0\n 0 NAND 0 = 1\n 1 NAND 0 = 1\n" }, { "code": null, "e": 41700, "s": 40728, "text": "NOR GateThe NOR gate (negated OR) gives an output of 1 if both inputs are 0, it gives 1 otherwise.Below are the programs to implement NOR gate using various methods:Using + Operator.Using if else.+ OperatorIf-Else+ Operator// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}If-Else// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}Output:1 NOR 0 = 0\n 0 NOR 1 = 0\n 1 NOR 1 = 0\n 0 NOR 0 = 1\n 1 NOR 0 = 0\n" }, { "code": null, "e": 41768, "s": 41700, "text": "Below are the programs to implement NOR gate using various methods:" }, { "code": null, "e": 41800, "s": 41768, "text": "Using + Operator.Using if else." }, { "code": null, "e": 41818, "s": 41800, "text": "Using + Operator." }, { "code": null, "e": 41833, "s": 41818, "text": "Using if else." }, { "code": null, "e": 41844, "s": 41833, "text": "+ Operator" }, { "code": null, "e": 41852, "s": 41844, "text": "If-Else" }, { "code": "// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i] + b[i]); printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}", "e": 42159, "s": 41852, "text": null }, { "code": "// C program implementing the NOR gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int b[5] = { 0, 1, 1, 0, 0 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0 && b[i] == 0) ans = 1; else ans = 0; printf(\"\\n %d NOR %d = %d\", a[i], b[i], ans); }}", "e": 42524, "s": 42159, "text": null }, { "code": null, "e": 42589, "s": 42524, "text": "1 NOR 0 = 0\n 0 NOR 1 = 0\n 1 NOR 1 = 0\n 0 NOR 0 = 1\n 1 NOR 0 = 0\n" }, { "code": null, "e": 43458, "s": 42589, "text": "NOT GateIt acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.Below are the programs to implement NOT gate using various methods:Using ! Operator.Using if else.If-Else! OperatorIf-Else// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf(\"\\n NOT %d = %d\", a[i], ans); }}! Operator// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf(\"\\n NOT %d = %d\", a[i], ans); }}Output:NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n" }, { "code": null, "e": 43582, "s": 43458, "text": "It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa." }, { "code": null, "e": 43650, "s": 43582, "text": "Below are the programs to implement NOT gate using various methods:" }, { "code": null, "e": 43682, "s": 43650, "text": "Using ! Operator.Using if else." }, { "code": null, "e": 43700, "s": 43682, "text": "Using ! Operator." }, { "code": null, "e": 43715, "s": 43700, "text": "Using if else." }, { "code": null, "e": 43723, "s": 43715, "text": "If-Else" }, { "code": null, "e": 43734, "s": 43723, "text": "! Operator" }, { "code": "// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { if (a[i] == 0) ans = 1; else ans = 0; printf(\"\\n NOT %d = %d\", a[i], ans); }}", "e": 44031, "s": 43734, "text": null }, { "code": "// C program implementing the NOT gate #include <stdio.h>#include <stdlib.h> int main(){ int a[5] = { 1, 0, 1, 0, 1 }; int i, ans; for (i = 0; i < 5; i++) { ans = !(a[i]); printf(\"\\n NOT %d = %d\", a[i], ans); }}", "e": 44276, "s": 44031, "text": null }, { "code": null, "e": 44335, "s": 44276, "text": "NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n NOT 0 = 1\n NOT 1 = 0\n" }, { "code": null, "e": 44370, "s": 44335, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 44391, "s": 44370, "text": "Programming Language" }, { "code": null, "e": 44489, "s": 44391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44498, "s": 44489, "text": "Comments" }, { "code": null, "e": 44511, "s": 44498, "text": "Old Comments" }, { "code": null, "e": 44544, "s": 44511, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 44585, "s": 44544, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 44615, "s": 44585, "text": "4-bit binary Adder-Subtractor" }, { "code": null, "e": 44645, "s": 44615, "text": "Multiplexers in Digital Logic" }, { "code": null, "e": 44683, "s": 44645, "text": "Magnitude Comparator in Digital Logic" }, { "code": null, "e": 44724, "s": 44683, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 44767, "s": 44724, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 44785, "s": 44767, "text": "Structures in C++" }, { "code": null, "e": 44848, "s": 44785, "text": "Differences between Procedural and Object Oriented Programming" } ]
Legality of Web Scraping
With Python, we can scrape any website or particular elements of a web page but do you have any idea whether it is legal or not? Before scraping any website we must have to know about the legality of web scraping. This chapter will explain the concepts related to legality of web scraping. Generally, if you are going to use the scraped data for personal use, then there may not be any problem. But if you are going to republish that data, then before doing the same you should make download request to the owner or do some background research about policies as well about the data you are going to scrape. If you are targeting a website for scraping data from it, we need to understand its scale and structure. Following are some of the files which we need to analyze before starting web scraping. Actually most of the publishers allow programmers to crawl their websites at some extent. In other sense, publishers want specific portions of the websites to be crawled. To define this, websites must put some rules for stating which portions can be crawled and which cannot be. Such rules are defined in a file called robots.txt. robots.txt is human readable file used to identify the portions of the website that crawlers are allowed as well as not allowed to scrape. There is no standard format of robots.txt file and the publishers of website can do modifications as per their needs. We can check the robots.txt file for a particular website by providing a slash and robots.txt after url of that website. For example, if we want to check it for Google.com, then we need to type https://www.google.com/robots.txt and we will get something as follows − User-agent: * Disallow: /search Allow: /search/about Allow: /search/static Allow: /search/howsearchworks Disallow: /sdch Disallow: /groups Disallow: /index.html? Disallow: /? Allow: /?hl= Disallow: /?hl=*& Allow: /?hl=*&gws_rd=ssl$ and so on........ Some of the most common rules that are defined in a website’s robots.txt file are as follows − User-agent: BadCrawler Disallow: / The above rule means the robots.txt file asks a crawler with BadCrawler user agent not to crawl their website. User-agent: * Crawl-delay: 5 Disallow: /trap The above rule means the robots.txt file delays a crawler for 5 seconds between download requests for all user-agents for avoiding overloading server. The /trap link will try to block malicious crawlers who follow disallowed links. There are many more rules that can be defined by the publisher of the website as per their requirements. Some of them are discussed here − What you supposed to do if you want to crawl a website for updated information? You will crawl every web page for getting that updated information, but this will increase the server traffic of that particular website. That is why websites provide sitemap files for helping the crawlers to locate updating content without needing to crawl every web page. Sitemap standard is defined at http://www.sitemaps.org/protocol.html. The following is the content of sitemap file of https://www.microsoft.com/robots.txt that is discovered in robot.txt file − Sitemap: https://www.microsoft.com/en-us/explore/msft_sitemap_index.xml Sitemap: https://www.microsoft.com/learning/sitemap.xml Sitemap: https://www.microsoft.com/en-us/licensing/sitemap.xml Sitemap: https://www.microsoft.com/en-us/legal/sitemap.xml Sitemap: https://www.microsoft.com/filedata/sitemaps/RW5xN8 Sitemap: https://www.microsoft.com/store/collections.xml Sitemap: https://www.microsoft.com/store/productdetailpages.index.xml Sitemap: https://www.microsoft.com/en-us/store/locations/store-locationssitemap.xml The above content shows that the sitemap lists the URLs on website and further allows a webmaster to specify some additional information like last updated date, change of contents, importance of URL with relation to others etc. about each URL. Is the size of a website, i.e. the number of web pages of a website affects the way we crawl? Certainly yes. Because if we have less number of web pages to crawl, then the efficiency would not be a serious issue, but suppose if our website has millions of web pages, for example Microsoft.com, then downloading each web page sequentially would take several months and then efficiency would be a serious concern. By checking the size of result of Google’s crawler, we can have an estimate of the size of a website. Our result can be filtered by using the keyword site while doing the Google search. For example, estimating the size of https://authoraditiagarwal.com/ is given below − You can see there are around 60 results which mean it is not a big website and crawling would not lead the efficiency issue. Another important question is whether the technology used by website affects the way we crawl? Yes, it affects. But how we can check about the technology used by a website? There is a Python library named builtwith with the help of which we can find out about the technology used by a website. In this example we are going to check the technology used by the website https://authoraditiagarwal.com with the help of Python library builtwith. But before using this library, we need to install it as follows − (base) D:\ProgramData>pip install builtwith Collecting builtwith Downloading https://files.pythonhosted.org/packages/9b/b8/4a320be83bb3c9c1b3ac3f9469a5d66e0 2918e20d226aa97a3e86bddd130/builtwith-1.3.3.tar.gz Requirement already satisfied: six in d:\programdata\lib\site-packages (from builtwith) (1.10.0) Building wheels for collected packages: builtwith Running setup.py bdist_wheel for builtwith ... done Stored in directory: C:\Users\gaurav\AppData\Local\pip\Cache\wheels\2b\00\c2\a96241e7fe520e75093898b f926764a924873e0304f10b2524 Successfully built builtwith Installing collected packages: builtwith Successfully installed builtwith-1.3.3 Now, with the help of following simple line of codes we can check the technology used by a particular website − In [1]: import builtwith In [2]: builtwith.parse('http://authoraditiagarwal.com') Out[2]: {'blogs': ['PHP', 'WordPress'], 'cms': ['WordPress'], 'ecommerce': ['WooCommerce'], 'font-scripts': ['Font Awesome'], 'javascript-frameworks': ['jQuery'], 'programming-languages': ['PHP'], 'web-servers': ['Apache']} The owner of the website also matters because if the owner is known for blocking the crawlers, then the crawlers must be careful while scraping the data from website. There is a protocol named Whois with the help of which we can find out about the owner of the website. In this example we are going to check the owner of the website say microsoft.com with the help of Whois. But before using this library, we need to install it as follows − (base) D:\ProgramData>pip install python-whois Collecting python-whois Downloading https://files.pythonhosted.org/packages/63/8a/8ed58b8b28b6200ce1cdfe4e4f3bbc8b8 5a79eef2aa615ec2fef511b3d68/python-whois-0.7.0.tar.gz (82kB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 92kB 164kB/s Requirement already satisfied: future in d:\programdata\lib\site-packages (from python-whois) (0.16.0) Building wheels for collected packages: python-whois Running setup.py bdist_wheel for python-whois ... done Stored in directory: C:\Users\gaurav\AppData\Local\pip\Cache\wheels\06\cb\7d\33704632b0e1bb64460dc2b 4dcc81ab212a3d5e52ab32dc531 Successfully built python-whois Installing collected packages: python-whois Successfully installed python-whois-0.7.0 Now, with the help of following simple line of codes we can check the technology used by a particular website − In [1]: import whois In [2]: print (whois.whois('microsoft.com')) { "domain_name": [ "MICROSOFT.COM", "microsoft.com" ], ------- "name_servers": [ "NS1.MSFT.NET", "NS2.MSFT.NET", "NS3.MSFT.NET", "NS4.MSFT.NET", "ns3.msft.net", "ns1.msft.net", "ns4.msft.net", "ns2.msft.net" ], "emails": [ "abusecomplaints@markmonitor.com", "domains@microsoft.com", "msnhst@microsoft.com", "whoisrelay@markmonitor.com" ], } 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2202, "s": 1912, "text": "With Python, we can scrape any website or particular elements of a web page but do you have any idea whether it is legal or not? Before scraping any website we must have to know about the legality of web scraping. This chapter will explain the concepts related to legality of web scraping." }, { "code": null, "e": 2519, "s": 2202, "text": "Generally, if you are going to use the scraped data for personal use, then there may not be any problem. But if you are going to republish that data, then before doing the same you should make download request to the owner or do some background research about policies as well about the data you are going to scrape." }, { "code": null, "e": 2711, "s": 2519, "text": "If you are targeting a website for scraping data from it, we need to understand its scale and structure. Following are some of the files which we need to analyze before starting web scraping." }, { "code": null, "e": 3042, "s": 2711, "text": "Actually most of the publishers allow programmers to crawl their websites at some extent. In other sense, publishers want specific portions of the websites to be crawled. To define this, websites must put some rules for stating which portions can be crawled and which cannot be. Such rules are defined in a file called robots.txt." }, { "code": null, "e": 3566, "s": 3042, "text": "robots.txt is human readable file used to identify the portions of the website that crawlers are allowed as well as not allowed to scrape. There is no standard format of robots.txt file and the publishers of website can do modifications as per their needs. We can check the robots.txt file for a particular website by providing a slash and robots.txt after url of that website. For example, if we want to check it for Google.com, then we need to type https://www.google.com/robots.txt and we will get something as follows −" }, { "code": null, "e": 3817, "s": 3566, "text": "User-agent: *\nDisallow: /search\nAllow: /search/about\nAllow: /search/static\nAllow: /search/howsearchworks\nDisallow: /sdch\nDisallow: /groups\nDisallow: /index.html?\nDisallow: /?\nAllow: /?hl=\nDisallow: /?hl=*&\nAllow: /?hl=*&gws_rd=ssl$\nand so on........\n" }, { "code": null, "e": 3912, "s": 3817, "text": "Some of the most common rules that are defined in a website’s robots.txt file are as follows −" }, { "code": null, "e": 3951, "s": 3912, "text": " User-agent: BadCrawler\nDisallow: /\n" }, { "code": null, "e": 4062, "s": 3951, "text": "The above rule means the robots.txt file asks a crawler with BadCrawler user agent not to crawl their website." }, { "code": null, "e": 4108, "s": 4062, "text": "User-agent: *\nCrawl-delay: 5\nDisallow: /trap\n" }, { "code": null, "e": 4479, "s": 4108, "text": "The above rule means the robots.txt file delays a crawler for 5 seconds between download requests for all user-agents for avoiding overloading server. The /trap link will try to block malicious crawlers who follow disallowed links. There are many more rules that can be defined by the publisher of the website as per their requirements. Some of them are discussed here −" }, { "code": null, "e": 4903, "s": 4479, "text": "What you supposed to do if you want to crawl a website for updated information? You will crawl every web page for getting that updated information, but this will increase the server traffic of that particular website. That is why websites provide sitemap files for helping the crawlers to locate updating content without needing to crawl every web page. Sitemap standard is defined at http://www.sitemaps.org/protocol.html." }, { "code": null, "e": 5027, "s": 4903, "text": "The following is the content of sitemap file of https://www.microsoft.com/robots.txt that is discovered in robot.txt file −" }, { "code": null, "e": 5549, "s": 5027, "text": "Sitemap: https://www.microsoft.com/en-us/explore/msft_sitemap_index.xml\nSitemap: https://www.microsoft.com/learning/sitemap.xml\nSitemap: https://www.microsoft.com/en-us/licensing/sitemap.xml\nSitemap: https://www.microsoft.com/en-us/legal/sitemap.xml\nSitemap: https://www.microsoft.com/filedata/sitemaps/RW5xN8\nSitemap: https://www.microsoft.com/store/collections.xml\nSitemap: https://www.microsoft.com/store/productdetailpages.index.xml\nSitemap: https://www.microsoft.com/en-us/store/locations/store-locationssitemap.xml\n" }, { "code": null, "e": 5793, "s": 5549, "text": "The above content shows that the sitemap lists the URLs on website and further allows a webmaster to specify some additional information like last updated date, change of contents, importance of URL with relation to others etc. about each URL." }, { "code": null, "e": 6205, "s": 5793, "text": "Is the size of a website, i.e. the number of web pages of a website affects the way we crawl? Certainly yes. Because if we have less number of web pages to crawl, then the efficiency would not be a serious issue, but suppose if our website has millions of web pages, for example Microsoft.com, then downloading each web page sequentially would take several months and then efficiency would be a serious concern." }, { "code": null, "e": 6476, "s": 6205, "text": "By checking the size of result of Google’s crawler, we can have an estimate of the size of a website. Our result can be filtered by using the keyword site while doing the Google search. For example, estimating the size of https://authoraditiagarwal.com/ is given below −" }, { "code": null, "e": 6601, "s": 6476, "text": "You can see there are around 60 results which mean it is not a big website and crawling would not lead the efficiency issue." }, { "code": null, "e": 6895, "s": 6601, "text": "Another important question is whether the technology used by website affects the way we crawl? Yes, it affects. But how we can check about the technology used by a website? There is a Python library named builtwith with the help of which we can find out about the technology used by a website." }, { "code": null, "e": 7109, "s": 6895, "text": "In this example we are going to check the technology used by the website \nhttps://authoraditiagarwal.com with the help of Python library builtwith. But before using this library, we need to install it as follows −" }, { "code": null, "e": 7764, "s": 7109, "text": "(base) D:\\ProgramData>pip install builtwith\nCollecting builtwith\n Downloading\nhttps://files.pythonhosted.org/packages/9b/b8/4a320be83bb3c9c1b3ac3f9469a5d66e0\n2918e20d226aa97a3e86bddd130/builtwith-1.3.3.tar.gz\nRequirement already satisfied: six in d:\\programdata\\lib\\site-packages (from\nbuiltwith) (1.10.0)\nBuilding wheels for collected packages: builtwith\n Running setup.py bdist_wheel for builtwith ... done\n Stored in directory:\nC:\\Users\\gaurav\\AppData\\Local\\pip\\Cache\\wheels\\2b\\00\\c2\\a96241e7fe520e75093898b\nf926764a924873e0304f10b2524\nSuccessfully built builtwith\nInstalling collected packages: builtwith\nSuccessfully installed builtwith-1.3.3\n" }, { "code": null, "e": 7876, "s": 7764, "text": "Now, with the help of following simple line of codes we can check the technology used by a particular website −" }, { "code": null, "e": 8201, "s": 7876, "text": "In [1]: import builtwith\nIn [2]: builtwith.parse('http://authoraditiagarwal.com')\nOut[2]:\n{'blogs': ['PHP', 'WordPress'],\n 'cms': ['WordPress'],\n 'ecommerce': ['WooCommerce'],\n 'font-scripts': ['Font Awesome'],\n 'javascript-frameworks': ['jQuery'],\n 'programming-languages': ['PHP'],\n 'web-servers': ['Apache']}\n" }, { "code": null, "e": 8471, "s": 8201, "text": "The owner of the website also matters because if the owner is known for blocking the crawlers, then the crawlers must be careful while scraping the data from website. There is a protocol named Whois with the help of which we can find out about the owner of the website." }, { "code": null, "e": 8642, "s": 8471, "text": "In this example we are going to check the owner of the website say microsoft.com with the help of Whois. But before using this library, we need to install it as follows −" }, { "code": null, "e": 9390, "s": 8642, "text": "(base) D:\\ProgramData>pip install python-whois\nCollecting python-whois\n Downloading\nhttps://files.pythonhosted.org/packages/63/8a/8ed58b8b28b6200ce1cdfe4e4f3bbc8b8\n5a79eef2aa615ec2fef511b3d68/python-whois-0.7.0.tar.gz (82kB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 92kB 164kB/s\nRequirement already satisfied: future in d:\\programdata\\lib\\site-packages (from\npython-whois) (0.16.0)\nBuilding wheels for collected packages: python-whois\n Running setup.py bdist_wheel for python-whois ... done\n Stored in directory:\nC:\\Users\\gaurav\\AppData\\Local\\pip\\Cache\\wheels\\06\\cb\\7d\\33704632b0e1bb64460dc2b\n4dcc81ab212a3d5e52ab32dc531\nSuccessfully built python-whois\nInstalling collected packages: python-whois\nSuccessfully installed python-whois-0.7.0\n" }, { "code": null, "e": 9502, "s": 9390, "text": "Now, with the help of following simple line of codes we can check the technology used by a particular website −" }, { "code": null, "e": 10015, "s": 9502, "text": "In [1]: import whois\nIn [2]: print (whois.whois('microsoft.com'))\n{\n \"domain_name\": [\n \"MICROSOFT.COM\",\n \"microsoft.com\"\n ],\n -------\n \"name_servers\": [\n \"NS1.MSFT.NET\",\n \"NS2.MSFT.NET\",\n \"NS3.MSFT.NET\",\n \"NS4.MSFT.NET\",\n \"ns3.msft.net\",\n \"ns1.msft.net\",\n \"ns4.msft.net\",\n \"ns2.msft.net\"\n ],\n \"emails\": [\n \"abusecomplaints@markmonitor.com\",\n \"domains@microsoft.com\",\n \"msnhst@microsoft.com\",\n \"whoisrelay@markmonitor.com\"\n ],\n}\n" }, { "code": null, "e": 10052, "s": 10015, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10068, "s": 10052, "text": " Malhar Lathkar" }, { "code": null, "e": 10101, "s": 10068, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 10120, "s": 10101, "text": " Arnab Chakraborty" }, { "code": null, "e": 10155, "s": 10120, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 10177, "s": 10155, "text": " In28Minutes Official" }, { "code": null, "e": 10211, "s": 10177, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 10239, "s": 10211, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10274, "s": 10239, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 10288, "s": 10274, "text": " Lets Kode It" }, { "code": null, "e": 10321, "s": 10288, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 10338, "s": 10321, "text": " Abhilash Nelson" }, { "code": null, "e": 10345, "s": 10338, "text": " Print" }, { "code": null, "e": 10356, "s": 10345, "text": " Add Notes" } ]
Concatenate two columns when one of such column values is null in MySQL
To avoid any issues while running a query, use IFNULL(). Let us first create a table − mysql> create table DemoTable1793 ( StudentFirstName varchar(20), StudentLastName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1793 values('John','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1793 values('Carol',NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1793 values(NULL,'Brown'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1793; This will produce the following output − +------------------+-----------------+ | StudentFirstName | StudentLastName | +------------------+-----------------+ | John | Smith | | Carol | NULL | | NULL | Brown | +------------------+-----------------+ 3 rows in set (0.00 sec) Here is the query to concatenate two columns when one of such column values is null − mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793; This will produce the following output − +----------------------------------------------------------------+ | concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) | +----------------------------------------------------------------+ | JohnSmith | | Carol | | Brown | +----------------------------------------------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1149, "s": 1062, "text": "To avoid any issues while running a query, use IFNULL(). Let us first create a table −" }, { "code": null, "e": 1303, "s": 1149, "text": "mysql> create table DemoTable1793\n (\n StudentFirstName varchar(20),\n StudentLastName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1359, "s": 1303, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1634, "s": 1359, "text": "mysql> insert into DemoTable1793 values('John','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1793 values('Carol',NULL);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1793 values(NULL,'Brown');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1694, "s": 1634, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1730, "s": 1694, "text": "mysql> select * from DemoTable1793;" }, { "code": null, "e": 1771, "s": 1730, "text": "This will produce the following output −" }, { "code": null, "e": 2069, "s": 1771, "text": "+------------------+-----------------+\n| StudentFirstName | StudentLastName |\n+------------------+-----------------+\n| John | Smith |\n| Carol | NULL |\n| NULL | Brown |\n+------------------+-----------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2155, "s": 2069, "text": "Here is the query to concatenate two columns when one of such column values is null −" }, { "code": null, "e": 2252, "s": 2155, "text": "mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793;" }, { "code": null, "e": 2293, "s": 2252, "text": "This will produce the following output −" }, { "code": null, "e": 2787, "s": 2293, "text": "+----------------------------------------------------------------+\n| concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) |\n+----------------------------------------------------------------+\n| JohnSmith |\n| Carol |\n| Brown |\n+----------------------------------------------------------------+\n3 rows in set (0.00 sec)" } ]
Java - acos() Method
The method returns the arccosine of the specified double value. double acos(double d) Here is the detail of parameters − d − A double data type. d − A double data type. This method returns the arccosine of the specified double value. This method returns the arccosine of the specified double value. public class Test { public static void main(String args[]) { double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The arccosine of %.4f is %.4f degrees %n", Math.cos(radians), Math.toDegrees(Math.acos(Math.cos(radians)))); } } This will produce the following result − The value of pi is 3.1416 The arccosine of 0.7071 is 45.0000 degrees 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2441, "s": 2377, "text": "The method returns the arccosine of the specified double value." }, { "code": null, "e": 2464, "s": 2441, "text": "double acos(double d)\n" }, { "code": null, "e": 2499, "s": 2464, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2523, "s": 2499, "text": "d − A double data type." }, { "code": null, "e": 2547, "s": 2523, "text": "d − A double data type." }, { "code": null, "e": 2612, "s": 2547, "text": "This method returns the arccosine of the specified double value." }, { "code": null, "e": 2677, "s": 2612, "text": "This method returns the arccosine of the specified double value." }, { "code": null, "e": 3034, "s": 2677, "text": "public class Test { \n\n public static void main(String args[]) {\n double degrees = 45.0;\n double radians = Math.toRadians(degrees);\n\n System.out.format(\"The value of pi is %.4f%n\", Math.PI);\n System.out.format(\"The arccosine of %.4f is %.4f degrees %n\", Math.cos(radians),\n Math.toDegrees(Math.acos(Math.cos(radians))));\n }\n}" }, { "code": null, "e": 3075, "s": 3034, "text": "This will produce the following result −" }, { "code": null, "e": 3145, "s": 3075, "text": "The value of pi is 3.1416\nThe arccosine of 0.7071 is 45.0000 degrees\n" }, { "code": null, "e": 3178, "s": 3145, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3194, "s": 3178, "text": " Malhar Lathkar" }, { "code": null, "e": 3227, "s": 3194, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3243, "s": 3227, "text": " Malhar Lathkar" }, { "code": null, "e": 3278, "s": 3243, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3292, "s": 3278, "text": " Anadi Sharma" }, { "code": null, "e": 3326, "s": 3292, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3340, "s": 3326, "text": " Tushar Kale" }, { "code": null, "e": 3377, "s": 3340, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3392, "s": 3377, "text": " Monica Mittal" }, { "code": null, "e": 3425, "s": 3392, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3444, "s": 3425, "text": " Arnab Chakraborty" }, { "code": null, "e": 3451, "s": 3444, "text": " Print" }, { "code": null, "e": 3462, "s": 3451, "text": " Add Notes" } ]
Pandas query method saves double handling of variables | by Alexis Lucattini | Towards Data Science
Standard methods to retrieve rows with certain conditions in a pandas DataFrame object requires ‘double handling’; it’s not particularly elegant. For example, we want to retrieve rows where column A is greater than 1, this is the standard way to do it using the .loc attribute. ## Setup ### Import pandasimport pandas as pd# Create dataframe from dict# Specify the type in the suffix of each column namemy_df = pd.DataFrame({"A_int": [1, 2, -3], "B_float": [7.5, 1.9, 8.4], "C_str": ['eight', 'nine', 'Ten'], "D_str": ['Mar 2017', 'May 2018', 'Jun 2016']} )# Convert to datetime columnmy_df['D_date'] = pd.to_datetime(my_df['D_str'])""">>> my_df A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-012 -3 8.4 Ten Jun 2016 2016-06-01"""## Show loc example 1 ##ex_1_loc = my_df.loc[my_df['A_int'] > 0, :]""">>> ex_1_loc A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01""" Here we obtain the Boolean series of rows where column A is greater than 0 for that given row. The .loc is used to pull out rows set to True. Note that the variable my_df is used twice here in a single line of code.It is fortunate that this variable name is not very long. I find this ‘double handling’ of the variable syntactically similar to base methods in R, particularly intimidating when nested and overall quite unnecessary. Some other languages can perform this filtering in a much more readable format: ## SQL EXAMPLE ##SELECT *FROM my_dfWHERE A > 0## R-TIDYVERSE EXAMPLE ##library(tidyverse)my_df %>% dplyr::filter(A > 0) For python, we can do this simpler (and similar to the SQL / R-Tidyverse structure above) with pandas ‘query’ method. query returns only the rows that match the given condition, all columns remain present in the dataframe. #ex_1_loc = my_df.loc[my_df['A_int'] > 0, :]ex_1_query = my_df.query("A > 0")# Or use @ when referencing a variablepivot_val = 0ex_1a_query = my_df.query("A > @pivot_val") Let's see six more examples where query is an appropriate replacement to the .loc approach Given an external list, obtain rows of the dataframe where a certain column matches an element in that list # Create a list of legitimate entrieslegit_entries = ['eight', 'nine', 'ten']# Filter column 'C_str' by the arrayex_2_loc = my_df.loc[my_df['C_str'].isin(legit_entries), :]ex_2_query = my_df.query("C_str in @legit_entries")""" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01""" Compare two columns — this requires triple handling in the .loc example. # Return rows where 'A_int' is greater than 'B_float'ex_3_loc = my_df.loc[my_df['A_int'] > my_df['B_float'], :]ex_3_query = my_df.query("A_int > B_float")""" A_int B_float C_str D_str D_date1 2 1.9 nine May 2018 2018-05-01""" Filter using multiple conditions over potentially multiple columns. Both & and | bitwise operators are allowed. # Return rows where 'A_int' is greater than zero# And where C_str is in the legit_entries arrayex_4_loc = my_df.loc[(my_df["A_int"] > 0) & (my_df['C_str'].isin(legit_entries)), :]ex_4_query = my_df.query("A_int > 0 & C_str in @legit_entries")""" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01""" Query recognises dates and can compare them to strings. All strings inside a query quote must be quoted. # Return rows where D_date is after Jan 2018ex_5_loc = my_df.loc[my_df['D_date'] > 'Jan 2018', :]ex_5_query = my_df.query("D_date > 'Jan 2018'")""" A_int B_float C_str D_str D_date1 2 1.9 nine May 2018 2018-05-01""" You can perform a function on a given column prior to comparison.Note that the output of the dataframe still contains the C_str column in its original format? # First convert C_str to lowercase, than compare entriesex_6_loc = my_df.loc[my_df['C_str'].str.lower().isin(legit_entries), :]ex_6_query = my_df.query("C_str.str.lower() in @legit_entries")""" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-012 -3 8.4 Ten Jun 2016 2016-06-01""" 7. Column names containing spacesInitially forbidden with pandas query, this has been resolved as of 0.25.2.Quote the column with backticks. Other special characters in the column may not work. # Return rows where 'E rogue column str' column contains the word 'this'my_df['E rogue_column_str'] = ['this', 'and', 'that']""">>>my_df A_int B_float C_str D_str D_date E rogue_column_str0 1 7.5 eight Mar 2017 2017-03-01 this1 2 1.9 nine May 2018 2018-05-01 and2 -3 8.4 Ten Jun 2016 2016-06-01 that"""ex_7_loc = my_df.loc[my_df["E rogue_column_str"] == 'this', :]ex_7_query = my_df.query("`E rogue_column_str` == 'this'"))""" A_int B_float C_str D_str D_date E rogue_column_str0 1 7.5 eight Mar 2017 2017-03-01 this""" In the latest release of pandas (0.25.3 at the time of writing), the .item() method was deprecated. Combined with the query function, item was a highly useful tool to obtain a single value from a given column when it was appropriate to assume that only one row would be returned. This would convert the column from a type pd.Series to that of the series’ datatype i.e int, str, float etc. If more than one row was returned, a ValueError is raised by the method. We can use the squeeze method as an alternative with some small changes in the code. Like item, squeeze will convert a pandas series from series type to the datatype when the filtered series is only one row long. However, a ValueError is not raised if multiple values exist in the series, instead just the same series is returned. We can exploit this by checking if the returned value is still of a series type. # Previous codetry: single_value = ex_3_query['B_float'].item() print(single_value)except ValueError: print("Error, expected to return only one value, got %d" % len(ex_3_query['B_float']))# New codesingle_value = ex_3_query['B_float'].squeeze()if isinstance(single_value, pd.Series): print("Error, expected to return only one value, got %d" % len(ex_3_query['B_float']))else: print(single_value) References:Pandas Query API
[ { "code": null, "e": 318, "s": 172, "text": "Standard methods to retrieve rows with certain conditions in a pandas DataFrame object requires ‘double handling’; it’s not particularly elegant." }, { "code": null, "e": 450, "s": 318, "text": "For example, we want to retrieve rows where column A is greater than 1, this is the standard way to do it using the .loc attribute." }, { "code": null, "e": 1303, "s": 450, "text": "## Setup ### Import pandasimport pandas as pd# Create dataframe from dict# Specify the type in the suffix of each column namemy_df = pd.DataFrame({\"A_int\": [1, 2, -3], \"B_float\": [7.5, 1.9, 8.4], \"C_str\": ['eight', 'nine', 'Ten'], \"D_str\": ['Mar 2017', 'May 2018', 'Jun 2016']} )# Convert to datetime columnmy_df['D_date'] = pd.to_datetime(my_df['D_str'])\"\"\">>> my_df A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-012 -3 8.4 Ten Jun 2016 2016-06-01\"\"\"## Show loc example 1 ##ex_1_loc = my_df.loc[my_df['A_int'] > 0, :]\"\"\">>> ex_1_loc A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01\"\"\"" }, { "code": null, "e": 1735, "s": 1303, "text": "Here we obtain the Boolean series of rows where column A is greater than 0 for that given row. The .loc is used to pull out rows set to True. Note that the variable my_df is used twice here in a single line of code.It is fortunate that this variable name is not very long. I find this ‘double handling’ of the variable syntactically similar to base methods in R, particularly intimidating when nested and overall quite unnecessary." }, { "code": null, "e": 1815, "s": 1735, "text": "Some other languages can perform this filtering in a much more readable format:" }, { "code": null, "e": 1936, "s": 1815, "text": "## SQL EXAMPLE ##SELECT *FROM my_dfWHERE A > 0## R-TIDYVERSE EXAMPLE ##library(tidyverse)my_df %>% dplyr::filter(A > 0)" }, { "code": null, "e": 2159, "s": 1936, "text": "For python, we can do this simpler (and similar to the SQL / R-Tidyverse structure above) with pandas ‘query’ method. query returns only the rows that match the given condition, all columns remain present in the dataframe." }, { "code": null, "e": 2331, "s": 2159, "text": "#ex_1_loc = my_df.loc[my_df['A_int'] > 0, :]ex_1_query = my_df.query(\"A > 0\")# Or use @ when referencing a variablepivot_val = 0ex_1a_query = my_df.query(\"A > @pivot_val\")" }, { "code": null, "e": 2422, "s": 2331, "text": "Let's see six more examples where query is an appropriate replacement to the .loc approach" }, { "code": null, "e": 2530, "s": 2422, "text": "Given an external list, obtain rows of the dataframe where a certain column matches an element in that list" }, { "code": null, "e": 2895, "s": 2530, "text": "# Create a list of legitimate entrieslegit_entries = ['eight', 'nine', 'ten']# Filter column 'C_str' by the arrayex_2_loc = my_df.loc[my_df['C_str'].isin(legit_entries), :]ex_2_query = my_df.query(\"C_str in @legit_entries\")\"\"\" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01\"\"\"" }, { "code": null, "e": 2968, "s": 2895, "text": "Compare two columns — this requires triple handling in the .loc example." }, { "code": null, "e": 3217, "s": 2968, "text": "# Return rows where 'A_int' is greater than 'B_float'ex_3_loc = my_df.loc[my_df['A_int'] > my_df['B_float'], :]ex_3_query = my_df.query(\"A_int > B_float\")\"\"\" A_int B_float C_str D_str D_date1 2 1.9 nine May 2018 2018-05-01\"\"\"" }, { "code": null, "e": 3329, "s": 3217, "text": "Filter using multiple conditions over potentially multiple columns. Both & and | bitwise operators are allowed." }, { "code": null, "e": 3733, "s": 3329, "text": "# Return rows where 'A_int' is greater than zero# And where C_str is in the legit_entries arrayex_4_loc = my_df.loc[(my_df[\"A_int\"] > 0) & (my_df['C_str'].isin(legit_entries)), :]ex_4_query = my_df.query(\"A_int > 0 & C_str in @legit_entries\")\"\"\" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-01\"\"\"" }, { "code": null, "e": 3838, "s": 3733, "text": "Query recognises dates and can compare them to strings. All strings inside a query quote must be quoted." }, { "code": null, "e": 4077, "s": 3838, "text": "# Return rows where D_date is after Jan 2018ex_5_loc = my_df.loc[my_df['D_date'] > 'Jan 2018', :]ex_5_query = my_df.query(\"D_date > 'Jan 2018'\")\"\"\" A_int B_float C_str D_str D_date1 2 1.9 nine May 2018 2018-05-01\"\"\"" }, { "code": null, "e": 4236, "s": 4077, "text": "You can perform a function on a given column prior to comparison.Note that the output of the dataframe still contains the C_str column in its original format?" }, { "code": null, "e": 4633, "s": 4236, "text": "# First convert C_str to lowercase, than compare entriesex_6_loc = my_df.loc[my_df['C_str'].str.lower().isin(legit_entries), :]ex_6_query = my_df.query(\"C_str.str.lower() in @legit_entries\")\"\"\" A_int B_float C_str D_str D_date0 1 7.5 eight Mar 2017 2017-03-011 2 1.9 nine May 2018 2018-05-012 -3 8.4 Ten Jun 2016 2016-06-01\"\"\"" }, { "code": null, "e": 4827, "s": 4633, "text": "7. Column names containing spacesInitially forbidden with pandas query, this has been resolved as of 0.25.2.Quote the column with backticks. Other special characters in the column may not work." }, { "code": null, "e": 5478, "s": 4827, "text": "# Return rows where 'E rogue column str' column contains the word 'this'my_df['E rogue_column_str'] = ['this', 'and', 'that']\"\"\">>>my_df A_int B_float C_str D_str D_date E rogue_column_str0 1 7.5 eight Mar 2017 2017-03-01 this1 2 1.9 nine May 2018 2018-05-01 and2 -3 8.4 Ten Jun 2016 2016-06-01 that\"\"\"ex_7_loc = my_df.loc[my_df[\"E rogue_column_str\"] == 'this', :]ex_7_query = my_df.query(\"`E rogue_column_str` == 'this'\"))\"\"\" A_int B_float C_str D_str D_date E rogue_column_str0 1 7.5 eight Mar 2017 2017-03-01 this\"\"\"" }, { "code": null, "e": 5940, "s": 5478, "text": "In the latest release of pandas (0.25.3 at the time of writing), the .item() method was deprecated. Combined with the query function, item was a highly useful tool to obtain a single value from a given column when it was appropriate to assume that only one row would be returned. This would convert the column from a type pd.Series to that of the series’ datatype i.e int, str, float etc. If more than one row was returned, a ValueError is raised by the method." }, { "code": null, "e": 6352, "s": 5940, "text": "We can use the squeeze method as an alternative with some small changes in the code. Like item, squeeze will convert a pandas series from series type to the datatype when the filtered series is only one row long. However, a ValueError is not raised if multiple values exist in the series, instead just the same series is returned. We can exploit this by checking if the returned value is still of a series type." }, { "code": null, "e": 6781, "s": 6352, "text": "# Previous codetry: single_value = ex_3_query['B_float'].item() print(single_value)except ValueError: print(\"Error, expected to return only one value, got %d\" % len(ex_3_query['B_float']))# New codesingle_value = ex_3_query['B_float'].squeeze()if isinstance(single_value, pd.Series): print(\"Error, expected to return only one value, got %d\" % len(ex_3_query['B_float']))else: print(single_value)" } ]
Iterative Depth First Traversal of Graph - GeeksforGeeks
26 Nov, 2021 Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram: Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram: The recursive implementation of DFS is already discussed: previous post. Solution: Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally print the nodes in the path. The only difference between iterative DFS and recursive DFS is that the recursive stack is replaced by a stack of nodes. Algorithm: Created a stack of nodes and visited array.Insert the root in the stack.Run a loop till the stack is not empty.Pop the element from the stack and print the element.For every adjacent and unvisited node of current node, mark the node and insert it in the stack. Created a stack of nodes and visited array.Insert the root in the stack.Run a loop till the stack is not empty.Pop the element from the stack and print the element.For every adjacent and unvisited node of current node, mark the node and insert it in the stack. Created a stack of nodes and visited array. Insert the root in the stack. Run a loop till the stack is not empty. Pop the element from the stack and print the element. For every adjacent and unvisited node of current node, mark the node and insert it in the stack. Implementation of Iterative DFS: This is similar to BFS, the only difference is queue is replaced by stack. C++ Java Python3 C# Javascript // An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices list<int> *adj; // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph void DFS(int s); // prints all vertices in DFS manner // from a given source.}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // prints all not yet visited vertices reachable from svoid Graph::DFS(int s){ // Initially mark all vertices as not visited vector<bool> visited(V, false); // Create a stack for DFS stack<int> stack; // Push the current source node. stack.push(s); while (!stack.empty()) { // Pop a vertex from stack and print it int s = stack.top(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (!visited[s]) { cout << s << " "; visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (auto i = adj[s].begin(); i != adj[s].end(); ++i) if (!visited[*i]) stack.push(*i); }} // Driver program to test methods of graph classint main(){ Graph g(5); // Total 5 vertices in graph g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); cout << "Following is Depth First Traversal\n"; g.DFS(0); return 0;} //An Iterative Java program to do DFS traversal from//a given source vertex. DFS(int s) traverses vertices//reachable from s. import java.util.*; public class GFG{ // This class represents a directed graph using adjacency // list representation static class Graph { int V; //Number of Vertices LinkedList<Integer>[] adj; // adjacency lists //Constructor Graph(int V) { this.V = V; adj = new LinkedList[V]; for (int i = 0; i < adj.length; i++) adj[i] = new LinkedList<Integer>(); } //To add an edge to graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s void DFS(int s) { // Initially mark all vertices as not visited Vector<Boolean> visited = new Vector<Boolean>(V); for (int i = 0; i < V; i++) visited.add(false); // Create a stack for DFS Stack<Integer> stack = new Stack<>(); // Push the current source node stack.push(s); while(stack.empty() == false) { // Pop a vertex from stack and print it s = stack.peek(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited.get(s) == false) { System.out.print(s + " "); visited.set(s, true); } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. Iterator<Integer> itr = adj[s].iterator(); while (itr.hasNext()) { int v = itr.next(); if(!visited.get(v)) stack.push(v); } } } } // Driver program to test methods of graph class public static void main(String[] args) { // Total 5 vertices in graph Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); System.out.println("Following is the Depth First Traversal"); g.DFS(0); }} # An Iterative Python program to do DFS traversal from# a given source vertex. DFS(int s) traverses vertices# reachable from s. # This class represents a directed graph using adjacency# list representationclass Graph: def __init__(self,V): # Constructor self.V = V # No. of vertices self.adj = [[] for i in range(V)] # adjacency lists def addEdge(self,v, w): # to add an edge to graph self.adj[v].append(w) # Add w to v’s list. # prints all not yet visited vertices reachable from s def DFS(self,s): # prints all vertices in DFS manner from a given source. # Initially mark all vertices as not visited visited = [False for i in range(self.V)] # Create a stack for DFS stack = [] # Push the current source node. stack.append(s) while (len(stack)): # Pop a vertex from stack and print it s = stack[-1] stack.pop() # Stack may contain same vertex twice. So # we need to print the popped item only # if it is not visited. if (not visited[s]): print(s,end=' ') visited[s] = True # Get all adjacent vertices of the popped vertex s # If a adjacent has not been visited, then push it # to the stack. for node in self.adj[s]: if (not visited[node]): stack.append(node) # Driver program to test methods of graph class g = Graph(5); # Total 5 vertices in graphg.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4); print("Following is Depth First Traversal")g.DFS(0) # This code is contributed by ankush_953 // An Iterative C# program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.using System;using System.Collections.Generic; class GFG{ // This class represents a directed graph using adjacency // list representation public class Graph { public int V; // Number of Vertices public LinkedList<int>[] adj; // adjacency lists // Constructor public Graph(int V) { this.V = V; adj = new LinkedList<int>[V]; for (int i = 0; i < adj.Length; i++) adj[i] = new LinkedList<int>(); } // To add an edge to graph public void addEdge(int v, int w) { adj[v].AddLast(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s public void DFS(int s) { // Initially mark all vertices as not visited Boolean []visited = new Boolean[V]; // Create a stack for DFS Stack<int> stack = new Stack<int>(); // Push the current source node stack.Push(s); while(stack.Count > 0) { // Pop a vertex from stack and print it s = stack.Peek(); stack.Pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { Console.Write(s + " "); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. foreach(int v in adj[s]) { if(!visited[v]) stack.Push(v); } } } } // Driver code public static void Main(String []args) { // Total 5 vertices in graph Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); Console.Write("Following is the Depth First Traversal\n"); g.DFS(0); }} // This code is contributed by Arnasb Kundu <script> // An Iterative Javascript program to// do DFS traversal from a given source// vertex. DFS(int s) traverses vertices// reachable from s. // This class represents a directed graph// using adjacency list representationclass Graph{ constructor(V){ this.V = V; this.adj = new Array(V); for(let i = 0; i < this.adj.length; i++) this.adj[i] = [];} // To add an edge to graphaddEdge(v, w){ // Add w to v’s list. this.adj[v].push(w);} // Prints all not yet visited// vertices reachable from sDFS(s){ // Initially mark all vertices as not visited let visited = []; for(let i = 0; i < this.V; i++) visited.push(false); // Create a stack for DFS let stack = []; // Push the current source node stack.push(s); while(stack.length != 0) { // Pop a vertex from stack and print it s = stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (visited[s] == false) { document.write(s + " "); visited[s] = true; } // Get all adjacent vertices of the // popped vertex s. If a adjacent has // not been visited, then push it // to the stack. for(let node = 0; node < this.adj[s].length; node++) { if (!visited[this.adj[s][node]]) stack.push(this.adj[s][node]) } }}} // Driver code // Total 5 vertices in graphlet g = new Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4); document.write("Following is the Depth " + "First Traversal<br>");g.DFS(0); // This code is contributed by rag2127 </script> Output: Following is Depth First Traversal 0 3 2 1 4 Complexity Analysis: Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.Space Complexity: O(V). Since an extra visited array is needed of size V. Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph. Space Complexity: O(V). Since an extra visited array is needed of size V. Modification of the above Solution: Note that the above implementation prints only vertices that are reachable from a given vertex. For example, if the edges 0-3 and 0-2 are removed, then the above program would only print 0. To print all vertices of a graph, call DFS for every unvisited vertex. Implementation: C++ Java Python3 C# Javascript // An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices list<int> *adj; // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph void DFS(); // prints all vertices in DFS manner // prints all not yet visited vertices reachable from s void DFSUtil(int s, vector<bool> &visited);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // prints all not yet visited vertices reachable from svoid Graph::DFSUtil(int s, vector<bool> &visited){ // Create a stack for DFS stack<int> stack; // Push the current source node. stack.push(s); while (!stack.empty()) { // Pop a vertex from stack and print it int s = stack.top(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (!visited[s]) { cout << s << " "; visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (auto i = adj[s].begin(); i != adj[s].end(); ++i) if (!visited[*i]) stack.push(*i); }} // prints all vertices in DFS mannervoid Graph::DFS(){ // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited);} // Driver program to test methods of graph classint main(){ Graph g(5); // Total 5 vertices in graph g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); cout << "Following is Depth First Traversal\n"; g.DFS(); return 0;} //An Iterative Java program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s. import java.util.*; public class GFG{ // This class represents a directed graph using adjacency // list representation static class Graph { int V; //Number of Vertices LinkedList<Integer>[] adj; // adjacency lists //Constructor Graph(int V) { this.V = V; adj = new LinkedList[V]; for (int i = 0; i < adj.length; i++) adj[i] = new LinkedList<Integer>(); } //To add an edge to graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s void DFSUtil(int s, Vector<Boolean> visited) { // Create a stack for DFS Stack<Integer> stack = new Stack<>(); // Push the current source node stack.push(s); while(stack.empty() == false) { // Pop a vertex from stack and print it s = stack.peek(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited.get(s) == false) { System.out.print(s + " "); visited.set(s, true); } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. Iterator<Integer> itr = adj[s].iterator(); while (itr.hasNext()) { int v = itr.next(); if(!visited.get(v)) stack.push(v); } } } // prints all vertices in DFS manner void DFS() { Vector<Boolean> visited = new Vector<Boolean>(V); // Mark all the vertices as not visited for (int i = 0; i < V; i++) visited.add(false); for (int i = 0; i < V; i++) if (!visited.get(i)) DFSUtil(i, visited); } } // Driver program to test methods of graph class public static void main(String[] args) { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); System.out.println("Following is Depth First Traversal"); g.DFS(); }} # An Iterative Python3 program to do DFS# traversal from a given source vertex.# DFS(s) traverses vertices reachable from s.class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, v, w): self.adj[v].append(w) # Add w to v’s list. # prints all not yet visited vertices # reachable from s def DFSUtil(self, s, visited): # Create a stack for DFS stack = [] # Push the current source node. stack.append(s) while (len(stack) != 0): # Pop a vertex from stack and print it s = stack.pop() # Stack may contain same vertex twice. # So we need to print the popped item only # if it is not visited. if (not visited[s]): print(s, end = " ") visited[s] = True # Get all adjacent vertices of the # popped vertex s. If a adjacent has not # been visited, then push it to the stack. i = 0 while i < len(self.adj[s]): if (not visited[self.adj[s][i]]): stack.append(self.adj[s][i]) i += 1 # prints all vertices in DFS manner def DFS(self): # Mark all the vertices as not visited visited = [False] * self.V for i in range(self.V): if (not visited[i]): self.DFSUtil(i, visited) # Driver Codeif __name__ == '__main__': g = Graph(5) # Total 5 vertices in graph g.addEdge(1, 0) g.addEdge(2, 1) g.addEdge(3, 4) g.addEdge(4, 0) print("Following is Depth First Traversal") g.DFS() # This code is contributed by PranchalK // An Iterative C# program to do DFS traversal from// a given source vertex. DFS() traverses vertices// reachable from s.using System;using System.Collections.Generic; class GFG{ // This class represents a directed graph using adjacency // list representation class Graph { public int V; // Number of Vertices public List<int>[] adj; // adjacency lists // Constructor public Graph(int V) { this.V = V; adj = new List<int>[V]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); } // To add an edge to graph public void addEdge(int v, int w) { adj[v].Add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s public void DFSUtil(int s, List<Boolean> visited) { // Create a stack for DFS Stack<int> stack = new Stack<int>(); // Push the current source node stack.Push(s); while(stack.Count != 0) { // Pop a vertex from stack and print it s = stack.Peek(); stack.Pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { Console.Write(s + " "); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. foreach(int itr in adj[s]) { int v = itr; if(!visited[v]) stack.Push(v); } } } // prints all vertices in DFS manner public void DFS() { List<Boolean> visited = new List<Boolean>(V); // Mark all the vertices as not visited for (int i = 0; i < V; i++) visited.Add(false); for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited); } } // Driver code public static void Main(String[] args) { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); Console.WriteLine("Following is Depth First Traversal"); g.DFS(); }} // This code is contributed by 29AjayKumar <script>//An Iterative Javascript program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s. // This class represents a directed graph using adjacency // list representationclass Graph{ //Constructor constructor(V) { this.V=V; this.adj = new Array(V); for (let i = 0; i < this.adj.length; i++) this.adj[i] = []; } //To add an edge to graph addEdge(v,w) { this.adj[v].push(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s DFSUtil(s,visited) { // Create a stack for DFS let stack = []; // Push the current source node stack.push(s); while(stack.length != 0) { // Pop a vertex from stack and print it s = stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { document.write(s + " "); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (let itr=0;itr<this.adj[s].length;itr++) { let v = this.adj[s][itr]; if(!visited[v]) stack.push(v); } } } // prints all vertices in DFS manner DFS() { let visited = [] // Mark all the vertices as not visited for (let i = 0; i < this.V; i++) visited.push(false); for (let i = 0; i < this.V; i++) if (!visited[i]) this.DFSUtil(i, visited); } } // Driver program to test methods of graph classlet g = new Graph(5);g.addEdge(1, 0);g.addEdge(2, 1);g.addEdge(3, 4);g.addEdge(4, 0); document.write("Following is Depth First Traversal<br>");g.DFS(); // This code is contributed by avanitrachhadiya2155</script> Output: Following is Depth First Traversal 0 1 2 3 4 Like recursive traversal, the time complexity of iterative implementation is O(V + E). This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranchalKatiyar ankush_953 the_alphaEye nidhi_biet andrew1234 29AjayKumar abhinavgalodha ashishkaushik53552 rag2127 avanitrachhadiya2155 vishalthoke2 varshagumber28 Kirti_Mangal DFS Graph Stack Stack DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Detect Cycle in a Directed Graph Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 24587, "s": 24559, "text": "\n26 Nov, 2021" }, { "code": null, "e": 24858, "s": 24587, "text": "Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. " }, { "code": null, "e": 24869, "s": 24858, "text": "Example: " }, { "code": null, "e": 25000, "s": 24869, "text": "Input: n = 4, e = 6 0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3 Output: DFS from vertex 1 : 1 2 0 3 Explanation: DFS Diagram: " }, { "code": null, "e": 25131, "s": 25000, "text": "Input: n = 4, e = 6 2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3 Output: DFS from vertex 2 : 2 0 1 3 Explanation: DFS Diagram: " }, { "code": null, "e": 25216, "s": 25133, "text": "The recursive implementation of DFS is already discussed: previous post. Solution:" }, { "code": null, "e": 25916, "s": 25216, "text": "Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally print the nodes in the path. The only difference between iterative DFS and recursive DFS is that the recursive stack is replaced by a stack of nodes." }, { "code": null, "e": 26188, "s": 25916, "text": "Algorithm: Created a stack of nodes and visited array.Insert the root in the stack.Run a loop till the stack is not empty.Pop the element from the stack and print the element.For every adjacent and unvisited node of current node, mark the node and insert it in the stack." }, { "code": null, "e": 26449, "s": 26188, "text": "Created a stack of nodes and visited array.Insert the root in the stack.Run a loop till the stack is not empty.Pop the element from the stack and print the element.For every adjacent and unvisited node of current node, mark the node and insert it in the stack." }, { "code": null, "e": 26493, "s": 26449, "text": "Created a stack of nodes and visited array." }, { "code": null, "e": 26523, "s": 26493, "text": "Insert the root in the stack." }, { "code": null, "e": 26563, "s": 26523, "text": "Run a loop till the stack is not empty." }, { "code": null, "e": 26617, "s": 26563, "text": "Pop the element from the stack and print the element." }, { "code": null, "e": 26714, "s": 26617, "text": "For every adjacent and unvisited node of current node, mark the node and insert it in the stack." }, { "code": null, "e": 26822, "s": 26714, "text": "Implementation of Iterative DFS: This is similar to BFS, the only difference is queue is replaced by stack." }, { "code": null, "e": 26826, "s": 26822, "text": "C++" }, { "code": null, "e": 26831, "s": 26826, "text": "Java" }, { "code": null, "e": 26839, "s": 26831, "text": "Python3" }, { "code": null, "e": 26842, "s": 26839, "text": "C#" }, { "code": null, "e": 26853, "s": 26842, "text": "Javascript" }, { "code": "// An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices list<int> *adj; // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph void DFS(int s); // prints all vertices in DFS manner // from a given source.}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // prints all not yet visited vertices reachable from svoid Graph::DFS(int s){ // Initially mark all vertices as not visited vector<bool> visited(V, false); // Create a stack for DFS stack<int> stack; // Push the current source node. stack.push(s); while (!stack.empty()) { // Pop a vertex from stack and print it int s = stack.top(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (!visited[s]) { cout << s << \" \"; visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (auto i = adj[s].begin(); i != adj[s].end(); ++i) if (!visited[*i]) stack.push(*i); }} // Driver program to test methods of graph classint main(){ Graph g(5); // Total 5 vertices in graph g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); cout << \"Following is Depth First Traversal\\n\"; g.DFS(0); return 0;}", "e": 28703, "s": 26853, "text": null }, { "code": "//An Iterative Java program to do DFS traversal from//a given source vertex. DFS(int s) traverses vertices//reachable from s. import java.util.*; public class GFG{ // This class represents a directed graph using adjacency // list representation static class Graph { int V; //Number of Vertices LinkedList<Integer>[] adj; // adjacency lists //Constructor Graph(int V) { this.V = V; adj = new LinkedList[V]; for (int i = 0; i < adj.length; i++) adj[i] = new LinkedList<Integer>(); } //To add an edge to graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s void DFS(int s) { // Initially mark all vertices as not visited Vector<Boolean> visited = new Vector<Boolean>(V); for (int i = 0; i < V; i++) visited.add(false); // Create a stack for DFS Stack<Integer> stack = new Stack<>(); // Push the current source node stack.push(s); while(stack.empty() == false) { // Pop a vertex from stack and print it s = stack.peek(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited.get(s) == false) { System.out.print(s + \" \"); visited.set(s, true); } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. Iterator<Integer> itr = adj[s].iterator(); while (itr.hasNext()) { int v = itr.next(); if(!visited.get(v)) stack.push(v); } } } } // Driver program to test methods of graph class public static void main(String[] args) { // Total 5 vertices in graph Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); System.out.println(\"Following is the Depth First Traversal\"); g.DFS(0); }}", "e": 31353, "s": 28703, "text": null }, { "code": "# An Iterative Python program to do DFS traversal from# a given source vertex. DFS(int s) traverses vertices# reachable from s. # This class represents a directed graph using adjacency# list representationclass Graph: def __init__(self,V): # Constructor self.V = V # No. of vertices self.adj = [[] for i in range(V)] # adjacency lists def addEdge(self,v, w): # to add an edge to graph self.adj[v].append(w) # Add w to v’s list. # prints all not yet visited vertices reachable from s def DFS(self,s): # prints all vertices in DFS manner from a given source. # Initially mark all vertices as not visited visited = [False for i in range(self.V)] # Create a stack for DFS stack = [] # Push the current source node. stack.append(s) while (len(stack)): # Pop a vertex from stack and print it s = stack[-1] stack.pop() # Stack may contain same vertex twice. So # we need to print the popped item only # if it is not visited. if (not visited[s]): print(s,end=' ') visited[s] = True # Get all adjacent vertices of the popped vertex s # If a adjacent has not been visited, then push it # to the stack. for node in self.adj[s]: if (not visited[node]): stack.append(node) # Driver program to test methods of graph class g = Graph(5); # Total 5 vertices in graphg.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4); print(\"Following is Depth First Traversal\")g.DFS(0) # This code is contributed by ankush_953", "e": 33104, "s": 31353, "text": null }, { "code": "// An Iterative C# program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.using System;using System.Collections.Generic; class GFG{ // This class represents a directed graph using adjacency // list representation public class Graph { public int V; // Number of Vertices public LinkedList<int>[] adj; // adjacency lists // Constructor public Graph(int V) { this.V = V; adj = new LinkedList<int>[V]; for (int i = 0; i < adj.Length; i++) adj[i] = new LinkedList<int>(); } // To add an edge to graph public void addEdge(int v, int w) { adj[v].AddLast(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s public void DFS(int s) { // Initially mark all vertices as not visited Boolean []visited = new Boolean[V]; // Create a stack for DFS Stack<int> stack = new Stack<int>(); // Push the current source node stack.Push(s); while(stack.Count > 0) { // Pop a vertex from stack and print it s = stack.Peek(); stack.Pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { Console.Write(s + \" \"); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. foreach(int v in adj[s]) { if(!visited[v]) stack.Push(v); } } } } // Driver code public static void Main(String []args) { // Total 5 vertices in graph Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(1, 4); Console.Write(\"Following is the Depth First Traversal\\n\"); g.DFS(0); }} // This code is contributed by Arnasb Kundu", "e": 35611, "s": 33104, "text": null }, { "code": "<script> // An Iterative Javascript program to// do DFS traversal from a given source// vertex. DFS(int s) traverses vertices// reachable from s. // This class represents a directed graph// using adjacency list representationclass Graph{ constructor(V){ this.V = V; this.adj = new Array(V); for(let i = 0; i < this.adj.length; i++) this.adj[i] = [];} // To add an edge to graphaddEdge(v, w){ // Add w to v’s list. this.adj[v].push(w);} // Prints all not yet visited// vertices reachable from sDFS(s){ // Initially mark all vertices as not visited let visited = []; for(let i = 0; i < this.V; i++) visited.push(false); // Create a stack for DFS let stack = []; // Push the current source node stack.push(s); while(stack.length != 0) { // Pop a vertex from stack and print it s = stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (visited[s] == false) { document.write(s + \" \"); visited[s] = true; } // Get all adjacent vertices of the // popped vertex s. If a adjacent has // not been visited, then push it // to the stack. for(let node = 0; node < this.adj[s].length; node++) { if (!visited[this.adj[s][node]]) stack.push(this.adj[s][node]) } }}} // Driver code // Total 5 vertices in graphlet g = new Graph(5);g.addEdge(1, 0);g.addEdge(0, 2);g.addEdge(2, 1);g.addEdge(0, 3);g.addEdge(1, 4); document.write(\"Following is the Depth \" + \"First Traversal<br>\");g.DFS(0); // This code is contributed by rag2127 </script>", "e": 37419, "s": 35611, "text": null }, { "code": null, "e": 37428, "s": 37419, "text": "Output: " }, { "code": null, "e": 37473, "s": 37428, "text": "Following is Depth First Traversal\n0 3 2 1 4" }, { "code": null, "e": 37671, "s": 37473, "text": "Complexity Analysis: Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.Space Complexity: O(V). Since an extra visited array is needed of size V." }, { "code": null, "e": 37775, "s": 37671, "text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph." }, { "code": null, "e": 37849, "s": 37775, "text": "Space Complexity: O(V). Since an extra visited array is needed of size V." }, { "code": null, "e": 38146, "s": 37849, "text": "Modification of the above Solution: Note that the above implementation prints only vertices that are reachable from a given vertex. For example, if the edges 0-3 and 0-2 are removed, then the above program would only print 0. To print all vertices of a graph, call DFS for every unvisited vertex." }, { "code": null, "e": 38164, "s": 38146, "text": "Implementation: " }, { "code": null, "e": 38168, "s": 38164, "text": "C++" }, { "code": null, "e": 38173, "s": 38168, "text": "Java" }, { "code": null, "e": 38181, "s": 38173, "text": "Python3" }, { "code": null, "e": 38184, "s": 38181, "text": "C#" }, { "code": null, "e": 38195, "s": 38184, "text": "Javascript" }, { "code": "// An Iterative C++ program to do DFS traversal from// a given source vertex. DFS(int s) traverses vertices// reachable from s.#include<bits/stdc++.h>using namespace std; // This class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices list<int> *adj; // adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph void DFS(); // prints all vertices in DFS manner // prints all not yet visited vertices reachable from s void DFSUtil(int s, vector<bool> &visited);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // prints all not yet visited vertices reachable from svoid Graph::DFSUtil(int s, vector<bool> &visited){ // Create a stack for DFS stack<int> stack; // Push the current source node. stack.push(s); while (!stack.empty()) { // Pop a vertex from stack and print it int s = stack.top(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (!visited[s]) { cout << s << \" \"; visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (auto i = adj[s].begin(); i != adj[s].end(); ++i) if (!visited[*i]) stack.push(*i); }} // prints all vertices in DFS mannervoid Graph::DFS(){ // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited);} // Driver program to test methods of graph classint main(){ Graph g(5); // Total 5 vertices in graph g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); cout << \"Following is Depth First Traversal\\n\"; g.DFS(); return 0;}", "e": 40264, "s": 38195, "text": null }, { "code": "//An Iterative Java program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s. import java.util.*; public class GFG{ // This class represents a directed graph using adjacency // list representation static class Graph { int V; //Number of Vertices LinkedList<Integer>[] adj; // adjacency lists //Constructor Graph(int V) { this.V = V; adj = new LinkedList[V]; for (int i = 0; i < adj.length; i++) adj[i] = new LinkedList<Integer>(); } //To add an edge to graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s void DFSUtil(int s, Vector<Boolean> visited) { // Create a stack for DFS Stack<Integer> stack = new Stack<>(); // Push the current source node stack.push(s); while(stack.empty() == false) { // Pop a vertex from stack and print it s = stack.peek(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited.get(s) == false) { System.out.print(s + \" \"); visited.set(s, true); } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. Iterator<Integer> itr = adj[s].iterator(); while (itr.hasNext()) { int v = itr.next(); if(!visited.get(v)) stack.push(v); } } } // prints all vertices in DFS manner void DFS() { Vector<Boolean> visited = new Vector<Boolean>(V); // Mark all the vertices as not visited for (int i = 0; i < V; i++) visited.add(false); for (int i = 0; i < V; i++) if (!visited.get(i)) DFSUtil(i, visited); } } // Driver program to test methods of graph class public static void main(String[] args) { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); System.out.println(\"Following is Depth First Traversal\"); g.DFS(); }}", "e": 43068, "s": 40264, "text": null }, { "code": "# An Iterative Python3 program to do DFS# traversal from a given source vertex.# DFS(s) traverses vertices reachable from s.class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def addEdge(self, v, w): self.adj[v].append(w) # Add w to v’s list. # prints all not yet visited vertices # reachable from s def DFSUtil(self, s, visited): # Create a stack for DFS stack = [] # Push the current source node. stack.append(s) while (len(stack) != 0): # Pop a vertex from stack and print it s = stack.pop() # Stack may contain same vertex twice. # So we need to print the popped item only # if it is not visited. if (not visited[s]): print(s, end = \" \") visited[s] = True # Get all adjacent vertices of the # popped vertex s. If a adjacent has not # been visited, then push it to the stack. i = 0 while i < len(self.adj[s]): if (not visited[self.adj[s][i]]): stack.append(self.adj[s][i]) i += 1 # prints all vertices in DFS manner def DFS(self): # Mark all the vertices as not visited visited = [False] * self.V for i in range(self.V): if (not visited[i]): self.DFSUtil(i, visited) # Driver Codeif __name__ == '__main__': g = Graph(5) # Total 5 vertices in graph g.addEdge(1, 0) g.addEdge(2, 1) g.addEdge(3, 4) g.addEdge(4, 0) print(\"Following is Depth First Traversal\") g.DFS() # This code is contributed by PranchalK", "e": 44819, "s": 43068, "text": null }, { "code": "// An Iterative C# program to do DFS traversal from// a given source vertex. DFS() traverses vertices// reachable from s.using System;using System.Collections.Generic; class GFG{ // This class represents a directed graph using adjacency // list representation class Graph { public int V; // Number of Vertices public List<int>[] adj; // adjacency lists // Constructor public Graph(int V) { this.V = V; adj = new List<int>[V]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); } // To add an edge to graph public void addEdge(int v, int w) { adj[v].Add(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s public void DFSUtil(int s, List<Boolean> visited) { // Create a stack for DFS Stack<int> stack = new Stack<int>(); // Push the current source node stack.Push(s); while(stack.Count != 0) { // Pop a vertex from stack and print it s = stack.Peek(); stack.Pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { Console.Write(s + \" \"); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. foreach(int itr in adj[s]) { int v = itr; if(!visited[v]) stack.Push(v); } } } // prints all vertices in DFS manner public void DFS() { List<Boolean> visited = new List<Boolean>(V); // Mark all the vertices as not visited for (int i = 0; i < V; i++) visited.Add(false); for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited); } } // Driver code public static void Main(String[] args) { Graph g = new Graph(5); g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); g.addEdge(4, 0); Console.WriteLine(\"Following is Depth First Traversal\"); g.DFS(); }} // This code is contributed by 29AjayKumar", "e": 47563, "s": 44819, "text": null }, { "code": "<script>//An Iterative Javascript program to do DFS traversal from//a given source vertex. DFS() traverses vertices//reachable from s. // This class represents a directed graph using adjacency // list representationclass Graph{ //Constructor constructor(V) { this.V=V; this.adj = new Array(V); for (let i = 0; i < this.adj.length; i++) this.adj[i] = []; } //To add an edge to graph addEdge(v,w) { this.adj[v].push(w); // Add w to v’s list. } // prints all not yet visited vertices reachable from s DFSUtil(s,visited) { // Create a stack for DFS let stack = []; // Push the current source node stack.push(s); while(stack.length != 0) { // Pop a vertex from stack and print it s = stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if(visited[s] == false) { document.write(s + \" \"); visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then push it // to the stack. for (let itr=0;itr<this.adj[s].length;itr++) { let v = this.adj[s][itr]; if(!visited[v]) stack.push(v); } } } // prints all vertices in DFS manner DFS() { let visited = [] // Mark all the vertices as not visited for (let i = 0; i < this.V; i++) visited.push(false); for (let i = 0; i < this.V; i++) if (!visited[i]) this.DFSUtil(i, visited); } } // Driver program to test methods of graph classlet g = new Graph(5);g.addEdge(1, 0);g.addEdge(2, 1);g.addEdge(3, 4);g.addEdge(4, 0); document.write(\"Following is Depth First Traversal<br>\");g.DFS(); // This code is contributed by avanitrachhadiya2155</script>", "e": 49910, "s": 47563, "text": null }, { "code": null, "e": 49919, "s": 49910, "text": "Output: " }, { "code": null, "e": 49964, "s": 49919, "text": "Following is Depth First Traversal\n0 1 2 3 4" }, { "code": null, "e": 50052, "s": 49964, "text": "Like recursive traversal, the time complexity of iterative implementation is O(V + E). " }, { "code": null, "e": 50217, "s": 50052, "text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50233, "s": 50217, "text": "PranchalKatiyar" }, { "code": null, "e": 50244, "s": 50233, "text": "ankush_953" }, { "code": null, "e": 50257, "s": 50244, "text": "the_alphaEye" }, { "code": null, "e": 50268, "s": 50257, "text": "nidhi_biet" }, { "code": null, "e": 50279, "s": 50268, "text": "andrew1234" }, { "code": null, "e": 50291, "s": 50279, "text": "29AjayKumar" }, { "code": null, "e": 50306, "s": 50291, "text": "abhinavgalodha" }, { "code": null, "e": 50325, "s": 50306, "text": "ashishkaushik53552" }, { "code": null, "e": 50333, "s": 50325, "text": "rag2127" }, { "code": null, "e": 50354, "s": 50333, "text": "avanitrachhadiya2155" }, { "code": null, "e": 50367, "s": 50354, "text": "vishalthoke2" }, { "code": null, "e": 50382, "s": 50367, "text": "varshagumber28" }, { "code": null, "e": 50395, "s": 50382, "text": "Kirti_Mangal" }, { "code": null, "e": 50399, "s": 50395, "text": "DFS" }, { "code": null, "e": 50405, "s": 50399, "text": "Graph" }, { "code": null, "e": 50411, "s": 50405, "text": "Stack" }, { "code": null, "e": 50417, "s": 50411, "text": "Stack" }, { "code": null, "e": 50421, "s": 50417, "text": "DFS" }, { "code": null, "e": 50427, "s": 50421, "text": "Graph" }, { "code": null, "e": 50525, "s": 50427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50534, "s": 50525, "text": "Comments" }, { "code": null, "e": 50547, "s": 50534, "text": "Old Comments" }, { "code": null, "e": 50605, "s": 50547, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 50625, "s": 50605, "text": "Topological Sorting" }, { "code": null, "e": 50658, "s": 50625, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 50689, "s": 50658, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 50722, "s": 50689, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 50770, "s": 50722, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 50790, "s": 50770, "text": "Stack Class in Java" }, { "code": null, "e": 50806, "s": 50790, "text": "Stack in Python" }, { "code": null, "e": 50881, "s": 50806, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Data Visualization in Pandas. Quick data visualization using only... | by C K | Towards Data Science
In this article, I will demonstrate how to visualize data using only Pandas. It is not as flexible as Matplotlib or Seaborn, but it is very convenient for quick data exploration. First, let’s import pandas and load Iris dataset as an example. import pandas as pdimport seaborndf=seaborn.load_dataset('iris') and check the dataframe It contains 4 numerical columns and one categorical column. Let’s start with the simple line plot. It plots the numerical columns in different colors. The x-axis here is the index. You can also customize the plot, for example, if you only want to see sepal_length and sepal_width, you can do this: You can also change the axis. For example, plot sepal_length against petal_length (does not make sense here to use line plot though) The proper plot to show the relationship between sepal_length and petal_length should be a scatter plot. You can plot for different columns by replacing x and y. One trick to check the correlations for all the numerical columns is to plot the scatter plot matrix. You can do it by: It shows a matrix of scatter plots of different columns against others and histograms of the columns. The histogram is a useful plot to see the distribution of data, in Pandas you can quickly plot it using hist() It shows the histograms of the numerical variables. You can also plot the columns you want. Another useful plot the see the data distribution is the box plot. You can simply plot it by using df.plot.box() You might also want to compare different species, you can do this by combining pandas groupby() and plot.bar() It shows the mean value of the columns against species. It is also possible to plot a bar chart. Simply call plot.pie() . Please be noted that the plot() function in Pandas is built on top of Matplotlib, so you can always use matplotlib to modify the plot. For example, you can change the location of legend and hide the ylabel. That’s it. These plotting techniques in Pandas might not be as flexible and report-ready as matplotlib or seaborn, but they are still quite convenient in the early stage data exploration. Thanks for reading. You can check my other articles about Pandas, Numpy and Python.
[ { "code": null, "e": 351, "s": 172, "text": "In this article, I will demonstrate how to visualize data using only Pandas. It is not as flexible as Matplotlib or Seaborn, but it is very convenient for quick data exploration." }, { "code": null, "e": 415, "s": 351, "text": "First, let’s import pandas and load Iris dataset as an example." }, { "code": null, "e": 480, "s": 415, "text": "import pandas as pdimport seaborndf=seaborn.load_dataset('iris')" }, { "code": null, "e": 504, "s": 480, "text": "and check the dataframe" }, { "code": null, "e": 564, "s": 504, "text": "It contains 4 numerical columns and one categorical column." }, { "code": null, "e": 603, "s": 564, "text": "Let’s start with the simple line plot." }, { "code": null, "e": 802, "s": 603, "text": "It plots the numerical columns in different colors. The x-axis here is the index. You can also customize the plot, for example, if you only want to see sepal_length and sepal_width, you can do this:" }, { "code": null, "e": 935, "s": 802, "text": "You can also change the axis. For example, plot sepal_length against petal_length (does not make sense here to use line plot though)" }, { "code": null, "e": 1040, "s": 935, "text": "The proper plot to show the relationship between sepal_length and petal_length should be a scatter plot." }, { "code": null, "e": 1097, "s": 1040, "text": "You can plot for different columns by replacing x and y." }, { "code": null, "e": 1217, "s": 1097, "text": "One trick to check the correlations for all the numerical columns is to plot the scatter plot matrix. You can do it by:" }, { "code": null, "e": 1319, "s": 1217, "text": "It shows a matrix of scatter plots of different columns against others and histograms of the columns." }, { "code": null, "e": 1430, "s": 1319, "text": "The histogram is a useful plot to see the distribution of data, in Pandas you can quickly plot it using hist()" }, { "code": null, "e": 1522, "s": 1430, "text": "It shows the histograms of the numerical variables. You can also plot the columns you want." }, { "code": null, "e": 1635, "s": 1522, "text": "Another useful plot the see the data distribution is the box plot. You can simply plot it by using df.plot.box()" }, { "code": null, "e": 1746, "s": 1635, "text": "You might also want to compare different species, you can do this by combining pandas groupby() and plot.bar()" }, { "code": null, "e": 1802, "s": 1746, "text": "It shows the mean value of the columns against species." }, { "code": null, "e": 1868, "s": 1802, "text": "It is also possible to plot a bar chart. Simply call plot.pie() ." }, { "code": null, "e": 2003, "s": 1868, "text": "Please be noted that the plot() function in Pandas is built on top of Matplotlib, so you can always use matplotlib to modify the plot." }, { "code": null, "e": 2075, "s": 2003, "text": "For example, you can change the location of legend and hide the ylabel." }, { "code": null, "e": 2263, "s": 2075, "text": "That’s it. These plotting techniques in Pandas might not be as flexible and report-ready as matplotlib or seaborn, but they are still quite convenient in the early stage data exploration." }, { "code": null, "e": 2283, "s": 2263, "text": "Thanks for reading." } ]
Getting current time from NTP Servers
In IoT devices, the timestamp becomes an important attribute of the packet exchanged between the device and the server. Therefore, it is necessary to have the correct time on your device at all times. One way is to use an RTC (Real Time Clock) interfaced with your ESP32. You can even use ESP32's internal RTC. Once given a reference time, it can correctly output future timestamps. But how will you get the reference time? One way is to hardcode the current time while programming the ESP32. But that is not a neat method. Secondly, the RTC is prone to drift and it is a good idea to keep providing it with reference timestamps regularly. In this chapter, we will see how to get the current time from NTP Servers, feed it to ESP32's internal RTC once, and print future timestamps. NTP stands for Network Time Protocol. It is a protocol for clock synchronization between computer systems. In layperson terms, there is a server sitting somewhere which maintains time accurately. Whenever a client requests the current time from the NTP server, it sends back time accurate up to 100s of milliseconds. You can read more about NTP here. For ESP32, there is an in−built time library that handles all the communication with the NTP servers. Let's explore the use of that library in the code walkthrough below. We will use an in−built example for this walkthrough. It can be found in File −> Examples −> ESP32 −> Time −> SimpleTime. It can also be found on GitHub. We begin with the inclusion of the WiFi and the time libraries. #include <WiFi.h> #include "time.h" Next, we define some global variables. Replace the WiFi SSID and password with the corresponding values for your WiFi. Next, we have defined the URL for the NTP Server. The gmtOffset_sec refers to the offset in seconds of your timezone from the GMT or the closely related UTC. For instance, in India, where the timezone is 5 hours and 30 mins ahead of the UTC, the gmtOffset_sec will be (5+0.5)*3600 = 19800. The daylightOffset_sec is relevant for countries that have daylight savings. It can simply be set to 0 in other countries. const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASS"; const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 3600; const int daylightOffset_sec = 3600; Next, you can see a function printLocalTime(). It simply fetches the local time from the internal RTC and prints it to serial. void printLocalTime() { struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); return; } Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); } You might be having three questions here − Where is the struct tm defined? Where is the getLocalTime() function defined? What are the %A, %B, etc. formatters? The struct tm is defined in the time.h file that we have included at the top. In fact, the time library is not an ESP32 specific library. It is an AVR library that is compatible to ESP32. You can find the source code at here. If you look at the time.h file, you will see the struct tm. struct tm { int8_t tm_sec; /**< seconds after the minute - [ 0 to 59 ] */ int8_t tm_min; /**< minutes after the hour - [ 0 to 59 ] */ int8_t tm_hour; /**< hours since midnight - [ 0 to 23 ] */ int8_t tm_mday; /**< day of the month - [ 1 to 31 ] */ int8_t tm_wday; /**< days since Sunday - [ 0 to 6 ] */ int8_t tm_mon; /**< months since January - [ 0 to 11 ] */ int16_t tm_year; /**< years since 1900 */ int16_t tm_yday; /**< days since January 1 - [ 0 to 365 ] */ int16_t tm_isdst; /**< Daylight Saving Time flag */ }; Now, the getLocalTime function is ESP32 specific. It is defined in the esp32−hal−time.c file. It is a part of the Arduino core for ESP32 and doesn't need a separate include in Arduino. You can see the source code here. Now, the meaning of the formatters is given below − /* %a Abbreviated weekday name %A Full weekday name %b Abbreviated month name %B Full month name %c Date and time representation for your locale %d Day of month as a decimal number (01−31) %H Hour in 24-hour format (00−23) %I Hour in 12-hour format (01−12) %j Day of year as decimal number (001−366) %m Month as decimal number (01−12) %M Minute as decimal number (00−59) %p Current locale's A.M./P.M. indicator for 12−hour clock %S Second as decimal number (00−59) %U Week of year as decimal number, Sunday as first day of week (00−51) %w Weekday as decimal number (0−6; Sunday is 0) %W Week of year as decimal number, Monday as first day of week (00−51) %x Date representation for current locale %X Time representation for current locale %y Year without century, as decimal number (00−99) %Y Year with century, as decimal number %z %Z Time-zone name or abbreviation, (no characters if time zone is unknown) %% Percent sign You can include text literals (such as spaces and colons) to make a neater display or for padding between adjoining columns. You can suppress the display of leading zeroes by using the "#" character (%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y) */ Thus, with our formatting scheme of %A, %B %d %Y %H:%M:%S, we can expect the output to be similar to the following: Sunday, November 15 2020 14:51:30. Now, coming to the setup and the loop. In the setup, we initialize Serial, connect to the internet using our WiFi, and configure the internal RTC of ESP32 using the configTime() function. As you can see, that function takes in three arguments, the gmtOffset, the daylightOffset and the ntpServer. It will fetch the time from ntpServer in UTC, apply the gmtOffset and the daylightOffset locally, and return the output time. This function, like getLocalTime, is defined in the esp32-hal-time.c file. As you can see from the file, TCP/IP protocol is used for fetching time from the NTP server. Once we've obtained the time from the NTP server and fed it to the internal RTC of the ESP32, we no longer need WiFi. Thus, We disconnect the WiFi and keep printing time in the loop every second. You can see on the serial monitor that the time gets incremented by one second in every print. This is because the internal RTC of ESP32 maintains the time once it got the reference. void setup() { Serial.begin(115200); //connect to WiFi Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" CONNECTED"); //init and get the time configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); printLocalTime(); //disconnect WiFi as it's no longer needed WiFi.disconnect(true); WiFi.mode(WIFI_OFF); } void loop() { delay(1000); printLocalTime(); } The Serial Monitor output will look like − That's it. You've learned how to get the correct time from the NTP servers and configure your ESP32's internal RTC. Now, in whatever packets you send to the server, you can add the timestamp. Network Time Protocol - Wikipedia Network Time Protocol - Wikipedia 54 Lectures 4.5 hours Frahaan Hussain 20 Lectures 5 hours Azaz Patel 20 Lectures 4 hours Azaz Patel 0 Lectures 0 mins Eduonix Learning Solutions 169 Lectures 12.5 hours Kalob Taulien 29 Lectures 2 hours Zenva Print Add Notes Bookmark this page
[ { "code": null, "e": 2966, "s": 2183, "text": "In IoT devices, the timestamp becomes an important attribute of the packet exchanged between the device and the server. Therefore, it is necessary to have the correct time on your device at all times. One way is to use an RTC (Real Time Clock) interfaced with your ESP32. You can even use ESP32's internal RTC. Once given a reference time, it can correctly output future timestamps. But how will you get the reference time? One way is to hardcode the current time while programming the ESP32. But that is not a neat method. Secondly, the RTC is prone to drift and it is a good idea to keep providing it with reference timestamps regularly. In this chapter, we will see how to get the current time from NTP Servers, feed it to ESP32's internal RTC once, and print future timestamps. " }, { "code": null, "e": 3488, "s": 2966, "text": "NTP stands for Network Time Protocol. It is a protocol for clock synchronization between computer systems. In layperson terms, there is a server sitting somewhere which maintains time accurately. Whenever a client requests the current time from the NTP server, it sends back time accurate up to 100s of milliseconds. You can read more about NTP here.\nFor ESP32, there is an in−built time library that handles all the communication with the NTP servers. Let's explore the use of that library in the code walkthrough below." }, { "code": null, "e": 3642, "s": 3488, "text": "We will use an in−built example for this walkthrough. It can be found in File −> Examples −> ESP32 −> Time −> SimpleTime. It can also be found on GitHub." }, { "code": null, "e": 3706, "s": 3642, "text": "We begin with the inclusion of the WiFi and the time libraries." }, { "code": null, "e": 3742, "s": 3706, "text": "#include <WiFi.h>\n#include \"time.h\"" }, { "code": null, "e": 4151, "s": 3742, "text": "Next, we define some global variables. Replace the WiFi SSID and password with the corresponding values for your WiFi. Next, we have defined the URL for the NTP Server. The gmtOffset_sec refers to the offset in seconds of your timezone from the GMT or the closely related UTC. For instance, in India, where the timezone is 5 hours and 30 mins ahead of the UTC, the gmtOffset_sec will be (5+0.5)*3600 = 19800." }, { "code": null, "e": 4275, "s": 4151, "text": "The daylightOffset_sec is relevant for countries that have daylight savings. It can simply be set to 0 in other countries. " }, { "code": null, "e": 4465, "s": 4275, "text": "const char* ssid = \"YOUR_SSID\";\nconst char* password = \"YOUR_PASS\";\n\nconst char* ntpServer = \"pool.ntp.org\";\nconst long gmtOffset_sec = 3600;\nconst int daylightOffset_sec = 3600;" }, { "code": null, "e": 4592, "s": 4465, "text": "Next, you can see a function printLocalTime(). It simply fetches the local time from the internal RTC and prints it to serial." }, { "code": null, "e": 4795, "s": 4592, "text": "void printLocalTime()\n{\n struct tm timeinfo;\n if(!getLocalTime(&timeinfo)){\n Serial.println(\"Failed to obtain time\");\n return;\n }\n Serial.println(&timeinfo, \"%A, %B %d %Y %H:%M:%S\");\n}" }, { "code": null, "e": 4838, "s": 4795, "text": "You might be having three questions here −" }, { "code": null, "e": 4870, "s": 4838, "text": "Where is the struct tm defined?" }, { "code": null, "e": 4916, "s": 4870, "text": "Where is the getLocalTime() function defined?" }, { "code": null, "e": 4954, "s": 4916, "text": "What are the %A, %B, etc. formatters?" }, { "code": null, "e": 5241, "s": 4954, "text": "The struct tm is defined in the time.h file that we have included at the top. In fact, the time library is not an ESP32 specific library. It is an AVR library that is compatible to ESP32. You can find the source code at here. If you look at the time.h file, you will see the struct tm. " }, { "code": null, "e": 5802, "s": 5241, "text": "struct tm {\n int8_t tm_sec; /**< seconds after the minute - [ 0 to 59 ] */\n int8_t tm_min; /**< minutes after the hour - [ 0 to 59 ] */\n int8_t tm_hour; /**< hours since midnight - [ 0 to 23 ] */\n int8_t tm_mday; /**< day of the month - [ 1 to 31 ] */\n int8_t tm_wday; /**< days since Sunday - [ 0 to 6 ] */\n int8_t tm_mon; /**< months since January - [ 0 to 11 ] */\n int16_t tm_year; /**< years since 1900 */\n int16_t tm_yday; /**< days since January 1 - [ 0 to 365 ] */\n int16_t tm_isdst; /**< Daylight Saving Time flag */\n};" }, { "code": null, "e": 6021, "s": 5802, "text": "Now, the getLocalTime function is ESP32 specific. It is defined in the esp32−hal−time.c file. It is a part of the Arduino core for ESP32 and doesn't need a separate include in Arduino. You can see the source code here." }, { "code": null, "e": 6074, "s": 6021, "text": " Now, the meaning of the formatters is given below −" }, { "code": null, "e": 7337, "s": 6074, "text": "/*\n %a Abbreviated weekday name\n %A Full weekday name\n %b Abbreviated month name\n %B Full month name\n %c Date and time representation for your locale\n %d Day of month as a decimal number (01−31)\n %H Hour in 24-hour format (00−23)\n %I Hour in 12-hour format (01−12)\n %j Day of year as decimal number (001−366)\n %m Month as decimal number (01−12)\n %M Minute as decimal number (00−59)\n %p Current locale's A.M./P.M. indicator for 12−hour clock\n %S Second as decimal number (00−59)\n %U Week of year as decimal number, Sunday as first day of week (00−51)\n %w Weekday as decimal number (0−6; Sunday is 0)\n %W Week of year as decimal number, Monday as first day of week (00−51)\n %x Date representation for current locale\n %X Time representation for current locale\n %y Year without century, as decimal number (00−99)\n %Y Year with century, as decimal number\n %z %Z Time-zone name or abbreviation, (no characters if time zone is unknown)\n %% Percent sign\n You can include text literals (such as spaces and colons) to make a neater display or for padding between adjoining columns.\n You can suppress the display of leading zeroes by using the \"#\" character (%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y)\n*/\n" }, { "code": null, "e": 7488, "s": 7337, "text": "Thus, with our formatting scheme of %A, %B %d %Y %H:%M:%S, we can expect the output to be similar to the following: Sunday, November 15 2020 14:51:30." }, { "code": null, "e": 8079, "s": 7488, "text": "Now, coming to the setup and the loop. In the setup, we initialize Serial, connect to the internet using our WiFi, and configure the internal RTC of ESP32 using the configTime() function. As you can see, that function takes in three arguments, the gmtOffset, the daylightOffset and the ntpServer. It will fetch the time from ntpServer in UTC, apply the gmtOffset and the daylightOffset locally,\nand return the output time. This function, like getLocalTime, is defined in the esp32-hal-time.c file. As\nyou can see from the file, TCP/IP protocol is used for fetching time from the NTP server." }, { "code": null, "e": 8458, "s": 8079, "text": "Once we've obtained the time from the NTP server and fed it to the internal RTC of the ESP32, we no longer need WiFi. Thus, We disconnect the WiFi and keep printing time in the loop every second. You can see on the serial monitor that the time gets incremented by one second in every print. This is because the internal RTC of ESP32 maintains the time once it got the reference." }, { "code": null, "e": 8984, "s": 8458, "text": "void setup()\n{\n Serial.begin(115200);\n \n //connect to WiFi\n Serial.printf(\"Connecting to %s \", ssid);\n WiFi.begin(ssid, password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n Serial.println(\" CONNECTED\");\n \n //init and get the time\n configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);\n printLocalTime();\n\n //disconnect WiFi as it's no longer needed\n WiFi.disconnect(true);\n WiFi.mode(WIFI_OFF);\n}\nvoid loop() {\n delay(1000);\n printLocalTime();\n}" }, { "code": null, "e": 9027, "s": 8984, "text": "The Serial Monitor output will look like −" }, { "code": null, "e": 9219, "s": 9027, "text": "That's it. You've learned how to get the correct time from the NTP servers and configure your ESP32's internal RTC. Now, in whatever packets you send to the server, you can add the timestamp." }, { "code": null, "e": 9253, "s": 9219, "text": "Network Time Protocol - Wikipedia" }, { "code": null, "e": 9287, "s": 9253, "text": "Network Time Protocol - Wikipedia" }, { "code": null, "e": 9322, "s": 9287, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9339, "s": 9322, "text": " Frahaan Hussain" }, { "code": null, "e": 9372, "s": 9339, "text": "\n 20 Lectures \n 5 hours \n" }, { "code": null, "e": 9384, "s": 9372, "text": " Azaz Patel" }, { "code": null, "e": 9417, "s": 9384, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 9429, "s": 9417, "text": " Azaz Patel" }, { "code": null, "e": 9459, "s": 9429, "text": "\n 0 Lectures \n 0 mins\n" }, { "code": null, "e": 9487, "s": 9459, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9524, "s": 9487, "text": "\n 169 Lectures \n 12.5 hours \n" }, { "code": null, "e": 9539, "s": 9524, "text": " Kalob Taulien" }, { "code": null, "e": 9572, "s": 9539, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 9579, "s": 9572, "text": " Zenva" }, { "code": null, "e": 9586, "s": 9579, "text": " Print" }, { "code": null, "e": 9597, "s": 9586, "text": " Add Notes" } ]
Use of _SYS_REPO in SAP HANA database
In SAP HANA system _SYS_REPO user is required to create run time objects that are saved in HANA database under _SYS_BIC schema. When you activate modeling views in HANA, SYS REPO provides the read access to users on these modeling views. That is why it is required to grant _SYS_REPO with SELECT with GRANT privilege to user schemas. GRANT SELECT ON SCHEMA "SCHEMA_NAME" TO _SYS_REPO WITH GRANT OPTION This is required when you use objects of a table/view of a schema to build HANA Modeling Views. You need to grant _SYS_REPO the SELECT WITH GRANT privilege on this schema.
[ { "code": null, "e": 1396, "s": 1062, "text": "In SAP HANA system _SYS_REPO user is required to create run time objects that are saved in HANA database under _SYS_BIC schema. When you activate modeling views in HANA, SYS REPO provides the read access to users on these modeling views. That is why it is required to grant _SYS_REPO with SELECT with GRANT privilege to user schemas." }, { "code": null, "e": 1464, "s": 1396, "text": "GRANT SELECT ON SCHEMA \"SCHEMA_NAME\" TO _SYS_REPO WITH GRANT OPTION" }, { "code": null, "e": 1636, "s": 1464, "text": "This is required when you use objects of a table/view of a schema to build HANA Modeling Views. You need to grant _SYS_REPO the SELECT WITH GRANT privilege on this schema." } ]
Special Stack | Practice | GeeksforGeeks
Design a data-structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. Your task is to complete all the functions, using stack data-Structure. Example 1: Input: Stack: 18 19 29 15 16 Output: 15 Explanation: The minimum element of the stack is 15. Your Task: Since this is a function problem, you don't need to take inputs. You just have to complete 5 functions, push() which takes the stack and an integer x as input and pushes it into the stack; pop() which takes the stack as input and pops out the topmost element from the stack; isEmpty() which takes the stack as input and returns true/false depending upon whether the stack is empty or not; isFull() which takes the stack and the size of the stack as input and returns true/false depending upon whether the stack is full or not (depending upon the given size); getMin() which takes the stack as input and returns the minimum element of the stack. Note: The output of the code will be the value returned by getMin() function. Expected Time Complexity: O(N) for getMin, O(1) for remaining all 4 functions. Expected Auxiliary Space: O(1) for all the 5 functions. Constraints: 1 ≤ N ≤ 104 0 amonk5 days ago #include<bits/stdc++.h> void push(stack<int>& s, int a){ // Your code goes here s.push(a); } bool isFull(stack<int>& s,int n){ // Your code goes here return s.size()==n; } bool isEmpty(stack<int>& s){ // Your code goes here return s.size()==0; } int pop(stack<int>& s){ // Your code goes here int x=s.top(); s.pop(); return x; } int getMin(stack<int>& s){ // Your code goes here int mn=INT_MAX; while(!s.empty()){ mn=min(s.top(),mn); s.pop(); } return mn; } 0 19059363 weeks ago void push(stack<int>& s, int a){s.push(a);} bool isFull(stack<int>& s,int n){if(s.size()==n){ return true;}else{ return false;}} bool isEmpty(stack<int>& s){if(s.empty()){ return true;}else{ return false;}} int pop(stack<int>& s){ s.pop();} int getMin(stack<int>& s){ //INT_MAX VALUE=2,147,483,647 or 1e9 //and for INT_MIN=-2,147,483,648 or -1e9int min=2147483647;if(s.size()==1){ min=s.top();}else{ while(!s.empty()){ if(s.top()<min){ min=s.top(); } s.pop(); }}return min;} 0 deepcsr43 weeks ago Java Code class GfG{ public void push(int a,Stack<Integer> s) { s.push(a); } public int pop(Stack<Integer> s) { return s.pop(); } public int min(Stack<Integer> s) { int m=pop(s); while(!isEmpty(s)){ int n=pop(s); if(n<m) m=n; } return m; } public boolean isFull(Stack<Integer>s, int n) { if (s.size() == n) { return true; } return false; } public boolean isEmpty(Stack<Integer> s) { return s.size() == 0; }} +1 amarrajsmart1971 month ago C++ Easy Solution time taken =0.0/1.4 sec.void push(stack<int>& s, int a){// Your code goes heres.push(a);} bool isFull(stack<int>& s,int n){// Your code goes hereif(s.size()==n)return true;return false;} bool isEmpty(stack<int>& s){// Your code goes hereif(s.empty())return true;return false;} int pop(stack<int>& s){// Your code goes heres.pop();} int getMin(stack<int>& s){// Your code goes hereint min_=10000;while(!s.empty()){if(s.top()<min_){ min_=s.top();}s.pop();}return min_;} 0 milindprajapatmst191 month ago Constant time and space solution Why does this work? Let us assume _min is the current minimum and x is the element that needs to be inserted into the stack. Let us say x is the new minimum element (x < _min) We push 2x - _min into the stack and update _min to x. Why do we push 2x - _min? Take this inequality (x < _min) Rearrange, x - _min < 0 Add x to both sides, 2x - _min < x, where x is the new minimum As you can see, 2x - _min, the element we will insert, will still be less than the new minimum element, x. So it does not affect the relative order of elements. Now let's see how this helps us retain the original elements. Let us assume _min is the current minimum and x is the element at the top. While we pop the element, we need to check whether the element at the top is the current minimum or not. If so, then we need to update the current minimum as well. Using inequality (2x - _min < x, where x is the new minimum), we know if the top element is less than the current minimum, then this is the current minimum that is being popped out of the stack. And we need to update the current minimum element. How can we do it? Remember, we pushed 2x - _min into the stack, where x is the new minimum, and _min is now the previous minimum. Rewriting, 2 _min - prev_min This is what we have on top, so we have its value. And hence prev_min can easily be calculated using, 2 _min - prev_min = top prev_min = 2 _min - top Implementation: int _min; void push(stack<int>& s, int a) { if (isEmpty(s)) { _min = a; s.push(a); } else if (a < _min) { s.push(2 * a - _min); _min = a; } else s.push(a); } bool isFull(stack<int>& s, int n) { return s.size() == n; } bool isEmpty(stack<int>& s) { return s.size() == 0; } int pop(stack<int>& s) { int top = s.top(); if (top < _min) _min = 2 * _min - top; s.pop(); } int getMin(stack<int>& s) { return _min; } 0 ravishraj121 month ago java solution: class GfG{ Stack<Integer> ss = new Stack<>();public void push(int a,Stack<Integer> s){ //add code here. s.push(a); if(ss.size()==0 || a<=ss.peek()) ss.push(a); return;}public int pop(Stack<Integer> s) { //add code here. if(s.size()==0) return -1; int ans = s.peek(); s.pop(); if(ss.peek() == ans) ss.pop(); return ans;}public int min(Stack<Integer> s) { //add code here. if(ss.size()==0) return -1; return ss.peek();}public boolean isFull(Stack<Integer>s, int n) { //add code here. return s.size()==n;}public boolean isEmpty(Stack<Integer>s) { //add code here. return s.size()==0;}} 0 shibombhowmik12091 month ago //based on constraints we can apply the below algo which //handles positive numbers only. int min1; void push(stack<int>& s, int a){ // Your code goes here if(s.empty()){ s.push(a); min1=a; } else if(a<=min1){ s.push(a-min1); min1=a; } else{ s.push(a); } } bool isFull(stack<int>& s,int n){ // Your code goes here return (s.size()==n); } bool isEmpty(stack<int>& s){ // Your code goes here return (s.empty()); } int pop(stack<int>& s){ // Your code goes here int t=s.top(); s.pop(); if(t<=0){ int res=min1; min1=min1-t; return res; } return t; } int getMin(stack<int>& s){ // Your code goes here return min1; } 0 shubhamnikum21311 month ago c++ solution void push(stack<int>& s, int a){// Your code goes heres.push(a);} bool isFull(stack<int>& s,int n){// Your code goes hereif(s.size()==n) return true;else return false;} bool isEmpty(stack<int>& s){// Your code goes hereif(s.empty()) return true;else return false;} int pop(stack<int>& s){// Your code goes here s.pop();} int getMin(stack<int>& s){// Your code goes hereint ans=10000;if(s.size()==1) ans=s.top();else{while(!s.empty()){if(s.top()<ans) ans=s.top();else s.pop(); }}return ans; } -2 sanketbhagat2 months ago SIMPLE JAVA SOLUTION class GfG{ public void push(int a,Stack<Integer> s){ //add code here. s.push(a); } public int pop(Stack<Integer> s){ //add code here. return s.pop(); } public int min(Stack<Integer> s){ //add code here. int min = Integer.MAX_VALUE; Stack<Integer> temp = new Stack<>(); while(!s.isEmpty()) temp.push(s.pop()); while(!temp.isEmpty()){ int curr = temp.pop(); min = Math.min(min,curr); s.push(curr); } return min; } public boolean isFull(Stack<Integer>s, int n){ //add code here. return s.size()==n; } public boolean isEmpty(Stack<Integer>s){ //add code here. return s.size()==0; } } 0 tirtha19025682 months ago class GfG{ public void push(int a,Stack<Integer> s) { s.push(a); } public int pop(Stack<Integer> s) { return s.pop(); } public int min(Stack<Integer> s) { int min = Integer.MAX_VALUE; Stack<Integer>stk = new Stack<>(); while(s.isEmpty()==false){ if(s.peek() < min){ min = s.peek(); } stk.push(s.pop()); } while(stk.isEmpty()==false){ s.push(stk.pop()); } return min; } public boolean isFull(Stack<Integer>s, int n) { if(s.size()<n) return false; return true; } public boolean isEmpty(Stack<Integer>s) { return s.isEmpty(); } } 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": 522, "s": 238, "text": "Design a data-structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. Your task is to complete all the functions, using stack data-Structure." }, { "code": null, "e": 534, "s": 522, "text": "\nExample 1:" }, { "code": null, "e": 628, "s": 534, "text": "Input:\nStack: 18 19 29 15 16\nOutput: 15\nExplanation:\nThe minimum element of the stack is 15.\n" }, { "code": null, "e": 1366, "s": 630, "text": "\nYour Task:\nSince this is a function problem, you don't need to take inputs. You just have to complete 5 functions, push() which takes the stack and an integer x as input and pushes it into the stack; pop() which takes the stack as input and pops out the topmost element from the stack; isEmpty() which takes the stack as input and returns true/false depending upon whether the stack is empty or not; isFull() which takes the stack and the size of the stack as input and returns true/false depending upon whether the stack is full or not (depending upon the\ngiven size); getMin() which takes the stack as input and returns the minimum element of the stack. \nNote: The output of the code will be the value returned by getMin() function." }, { "code": null, "e": 1502, "s": 1366, "text": "\nExpected Time Complexity: O(N) for getMin, O(1) for remaining all 4 functions.\nExpected Auxiliary Space: O(1) for all the 5 functions." }, { "code": null, "e": 1528, "s": 1502, "text": "\nConstraints:\n1 ≤ N ≤ 104" }, { "code": null, "e": 1530, "s": 1528, "text": "0" }, { "code": null, "e": 1546, "s": 1530, "text": "amonk5 days ago" }, { "code": null, "e": 2037, "s": 1546, "text": "#include<bits/stdc++.h>\nvoid push(stack<int>& s, int a){\n\t// Your code goes here\n\ts.push(a);\n}\n\nbool isFull(stack<int>& s,int n){\n\t// Your code goes here\n\treturn s.size()==n;\n}\n\nbool isEmpty(stack<int>& s){\n\t// Your code goes here\n\treturn s.size()==0;\n}\n\nint pop(stack<int>& s){\n\t// Your code goes here\n\tint x=s.top();\n\ts.pop();\n\treturn x;\n}\n\nint getMin(stack<int>& s){\n\t// Your code goes here\n\t\n\tint mn=INT_MAX;\n\t\n\twhile(!s.empty()){\n\t mn=min(s.top(),mn);\n\t s.pop();\n\t}\n\treturn mn;\n}" }, { "code": null, "e": 2039, "s": 2037, "text": "0" }, { "code": null, "e": 2058, "s": 2039, "text": "19059363 weeks ago" }, { "code": null, "e": 2102, "s": 2058, "text": "void push(stack<int>& s, int a){s.push(a);}" }, { "code": null, "e": 2193, "s": 2102, "text": "bool isFull(stack<int>& s,int n){if(s.size()==n){ return true;}else{ return false;}}" }, { "code": null, "e": 2277, "s": 2193, "text": "bool isEmpty(stack<int>& s){if(s.empty()){ return true;}else{ return false;}}" }, { "code": null, "e": 2313, "s": 2277, "text": "int pop(stack<int>& s){ s.pop();}" }, { "code": null, "e": 2591, "s": 2313, "text": "int getMin(stack<int>& s){ //INT_MAX VALUE=2,147,483,647 or 1e9 //and for INT_MIN=-2,147,483,648 or -1e9int min=2147483647;if(s.size()==1){ min=s.top();}else{ while(!s.empty()){ if(s.top()<min){ min=s.top(); } s.pop(); }}return min;}" }, { "code": null, "e": 2593, "s": 2591, "text": "0" }, { "code": null, "e": 2613, "s": 2593, "text": "deepcsr43 weeks ago" }, { "code": null, "e": 2623, "s": 2613, "text": "Java Code" }, { "code": null, "e": 2702, "s": 2625, "text": "class GfG{ public void push(int a,Stack<Integer> s) { s.push(a); }" }, { "code": null, "e": 2766, "s": 2702, "text": " public int pop(Stack<Integer> s) { return s.pop(); }" }, { "code": null, "e": 2939, "s": 2766, "text": " public int min(Stack<Integer> s) { int m=pop(s); while(!isEmpty(s)){ int n=pop(s); if(n<m) m=n; } return m; }" }, { "code": null, "e": 3074, "s": 2939, "text": " public boolean isFull(Stack<Integer>s, int n) { if (s.size() == n) { return true; } return false; }" }, { "code": null, "e": 3153, "s": 3074, "text": " public boolean isEmpty(Stack<Integer> s) { return s.size() == 0; }}" }, { "code": null, "e": 3156, "s": 3153, "text": "+1" }, { "code": null, "e": 3183, "s": 3156, "text": "amarrajsmart1971 month ago" }, { "code": null, "e": 3293, "s": 3183, "text": "C++ Easy Solution time taken =0.0/1.4 sec.void push(stack<int>& s, int a){// Your code goes heres.push(a);}" }, { "code": null, "e": 3390, "s": 3293, "text": "bool isFull(stack<int>& s,int n){// Your code goes hereif(s.size()==n)return true;return false;}" }, { "code": null, "e": 3480, "s": 3390, "text": "bool isEmpty(stack<int>& s){// Your code goes hereif(s.empty())return true;return false;}" }, { "code": null, "e": 3535, "s": 3480, "text": "int pop(stack<int>& s){// Your code goes heres.pop();}" }, { "code": null, "e": 3674, "s": 3535, "text": "int getMin(stack<int>& s){// Your code goes hereint min_=10000;while(!s.empty()){if(s.top()<min_){ min_=s.top();}s.pop();}return min_;}" }, { "code": null, "e": 3678, "s": 3676, "text": "0" }, { "code": null, "e": 3709, "s": 3678, "text": "milindprajapatmst191 month ago" }, { "code": null, "e": 5637, "s": 3709, "text": "Constant time and space solution\nWhy does this work?\nLet us assume _min is the current minimum and x is the element that needs to be inserted into the stack.\nLet us say x is the new minimum element (x < _min)\nWe push 2x - _min into the stack and update _min to x.\nWhy do we push 2x - _min?\nTake this inequality (x < _min)\nRearrange, x - _min < 0\nAdd x to both sides, 2x - _min < x, where x is the new minimum\nAs you can see, 2x - _min, the element we will insert, will still be less than the new minimum element, x. So it does not affect the relative order of elements.\nNow let's see how this helps us retain the original elements.\nLet us assume _min is the current minimum and x is the element at the top.\nWhile we pop the element, we need to check whether the element at the top is the current minimum or not. If so, then we need to update the current minimum as well.\nUsing inequality (2x - _min < x, where x is the new minimum), we know if the top element is less than the current minimum, then this is the current minimum that is being popped out of the stack. And we need to update the current minimum element.\nHow can we do it?\nRemember, we pushed 2x - _min into the stack, where x is the new minimum, and _min is now the previous minimum.\nRewriting, 2 _min - prev_min\nThis is what we have on top, so we have its value. And hence prev_min can easily be calculated using, \n2 _min - prev_min = top\nprev_min = 2 _min - top\n\nImplementation:\n\nint _min;\nvoid push(stack<int>& s, int a) {\n if (isEmpty(s)) {\n _min = a;\n s.push(a);\n }\n else if (a < _min) {\n s.push(2 * a - _min);\n _min = a;\n }\n else\n s.push(a);\n}\nbool isFull(stack<int>& s, int n) {\n\treturn s.size() == n;\n}\nbool isEmpty(stack<int>& s) {\n\treturn s.size() == 0;\n}\nint pop(stack<int>& s) {\n\tint top = s.top();\n\tif (top < _min)\n\t _min = 2 * _min - top;\n\ts.pop();\n}\nint getMin(stack<int>& s) {\n return _min;\n}" }, { "code": null, "e": 5639, "s": 5637, "text": "0" }, { "code": null, "e": 5662, "s": 5639, "text": "ravishraj121 month ago" }, { "code": null, "e": 5677, "s": 5662, "text": "java solution:" }, { "code": null, "e": 6475, "s": 5677, "text": "class GfG{ Stack<Integer> ss = new Stack<>();public void push(int a,Stack<Integer> s){ //add code here. s.push(a); if(ss.size()==0 || a<=ss.peek()) ss.push(a); return;}public int pop(Stack<Integer> s) { //add code here. if(s.size()==0) return -1; int ans = s.peek(); s.pop(); if(ss.peek() == ans) ss.pop(); return ans;}public int min(Stack<Integer> s) { //add code here. if(ss.size()==0) return -1; return ss.peek();}public boolean isFull(Stack<Integer>s, int n) { //add code here. return s.size()==n;}public boolean isEmpty(Stack<Integer>s) { //add code here. return s.size()==0;}}" }, { "code": null, "e": 6477, "s": 6475, "text": "0" }, { "code": null, "e": 6506, "s": 6477, "text": "shibombhowmik12091 month ago" }, { "code": null, "e": 7184, "s": 6506, "text": "//based on constraints we can apply the below algo which //handles positive numbers only.\n\nint min1;\n\nvoid push(stack<int>& s, int a){\n\t// Your code goes here\n\tif(s.empty()){\n\t s.push(a);\n\t min1=a;\n\t}\n\telse if(a<=min1){\n\t s.push(a-min1);\n\t min1=a;\n\t}\n\telse{\n\t s.push(a);\n\t}\n}\n\nbool isFull(stack<int>& s,int n){\n\t// Your code goes here\n\treturn (s.size()==n);\n}\n\nbool isEmpty(stack<int>& s){\n\t// Your code goes here\n\treturn (s.empty());\n}\n\nint pop(stack<int>& s){\n\t// Your code goes here\n\tint t=s.top();\n\ts.pop();\n\tif(t<=0){\n\t int res=min1;\n\t min1=min1-t;\n\t return res;\n\t}\n\t\n\treturn t;\n}\n\nint getMin(stack<int>& s){\n\t// Your code goes here\n\treturn min1;\n}" }, { "code": null, "e": 7186, "s": 7184, "text": "0" }, { "code": null, "e": 7214, "s": 7186, "text": "shubhamnikum21311 month ago" }, { "code": null, "e": 7227, "s": 7214, "text": "c++ solution" }, { "code": null, "e": 7295, "s": 7229, "text": "void push(stack<int>& s, int a){// Your code goes heres.push(a);}" }, { "code": null, "e": 7404, "s": 7295, "text": "bool isFull(stack<int>& s,int n){// Your code goes hereif(s.size()==n) return true;else return false;}" }, { "code": null, "e": 7506, "s": 7404, "text": "bool isEmpty(stack<int>& s){// Your code goes hereif(s.empty()) return true;else return false;}" }, { "code": null, "e": 7564, "s": 7506, "text": "int pop(stack<int>& s){// Your code goes here s.pop();}" }, { "code": null, "e": 7745, "s": 7564, "text": "int getMin(stack<int>& s){// Your code goes hereint ans=10000;if(s.size()==1) ans=s.top();else{while(!s.empty()){if(s.top()<ans) ans=s.top();else s.pop(); }}return ans;" }, { "code": null, "e": 7747, "s": 7745, "text": "}" }, { "code": null, "e": 7750, "s": 7747, "text": "-2" }, { "code": null, "e": 7775, "s": 7750, "text": "sanketbhagat2 months ago" }, { "code": null, "e": 7796, "s": 7775, "text": "SIMPLE JAVA SOLUTION" }, { "code": null, "e": 8536, "s": 7796, "text": "class GfG{\n\tpublic void push(int a,Stack<Integer> s){\n\t //add code here.\n\t s.push(a);\n\t}\n\tpublic int pop(Stack<Integer> s){\n //add code here.\n return s.pop();\n\t}\n\tpublic int min(Stack<Integer> s){\n //add code here.\n int min = Integer.MAX_VALUE;\n Stack<Integer> temp = new Stack<>();\n while(!s.isEmpty()) temp.push(s.pop());\n while(!temp.isEmpty()){\n int curr = temp.pop();\n min = Math.min(min,curr);\n s.push(curr);\n }\n return min;\n\t}\n\tpublic boolean isFull(Stack<Integer>s, int n){\n //add code here.\n return s.size()==n;\n\t}\n\tpublic boolean isEmpty(Stack<Integer>s){\n //add code here.\n return s.size()==0;\n\t}\n}" }, { "code": null, "e": 8538, "s": 8536, "text": "0" }, { "code": null, "e": 8564, "s": 8538, "text": "tirtha19025682 months ago" }, { "code": null, "e": 9329, "s": 8564, "text": "class GfG{\npublic void push(int a,Stack<Integer> s)\n{\n s.push(a);\n}\npublic int pop(Stack<Integer> s)\n {\n return s.pop();\n}\npublic int min(Stack<Integer> s)\n {\n int min = Integer.MAX_VALUE;\n Stack<Integer>stk = new Stack<>();\n while(s.isEmpty()==false){\n if(s.peek() < min){\n min = s.peek();\n }\n stk.push(s.pop());\n }\n \n while(stk.isEmpty()==false){\n s.push(stk.pop());\n }\n \n return min;\n}\npublic boolean isFull(Stack<Integer>s, int n)\n {\n if(s.size()<n) return false;\n return true;\n}\npublic boolean isEmpty(Stack<Integer>s)\n {\n return s.isEmpty();\n}\n}" }, { "code": null, "e": 9475, "s": 9329, "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": 9511, "s": 9475, "text": " Login to access your submissions. " }, { "code": null, "e": 9521, "s": 9511, "text": "\nProblem\n" }, { "code": null, "e": 9531, "s": 9521, "text": "\nContest\n" }, { "code": null, "e": 9594, "s": 9531, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9742, "s": 9594, "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": 9950, "s": 9742, "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": 10056, "s": 9950, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to pass an object from one Activity to another in Android?
This example demonstrates how do I pass an object from one Activity to another 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" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click here to pass object to Second Activity!" android:id="@+id/button" android:layout_centerInParent="true" /> </RelativeLayout> Step 3 − Create a java class and add the following code in Character.java import java.io.Serializable; public class Character implements Serializable { String name, Proffession, Position; String[] abilities; public Character(String name, String proffession, String position, String[] abilities) { this.name = name; Proffession = proffession; Position = position; this.abilities = abilities; } } Step 4 − Add the following code to MainActivity.java import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), SecondActivity.class); Character sports = new Character("CR7", "Football", "Left Winger", new String[]{"Best Freeckicker in the World"}); intent.putExtra("Character", sports); startActivity(intent); } }); } } Step 5 − Create an emty activity, name it as SecondActivity and add the following code in SecondActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.Arrays; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Character sports = (Character)getIntent().getSerializableExtra("Character"); TextView textView = findViewById(R.id.textView); textView.setText(sports.name +"\n" + sports.Proffession + "\n" + sports.Position+ "\n" + Arrays.toString(sports.abilities)); } } Step 6 − Add the following code in 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" tools:context=".SecondActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:textSize="20sp" android:layout_centerInParent="true"/> </RelativeLayout> 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 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": 1153, "s": 1062, "text": "This example demonstrates how do I pass an object from one Activity to another in android." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1882, "s": 1347, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Click here to pass object to Second Activity!\"\n android:id=\"@+id/button\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 1956, "s": 1882, "text": "Step 3 − Create a java class and add the following code in Character.java" }, { "code": null, "e": 2313, "s": 1956, "text": "import java.io.Serializable;\npublic class Character implements Serializable {\n String name, Proffession, Position;\n String[] abilities;\n public Character(String name, String proffession, String position, String[] abilities) {\n this.name = name;\n Proffession = proffession;\n Position = position;\n this.abilities = abilities;\n }\n}" }, { "code": null, "e": 2366, "s": 2313, "text": "Step 4 − Add the following code to MainActivity.java" }, { "code": null, "e": 3243, "s": 2366, "text": "import android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button = (Button) findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(getApplicationContext(), SecondActivity.class);\n Character sports = new Character(\"CR7\", \"Football\", \"Left Winger\", new String[]{\"Best Freeckicker in the World\"});\n intent.putExtra(\"Character\", sports);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3353, "s": 3243, "text": "Step 5 − Create an emty activity, name it as SecondActivity and add the following code in SecondActivity.java" }, { "code": null, "e": 3976, "s": 3353, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.util.Arrays;\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n Character sports = (Character)getIntent().getSerializableExtra(\"Character\");\n TextView textView = findViewById(R.id.textView);\n textView.setText(sports.name +\"\\n\" + sports.Proffession + \"\\n\" + sports.Position+ \"\\n\" + Arrays.toString(sports.abilities));\n }\n}" }, { "code": null, "e": 4031, "s": 3976, "text": "Step 6 − Add the following code in activity_second.xml" }, { "code": null, "e": 4531, "s": 4031, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".SecondActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:textSize=\"20sp\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 4878, "s": 4531, "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 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": 4919, "s": 4878, "text": "Click here to download the project code." } ]
How to convert BLOB to Byte Array in java?
You can contents of a blob into a byte array using the getBytes() method. import java.awt.Image; import java.awt.image.BufferedImage; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; public class BlobToByteArray { public static void main(String[] args) throws Exception { Image image = new BufferedImage(300,400, BufferedImage.TYPE_INT_RGB); String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/mydb"; String USER = "root"; String PASS = "password"; Connection conn = null; Statement stmt = null; Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); System.out.println("getting blob......."); stmt = conn.createStatement(); String sql = "SELECT * FROM sample"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { Blob blob = rs.getBlob("image"); byte [] bytes = blob.getBytes(1l, (int)blob.length()); for(int i=0; i<bytes.length;i++) { System.out.println(Arrays.toString(bytes)); } } } } Connecting to a selected database... Connected database successfully... getting blob....... [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103] [100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[ { "code": null, "e": 1136, "s": 1062, "text": "You can contents of a blob into a byte array using the getBytes() method." }, { "code": null, "e": 2417, "s": 1136, "text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.sql.Blob;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.util.Arrays;\npublic class BlobToByteArray {\n public static void main(String[] args) throws Exception {\n Image image = new BufferedImage(300,400, BufferedImage.TYPE_INT_RGB);\n String JDBC_DRIVER = \"com.mysql.jdbc.Driver\";\n String DB_URL = \"jdbc:mysql://localhost/mydb\";\n String USER = \"root\";\n String PASS = \"password\";\n Connection conn = null;\n Statement stmt = null;\n Class.forName(\"com.mysql.jdbc.Driver\");\n System.out.println(\"Connecting to a selected database...\");\n conn = DriverManager.getConnection(DB_URL, USER, PASS);\n System.out.println(\"Connected database successfully...\");\n System.out.println(\"getting blob.......\");\n stmt = conn.createStatement();\n String sql = \"SELECT * FROM sample\";\n ResultSet rs = stmt.executeQuery(sql);\n while(rs.next()) {\n Blob blob = rs.getBlob(\"image\");\n byte [] bytes = blob.getBytes(1l, (int)blob.length());\n for(int i=0; i<bytes.length;i++) {\n System.out.println(Arrays.toString(bytes));\n }\n }\n }\n}" }, { "code": null, "e": 3205, "s": 2417, "text": "Connecting to a selected database...\nConnected database successfully...\ngetting blob.......\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]\n[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]" } ]
What are different ways of defining functions in JavaScript?
The following are some of the ways of defining functions in JavaScript − The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. Here’s an example showing normal function definition − <script> <!-- function Display() { alert("Hello World!"); } //--> </script> Another way of defining functions in JavaScript is to use Immediately Invoked Functions. The purpose of wrapping is to the namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function. Here’s the syntax − (function() { // code })(); As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression − function(){...} In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above. Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name − This is how JavaScript anonymous functions can be used − var func = function() { alert(‘This is anonymous'); } func(); //anonymous function var a = function() { return 5; } The function() constructor is used in JavaScript to create a new function object. The objects created are parsed when the function is created. You can try to run the following code to learn how to work with function() constructor − <html> <body> <script> var num = new Function('p', 'q', 'r', 'return p * q * r'); document.write("Value after multiplication: "+num(5, 2, 9)); </script> </body> </html>
[ { "code": null, "e": 1135, "s": 1062, "text": "The following are some of the ways of defining functions in JavaScript −" }, { "code": null, "e": 1354, "s": 1135, "text": "The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces." }, { "code": null, "e": 1409, "s": 1354, "text": "Here’s an example showing normal function definition −" }, { "code": null, "e": 1518, "s": 1409, "text": "<script>\n <!--\n function Display()\n {\n alert(\"Hello World!\");\n }\n //-->\n</script>" }, { "code": null, "e": 1892, "s": 1518, "text": "Another way of defining functions in JavaScript is to use Immediately Invoked Functions. The purpose of wrapping is to the namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function." }, { "code": null, "e": 1912, "s": 1892, "text": "Here’s the syntax −" }, { "code": null, "e": 1943, "s": 1912, "text": "(function() {\n // code\n})();" }, { "code": null, "e": 2061, "s": 1943, "text": "As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression −" }, { "code": null, "e": 2077, "s": 2061, "text": "function(){...}" }, { "code": null, "e": 2231, "s": 2077, "text": "In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above." }, { "code": null, "e": 2466, "s": 2231, "text": "Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name −" }, { "code": null, "e": 2523, "s": 2466, "text": "This is how JavaScript anonymous functions can be used −" }, { "code": null, "e": 2588, "s": 2523, "text": "var func = function() {\n alert(‘This is anonymous');\n}\nfunc();" }, { "code": null, "e": 2645, "s": 2588, "text": "//anonymous function\nvar a = function() {\n return 5;\n}" }, { "code": null, "e": 2788, "s": 2645, "text": "The function() constructor is used in JavaScript to create a new function object. The objects created are parsed when the function is created." }, { "code": null, "e": 2877, "s": 2788, "text": "You can try to run the following code to learn how to work with function() constructor −" }, { "code": null, "e": 3082, "s": 2877, "text": "<html>\n <body>\n <script>\n var num = new Function('p', 'q', 'r', 'return p * q * r');\n document.write(\"Value after multiplication: \"+num(5, 2, 9));\n </script>\n </body>\n</html>" } ]
Python Data Preprocessing Using Pandas DataFrame, Spark DataFrame, and Koalas DataFrame | by Yuefeng Zhang, PhD | Towards Data Science
With widespread use in data preprocessing, data analytics, and machine learning, Pandas, in conjunction with Numpy, Scikit-Learn, and Matplotlib, becomes a de facto data science stack in Python. However, one of the major limitations of Pandas is that Pandas was designed for small datasets that can be handled on a single machine and thus it does not scale well to big data. On the contrary, Apache spark was designed for big data, but it has a very different API and also lacks many of the easy-to-use functionality in Pandas for data wrangling and visualization. Recently a new open source Koalas was announced that bridges the gap between Pandas DataFrame and Spark DataFrame by augmenting PySpark’s DataFrame API to make it compatible with pandas DataFrame API. In this post, similar to the comparison between Pandas DataFrame and Spark DataFrame, I use a public dataset sample_stocks.csv to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing steps for machine learning, including: loading data (e.g., load csv file from internet)exploring data (e.g., summary statistics, data visualization, etc.)cleaning data (e.g., handle missing data)transforming data (e.g., features engineering, scaling, reformatting as Numpy array or Spark RDD (Resilient Distributed Dataset)) loading data (e.g., load csv file from internet) exploring data (e.g., summary statistics, data visualization, etc.) cleaning data (e.g., handle missing data) transforming data (e.g., features engineering, scaling, reformatting as Numpy array or Spark RDD (Resilient Distributed Dataset)) For convenience, it is assumed that the following Python libraries have been installed on a local machine such as Mac: Anaconda (conda 4.7.10) with Numpy, Pandas, Matplotlib, and Scikit-Learn Spark 2.4.4 Koalas A dataset (e.g., the public sample_stocks.csv file) needs to be loaded into memory before any data preprocessing can begin. To this end, let’s import the related Python libraries: import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinefrom pyspark import SparkContexttry: sc = SparkContext('local', 'Pyspark demo')except ValueError: print('SparkContext already exists!')from pyspark.sql import SparkSessiontry: spark = SparkSession.builder.appName('Recommendation_system').getOrCreate()except ValueError: print('SparkSession already exists!') Pandas provides a read_csv() function that can read both local csv file and csv file from internet as a Pandas DataFrame: pd_df = pd.read_csv("https://raw.githubusercontent.com/databricks/koalas/master/data/sample_stocks.csv")pd_df.head(1) In Spark, the SparkSession provides only a method to read from a local csv file or a RDD in memory as a Spark DataFrame. Spark needs to be combined with other Python libraries to read a csv file remotely from the internet. One way of doing that is to use the URL request and response package to read the contents of the csv file from the internet first and then convert the contents into a Spark RDD for SparkSession to load as a Spark DataFrame. import urllib.requesturl = "https://raw.githubusercontent.com/databricks/koalas/master/data/sample_stocks.csv"response = urllib.request.urlopen(url)data = response.read() text = data.decode('utf-8') spark_df1 = spark.read.csv(sc.parallelize(text.splitlines()), header=True)print(spark_df1.show(1)) The other method is to use Pandas to read the csv file as a Pandas DataFrame first and then use SparkSession to create a Spark DataFrame from Pandas DataFrame. spark_df2 = spark.createDataFrame(pd.read_csv(url)) Like Spark, Koalas only provides a method to read from a local csv file. It needs to be combined with other Python libraries to read a csv file from the internet. One simple method is to use Pandas to read the csv file as a Pandas DataFrame first and then convert it into a Koalas DataFrame. import databricks.koalas as ksks_df = ks.from_pandas(pd.read_csv(url))ks_df.head(1) Once a dataset is loaded into memory as a DataFrame, we can explore it from different aspects using various functions of the DataFrame. Typically, the first step to explore a DataFrame is to understand its schema: column names and corresponding data types. The way of obtaining both DataFrame column names and data types is similar for Pandas, Spark, and Koalas DataFrames. All of those DataFrames provide an attribute columns for column names and an attribute dtypes for column data types. One thing to note is that the data types of Spark DataFrame depend on how the sample public csv file is loaded. The column data types are string type by default if the csv file is loaded by using URL request and response package with Spark, while the column data types are double if the csv file is loaded by using Pandas with Spark. # DataFrame column namespandas_column_names = pd_df.columnsspark_column_names = spark_df1.columnsks_column_names = ks_df.columns# DataFrame column data typepandas_column_data_types = pd_df.dtypesspark_column_data_types = spark_df1.dtypesks_column_data_types = ks_df.dtypes Once we understand the schema of a DataFrame, the next step to explore data is to look at the summary statistics such as five number summary. All of the Pandas, Spark, and Koalas DataFrames provide the same function describe() for obtaining such basic summary statistics, including the total number of rows, min, mean, max, and percentile of each of the columns of the DataFrame. pd_df.describe() spark_df1.describe()ks_df.describe() In addition to the basic summary statistics, the other element of summary statistics is the correlation among different columns in a DataFrame. All of the Pandas, Spark, Koalas DataFrames provide a function corr() to calculate correlation coefficients. The corr() function of Pandas and Koalas DataFrame can handle any number of columns, but the corr() function of Spark DataFrame allows only two columns. pd_df[['Open','Close', 'Volume']].corr()ks_df[['Open','Close', 'Volume']].corr() from pyspark.sql.functions import corrspark_df2.select(corr("Open","Close")).show() Grouping by and aggregation (e.g., min, max, mean, etc.) are another element of summary statistics. Pandas and Koalas DataFrames provide the same function for group by and aggregation: pd_df.groupby('Symbol').max()['Open']ks_df.groupby('Symbol').max()['Open'] However, the Spark DataFrame function for group by and aggregation has a different format: from pyspark.sql.functions import maxspark_df2.groupBy("Symbol").agg(max("Open")).show() Data visualization is an important and efficient method for understanding data. Both Pandas and Koalas DataFrames provide similar plot functions for data visualization, but the quality of plots can be different significantly. For example, the Koalas DataFrame scatter plot below missed many data points compared with the scatter plot of Pandas DataFrame. However, Spark DataFrame does not directly provide any data visualization functions. One easy workaround is to convert Spark DataFrame to Pandas or Koalas DataFrame for data visualization. pd_df_sub = pd_df[['Open', 'Close']]pd_df_sub.plot.scatter(x='Open', y='Close') ks_df_sub = ks_df[['Open', 'Close']]ks_df_sub.plot.scatter(x='Open', y='Close') The scatter plot function in Pandas and Koalas DataFrame can only handle two columns. The Pandas plotting module provides a scatter_matrix() function that can draw a scatter plot diagram for each pair of any number of columns. from pandas.plotting import scatter_matrixpd_df_sub = pd_df[['Open', 'Close', 'Volume']]scatter_matrix(pd_df_sub, alpha=0.2) Two of the major goals of data cleaning are to handle missing data and filter out outliers. To demonstrate how to handle missing data, first let’s assign a missing data item (e.g., np.nan) into the Pandas DataFrame: pd_df_missing = pd_df.copy()pd_df_missing.loc[0, 'Open'] = np.nanpd_df_missing[pd_df_missing['Open'].isnull()] Pandas DataFrame provides a fillna() function that can fill missing data items with any string or number. Spark and Koalas DataFrames provide a similar function, but they only allow a value that matches the data type of the corresponding column. pd_df_missing.fillna('N/A', inplace = True)pd_df_missing.fillna(0, inplace = True)# Spark and Koalas allow only a numberks_df_missing.fillna(0, inplace = True) spark_df_missing = spark_df_missing.na.fill(0) Data filtering can be used for removing outliers and many other purposes. As shown in the sample code below, Pandas and Koalas DataFrames have the same API for conditionally selecting data rows and columns. However, the Spark DataFrame has a different API. pd_df.loc[pd_df['Open'] >= 168, ['Open','Close']].head()ks_df.loc[ks_df['Open'] >= 168, ['Open','Close']].head()spark_df.filter("Open > 168").select("Open","Close").show(5) Features engineering can be fundamental to the application of machine learning and it is achieved by various types of data transformation. A feature is a data column in DataFrame. The scope of features engineering varies, but typically includes the following: Select a subset of existing data columns that are correlated with the prediction target in machine learning (i.e., labels in supervised machine learning) Rename an existing column with a more meaningful name Create new columns based on existing columns (i.e., create derived features) Scale column values into a certain range (i.e., scaling column values into the range of [0,1] or [-1,1] in deep learning) As described before, Pandas and Koalas DataFrames provide the same method for selecting columns, but Spark DataFrame provides a different API. pd_df[['Open', 'Close']]ks_df[['Open', 'Close']]spark_df.select('Open', 'Close') Pandas and Spark DataFrames use different function names with similar functionality of renaming columns. pd_df.rename(columns = {"Symbol": "SYMBOL"}, inplace = True)spark_df = spark_df.withColumnRenamed("Symbol", "SYMBOL") However, the current Koalas DataFrame does not support the functionality of renaming columns. It’s normally necessary to derive new features from existing features for machine learning, that is, create new data columns from existing columns: from pyspark.sql.functions import colpd_df['Sum'] = pd_df['Open'] + pd_df['Close']ks_df['Sum'] = ks_df['Open'] + ks_df['Close']spark_df1 = spark_df1.withColumn("Sum", col("Open") + col("Close")) Unnecessary columns (e.g., AdjOpen and AdjHigh) can be dropped as follows: pd_df = pd_df.drop(['AdjOpen', 'AdjHigh'], axis=1)ks_df = ks_df.drop(['AdjOpen', 'AdjHigh'], axis=1)spark_df = spark_df.drop('AdjOpen', 'AdjHigh') As described before, it’s necessary to scale the values of columns into a certain range (e.g., [0,1 or [-1,1]) in machine learning if different columns have values in very different ranges. For Pandas DataFrame, scikit-learn library provides two frequently used functions MinMaxScaler() and StandardScaler() for this purpose. However, these functions cannot directly apply to Koalas DataFrame. A Koalas DataFrame needs to be converted into Pandas DataFrame to take advantage of those functions. Scaling columns can be done for Spark DataFrame, but the implementation can be much more involved compared with using scikit-learn functions for Pandas DataFrame. As an example, similar to the Spark data scaling example, the following code uses the Spark MinMaxScaler, VectorAssembler, and Pipeline objects to scale Spark DataFrame columns: from pyspark.ml.feature import MinMaxScalerfrom pyspark.ml import Pipelinefrom pyspark.ml.feature import VectorAssembler# VectorAssembler Transformation - Converting column to vector typeassembler = VectorAssembler(inputCols=['Open'], outputCol="Open_Vect")scaler = MinMaxScaler(inputCol="Open_Vect", outputCol="Open_Scaled")# Pipeline of VectorAssembler and MinMaxScalerpipeline = Pipeline(stages=[assembler, scaler])# Fitting pipeline on dataframespark_df3 = pipeline.fit(spark_df2).transform(spark_df2).drop("Open_Vect")spark_df3.show(1) The values of a column of categorical data type need to be converted into new columns of numerical data types using one-hot encoding: pd_df_dummies = pd.get_dummies(pd_df)ks_df_dummies = ks.get_dummies(ks_df) However, Spark DataFrame does not provide such a function. A workaround is to convert the DataFrame to either Pandas or Koalas DataFrame. The final step of data preprocessing is to convert a DataFrame into an appropriate format for the consumption of machine learning modeling, depending on the machine learning library in use. If a Numpy-based machine learning or deep learning library (i.e., scikit-learn, Keras, etc.) is used, then a DataFrame needs to be converted into a Numpy array for modeling. The Pandas DataFrame provides a values attribute to get a NumPy array from a Pandas DataFrame. But the current Koalas DataFrame does not support such a method. A Spark or Koalas DataFrame can be converted into a Pandas DataFrame as follows to obtain a corresponding Numpy array easily if the dataset can be handled on a single machine. pd_df_from_koalas = ks_df.to_pandas()pd_df_from_spark = spark_df.toPandas() If a Spark-based machine learning library like MLlib is used, then a DataFrame needs to be converted into either RDD or Spark DataFrame. A Spark DataFrame can be directly fed into an appropriately designed MLlib pipeline (see MLlib for example) or be converted into RDD if the RDD-based MLlib API is used for modeling. The Spark DataFrame provides an rdd attribute to return an RDD. In this case, a Pandas or Koalas DataFrame needs to be converted into a Spark DataFrame first for modeling purposes. This can be achieved as follows: spark_df_from_pandas = spark.createDataFrame(pd_df)spark_df_from_koalas = ks_df.to_spark() As described in the Koalas announcement, data scientists tend to use Pandas DataFrame to explore data. They are reluctant to use Spark DataFrame due to the sharp learning curve. Koalas seems to fill the gap between them by providing an easy-to-use API similar to Pandas DataFrame that can run on Spark. In this post, as shown in the summary table below, I use a public dataset sample_stocks.csv to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing tasks for machine learning. Koalas is still in the early stage of development. As shown in the table above, it does not support some of the basic functions of data preprocessing. Certain supported functions are not yet matured. With the advance of development, many potential advantages of Koalas’ easy-to-use API for data transformation and visualization on Spark will start to shine in the case of large-scale datasets (e.g., hundreds millions of data records). DISCLOSURE STATEMENT: © 2019 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners.
[ { "code": null, "e": 367, "s": 172, "text": "With widespread use in data preprocessing, data analytics, and machine learning, Pandas, in conjunction with Numpy, Scikit-Learn, and Matplotlib, becomes a de facto data science stack in Python." }, { "code": null, "e": 938, "s": 367, "text": "However, one of the major limitations of Pandas is that Pandas was designed for small datasets that can be handled on a single machine and thus it does not scale well to big data. On the contrary, Apache spark was designed for big data, but it has a very different API and also lacks many of the easy-to-use functionality in Pandas for data wrangling and visualization. Recently a new open source Koalas was announced that bridges the gap between Pandas DataFrame and Spark DataFrame by augmenting PySpark’s DataFrame API to make it compatible with pandas DataFrame API." }, { "code": null, "e": 1222, "s": 938, "text": "In this post, similar to the comparison between Pandas DataFrame and Spark DataFrame, I use a public dataset sample_stocks.csv to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing steps for machine learning, including:" }, { "code": null, "e": 1508, "s": 1222, "text": "loading data (e.g., load csv file from internet)exploring data (e.g., summary statistics, data visualization, etc.)cleaning data (e.g., handle missing data)transforming data (e.g., features engineering, scaling, reformatting as Numpy array or Spark RDD (Resilient Distributed Dataset))" }, { "code": null, "e": 1557, "s": 1508, "text": "loading data (e.g., load csv file from internet)" }, { "code": null, "e": 1625, "s": 1557, "text": "exploring data (e.g., summary statistics, data visualization, etc.)" }, { "code": null, "e": 1667, "s": 1625, "text": "cleaning data (e.g., handle missing data)" }, { "code": null, "e": 1797, "s": 1667, "text": "transforming data (e.g., features engineering, scaling, reformatting as Numpy array or Spark RDD (Resilient Distributed Dataset))" }, { "code": null, "e": 1916, "s": 1797, "text": "For convenience, it is assumed that the following Python libraries have been installed on a local machine such as Mac:" }, { "code": null, "e": 1989, "s": 1916, "text": "Anaconda (conda 4.7.10) with Numpy, Pandas, Matplotlib, and Scikit-Learn" }, { "code": null, "e": 2001, "s": 1989, "text": "Spark 2.4.4" }, { "code": null, "e": 2008, "s": 2001, "text": "Koalas" }, { "code": null, "e": 2188, "s": 2008, "text": "A dataset (e.g., the public sample_stocks.csv file) needs to be loaded into memory before any data preprocessing can begin. To this end, let’s import the related Python libraries:" }, { "code": null, "e": 2594, "s": 2188, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinefrom pyspark import SparkContexttry: sc = SparkContext('local', 'Pyspark demo')except ValueError: print('SparkContext already exists!')from pyspark.sql import SparkSessiontry: spark = SparkSession.builder.appName('Recommendation_system').getOrCreate()except ValueError: print('SparkSession already exists!')" }, { "code": null, "e": 2716, "s": 2594, "text": "Pandas provides a read_csv() function that can read both local csv file and csv file from internet as a Pandas DataFrame:" }, { "code": null, "e": 2834, "s": 2716, "text": "pd_df = pd.read_csv(\"https://raw.githubusercontent.com/databricks/koalas/master/data/sample_stocks.csv\")pd_df.head(1)" }, { "code": null, "e": 3057, "s": 2834, "text": "In Spark, the SparkSession provides only a method to read from a local csv file or a RDD in memory as a Spark DataFrame. Spark needs to be combined with other Python libraries to read a csv file remotely from the internet." }, { "code": null, "e": 3281, "s": 3057, "text": "One way of doing that is to use the URL request and response package to read the contents of the csv file from the internet first and then convert the contents into a Spark RDD for SparkSession to load as a Spark DataFrame." }, { "code": null, "e": 3585, "s": 3281, "text": "import urllib.requesturl = \"https://raw.githubusercontent.com/databricks/koalas/master/data/sample_stocks.csv\"response = urllib.request.urlopen(url)data = response.read() text = data.decode('utf-8') spark_df1 = spark.read.csv(sc.parallelize(text.splitlines()), header=True)print(spark_df1.show(1))" }, { "code": null, "e": 3745, "s": 3585, "text": "The other method is to use Pandas to read the csv file as a Pandas DataFrame first and then use SparkSession to create a Spark DataFrame from Pandas DataFrame." }, { "code": null, "e": 3797, "s": 3745, "text": "spark_df2 = spark.createDataFrame(pd.read_csv(url))" }, { "code": null, "e": 4089, "s": 3797, "text": "Like Spark, Koalas only provides a method to read from a local csv file. It needs to be combined with other Python libraries to read a csv file from the internet. One simple method is to use Pandas to read the csv file as a Pandas DataFrame first and then convert it into a Koalas DataFrame." }, { "code": null, "e": 4173, "s": 4089, "text": "import databricks.koalas as ksks_df = ks.from_pandas(pd.read_csv(url))ks_df.head(1)" }, { "code": null, "e": 4309, "s": 4173, "text": "Once a dataset is loaded into memory as a DataFrame, we can explore it from different aspects using various functions of the DataFrame." }, { "code": null, "e": 4430, "s": 4309, "text": "Typically, the first step to explore a DataFrame is to understand its schema: column names and corresponding data types." }, { "code": null, "e": 4664, "s": 4430, "text": "The way of obtaining both DataFrame column names and data types is similar for Pandas, Spark, and Koalas DataFrames. All of those DataFrames provide an attribute columns for column names and an attribute dtypes for column data types." }, { "code": null, "e": 4998, "s": 4664, "text": "One thing to note is that the data types of Spark DataFrame depend on how the sample public csv file is loaded. The column data types are string type by default if the csv file is loaded by using URL request and response package with Spark, while the column data types are double if the csv file is loaded by using Pandas with Spark." }, { "code": null, "e": 5281, "s": 4998, "text": "# DataFrame column namespandas_column_names = pd_df.columnsspark_column_names = spark_df1.columnsks_column_names = ks_df.columns# DataFrame column data typepandas_column_data_types = pd_df.dtypesspark_column_data_types = spark_df1.dtypesks_column_data_types = ks_df.dtypes" }, { "code": null, "e": 5661, "s": 5281, "text": "Once we understand the schema of a DataFrame, the next step to explore data is to look at the summary statistics such as five number summary. All of the Pandas, Spark, and Koalas DataFrames provide the same function describe() for obtaining such basic summary statistics, including the total number of rows, min, mean, max, and percentile of each of the columns of the DataFrame." }, { "code": null, "e": 5678, "s": 5661, "text": "pd_df.describe()" }, { "code": null, "e": 5715, "s": 5678, "text": "spark_df1.describe()ks_df.describe()" }, { "code": null, "e": 6121, "s": 5715, "text": "In addition to the basic summary statistics, the other element of summary statistics is the correlation among different columns in a DataFrame. All of the Pandas, Spark, Koalas DataFrames provide a function corr() to calculate correlation coefficients. The corr() function of Pandas and Koalas DataFrame can handle any number of columns, but the corr() function of Spark DataFrame allows only two columns." }, { "code": null, "e": 6202, "s": 6121, "text": "pd_df[['Open','Close', 'Volume']].corr()ks_df[['Open','Close', 'Volume']].corr()" }, { "code": null, "e": 6286, "s": 6202, "text": "from pyspark.sql.functions import corrspark_df2.select(corr(\"Open\",\"Close\")).show()" }, { "code": null, "e": 6471, "s": 6286, "text": "Grouping by and aggregation (e.g., min, max, mean, etc.) are another element of summary statistics. Pandas and Koalas DataFrames provide the same function for group by and aggregation:" }, { "code": null, "e": 6546, "s": 6471, "text": "pd_df.groupby('Symbol').max()['Open']ks_df.groupby('Symbol').max()['Open']" }, { "code": null, "e": 6637, "s": 6546, "text": "However, the Spark DataFrame function for group by and aggregation has a different format:" }, { "code": null, "e": 6726, "s": 6637, "text": "from pyspark.sql.functions import maxspark_df2.groupBy(\"Symbol\").agg(max(\"Open\")).show()" }, { "code": null, "e": 7081, "s": 6726, "text": "Data visualization is an important and efficient method for understanding data. Both Pandas and Koalas DataFrames provide similar plot functions for data visualization, but the quality of plots can be different significantly. For example, the Koalas DataFrame scatter plot below missed many data points compared with the scatter plot of Pandas DataFrame." }, { "code": null, "e": 7270, "s": 7081, "text": "However, Spark DataFrame does not directly provide any data visualization functions. One easy workaround is to convert Spark DataFrame to Pandas or Koalas DataFrame for data visualization." }, { "code": null, "e": 7350, "s": 7270, "text": "pd_df_sub = pd_df[['Open', 'Close']]pd_df_sub.plot.scatter(x='Open', y='Close')" }, { "code": null, "e": 7430, "s": 7350, "text": "ks_df_sub = ks_df[['Open', 'Close']]ks_df_sub.plot.scatter(x='Open', y='Close')" }, { "code": null, "e": 7657, "s": 7430, "text": "The scatter plot function in Pandas and Koalas DataFrame can only handle two columns. The Pandas plotting module provides a scatter_matrix() function that can draw a scatter plot diagram for each pair of any number of columns." }, { "code": null, "e": 7782, "s": 7657, "text": "from pandas.plotting import scatter_matrixpd_df_sub = pd_df[['Open', 'Close', 'Volume']]scatter_matrix(pd_df_sub, alpha=0.2)" }, { "code": null, "e": 7874, "s": 7782, "text": "Two of the major goals of data cleaning are to handle missing data and filter out outliers." }, { "code": null, "e": 7998, "s": 7874, "text": "To demonstrate how to handle missing data, first let’s assign a missing data item (e.g., np.nan) into the Pandas DataFrame:" }, { "code": null, "e": 8109, "s": 7998, "text": "pd_df_missing = pd_df.copy()pd_df_missing.loc[0, 'Open'] = np.nanpd_df_missing[pd_df_missing['Open'].isnull()]" }, { "code": null, "e": 8355, "s": 8109, "text": "Pandas DataFrame provides a fillna() function that can fill missing data items with any string or number. Spark and Koalas DataFrames provide a similar function, but they only allow a value that matches the data type of the corresponding column." }, { "code": null, "e": 8562, "s": 8355, "text": "pd_df_missing.fillna('N/A', inplace = True)pd_df_missing.fillna(0, inplace = True)# Spark and Koalas allow only a numberks_df_missing.fillna(0, inplace = True) spark_df_missing = spark_df_missing.na.fill(0)" }, { "code": null, "e": 8636, "s": 8562, "text": "Data filtering can be used for removing outliers and many other purposes." }, { "code": null, "e": 8819, "s": 8636, "text": "As shown in the sample code below, Pandas and Koalas DataFrames have the same API for conditionally selecting data rows and columns. However, the Spark DataFrame has a different API." }, { "code": null, "e": 8992, "s": 8819, "text": "pd_df.loc[pd_df['Open'] >= 168, ['Open','Close']].head()ks_df.loc[ks_df['Open'] >= 168, ['Open','Close']].head()spark_df.filter(\"Open > 168\").select(\"Open\",\"Close\").show(5)" }, { "code": null, "e": 9252, "s": 8992, "text": "Features engineering can be fundamental to the application of machine learning and it is achieved by various types of data transformation. A feature is a data column in DataFrame. The scope of features engineering varies, but typically includes the following:" }, { "code": null, "e": 9406, "s": 9252, "text": "Select a subset of existing data columns that are correlated with the prediction target in machine learning (i.e., labels in supervised machine learning)" }, { "code": null, "e": 9460, "s": 9406, "text": "Rename an existing column with a more meaningful name" }, { "code": null, "e": 9537, "s": 9460, "text": "Create new columns based on existing columns (i.e., create derived features)" }, { "code": null, "e": 9659, "s": 9537, "text": "Scale column values into a certain range (i.e., scaling column values into the range of [0,1] or [-1,1] in deep learning)" }, { "code": null, "e": 9802, "s": 9659, "text": "As described before, Pandas and Koalas DataFrames provide the same method for selecting columns, but Spark DataFrame provides a different API." }, { "code": null, "e": 9883, "s": 9802, "text": "pd_df[['Open', 'Close']]ks_df[['Open', 'Close']]spark_df.select('Open', 'Close')" }, { "code": null, "e": 9988, "s": 9883, "text": "Pandas and Spark DataFrames use different function names with similar functionality of renaming columns." }, { "code": null, "e": 10106, "s": 9988, "text": "pd_df.rename(columns = {\"Symbol\": \"SYMBOL\"}, inplace = True)spark_df = spark_df.withColumnRenamed(\"Symbol\", \"SYMBOL\")" }, { "code": null, "e": 10200, "s": 10106, "text": "However, the current Koalas DataFrame does not support the functionality of renaming columns." }, { "code": null, "e": 10348, "s": 10200, "text": "It’s normally necessary to derive new features from existing features for machine learning, that is, create new data columns from existing columns:" }, { "code": null, "e": 10543, "s": 10348, "text": "from pyspark.sql.functions import colpd_df['Sum'] = pd_df['Open'] + pd_df['Close']ks_df['Sum'] = ks_df['Open'] + ks_df['Close']spark_df1 = spark_df1.withColumn(\"Sum\", col(\"Open\") + col(\"Close\"))" }, { "code": null, "e": 10618, "s": 10543, "text": "Unnecessary columns (e.g., AdjOpen and AdjHigh) can be dropped as follows:" }, { "code": null, "e": 10765, "s": 10618, "text": "pd_df = pd_df.drop(['AdjOpen', 'AdjHigh'], axis=1)ks_df = ks_df.drop(['AdjOpen', 'AdjHigh'], axis=1)spark_df = spark_df.drop('AdjOpen', 'AdjHigh')" }, { "code": null, "e": 11091, "s": 10765, "text": "As described before, it’s necessary to scale the values of columns into a certain range (e.g., [0,1 or [-1,1]) in machine learning if different columns have values in very different ranges. For Pandas DataFrame, scikit-learn library provides two frequently used functions MinMaxScaler() and StandardScaler() for this purpose." }, { "code": null, "e": 11260, "s": 11091, "text": "However, these functions cannot directly apply to Koalas DataFrame. A Koalas DataFrame needs to be converted into Pandas DataFrame to take advantage of those functions." }, { "code": null, "e": 11601, "s": 11260, "text": "Scaling columns can be done for Spark DataFrame, but the implementation can be much more involved compared with using scikit-learn functions for Pandas DataFrame. As an example, similar to the Spark data scaling example, the following code uses the Spark MinMaxScaler, VectorAssembler, and Pipeline objects to scale Spark DataFrame columns:" }, { "code": null, "e": 12142, "s": 11601, "text": "from pyspark.ml.feature import MinMaxScalerfrom pyspark.ml import Pipelinefrom pyspark.ml.feature import VectorAssembler# VectorAssembler Transformation - Converting column to vector typeassembler = VectorAssembler(inputCols=['Open'], outputCol=\"Open_Vect\")scaler = MinMaxScaler(inputCol=\"Open_Vect\", outputCol=\"Open_Scaled\")# Pipeline of VectorAssembler and MinMaxScalerpipeline = Pipeline(stages=[assembler, scaler])# Fitting pipeline on dataframespark_df3 = pipeline.fit(spark_df2).transform(spark_df2).drop(\"Open_Vect\")spark_df3.show(1)" }, { "code": null, "e": 12276, "s": 12142, "text": "The values of a column of categorical data type need to be converted into new columns of numerical data types using one-hot encoding:" }, { "code": null, "e": 12351, "s": 12276, "text": "pd_df_dummies = pd.get_dummies(pd_df)ks_df_dummies = ks.get_dummies(ks_df)" }, { "code": null, "e": 12489, "s": 12351, "text": "However, Spark DataFrame does not provide such a function. A workaround is to convert the DataFrame to either Pandas or Koalas DataFrame." }, { "code": null, "e": 12679, "s": 12489, "text": "The final step of data preprocessing is to convert a DataFrame into an appropriate format for the consumption of machine learning modeling, depending on the machine learning library in use." }, { "code": null, "e": 13189, "s": 12679, "text": "If a Numpy-based machine learning or deep learning library (i.e., scikit-learn, Keras, etc.) is used, then a DataFrame needs to be converted into a Numpy array for modeling. The Pandas DataFrame provides a values attribute to get a NumPy array from a Pandas DataFrame. But the current Koalas DataFrame does not support such a method. A Spark or Koalas DataFrame can be converted into a Pandas DataFrame as follows to obtain a corresponding Numpy array easily if the dataset can be handled on a single machine." }, { "code": null, "e": 13265, "s": 13189, "text": "pd_df_from_koalas = ks_df.to_pandas()pd_df_from_spark = spark_df.toPandas()" }, { "code": null, "e": 13798, "s": 13265, "text": "If a Spark-based machine learning library like MLlib is used, then a DataFrame needs to be converted into either RDD or Spark DataFrame. A Spark DataFrame can be directly fed into an appropriately designed MLlib pipeline (see MLlib for example) or be converted into RDD if the RDD-based MLlib API is used for modeling. The Spark DataFrame provides an rdd attribute to return an RDD. In this case, a Pandas or Koalas DataFrame needs to be converted into a Spark DataFrame first for modeling purposes. This can be achieved as follows:" }, { "code": null, "e": 13889, "s": 13798, "text": "spark_df_from_pandas = spark.createDataFrame(pd_df)spark_df_from_koalas = ks_df.to_spark()" }, { "code": null, "e": 14192, "s": 13889, "text": "As described in the Koalas announcement, data scientists tend to use Pandas DataFrame to explore data. They are reluctant to use Spark DataFrame due to the sharp learning curve. Koalas seems to fill the gap between them by providing an easy-to-use API similar to Pandas DataFrame that can run on Spark." }, { "code": null, "e": 14430, "s": 14192, "text": "In this post, as shown in the summary table below, I use a public dataset sample_stocks.csv to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing tasks for machine learning." }, { "code": null, "e": 14866, "s": 14430, "text": "Koalas is still in the early stage of development. As shown in the table above, it does not support some of the basic functions of data preprocessing. Certain supported functions are not yet matured. With the advance of development, many potential advantages of Koalas’ easy-to-use API for data transformation and visualization on Spark will start to shine in the case of large-scale datasets (e.g., hundreds millions of data records)." } ]
Sentiment Analysis using ALBERT. Let’s fine-tune Google’s latest NLP... | by Gagandeep Singh | Towards Data Science
Every researcher or NLP practitioner is well aware of BERT which came in 2018. Since then the NLP industry has transformed by a much larger extent. Albert which is A Lite BERT was made in focus to make it as light as possible by reducing parameter size. The great advantage of Deep Learning for Sentiment Analysis Task is that the step where we preprocess data gets reduced. The only preprocessing required would be to convert them to lower case. If we are using machine learning methods like logistic regression with TF-IDF then you’ll need to lemmatize words and also remove the unnecessary words. If you are thinking about removing Stopwords then check this article towardsdatascience.com If you want to learn about the latest text preprocessing steps then check out this article. towardsdatascience.com First clone this GitHub repo.Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory.Dataset will have 2 columns. One will contain text and the other will contain the label.Write train command First clone this GitHub repo. Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory. Dataset will have 2 columns. One will contain text and the other will contain the label. Write train command $ python run_glue.py --data_dir data --model_type albert --model_name_or_path albert-base-v2 --output_dir output --do_train --task_type sst-2 data-dir - where train.tsv file is placed model_type - The model which you want to use for sentiment analysis task. Here we are using ALBERT. model_name_or_path - The variant of the model that you want to use. Here we are using albert-base-v2. output-dir- The directory where you want to save the model. The script will automatically create the folder. do-train - Because we are performing train operation. task_type - Two tasks can be performed — SST-2 and SST-5. Here is a list of various models that you can use 5. After the model has been trained, all the model files will be inside a folder. 6. Replace the model directory in the api.py file. 7. Run api.py file $ python api.py 8. If you want to call its predict method then $ from api import SentimentAnalyzer$ classifier = SentimentAnalyszer()$ classifier.predict('It was a good movie')
[ { "code": null, "e": 319, "s": 171, "text": "Every researcher or NLP practitioner is well aware of BERT which came in 2018. Since then the NLP industry has transformed by a much larger extent." }, { "code": null, "e": 425, "s": 319, "text": "Albert which is A Lite BERT was made in focus to make it as light as possible by reducing parameter size." }, { "code": null, "e": 840, "s": 425, "text": "The great advantage of Deep Learning for Sentiment Analysis Task is that the step where we preprocess data gets reduced. The only preprocessing required would be to convert them to lower case. If we are using machine learning methods like logistic regression with TF-IDF then you’ll need to lemmatize words and also remove the unnecessary words. If you are thinking about removing Stopwords then check this article" }, { "code": null, "e": 863, "s": 840, "text": "towardsdatascience.com" }, { "code": null, "e": 955, "s": 863, "text": "If you want to learn about the latest text preprocessing steps then check out this article." }, { "code": null, "e": 978, "s": 955, "text": "towardsdatascience.com" }, { "code": null, "e": 1245, "s": 978, "text": "First clone this GitHub repo.Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory.Dataset will have 2 columns. One will contain text and the other will contain the label.Write train command" }, { "code": null, "e": 1275, "s": 1245, "text": "First clone this GitHub repo." }, { "code": null, "e": 1406, "s": 1275, "text": "Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory." }, { "code": null, "e": 1495, "s": 1406, "text": "Dataset will have 2 columns. One will contain text and the other will contain the label." }, { "code": null, "e": 1515, "s": 1495, "text": "Write train command" }, { "code": null, "e": 1657, "s": 1515, "text": "$ python run_glue.py --data_dir data --model_type albert --model_name_or_path albert-base-v2 --output_dir output --do_train --task_type sst-2" }, { "code": null, "e": 1699, "s": 1657, "text": "data-dir - where train.tsv file is placed" }, { "code": null, "e": 1799, "s": 1699, "text": "model_type - The model which you want to use for sentiment analysis task. Here we are using ALBERT." }, { "code": null, "e": 1901, "s": 1799, "text": "model_name_or_path - The variant of the model that you want to use. Here we are using albert-base-v2." }, { "code": null, "e": 2010, "s": 1901, "text": "output-dir- The directory where you want to save the model. The script will automatically create the folder." }, { "code": null, "e": 2064, "s": 2010, "text": "do-train - Because we are performing train operation." }, { "code": null, "e": 2122, "s": 2064, "text": "task_type - Two tasks can be performed — SST-2 and SST-5." }, { "code": null, "e": 2172, "s": 2122, "text": "Here is a list of various models that you can use" }, { "code": null, "e": 2254, "s": 2172, "text": "5. After the model has been trained, all the model files will be inside a folder." }, { "code": null, "e": 2305, "s": 2254, "text": "6. Replace the model directory in the api.py file." }, { "code": null, "e": 2324, "s": 2305, "text": "7. Run api.py file" }, { "code": null, "e": 2340, "s": 2324, "text": "$ python api.py" }, { "code": null, "e": 2387, "s": 2340, "text": "8. If you want to call its predict method then" } ]
JavaScript - Animation
You can use JavaScript to create a complex animation having, but not limited to, the following elements − Fireworks Fade Effect Roll-in or Roll-out Page-in or Page-out Object movements You might be interested in existing JavaScript based animation library: Script.Aculo.us. This tutorial provides a basic understanding of how to use JavaScript to create an animation. JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function. JavaScript provides the following two functions to be frequently used in animation programs. setTimeout( function, duration) − This function calls function after duration milliseconds from now. setTimeout( function, duration) − This function calls function after duration milliseconds from now. setInterval(function, duration) − This function calls function after every duration milliseconds. setInterval(function, duration) − This function calls function after every duration milliseconds. clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions. clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions. JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax. // Set distance from left edge of the screen. object.style.left = distance in pixels or points; or // Set distance from top edge of the screen. object.style.top = distance in pixels or points; So let's implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods. We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj. We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj. We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes. We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes. We are calling initialization function at the time of window load. We are calling initialization function at the time of window load. Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side. Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side. Try the following example. <html> <head> <title>JavaScript Animation</title> <script type = "text/javascript"> <!-- var imgObj = null; function init() { imgObj = document.getElementById('myImage'); imgObj.style.position= 'relative'; imgObj.style.left = '0px'; } function moveRight() { imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; } window.onload = init; //--> </script> </head> <body> <form> <img id = "myImage" src = "/images/html.gif" /> <p>Click button below to move the image to right</p> <input type = "button" value = "Click Me" onclick = "moveRight();" /> </form> </body> </html> Click button below to move the image to right In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows − Here we have added more methods. So let's see what is new here − The moveRight() function is calling setTimeout() function to set the position of imgObj. The moveRight() function is calling setTimeout() function to set the position of imgObj. We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position. We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position. Try the following example code. <html> <head> <title>JavaScript Animation</title> <script type = "text/javascript"> <!-- var imgObj = null; var animate ; function init() { imgObj = document.getElementById('myImage'); imgObj.style.position= 'relative'; imgObj.style.left = '0px'; } function moveRight() { imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; animate = setTimeout(moveRight,20); // call moveRight in 20msec } function stop() { clearTimeout(animate); imgObj.style.left = '0px'; } window.onload = init; //--> </script> </head> <body> <form> <img id = "myImage" src = "/images/html.gif" /> <p>Click the buttons below to handle animation</p> <input type = "button" value = "Start" onclick = "moveRight();" /> <input type = "button" value = "Stop" onclick = "stop();" /> </form> </body> </html> Click the buttons below to handle animation Here is a simple example showing image rollover with a mouse event. Let's see what we are using in the following example − At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed. At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed. The Image() constructor creates and preloads a new image object called image1. The Image() constructor creates and preloads a new image object called image1. The src property is assigned the name of the external image file called /images/html.gif. The src property is assigned the name of the external image file called /images/html.gif. Similarly, we have created image2 object and assigned /images/http.gif in this object. Similarly, we have created image2 object and assigned /images/http.gif in this object. The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image. The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image. The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image). The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image). When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed. When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed. When the mouse is moved away from the link, the initial image html.gif will reappear on the screen. When the mouse is moved away from the link, the initial image html.gif will reappear on the screen. <html> <head> <title>Rollover with a Mouse Events</title> <script type = "text/javascript"> <!-- if(document.images) { var image1 = new Image(); // Preload an image image1.src = "/images/html.gif"; var image2 = new Image(); // Preload second image image2.src = "/images/http.gif"; } //--> </script> </head> <body> <p>Move your mouse over the image to see the result</p> <a href = "#" onMouseOver = "document.myImage.src = image2.src;" onMouseOut = "document.myImage.src = image1.src;"> <img name = "myImage" src = "/images/html.gif" /> </a> </body> </html> Move your mouse over the image to see the result 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2572, "s": 2466, "text": "You can use JavaScript to create a complex animation having, but not limited to, the following elements −" }, { "code": null, "e": 2582, "s": 2572, "text": "Fireworks" }, { "code": null, "e": 2594, "s": 2582, "text": "Fade Effect" }, { "code": null, "e": 2614, "s": 2594, "text": "Roll-in or Roll-out" }, { "code": null, "e": 2634, "s": 2614, "text": "Page-in or Page-out" }, { "code": null, "e": 2651, "s": 2634, "text": "Object movements" }, { "code": null, "e": 2740, "s": 2651, "text": "You might be interested in existing JavaScript based animation library: Script.Aculo.us." }, { "code": null, "e": 2834, "s": 2740, "text": "This tutorial provides a basic understanding of how to use JavaScript to create an animation." }, { "code": null, "e": 3029, "s": 2834, "text": "JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function." }, { "code": null, "e": 3122, "s": 3029, "text": "JavaScript provides the following two functions to be frequently used in animation programs." }, { "code": null, "e": 3223, "s": 3122, "text": "setTimeout( function, duration) − This function calls function after duration milliseconds from now." }, { "code": null, "e": 3324, "s": 3223, "text": "setTimeout( function, duration) − This function calls function after duration milliseconds from now." }, { "code": null, "e": 3422, "s": 3324, "text": "setInterval(function, duration) − This function calls function after every duration milliseconds." }, { "code": null, "e": 3520, "s": 3422, "text": "setInterval(function, duration) − This function calls function after every duration milliseconds." }, { "code": null, "e": 3628, "s": 3520, "text": "clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions." }, { "code": null, "e": 3736, "s": 3628, "text": "clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout() functions." }, { "code": null, "e": 3944, "s": 3736, "text": "JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is its syntax." }, { "code": null, "e": 4142, "s": 3944, "text": "// Set distance from left edge of the screen.\nobject.style.left = distance in pixels or points; \n\nor\n\n// Set distance from top edge of the screen.\nobject.style.top = distance in pixels or points; \n" }, { "code": null, "e": 4298, "s": 4142, "text": "So let's implement one simple animation using DOM object properties and JavaScript functions as follows. The following list contains different DOM methods." }, { "code": null, "e": 4423, "s": 4298, "text": "We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj." }, { "code": null, "e": 4548, "s": 4423, "text": "We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj." }, { "code": null, "e": 4671, "s": 4548, "text": "We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes." }, { "code": null, "e": 4794, "s": 4671, "text": "We have defined an initialization function init() to initialize imgObj where we have set its position and left attributes." }, { "code": null, "e": 4861, "s": 4794, "text": "We are calling initialization function at the time of window load." }, { "code": null, "e": 4928, "s": 4861, "text": "We are calling initialization function at the time of window load." }, { "code": null, "e": 5088, "s": 4928, "text": "Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side." }, { "code": null, "e": 5248, "s": 5088, "text": "Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side." }, { "code": null, "e": 5275, "s": 5248, "text": "Try the following example." }, { "code": null, "e": 6120, "s": 5275, "text": "<html> \n <head>\n <title>JavaScript Animation</title> \n <script type = \"text/javascript\">\n <!--\n var imgObj = null;\n \n function init() {\n imgObj = document.getElementById('myImage');\n imgObj.style.position= 'relative'; \n imgObj.style.left = '0px'; \n }\n function moveRight() {\n imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';\n }\n \n window.onload = init;\n //-->\n </script>\n </head>\n \n <body> \n <form>\n <img id = \"myImage\" src = \"/images/html.gif\" />\n <p>Click button below to move the image to right</p>\n <input type = \"button\" value = \"Click Me\" onclick = \"moveRight();\" />\n </form> \n </body>\n</html>" }, { "code": null, "e": 6166, "s": 6120, "text": "Click button below to move the image to right" }, { "code": null, "e": 6329, "s": 6166, "text": "In the above example, we saw how an image moves to right with every click. We can automate this process by using the JavaScript function setTimeout() as follows −" }, { "code": null, "e": 6394, "s": 6329, "text": "Here we have added more methods. So let's see what is new here −" }, { "code": null, "e": 6483, "s": 6394, "text": "The moveRight() function is calling setTimeout() function to set the position of imgObj." }, { "code": null, "e": 6572, "s": 6483, "text": "The moveRight() function is calling setTimeout() function to set the position of imgObj." }, { "code": null, "e": 6703, "s": 6572, "text": "We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position." }, { "code": null, "e": 6834, "s": 6703, "text": "We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position." }, { "code": null, "e": 6866, "s": 6834, "text": "Try the following example code." }, { "code": null, "e": 8009, "s": 6866, "text": "<html> \n <head>\n <title>JavaScript Animation</title> \n <script type = \"text/javascript\">\n <!--\n var imgObj = null;\n var animate ;\n \n function init() {\n imgObj = document.getElementById('myImage');\n imgObj.style.position= 'relative'; \n imgObj.style.left = '0px'; \n }\n function moveRight() {\n imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';\n animate = setTimeout(moveRight,20); // call moveRight in 20msec\n }\n function stop() {\n clearTimeout(animate);\n imgObj.style.left = '0px'; \n }\n \n window.onload = init;\n //-->\n </script>\n </head>\n \n <body> \n <form>\n <img id = \"myImage\" src = \"/images/html.gif\" />\n <p>Click the buttons below to handle animation</p>\n <input type = \"button\" value = \"Start\" onclick = \"moveRight();\" />\n <input type = \"button\" value = \"Stop\" onclick = \"stop();\" />\n </form> \n </body>\n</html>" }, { "code": null, "e": 8053, "s": 8009, "text": "Click the buttons below to handle animation" }, { "code": null, "e": 8121, "s": 8053, "text": "Here is a simple example showing image rollover with a mouse event." }, { "code": null, "e": 8176, "s": 8121, "text": "Let's see what we are using in the following example −" }, { "code": null, "e": 8344, "s": 8176, "text": "At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed." }, { "code": null, "e": 8512, "s": 8344, "text": "At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed." }, { "code": null, "e": 8591, "s": 8512, "text": "The Image() constructor creates and preloads a new image object called image1." }, { "code": null, "e": 8670, "s": 8591, "text": "The Image() constructor creates and preloads a new image object called image1." }, { "code": null, "e": 8760, "s": 8670, "text": "The src property is assigned the name of the external image file called /images/html.gif." }, { "code": null, "e": 8850, "s": 8760, "text": "The src property is assigned the name of the external image file called /images/html.gif." }, { "code": null, "e": 8937, "s": 8850, "text": "Similarly, we have created image2 object and assigned /images/http.gif in this object." }, { "code": null, "e": 9024, "s": 8937, "text": "Similarly, we have created image2 object and assigned /images/http.gif in this object." }, { "code": null, "e": 9145, "s": 9024, "text": "The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image." }, { "code": null, "e": 9266, "s": 9145, "text": "The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image." }, { "code": null, "e": 9454, "s": 9266, "text": "The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image)." }, { "code": null, "e": 9642, "s": 9454, "text": "The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image)." }, { "code": null, "e": 9820, "s": 9642, "text": "When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed." }, { "code": null, "e": 9998, "s": 9820, "text": "When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed." }, { "code": null, "e": 10098, "s": 9998, "text": "When the mouse is moved away from the link, the initial image html.gif will reappear on the screen." }, { "code": null, "e": 10198, "s": 10098, "text": "When the mouse is moved away from the link, the initial image html.gif will reappear on the screen." }, { "code": null, "e": 10953, "s": 10198, "text": "<html>\n \n <head>\n <title>Rollover with a Mouse Events</title>\n \n <script type = \"text/javascript\">\n <!--\n if(document.images) {\n var image1 = new Image(); // Preload an image\n image1.src = \"/images/html.gif\";\n var image2 = new Image(); // Preload second image\n image2.src = \"/images/http.gif\";\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Move your mouse over the image to see the result</p>\n \n <a href = \"#\" onMouseOver = \"document.myImage.src = image2.src;\"\n onMouseOut = \"document.myImage.src = image1.src;\">\n <img name = \"myImage\" src = \"/images/html.gif\" />\n </a>\n </body>\n</html>" }, { "code": null, "e": 11002, "s": 10953, "text": "Move your mouse over the image to see the result" }, { "code": null, "e": 11037, "s": 11002, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11051, "s": 11037, "text": " Anadi Sharma" }, { "code": null, "e": 11085, "s": 11051, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 11099, "s": 11085, "text": " Lets Kode It" }, { "code": null, "e": 11134, "s": 11099, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11151, "s": 11134, "text": " Frahaan Hussain" }, { "code": null, "e": 11186, "s": 11151, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11203, "s": 11186, "text": " Frahaan Hussain" }, { "code": null, "e": 11236, "s": 11203, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 11264, "s": 11236, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11298, "s": 11264, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 11326, "s": 11298, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11333, "s": 11326, "text": " Print" }, { "code": null, "e": 11344, "s": 11333, "text": " Add Notes" } ]
ARIMA Forecasting in Python. Manual and automatic ARIMA quickly up... | by Daniel Holmberg | Towards Data Science
I will use the weekly Spotify global top 200 list as a timeseries for experimenting with ARIMA models. The data ranges from 2017 to 2019 and the whole jupyter notebook is available here. Here is a subset of the data we are doing the forecasting on: feature_mean.head() ARIMA stands for Autoregressive Integrated Moving Average and it depends on three key variables p, d, q to be successful. Those are briefly as follows: p = number of lags / order of AR terms d = order of differencing q = number of lagged forecast errors / order of MA terms Mishra1 has written more in depth on the inner workings of the ARIMA model including the parameters. My goal here is to explain how to get ARIMA quickly up and running in Python both manually and automatically. I will do the forecasting on the acousticness feature: timeseries = feature_mean["acousticness"] Let’s use the Augmented Dickey Fuller (ADF) test to see if the timeseries is stationary: from statsmodels.tsa.stattools import adfullerprint("p-value:", adfuller(timeseries.dropna())[1]) p-value: 0.43 The p-value is greater than the significance level 0.05 so it is not stationary and differencing is as such needed, ie. d > 0. We start by finding out the order of differencing, d, using auto correlation: from statsmodels.graphics.tsaplots import plot_acf, plot_pacffig = plt.figure(figsize=(10, 10))ax1 = fig.add_subplot(311)fig = plot_acf(timeseries, ax=ax1, title="Autocorrelation on Original Series") ax2 = fig.add_subplot(312)fig = plot_acf(timeseries.diff().dropna(), ax=ax2, title="1st Order Differencing")ax3 = fig.add_subplot(313)fig = plot_acf(timeseries.diff().diff().dropna(), ax=ax3, title="2nd Order Differencing") The timeseries is stationary at d = 1 where only the first lag is above the significance level. If your series is slightly under differenced, try adding an additional AR term and if it is slightly over-differenced, maybe add an additional MA term. Knowing we should difference once, we go on to find out the order of AR, p. We get it by counting the number of lags above the level of significance in partial autocorrelation: plot_pacf(timeseries.diff().dropna(), lags=40) The first lag is the only one vastly above the signicance level and so p = 1. The autocorrelation function can tell the order of MA terms, q, needed to remove autocorrelation in the stationary series. plot_acf(timeseries.diff().dropna()) One lag can be found above the significance level and thus q = 1. from statsmodels.tsa.arima_model import ARIMAmodel = ARIMA(timeseries, order=(1, 1, 1))results = model.fit()results.plot_predict(1, 210) Akaike information criterion (AIC) estimates the relative amount of information lost by a given model. The less the better. results.summary() Model: ARIMA(1, 1, 1), ..., AIC: -806.848 ... We keep that in the back of our head and go on to test auto_arima: import pmdarima as pm Creating the model: automatic ARIMA using ADF to test stationarity, start values for p and q are set to 1, and the Spotify data is not assumed to be seasonal: def arimamodel(timeseries): automodel = pm.auto_arima(timeseries, start_p=1, start_q=1, test="adf", seasonal=False, trace=True) return automodel We want to plot it as neatly as was done using statsmodel’s plot_predict, therefore the area between the upper and lower prediction bounds has to be filled. def plotarima(n_periods, timeseries, automodel): # Forecast fc, confint = automodel.predict(n_periods=n_periods, return_conf_int=True) # Weekly index fc_ind = pd.date_range(timeseries.index[timeseries.shape[0]-1], periods=n_periods, freq="W") # Forecast series fc_series = pd.Series(fc, index=fc_ind) # Upper and lower confidence bounds lower_series = pd.Series(confint[:, 0], index=fc_ind) upper_series = pd.Series(confint[:, 1], index=fc_ind) # Create plot plt.figure(figsize=(10, 6)) plt.plot(timeseries) plt.plot(fc_series, color="red") plt.xlabel("date") plt.ylabel(timeseries.name) plt.fill_between(lower_series.index, lower_series, upper_series, color="k", alpha=0.25) plt.legend(("past", "forecast", "95% confidence interval"), loc="upper left") plt.show() Then we have all we need to fit and plot the model: automodel = arimamodel(feature_mean["danceability"])plotarima(70, feature_mean["acousticness"], automodel) automodel.summary() Model: ARIMA(1, 1, 1), ..., AIC: -806.848 ... This turned out to be the exact same parametrization we got manually. Wow that worked out well! It was far easier and faster to get the parameters right using auto_arima, the only slight downside is that the plotting has to be done from scratch to look as nice as the one statsmodels has built in. Huge credits to the exhausting guide2 on the ARIMA model over at MachineLearning+. Oh, and you can also try changing the feature from acousticness to something else eg. danceability using the aforementioned notebook. [1]: M. Mishra, Unboxing ARIMA Models (June 11 2018), https://towardsdatascience.com/unboxing-arima-models-1dc09d2746f8 [2]: ARIMA Model — Complete Guide to Time Series Forecasting in Python, https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/
[ { "code": null, "e": 359, "s": 172, "text": "I will use the weekly Spotify global top 200 list as a timeseries for experimenting with ARIMA models. The data ranges from 2017 to 2019 and the whole jupyter notebook is available here." }, { "code": null, "e": 421, "s": 359, "text": "Here is a subset of the data we are doing the forecasting on:" }, { "code": null, "e": 441, "s": 421, "text": "feature_mean.head()" }, { "code": null, "e": 593, "s": 441, "text": "ARIMA stands for Autoregressive Integrated Moving Average and it depends on three key variables p, d, q to be successful. Those are briefly as follows:" }, { "code": null, "e": 632, "s": 593, "text": "p = number of lags / order of AR terms" }, { "code": null, "e": 658, "s": 632, "text": "d = order of differencing" }, { "code": null, "e": 715, "s": 658, "text": "q = number of lagged forecast errors / order of MA terms" }, { "code": null, "e": 981, "s": 715, "text": "Mishra1 has written more in depth on the inner workings of the ARIMA model including the parameters. My goal here is to explain how to get ARIMA quickly up and running in Python both manually and automatically. I will do the forecasting on the acousticness feature:" }, { "code": null, "e": 1023, "s": 981, "text": "timeseries = feature_mean[\"acousticness\"]" }, { "code": null, "e": 1112, "s": 1023, "text": "Let’s use the Augmented Dickey Fuller (ADF) test to see if the timeseries is stationary:" }, { "code": null, "e": 1210, "s": 1112, "text": "from statsmodels.tsa.stattools import adfullerprint(\"p-value:\", adfuller(timeseries.dropna())[1])" }, { "code": null, "e": 1224, "s": 1210, "text": "p-value: 0.43" }, { "code": null, "e": 1351, "s": 1224, "text": "The p-value is greater than the significance level 0.05 so it is not stationary and differencing is as such needed, ie. d > 0." }, { "code": null, "e": 1429, "s": 1351, "text": "We start by finding out the order of differencing, d, using auto correlation:" }, { "code": null, "e": 1897, "s": 1429, "text": "from statsmodels.graphics.tsaplots import plot_acf, plot_pacffig = plt.figure(figsize=(10, 10))ax1 = fig.add_subplot(311)fig = plot_acf(timeseries, ax=ax1, title=\"Autocorrelation on Original Series\") ax2 = fig.add_subplot(312)fig = plot_acf(timeseries.diff().dropna(), ax=ax2, title=\"1st Order Differencing\")ax3 = fig.add_subplot(313)fig = plot_acf(timeseries.diff().diff().dropna(), ax=ax3, title=\"2nd Order Differencing\")" }, { "code": null, "e": 2145, "s": 1897, "text": "The timeseries is stationary at d = 1 where only the first lag is above the significance level. If your series is slightly under differenced, try adding an additional AR term and if it is slightly over-differenced, maybe add an additional MA term." }, { "code": null, "e": 2322, "s": 2145, "text": "Knowing we should difference once, we go on to find out the order of AR, p. We get it by counting the number of lags above the level of significance in partial autocorrelation:" }, { "code": null, "e": 2369, "s": 2322, "text": "plot_pacf(timeseries.diff().dropna(), lags=40)" }, { "code": null, "e": 2447, "s": 2369, "text": "The first lag is the only one vastly above the signicance level and so p = 1." }, { "code": null, "e": 2570, "s": 2447, "text": "The autocorrelation function can tell the order of MA terms, q, needed to remove autocorrelation in the stationary series." }, { "code": null, "e": 2607, "s": 2570, "text": "plot_acf(timeseries.diff().dropna())" }, { "code": null, "e": 2673, "s": 2607, "text": "One lag can be found above the significance level and thus q = 1." }, { "code": null, "e": 2810, "s": 2673, "text": "from statsmodels.tsa.arima_model import ARIMAmodel = ARIMA(timeseries, order=(1, 1, 1))results = model.fit()results.plot_predict(1, 210)" }, { "code": null, "e": 2934, "s": 2810, "text": "Akaike information criterion (AIC) estimates the relative amount of information lost by a given model. The less the better." }, { "code": null, "e": 2952, "s": 2934, "text": "results.summary()" }, { "code": null, "e": 2998, "s": 2952, "text": "Model: ARIMA(1, 1, 1), ..., AIC: -806.848 ..." }, { "code": null, "e": 3065, "s": 2998, "text": "We keep that in the back of our head and go on to test auto_arima:" }, { "code": null, "e": 3087, "s": 3065, "text": "import pmdarima as pm" }, { "code": null, "e": 3246, "s": 3087, "text": "Creating the model: automatic ARIMA using ADF to test stationarity, start values for p and q are set to 1, and the Spotify data is not assumed to be seasonal:" }, { "code": null, "e": 3544, "s": 3246, "text": "def arimamodel(timeseries): automodel = pm.auto_arima(timeseries, start_p=1, start_q=1, test=\"adf\", seasonal=False, trace=True) return automodel" }, { "code": null, "e": 3701, "s": 3544, "text": "We want to plot it as neatly as was done using statsmodel’s plot_predict, therefore the area between the upper and lower prediction bounds has to be filled." }, { "code": null, "e": 4683, "s": 3701, "text": "def plotarima(n_periods, timeseries, automodel): # Forecast fc, confint = automodel.predict(n_periods=n_periods, return_conf_int=True) # Weekly index fc_ind = pd.date_range(timeseries.index[timeseries.shape[0]-1], periods=n_periods, freq=\"W\") # Forecast series fc_series = pd.Series(fc, index=fc_ind) # Upper and lower confidence bounds lower_series = pd.Series(confint[:, 0], index=fc_ind) upper_series = pd.Series(confint[:, 1], index=fc_ind) # Create plot plt.figure(figsize=(10, 6)) plt.plot(timeseries) plt.plot(fc_series, color=\"red\") plt.xlabel(\"date\") plt.ylabel(timeseries.name) plt.fill_between(lower_series.index, lower_series, upper_series, color=\"k\", alpha=0.25) plt.legend((\"past\", \"forecast\", \"95% confidence interval\"), loc=\"upper left\") plt.show()" }, { "code": null, "e": 4735, "s": 4683, "text": "Then we have all we need to fit and plot the model:" }, { "code": null, "e": 4842, "s": 4735, "text": "automodel = arimamodel(feature_mean[\"danceability\"])plotarima(70, feature_mean[\"acousticness\"], automodel)" }, { "code": null, "e": 4862, "s": 4842, "text": "automodel.summary()" }, { "code": null, "e": 4908, "s": 4862, "text": "Model: ARIMA(1, 1, 1), ..., AIC: -806.848 ..." }, { "code": null, "e": 5206, "s": 4908, "text": "This turned out to be the exact same parametrization we got manually. Wow that worked out well! It was far easier and faster to get the parameters right using auto_arima, the only slight downside is that the plotting has to be done from scratch to look as nice as the one statsmodels has built in." }, { "code": null, "e": 5423, "s": 5206, "text": "Huge credits to the exhausting guide2 on the ARIMA model over at MachineLearning+. Oh, and you can also try changing the feature from acousticness to something else eg. danceability using the aforementioned notebook." }, { "code": null, "e": 5543, "s": 5423, "text": "[1]: M. Mishra, Unboxing ARIMA Models (June 11 2018), https://towardsdatascience.com/unboxing-arima-models-1dc09d2746f8" } ]
Redis - Java
Before you start using Redis in your Java programs, you need to make sure that you have Redis Java driver and Java set up on the machine. You can check our Java tutorial for Java installation on your machine. Now, let us see how to set up Redis Java driver. You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it. You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it. You need to include the jedis.jar into your classpath. You need to include the jedis.jar into your classpath. import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //check whether server is running or not System.out.println("Server is running: "+jedis.ping()); } } Now, let's compile and run the above program to test the connection to Redis server. You can change your path as per your requirement. We are assuming the current version of jedis.jar is available in the current path. $javac RedisJava.java $java RedisJava Connection to server sucessfully Server is running: PONG import redis.clients.jedis.Jedis; public class RedisStringJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //set the data in redis string jedis.set("tutorial-name", "Redis tutorial"); // Get the stored data and print it System.out.println("Stored string in redis:: "+ jedis.get("tutorial-name")); } } Now, let's compile and run the above program. $javac RedisStringJava.java $java RedisStringJava Connection to server sucessfully Stored string in redis:: Redis tutorial import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list jedis.lpush("tutorial-list", "Redis"); jedis.lpush("tutorial-list", "Mongodb"); jedis.lpush("tutorial-list", "Mysql"); // Get the stored data and print it List<String> list = jedis.lrange("tutorial-list", 0 ,5); for(int i = 0; i<list.size(); i++) { System.out.println("Stored string in redis:: "+list.get(i)); } } } Now, let's compile and run the above program. $javac RedisListJava.java $java RedisListJava Connection to server sucessfully Stored string in redis:: Redis Stored string in redis:: Mongodb Stored string in redis:: Mysql import redis.clients.jedis.Jedis; public class RedisKeyJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list // Get the stored data and print it List<String> list = jedis.keys("*"); for(int i = 0; i<list.size(); i++) { System.out.println("List of stored keys:: "+list.get(i)); } } } Now, let's compile and run the above program. $javac RedisKeyJava.java $java RedisKeyJava Connection to server sucessfully List of stored keys:: tutorial-name List of stored keys:: tutorial-list 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 2045, "text": "Before you start using Redis in your Java programs, you need to make sure that you have Redis Java driver and Java set up on the machine. You can check our Java tutorial for Java installation on your machine." }, { "code": null, "e": 2303, "s": 2254, "text": "Now, let us see how to set up Redis Java driver." }, { "code": null, "e": 2414, "s": 2303, "text": "You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it." }, { "code": null, "e": 2525, "s": 2414, "text": "You need to download the jar from the path Download jedis.jar. Make sure to download the latest release of it." }, { "code": null, "e": 2580, "s": 2525, "text": "You need to include the jedis.jar into your classpath." }, { "code": null, "e": 2635, "s": 2580, "text": "You need to include the jedis.jar into your classpath." }, { "code": null, "e": 3019, "s": 2635, "text": "import redis.clients.jedis.Jedis; \n\npublic class RedisJava { \n public static void main(String[] args) { \n //Connecting to Redis server on localhost \n Jedis jedis = new Jedis(\"localhost\"); \n System.out.println(\"Connection to server sucessfully\"); \n //check whether server is running or not \n System.out.println(\"Server is running: \"+jedis.ping()); \n } \n} " }, { "code": null, "e": 3237, "s": 3019, "text": "Now, let's compile and run the above program to test the connection to Redis server. You can change your path as per your requirement. We are assuming the current version of jedis.jar is available in the current path." }, { "code": null, "e": 3336, "s": 3237, "text": "$javac RedisJava.java \n$java RedisJava \nConnection to server sucessfully \nServer is running: PONG\n" }, { "code": null, "e": 3832, "s": 3336, "text": "import redis.clients.jedis.Jedis; \n\npublic class RedisStringJava { \n public static void main(String[] args) { \n //Connecting to Redis server on localhost \n Jedis jedis = new Jedis(\"localhost\"); \n System.out.println(\"Connection to server sucessfully\"); \n //set the data in redis string \n jedis.set(\"tutorial-name\", \"Redis tutorial\"); \n // Get the stored data and print it \n System.out.println(\"Stored string in redis:: \"+ jedis.get(\"tutorial-name\")); \n } \n}" }, { "code": null, "e": 3878, "s": 3832, "text": "Now, let's compile and run the above program." }, { "code": null, "e": 4006, "s": 3878, "text": "$javac RedisStringJava.java \n$java RedisStringJava \nConnection to server sucessfully \nStored string in redis:: Redis tutorial \n" }, { "code": null, "e": 4706, "s": 4006, "text": "import redis.clients.jedis.Jedis; \n\npublic class RedisListJava { \n public static void main(String[] args) { \n \n //Connecting to Redis server on localhost \n Jedis jedis = new Jedis(\"localhost\"); \n System.out.println(\"Connection to server sucessfully\"); \n \n //store data in redis list \n jedis.lpush(\"tutorial-list\", \"Redis\"); \n jedis.lpush(\"tutorial-list\", \"Mongodb\"); \n jedis.lpush(\"tutorial-list\", \"Mysql\"); \n // Get the stored data and print it \n List<String> list = jedis.lrange(\"tutorial-list\", 0 ,5); \n \n for(int i = 0; i<list.size(); i++) { \n System.out.println(\"Stored string in redis:: \"+list.get(i)); \n } \n } \n} " }, { "code": null, "e": 4752, "s": 4706, "text": "Now, let's compile and run the above program." }, { "code": null, "e": 4932, "s": 4752, "text": "$javac RedisListJava.java \n$java RedisListJava \nConnection to server sucessfully \nStored string in redis:: Redis \nStored string in redis:: Mongodb \nStored string in redis:: Mysql\n" }, { "code": null, "e": 5460, "s": 4932, "text": "import redis.clients.jedis.Jedis; \n\npublic class RedisKeyJava { \n public static void main(String[] args) { \n \n //Connecting to Redis server on localhost \n Jedis jedis = new Jedis(\"localhost\"); \n System.out.println(\"Connection to server sucessfully\"); \n //store data in redis list \n // Get the stored data and print it \n List<String> list = jedis.keys(\"*\"); \n \n for(int i = 0; i<list.size(); i++) { \n System.out.println(\"List of stored keys:: \"+list.get(i)); \n } \n } \n}" }, { "code": null, "e": 5506, "s": 5460, "text": "Now, let's compile and run the above program." }, { "code": null, "e": 5661, "s": 5506, "text": "$javac RedisKeyJava.java \n$java RedisKeyJava \nConnection to server sucessfully \nList of stored keys:: tutorial-name \nList of stored keys:: tutorial-list \n" }, { "code": null, "e": 5693, "s": 5661, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 5713, "s": 5693, "text": " Skillbakerystudios" }, { "code": null, "e": 5720, "s": 5713, "text": " Print" }, { "code": null, "e": 5731, "s": 5720, "text": " Add Notes" } ]
How to Dockerize an Existing Flask Application | by Mahbub Zaman | Towards Data Science
In this post, I’ll explain how to Dockerize an existing Flask application. I’m going to use one of my Python projects for demonstration purposes. By using a Dockerized Flask application, other developers can easily run the project without any environment management, which is great for saving time and effort. Moreover, developers can focus on development. If you’re new to Docker, then read the following post where I’ve covered some basics. towardsdatascience.com First, you will need to install Docker and download a git repository from GitHub. For this setup, I’m using macOS. Now, I’ll create a Docker image that contains Python, and the web application framework Flask as a dependency. Let’s break down the individual ingredients of the Dockerfile file. FROM python:3.9.1ADD . /python-flaskWORKDIR /python-flaskRUN pip install -r requirements.txt To define the parent image, we need to use the From command. Here we are using the pre-built official image of Python from Docker Hub. To add everything in the current folder into a directory in the image called python-flask we need to use the ADD command. After that, we are going to set the working directory to python-flask using the WORKDIR command. Finally, using pip, we are going to install our application’s dependency: Flask. Now, I’ll create a Docker compose file to run a Docker container using the Docker image we just created. Let’s break down the individual ingredients of the docker-compose.yml file. version: "3.8"services: app: build: . command: python main.py ports: - "5000:5000" volumes: - .:/python-flask Inside the docker-compose.yml file, we have the version, services, app, build, command, ports, and volumes tag. The version tag is used to define the Compose file format. Have a look at the documentation to learn more. The services tag is used to define the services we want to use for our application. For our application, we only have one service called app. The build command will build our Docker image using the Dockerfile we created earlier. The command tag is used to run the main.py file. The ports tag is used to define both host and container ports. It maps port 5000 on the host to port 5000 on the container. Because by default, Flask runs on port 5000. Finally, the volumes tag is used to mount a folder from the host machine to the container. Now we are going to run the following command from the same directory where the docker-compose.yml file is located. The docker compose up command will start and run the entire app. docker compose up Congratulations! We are now successfully running a Flask application inside a Docker container. You can now access the Flask application via your favorite web browser by vising the URL http://localhost:5000/. Now run docker ps to see all the running containers. Here, I have one. Finally, let’s break down the individual ingredients of the main.py file. from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return 'Hello World'if __name__ == '__main__': app.run(host="0.0.0.0", debug=True) First, we imported the Flask class and then created an instance of that class. After that, using route() decorator, we are telling Flask to trigger the hello_world() function based on the URL. Finally, we have the entry point of our code, where we are running the Flask application using the run() method. The first argument ishost=”0.0.0.0" which makes the application available on all public IPs. The second argument is debug=True will enable debug mode. You can read more here about a Flask application and about debugging from here. Now you know how to run a Flask application inside a Docker container. I hope this will help you to get started with Flask and Docker. Happy coding!
[ { "code": null, "e": 615, "s": 172, "text": "In this post, I’ll explain how to Dockerize an existing Flask application. I’m going to use one of my Python projects for demonstration purposes. By using a Dockerized Flask application, other developers can easily run the project without any environment management, which is great for saving time and effort. Moreover, developers can focus on development. If you’re new to Docker, then read the following post where I’ve covered some basics." }, { "code": null, "e": 638, "s": 615, "text": "towardsdatascience.com" }, { "code": null, "e": 753, "s": 638, "text": "First, you will need to install Docker and download a git repository from GitHub. For this setup, I’m using macOS." }, { "code": null, "e": 932, "s": 753, "text": "Now, I’ll create a Docker image that contains Python, and the web application framework Flask as a dependency. Let’s break down the individual ingredients of the Dockerfile file." }, { "code": null, "e": 1025, "s": 932, "text": "FROM python:3.9.1ADD . /python-flaskWORKDIR /python-flaskRUN pip install -r requirements.txt" }, { "code": null, "e": 1460, "s": 1025, "text": "To define the parent image, we need to use the From command. Here we are using the pre-built official image of Python from Docker Hub. To add everything in the current folder into a directory in the image called python-flask we need to use the ADD command. After that, we are going to set the working directory to python-flask using the WORKDIR command. Finally, using pip, we are going to install our application’s dependency: Flask." }, { "code": null, "e": 1641, "s": 1460, "text": "Now, I’ll create a Docker compose file to run a Docker container using the Docker image we just created. Let’s break down the individual ingredients of the docker-compose.yml file." }, { "code": null, "e": 1774, "s": 1641, "text": "version: \"3.8\"services: app: build: . command: python main.py ports: - \"5000:5000\" volumes: - .:/python-flask" }, { "code": null, "e": 2531, "s": 1774, "text": "Inside the docker-compose.yml file, we have the version, services, app, build, command, ports, and volumes tag. The version tag is used to define the Compose file format. Have a look at the documentation to learn more. The services tag is used to define the services we want to use for our application. For our application, we only have one service called app. The build command will build our Docker image using the Dockerfile we created earlier. The command tag is used to run the main.py file. The ports tag is used to define both host and container ports. It maps port 5000 on the host to port 5000 on the container. Because by default, Flask runs on port 5000. Finally, the volumes tag is used to mount a folder from the host machine to the container." }, { "code": null, "e": 2712, "s": 2531, "text": "Now we are going to run the following command from the same directory where the docker-compose.yml file is located. The docker compose up command will start and run the entire app." }, { "code": null, "e": 2730, "s": 2712, "text": "docker compose up" }, { "code": null, "e": 2939, "s": 2730, "text": "Congratulations! We are now successfully running a Flask application inside a Docker container. You can now access the Flask application via your favorite web browser by vising the URL http://localhost:5000/." }, { "code": null, "e": 3010, "s": 2939, "text": "Now run docker ps to see all the running containers. Here, I have one." }, { "code": null, "e": 3084, "s": 3010, "text": "Finally, let’s break down the individual ingredients of the main.py file." }, { "code": null, "e": 3245, "s": 3084, "text": "from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world():\treturn 'Hello World'if __name__ == '__main__':\tapp.run(host=\"0.0.0.0\", debug=True)" }, { "code": null, "e": 3782, "s": 3245, "text": "First, we imported the Flask class and then created an instance of that class. After that, using route() decorator, we are telling Flask to trigger the hello_world() function based on the URL. Finally, we have the entry point of our code, where we are running the Flask application using the run() method. The first argument ishost=”0.0.0.0\" which makes the application available on all public IPs. The second argument is debug=True will enable debug mode. You can read more here about a Flask application and about debugging from here." } ]
Python | Summation of tuples in list - GeeksforGeeks
25 Aug, 2021 Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have application in cases in which we deal with a lot of records data. Let’s discuss certain ways in which this problem can be solved.Method #1 : Using sum() + map() Combination of above functions can be used to solve this particular problem. In this the task of summation is performed by sum(), and applying the summation functionality to each element in tuple list is performed by map(). Python3 # Python3 code to demonstrate working of# Summation of tuples in list# using sum() + map() # initialize list of tupletest_list = [(1, 3), (5, 6, 7), (2, 6)] # printing original tuples listprint("The original list : " + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(map(sum, test_list)) # printing resultprint("The summation of all tuple elements are : " + str(res)) The original list : [(1, 3), (5, 6, 7), (2, 6)] The summation of all tuple elements are : 30 Method #2 : Using sum() + izip() The combination of above functions can be used to perform this particular task. In this, we perform the task of map() using izip(). It helps to club all the elements for summation by sum(). Works only for single element tuple and only with Python2. Python3 # Python3 code to demonstrate working of# Summation of tuples in list# using sum() + izip()from itertools import izip # initialize list of tupletest_list = [(1, ), (5, ), (2, )] # printing original tuples listprint("The original list : " + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(*izip(*test_list)) # printing resultprint("The summation of all tuple elements are : " + str(res)) The original list : [(1, ), (5, ), (2, )] The summation of all tuple elements are : 8 gabaa406 Python tuple-programs 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 Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24468, "s": 24440, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25019, "s": 24468, "text": "Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have application in cases in which we deal with a lot of records data. Let’s discuss certain ways in which this problem can be solved.Method #1 : Using sum() + map() Combination of above functions can be used to solve this particular problem. In this the task of summation is performed by sum(), and applying the summation functionality to each element in tuple list is performed by map(). " }, { "code": null, "e": 25027, "s": 25019, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Summation of tuples in list# using sum() + map() # initialize list of tupletest_list = [(1, 3), (5, 6, 7), (2, 6)] # printing original tuples listprint(\"The original list : \" + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(map(sum, test_list)) # printing resultprint(\"The summation of all tuple elements are : \" + str(res))", "e": 25423, "s": 25027, "text": null }, { "code": null, "e": 25516, "s": 25423, "text": "The original list : [(1, 3), (5, 6, 7), (2, 6)]\nThe summation of all tuple elements are : 30" }, { "code": null, "e": 25802, "s": 25518, "text": " Method #2 : Using sum() + izip() The combination of above functions can be used to perform this particular task. In this, we perform the task of map() using izip(). It helps to club all the elements for summation by sum(). Works only for single element tuple and only with Python2. " }, { "code": null, "e": 25810, "s": 25802, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Summation of tuples in list# using sum() + izip()from itertools import izip # initialize list of tupletest_list = [(1, ), (5, ), (2, )] # printing original tuples listprint(\"The original list : \" + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(*izip(*test_list)) # printing resultprint(\"The summation of all tuple elements are : \" + str(res))", "e": 26225, "s": 25810, "text": null }, { "code": null, "e": 26311, "s": 26225, "text": "The original list : [(1, ), (5, ), (2, )]\nThe summation of all tuple elements are : 8" }, { "code": null, "e": 26322, "s": 26313, "text": "gabaa406" }, { "code": null, "e": 26344, "s": 26322, "text": "Python tuple-programs" }, { "code": null, "e": 26351, "s": 26344, "text": "Python" }, { "code": null, "e": 26367, "s": 26351, "text": "Python Programs" }, { "code": null, "e": 26465, "s": 26367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26483, "s": 26465, "text": "Python Dictionary" }, { "code": null, "e": 26518, "s": 26483, "text": "Read a file line by line in Python" }, { "code": null, "e": 26540, "s": 26518, "text": "Enumerate() in Python" }, { "code": null, "e": 26572, "s": 26540, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26602, "s": 26572, "text": "Iterate over a list in Python" }, { "code": null, "e": 26624, "s": 26602, "text": "Defaultdict in Python" }, { "code": null, "e": 26670, "s": 26624, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26709, "s": 26670, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26747, "s": 26709, "text": "Python | Convert a list to dictionary" } ]
Kotlin Functions
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are also known as methods. So it turns out you already know what a function is. You have been using it the whole time through this tutorial! For example, println() is a function. It is used to output/print text to the screen: fun main() { println("Hello World") } To create your own function, use the fun keyword, and write the name of the function, followed by parantheses (): Create a function named "myFunction" that should output some text: fun myFunction() { println("I just got executed!") } Now that you have created a function, you can execute it by calling it. To call a function in Kotlin, write the name of the function followed by two parantheses (). In the following example, myFunction() will print some text (the action), when it is called: fun main() { myFunction() // Call myFunction } // Outputs "I just got executed!" A function can be called multiple times, if you want: fun main() { myFunction() myFunction() myFunction() } // I just got executed! // I just got executed! // I just got executed! Information can be passed to functions as parameter. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. Just note that you must specify the type of each parameter (Int, String, etc). The following example has a function that takes a String called fname as parameter. When the function is called, we pass along a first name, which is used inside the function to print the full name: fun myFunction(fname: String) { println(fname + " Doe") } fun main() { myFunction("John") myFunction("Jane") myFunction("George") } // John Doe // Jane Doe // George Doe When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while John, Jane and George are arguments. You can have as many parameters as you like: fun myFunction(fname: String, age: Int) { println(fname + " is " + age) } fun main() { myFunction("John", 35) myFunction("Jane", 32) myFunction("George", 15) } // John is 35 // Jane is 32 // George is 15 Note: When working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order. In the examples above, we used functions to output a value. In the following example, we will use a function to return a value and assign it to a variable. To return a value, use the return keyword, and specify the return type after the function's parantheses (Int in this example): A function with one Int parameter, and Int return type: fun myFunction(x: Int): Int { return (x + 5) } fun main() { var result = myFunction(3) println(result) } // 8 (3 + 5) Using two parameters: A function with two Int parameters, and Int return type: fun myFunction(x: Int, y: Int): Int { return (x + y) } fun main() { var result = myFunction(3, 5) println(result) } // 8 (3 + 5) There is also a shorter syntax for returning values. You can use the = operator instead of return without specifying the return type. Kotlin is smart enough to automatically find out what it is: fun myFunction(x: Int, y: Int) = x + y fun main() { var result = myFunction(3, 5) println(result) } // 8 (3 + 5) We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 65, "s": 0, "text": "A function is a block of code which only runs when it is called." }, { "code": null, "e": 122, "s": 65, "text": "You can pass data, known as parameters, into a function." }, { "code": null, "e": 205, "s": 122, "text": "Functions are used to perform certain actions, and they are also known as methods." }, { "code": null, "e": 320, "s": 205, "text": "So it turns out you already know what a function is. You have been using it \nthe whole time through this tutorial!" }, { "code": null, "e": 405, "s": 320, "text": "For example, println() is a function. It is used to output/print text to the screen:" }, { "code": null, "e": 445, "s": 405, "text": "fun main() {\n println(\"Hello World\")\n}" }, { "code": null, "e": 560, "s": 445, "text": "To create your own function, use the fun keyword, and write the name of the \nfunction, followed by parantheses ():" }, { "code": null, "e": 627, "s": 560, "text": "Create a function named \"myFunction\" that should output some text:" }, { "code": null, "e": 683, "s": 627, "text": "fun myFunction() {\n println(\"I just got executed!\")\n} " }, { "code": null, "e": 756, "s": 683, "text": "Now that you have created a function, you can execute it by calling \nit." }, { "code": null, "e": 850, "s": 756, "text": "To call a function in Kotlin, write the name of the function followed by two \nparantheses ()." }, { "code": null, "e": 944, "s": 850, "text": "In the following example, myFunction() will \nprint some text (the action), when it is called:" }, { "code": null, "e": 1029, "s": 944, "text": "fun main() {\n myFunction() // Call myFunction\n}\n\n// Outputs \"I just got executed!\" " }, { "code": null, "e": 1083, "s": 1029, "text": "A function can be called multiple times, if you want:" }, { "code": null, "e": 1217, "s": 1083, "text": "fun main() {\n myFunction()\n myFunction()\n myFunction()\n}\n\n// I just got executed!\n// I just got executed!\n// I just got executed! " }, { "code": null, "e": 1270, "s": 1217, "text": "Information can be passed to functions as parameter." }, { "code": null, "e": 1502, "s": 1270, "text": "Parameters are specified after the function name, inside the parentheses.\nYou can add as many parameters as you want, just separate them with a comma. \nJust note that you must specify the type of each parameter (Int, String, etc). " }, { "code": null, "e": 1704, "s": 1502, "text": "\nThe following example has a \nfunction that takes a String called fname as parameter.\nWhen the function is called, we pass along a first name,\nwhich is used inside the function to print the full name:\n" }, { "code": null, "e": 1887, "s": 1704, "text": "fun myFunction(fname: String) {\n println(fname + \" Doe\")\n}\n\nfun main() {\n myFunction(\"John\")\n myFunction(\"Jane\")\n myFunction(\"George\")\n}\n \n// John Doe\n// Jane Doe\n// George Doe " }, { "code": null, "e": 2052, "s": 1887, "text": "When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while \nJohn, Jane and \nGeorge are arguments." }, { "code": null, "e": 2097, "s": 2052, "text": "You can have as many parameters as you like:" }, { "code": null, "e": 2312, "s": 2097, "text": "fun myFunction(fname: String, age: Int) {\n println(fname + \" is \" + age)\n}\n\nfun main() {\n myFunction(\"John\", 35)\n myFunction(\"Jane\", 32)\n myFunction(\"George\", 15)\n}\n\n// John is 35\n// Jane is 32\n// George is 15 " }, { "code": null, "e": 2492, "s": 2312, "text": "Note: When working with multiple parameters, the function call must \nhave the same number of arguments as there are parameters, and the arguments must be passed in the same order." }, { "code": null, "e": 2649, "s": 2492, "text": "In the examples above, we used functions to output a value. In the following example, we will use a function to \nreturn a value and assign it to a variable." }, { "code": null, "e": 2778, "s": 2649, "text": "To return a value, use the return keyword, and specify the \nreturn type after \nthe function's parantheses (Int in this example):" }, { "code": null, "e": 2834, "s": 2778, "text": "A function with one Int parameter, and Int return type:" }, { "code": null, "e": 2961, "s": 2834, "text": "fun myFunction(x: Int): Int {\n return (x + 5)\n}\n\nfun main() {\n var result = myFunction(3)\n println(result)\n}\n\n// 8 (3 + 5) " }, { "code": null, "e": 2983, "s": 2961, "text": "Using two parameters:" }, { "code": null, "e": 3040, "s": 2983, "text": "A function with two Int parameters, and Int return type:" }, { "code": null, "e": 3178, "s": 3040, "text": "fun myFunction(x: Int, y: Int): Int {\n return (x + y)\n}\n\nfun main() {\n var result = myFunction(3, 5)\n println(result)\n}\n\n// 8 (3 + 5) " }, { "code": null, "e": 3374, "s": 3178, "text": "There is also a shorter syntax for returning values. You can use the = operator instead of return \nwithout specifying the return type. Kotlin is smart enough to automatically find out what it is:" }, { "code": null, "e": 3494, "s": 3374, "text": "fun myFunction(x: Int, y: Int) = x + y\n\nfun main() {\n var result = myFunction(3, 5)\n println(result)\n}\n\n// 8 (3 + 5) " }, { "code": null, "e": 3527, "s": 3494, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3569, "s": 3527, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3676, "s": 3569, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3695, "s": 3676, "text": "help@w3schools.com" } ]
HTML - Button Tag
The HTML <button> tag is used for creating a button within HTML form. You can also use <input> tag to create similar buttons. <!DOCTYPE html> <html> <head> <title>HTML Button Tag</title> </head> <body> <form> <button name = "button" value = "OK" type = "button">Click Me</button> </form> </body> </html> This will produce the following result − This tag supports all the global attributes described in HTML Attribute Reference The HTML <button> tag also supports the following additional attributes − This tag supports all the event attributes described in HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2500, "s": 2374, "text": "The HTML <button> tag is used for creating a button within HTML form. You can also use <input> tag to create similar buttons." }, { "code": null, "e": 2720, "s": 2500, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Button Tag</title>\n </head>\n\n <body>\n <form>\n <button name = \"button\" value = \"OK\" type = \"button\">Click Me</button>\n </form>\n </body>\n\n</html>" }, { "code": null, "e": 2761, "s": 2720, "text": "This will produce the following result −" }, { "code": null, "e": 2843, "s": 2761, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 2918, "s": 2843, "text": "The HTML <button> tag also supports the following additional attributes −" }, { "code": null, "e": 2996, "s": 2918, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 3029, "s": 2996, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3043, "s": 3029, "text": " Anadi Sharma" }, { "code": null, "e": 3078, "s": 3043, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3092, "s": 3078, "text": " Anadi Sharma" }, { "code": null, "e": 3127, "s": 3092, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3144, "s": 3127, "text": " Frahaan Hussain" }, { "code": null, "e": 3179, "s": 3144, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3210, "s": 3179, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3243, "s": 3210, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3274, "s": 3243, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3309, "s": 3274, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3340, "s": 3309, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3347, "s": 3340, "text": " Print" }, { "code": null, "e": 3358, "s": 3347, "text": " Add Notes" } ]
VBScript Len Function
The Len Function returns the length of the given input string including the blank spaces. Len(String) <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> var1 = "Microsoft VBScript" document.write("Length of var1 is : " & Len(var1) & "<br />") var2 = "Microsoft VBScript" document.write("Length of var2 is : " & Len(var2) & "<br />") </script> </body> </html> When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result − Length of var1 is : 18 Length of var2 is : 36 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2080, "text": "The Len Function returns the length of the given input string including the blank spaces." }, { "code": null, "e": 2183, "s": 2170, "text": "Len(String)\n" }, { "code": null, "e": 2529, "s": 2183, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n var1 = \"Microsoft VBScript\"\n document.write(\"Length of var1 is : \" & Len(var1) & \"<br />\")\n\n var2 = \"Microsoft VBScript\"\n document.write(\"Length of var2 is : \" & Len(var2) & \"<br />\")\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 2650, "s": 2529, "text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −" }, { "code": null, "e": 2697, "s": 2650, "text": "Length of var1 is : 18\nLength of var2 is : 36\n" }, { "code": null, "e": 2730, "s": 2697, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 2747, "s": 2730, "text": " Frahaan Hussain" }, { "code": null, "e": 2754, "s": 2747, "text": " Print" }, { "code": null, "e": 2765, "s": 2754, "text": " Add Notes" } ]
Loading large datasets in Pandas. Effectively using Chunking and SQL for... | by Parul Pandey | Towards Data Science
The pandas’ library is a vital member of the Data Science ecosystem. However, the fact that it is unable to analyze datasets larger than memory makes it a little tricky for big data. Consider a situation when we want to analyze a large dataset by using only pandas. What kind of problems can we run into? For instance, let’s take a file comprising 3GB of data summarising yellow taxi trip data for March in 2016. To perform any sort of analysis, we will have to import it into memory. We readily use the pandas’ read_csv() function to perform the reading operation as follows: import pandas as pddf = pd.read_csv('yellow_tripdata_2016-03.csv') When I ran the cell/file, my system threw the following Memory Error. (The memory error would depend upon the capacity of the system that you are using). Before criticizing pandas, it is important to understand that pandas may not always be the right tool for every task. Pandas lack multiprocessing support, and other libraries are better at handling big data. One such alternative is Dask, which gives a pandas-like API foto work with larger than memory datasets. Even the pandas’ documentation explicitly mentions that for big data: it’s worth considering not using pandas. Pandas isn’t the right tool for all situations. In this article, however, we shall look at a method called chunking, by which you can load out of memory datasets in pandas. This method can sometimes offer a healthy way out to manage the out-of-memory problem in pandas but may not work all the time, which we shall see later in the chapter. Essentially we will look at two ways to import large datasets in python: Using pd.read_csv() with chunksize Using SQL and pandas Before working with an example, let’s try and understand what we mean by the work chunking. According to Wikipedia, Chunking refers to strategies for improving performance by using special knowledge of a situation to aggregate related memory-allocation requests. In order words, instead of reading all the data at once in the memory, we can divide into smaller parts or chunks. In the case of CSV files, this would mean only loading a few lines into the memory at a given point in time. Pandas’ read_csv() function comes with a chunk size parameter that controls the size of the chunk. Let’s see it in action. We’ll be working with the exact dataset that we used earlier in the article, but instead of loading it all in a single go, we’ll divide it into parts and load it. To enable chunking, we will declare the size of the chunk in the beginning. Then using read_csv() with the chunksize parameter, returns an object we can iterate over. chunk_size=50000batch_no=1for chunk in pd.read_csv('yellow_tripdata_2016-02.csv',chunksize=chunk_size): chunk.to_csv('chunk'+str(batch_no)+'.csv',index=False) batch_no+=1 We choose a chunk size of 50,000, which means at a time, only 50,000 rows of data will be imported. Here is a video of how the main CSV file splits into multiple files. We now have multiple chunks, and each chunk can easily be loaded as a pandas dataframe. df1 = pd.read_csv('chunk1.csv')df1.head() It works like a charm!. No more memory error. Let’s quickly look at the memory usage by this chunk: df1.info() Chunking creates various subsets of the data. As a result, it works well when the operation you’re performing requires zero or minimal coordination between chunks. This is an important consideration. Another drawback of using chunking is that some operations like groupby are much harder to do chunks. In such cases, it is better to use alternative libraries. (see References) Another way around is to build an SQLite database from the chunks and then extract the desired data using SQL queries. SQLite is a relational database management system based on the SQL language but optimized for small environments. It can be integrated with Python using a Python module called sqlite3. If you want to know more about using Sqlite with python, you can refer to an article that I wrote on this very subject: medium.com SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It is used to build an engine for creating a database from the original data, which is a large CSV file, in our case. For this article, we shall follow the following steps: import sqlite3from sqlalchemy import create_engine We shall name the database to be created as csv_database. csv_database = create_engine('sqlite:///csv_database.db') This process is similar to what we have seen earlier in this article. The loop reads the datasets in bunches specified by the chunksize. chunk_size=50000batch_no=1for chunk in pd.read_csv('yellow_tripdata_2016-02.csv',chunksize=chunk_size,iterator=True): chunk.to_sql('chunk_sql',csv_database, if_exists='append') batch_no+=1 print('index: {}'.format(batch_no)) Note that we use the function. chunk.to_sql instead of chunk.to_csv since we are writing the data to the database i.e csv_database.Also, chunk_sql is an arbitrary name given to the chunk. The database has been created. We can now easily query it to extract only those columns that we require; for instance, we can extract only those rows where the passenger count is less than 5 and the trip distance is greater than 10. pandas.read_sql_queryreads SQL query into a DataFrame. We now have a dataframe that fits well into our memory and can be used for further analysis. Pandas is a handy and versatile library when it comes to data analysis. However, it suffers from several bottlenecks when it comes to working with big data. In this article, we saw how chunking, coupled with SQL, could offer some solace for analyzing datasets larger than the system’s memory. However, this alternative is not a ‘one size fits all’ solution, and getting to work with libraries created for handling big data would be a better option. How to Read Very Big Files With SQL and Pandas in Python by Dr. Vytautas Bielinskas How to Read Very Big Files With SQL and Pandas in Python by Dr. Vytautas Bielinskas 2. Scaling to large datasets
[ { "code": null, "e": 749, "s": 172, "text": "The pandas’ library is a vital member of the Data Science ecosystem. However, the fact that it is unable to analyze datasets larger than memory makes it a little tricky for big data. Consider a situation when we want to analyze a large dataset by using only pandas. What kind of problems can we run into? For instance, let’s take a file comprising 3GB of data summarising yellow taxi trip data for March in 2016. To perform any sort of analysis, we will have to import it into memory. We readily use the pandas’ read_csv() function to perform the reading operation as follows:" }, { "code": null, "e": 816, "s": 749, "text": "import pandas as pddf = pd.read_csv('yellow_tripdata_2016-03.csv')" }, { "code": null, "e": 970, "s": 816, "text": "When I ran the cell/file, my system threw the following Memory Error. (The memory error would depend upon the capacity of the system that you are using)." }, { "code": null, "e": 1352, "s": 970, "text": "Before criticizing pandas, it is important to understand that pandas may not always be the right tool for every task. Pandas lack multiprocessing support, and other libraries are better at handling big data. One such alternative is Dask, which gives a pandas-like API foto work with larger than memory datasets. Even the pandas’ documentation explicitly mentions that for big data:" }, { "code": null, "e": 1441, "s": 1352, "text": "it’s worth considering not using pandas. Pandas isn’t the right tool for all situations." }, { "code": null, "e": 1807, "s": 1441, "text": "In this article, however, we shall look at a method called chunking, by which you can load out of memory datasets in pandas. This method can sometimes offer a healthy way out to manage the out-of-memory problem in pandas but may not work all the time, which we shall see later in the chapter. Essentially we will look at two ways to import large datasets in python:" }, { "code": null, "e": 1842, "s": 1807, "text": "Using pd.read_csv() with chunksize" }, { "code": null, "e": 1863, "s": 1842, "text": "Using SQL and pandas" }, { "code": null, "e": 1979, "s": 1863, "text": "Before working with an example, let’s try and understand what we mean by the work chunking. According to Wikipedia," }, { "code": null, "e": 2126, "s": 1979, "text": "Chunking refers to strategies for improving performance by using special knowledge of a situation to aggregate related memory-allocation requests." }, { "code": null, "e": 2350, "s": 2126, "text": "In order words, instead of reading all the data at once in the memory, we can divide into smaller parts or chunks. In the case of CSV files, this would mean only loading a few lines into the memory at a given point in time." }, { "code": null, "e": 2636, "s": 2350, "text": "Pandas’ read_csv() function comes with a chunk size parameter that controls the size of the chunk. Let’s see it in action. We’ll be working with the exact dataset that we used earlier in the article, but instead of loading it all in a single go, we’ll divide it into parts and load it." }, { "code": null, "e": 2803, "s": 2636, "text": "To enable chunking, we will declare the size of the chunk in the beginning. Then using read_csv() with the chunksize parameter, returns an object we can iterate over." }, { "code": null, "e": 2980, "s": 2803, "text": "chunk_size=50000batch_no=1for chunk in pd.read_csv('yellow_tripdata_2016-02.csv',chunksize=chunk_size): chunk.to_csv('chunk'+str(batch_no)+'.csv',index=False) batch_no+=1" }, { "code": null, "e": 3149, "s": 2980, "text": "We choose a chunk size of 50,000, which means at a time, only 50,000 rows of data will be imported. Here is a video of how the main CSV file splits into multiple files." }, { "code": null, "e": 3237, "s": 3149, "text": "We now have multiple chunks, and each chunk can easily be loaded as a pandas dataframe." }, { "code": null, "e": 3279, "s": 3237, "text": "df1 = pd.read_csv('chunk1.csv')df1.head()" }, { "code": null, "e": 3379, "s": 3279, "text": "It works like a charm!. No more memory error. Let’s quickly look at the memory usage by this chunk:" }, { "code": null, "e": 3390, "s": 3379, "text": "df1.info()" }, { "code": null, "e": 3750, "s": 3390, "text": "Chunking creates various subsets of the data. As a result, it works well when the operation you’re performing requires zero or minimal coordination between chunks. This is an important consideration. Another drawback of using chunking is that some operations like groupby are much harder to do chunks. In such cases, it is better to use alternative libraries." }, { "code": null, "e": 3767, "s": 3750, "text": "(see References)" }, { "code": null, "e": 4191, "s": 3767, "text": "Another way around is to build an SQLite database from the chunks and then extract the desired data using SQL queries. SQLite is a relational database management system based on the SQL language but optimized for small environments. It can be integrated with Python using a Python module called sqlite3. If you want to know more about using Sqlite with python, you can refer to an article that I wrote on this very subject:" }, { "code": null, "e": 4202, "s": 4191, "text": "medium.com" }, { "code": null, "e": 4459, "s": 4202, "text": "SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It is used to build an engine for creating a database from the original data, which is a large CSV file, in our case." }, { "code": null, "e": 4514, "s": 4459, "text": "For this article, we shall follow the following steps:" }, { "code": null, "e": 4565, "s": 4514, "text": "import sqlite3from sqlalchemy import create_engine" }, { "code": null, "e": 4623, "s": 4565, "text": "We shall name the database to be created as csv_database." }, { "code": null, "e": 4681, "s": 4623, "text": "csv_database = create_engine('sqlite:///csv_database.db')" }, { "code": null, "e": 4818, "s": 4681, "text": "This process is similar to what we have seen earlier in this article. The loop reads the datasets in bunches specified by the chunksize." }, { "code": null, "e": 5052, "s": 4818, "text": "chunk_size=50000batch_no=1for chunk in pd.read_csv('yellow_tripdata_2016-02.csv',chunksize=chunk_size,iterator=True): chunk.to_sql('chunk_sql',csv_database, if_exists='append') batch_no+=1 print('index: {}'.format(batch_no))" }, { "code": null, "e": 5240, "s": 5052, "text": "Note that we use the function. chunk.to_sql instead of chunk.to_csv since we are writing the data to the database i.e csv_database.Also, chunk_sql is an arbitrary name given to the chunk." }, { "code": null, "e": 5528, "s": 5240, "text": "The database has been created. We can now easily query it to extract only those columns that we require; for instance, we can extract only those rows where the passenger count is less than 5 and the trip distance is greater than 10. pandas.read_sql_queryreads SQL query into a DataFrame." }, { "code": null, "e": 5621, "s": 5528, "text": "We now have a dataframe that fits well into our memory and can be used for further analysis." }, { "code": null, "e": 6070, "s": 5621, "text": "Pandas is a handy and versatile library when it comes to data analysis. However, it suffers from several bottlenecks when it comes to working with big data. In this article, we saw how chunking, coupled with SQL, could offer some solace for analyzing datasets larger than the system’s memory. However, this alternative is not a ‘one size fits all’ solution, and getting to work with libraries created for handling big data would be a better option." }, { "code": null, "e": 6154, "s": 6070, "text": "How to Read Very Big Files With SQL and Pandas in Python by Dr. Vytautas Bielinskas" }, { "code": null, "e": 6238, "s": 6154, "text": "How to Read Very Big Files With SQL and Pandas in Python by Dr. Vytautas Bielinskas" } ]
CSS justify-content Property - GeeksforGeeks
14 Feb, 2022 The justify-content property in CSS is used to describe the alignment of the flexible box container. It contains the space between and around content items along the main axis of a flex container which is distributed in a browser. Note: This property cannot be used to describe items or containers along the vertical axis. For aligning the items vertically, we can use the align-items property The alignment is possible after applying the lengths and auto margins properties, ie., if there is at least one flexible element, with flex-grow property, other than 0, in a Flexbox layout then it will not impact & has any effect as there won’t be any available space. Syntax: justify-content: flex-start|flex-end|center|space-between| space-around|space-evenly|initial|inherit; Property Values: flex-start: It is the default value that is used to align flex items from the start of the container. Syntax: justify-content: flex-start; Example: This example illustrates the justify-content property where property value is set to flex-start to align the item from the start of the container. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: flex-start; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: flex-end: It is used to align flex items at the end of the container. Syntax: justify-content: flex-end; Example: This example illustrates the justify-content property where property value is set to flex-end. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: flex-end; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: center: It aligns flex items at the center of the container. Syntax: justify-content: center; Example: This example illustrates the justify-content property where property value is set to center. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: center; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: space-between: The flex items are placed with even spacing where the item is pushed to start and the last item is pushed to end. Syntax: justify-content: space-between; Example: This example illustrates the justify-content property where property value is set to space-between. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-between; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: space-around: The flex items are placed with equal spacing ie., before, between, and after, from each other & the corners. Syntax: justify-content: space-around; Example: This example illustrates the justify-content property where property value is set to space-around. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-around; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksForGeeks</p> </div> <div>2 <p>GeeksForGeeks</p> </div> <div>3 <p>GeeksForGeeks</p> </div> <div>4 <p>GeeksForGeeks</p> </div> </div></body> </html> Output: space-evenly: The items are positioned with equal spacing between them but the spacing from corners differs. Syntax: justify-content: space-evenly; Example: This example illustrates the justify-content property where property value is set to space-evenly. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-evenly; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: initial: The items are placed according to the default value. Syntax: justify-content: initial; Example: This example illustrates the justify-content property where property value is set to initial. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: initial; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: inherit: The items are placed according to their inherited parent element value. Syntax: justify-content: inherit; Example: This example illustrates the justify-content property where property value is set to inherit. HTML <!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: inherit; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id="box"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html> Output: Supported Browsers: The browser supported by CSS justify-content property are listed below: Google Chrome 29.0, 21.0 -webkit- Internet Explorer 11.0 Microsoft Edge 12.0 Firefox 28.0, 18.0 -moz- Opera 17.0 Safari 9.0, 6.1 -webkit- hritikbhatnagar2182 bhaskargeeksforgeeks varshagumber28 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23590, "s": 23562, "text": "\n14 Feb, 2022" }, { "code": null, "e": 23821, "s": 23590, "text": "The justify-content property in CSS is used to describe the alignment of the flexible box container. It contains the space between and around content items along the main axis of a flex container which is distributed in a browser." }, { "code": null, "e": 23984, "s": 23821, "text": "Note: This property cannot be used to describe items or containers along the vertical axis. For aligning the items vertically, we can use the align-items property" }, { "code": null, "e": 24253, "s": 23984, "text": "The alignment is possible after applying the lengths and auto margins properties, ie., if there is at least one flexible element, with flex-grow property, other than 0, in a Flexbox layout then it will not impact & has any effect as there won’t be any available space." }, { "code": null, "e": 24261, "s": 24253, "text": "Syntax:" }, { "code": null, "e": 24363, "s": 24261, "text": "justify-content: flex-start|flex-end|center|space-between|\nspace-around|space-evenly|initial|inherit;" }, { "code": null, "e": 24380, "s": 24363, "text": "Property Values:" }, { "code": null, "e": 24482, "s": 24380, "text": "flex-start: It is the default value that is used to align flex items from the start of the container." }, { "code": null, "e": 24490, "s": 24482, "text": "Syntax:" }, { "code": null, "e": 24519, "s": 24490, "text": "justify-content: flex-start;" }, { "code": null, "e": 24675, "s": 24519, "text": "Example: This example illustrates the justify-content property where property value is set to flex-start to align the item from the start of the container." }, { "code": null, "e": 24680, "s": 24675, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: flex-start; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 25349, "s": 24680, "text": null }, { "code": null, "e": 25357, "s": 25349, "text": "Output:" }, { "code": null, "e": 25427, "s": 25357, "text": "flex-end: It is used to align flex items at the end of the container." }, { "code": null, "e": 25435, "s": 25427, "text": "Syntax:" }, { "code": null, "e": 25462, "s": 25435, "text": "justify-content: flex-end;" }, { "code": null, "e": 25566, "s": 25462, "text": "Example: This example illustrates the justify-content property where property value is set to flex-end." }, { "code": null, "e": 25571, "s": 25566, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: flex-end; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 26238, "s": 25571, "text": null }, { "code": null, "e": 26247, "s": 26238, "text": "Output: " }, { "code": null, "e": 26308, "s": 26247, "text": "center: It aligns flex items at the center of the container." }, { "code": null, "e": 26316, "s": 26308, "text": "Syntax:" }, { "code": null, "e": 26341, "s": 26316, "text": "justify-content: center;" }, { "code": null, "e": 26443, "s": 26341, "text": "Example: This example illustrates the justify-content property where property value is set to center." }, { "code": null, "e": 26448, "s": 26443, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: center; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 27113, "s": 26448, "text": null }, { "code": null, "e": 27121, "s": 27113, "text": "Output:" }, { "code": null, "e": 27250, "s": 27121, "text": "space-between: The flex items are placed with even spacing where the item is pushed to start and the last item is pushed to end." }, { "code": null, "e": 27258, "s": 27250, "text": "Syntax:" }, { "code": null, "e": 27290, "s": 27258, "text": "justify-content: space-between;" }, { "code": null, "e": 27399, "s": 27290, "text": "Example: This example illustrates the justify-content property where property value is set to space-between." }, { "code": null, "e": 27404, "s": 27399, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-between; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 28076, "s": 27404, "text": null }, { "code": null, "e": 28084, "s": 28076, "text": "Output:" }, { "code": null, "e": 28207, "s": 28084, "text": "space-around: The flex items are placed with equal spacing ie., before, between, and after, from each other & the corners." }, { "code": null, "e": 28215, "s": 28207, "text": "Syntax:" }, { "code": null, "e": 28246, "s": 28215, "text": "justify-content: space-around;" }, { "code": null, "e": 28354, "s": 28246, "text": "Example: This example illustrates the justify-content property where property value is set to space-around." }, { "code": null, "e": 28359, "s": 28354, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-around; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksForGeeks</p> </div> <div>2 <p>GeeksForGeeks</p> </div> <div>3 <p>GeeksForGeeks</p> </div> <div>4 <p>GeeksForGeeks</p> </div> </div></body> </html>", "e": 29030, "s": 28359, "text": null }, { "code": null, "e": 29038, "s": 29030, "text": "Output:" }, { "code": null, "e": 29147, "s": 29038, "text": "space-evenly: The items are positioned with equal spacing between them but the spacing from corners differs." }, { "code": null, "e": 29155, "s": 29147, "text": "Syntax:" }, { "code": null, "e": 29186, "s": 29155, "text": "justify-content: space-evenly;" }, { "code": null, "e": 29294, "s": 29186, "text": "Example: This example illustrates the justify-content property where property value is set to space-evenly." }, { "code": null, "e": 29299, "s": 29294, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: space-evenly; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 29970, "s": 29299, "text": null }, { "code": null, "e": 29978, "s": 29970, "text": "Output:" }, { "code": null, "e": 30040, "s": 29978, "text": "initial: The items are placed according to the default value." }, { "code": null, "e": 30048, "s": 30040, "text": "Syntax:" }, { "code": null, "e": 30074, "s": 30048, "text": "justify-content: initial;" }, { "code": null, "e": 30177, "s": 30074, "text": "Example: This example illustrates the justify-content property where property value is set to initial." }, { "code": null, "e": 30182, "s": 30177, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: initial; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 30848, "s": 30182, "text": null }, { "code": null, "e": 30856, "s": 30848, "text": "Output:" }, { "code": null, "e": 30937, "s": 30856, "text": "inherit: The items are placed according to their inherited parent element value." }, { "code": null, "e": 30945, "s": 30937, "text": "Syntax:" }, { "code": null, "e": 30971, "s": 30945, "text": "justify-content: inherit;" }, { "code": null, "e": 31074, "s": 30971, "text": "Example: This example illustrates the justify-content property where property value is set to inherit." }, { "code": null, "e": 31079, "s": 31074, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS justify-content Property </title> <style> #box { display: flex; border: 1px solid black; justify-content: inherit; } #box div { width: 110px; height: 120px; border: 1px solid black; background: linear-gradient(green, silver); } </style></head> <body> <div id=\"box\"> <div>1 <p>GeeksforGeeks</p> </div> <div>2 <p>GeeksforGeeks</p> </div> <div>3 <p>GeeksforGeeks</p> </div> <div>4 <p>GeeksforGeeks</p> </div> </div></body> </html>", "e": 31745, "s": 31079, "text": null }, { "code": null, "e": 31753, "s": 31745, "text": "Output:" }, { "code": null, "e": 31845, "s": 31753, "text": "Supported Browsers: The browser supported by CSS justify-content property are listed below:" }, { "code": null, "e": 31879, "s": 31845, "text": "Google Chrome 29.0, 21.0 -webkit-" }, { "code": null, "e": 31902, "s": 31879, "text": "Internet Explorer 11.0" }, { "code": null, "e": 31922, "s": 31902, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 31947, "s": 31922, "text": "Firefox 28.0, 18.0 -moz-" }, { "code": null, "e": 31958, "s": 31947, "text": "Opera 17.0" }, { "code": null, "e": 31983, "s": 31958, "text": "Safari 9.0, 6.1 -webkit-" }, { "code": null, "e": 32003, "s": 31983, "text": "hritikbhatnagar2182" }, { "code": null, "e": 32024, "s": 32003, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 32039, "s": 32024, "text": "varshagumber28" }, { "code": null, "e": 32054, "s": 32039, "text": "CSS-Properties" }, { "code": null, "e": 32061, "s": 32054, "text": "Picked" }, { "code": null, "e": 32065, "s": 32061, "text": "CSS" }, { "code": null, "e": 32082, "s": 32065, "text": "Web Technologies" }, { "code": null, "e": 32180, "s": 32082, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32189, "s": 32180, "text": "Comments" }, { "code": null, "e": 32202, "s": 32189, "text": "Old Comments" }, { "code": null, "e": 32264, "s": 32202, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32314, "s": 32264, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32372, "s": 32314, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 32420, "s": 32372, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32457, "s": 32420, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 32499, "s": 32457, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32532, "s": 32499, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32594, "s": 32532, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32637, "s": 32594, "text": "How to fetch data from an API in ReactJS ?" } ]
Full Deployment of Jupyter Notebooks on a Server including TLS/SSL with Let’s Encrypt | by Nikolai Janakiev | Towards Data Science
Jupyter Notebook is a powerful tool, but how can you use it in all its glory on a server? In this tutorial, you will see how to set up Jupyter notebook on a server like Digital Ocean, Hetzner, AWS or most other hosting providers available. Additionally, you will see how to use Jupyter notebooks over SSH tunneling or TLS/SSL with Let’s Encrypt. This article was originally published here. Jupyter is an open source web application that enables interactive computing from the browser. You can create documents that feature live code, documentation with Markdown, equations, visualization and even widgets and other interesting capabilities. Jupyter comes from the three core languages that are supported: Julia, Python, and R. Jupyter connects to a kernel with a specific language, the most common being the IPython kernel. It supports a whole variety of kernels and you should find most languages you need. This tutorial was written in JupyterLab, the next developments of Jupyter notebook: In this tutorial, we will be working with Ubuntu 18.04/20.04 servers, but most steps should be fairly similar for Debian 9/10 distributions. We will first go through creating SSH keys, adding a new user on the server, and installing Python and Jupyter with Anaconda. Next, you will set up Jupyter to run on the server. Finally, you can either choose to run Jupyter notebooks over SSH tunneling or over SSL with Let’s Encrypt. We are starting with a fresh server and in order to add more security when accessing your server, you should consider using SSH key pairs. These key pairs consist of a public key which is uploaded to the server and a private key that stays on your machine. Some hosting providers require you to upload the public key before creating the server instance. To create a new SSH key you can use the ssh-keygen tool. To create the key pairs you can simply type the command: ssh-keygen this will prompt you to add the file path and a passphrase if you want to. There are other arguments of options you can choose from like public key algorithm or file name. You can find a very good tutorial here on how to create a new SSH key with ssh-keygen for Linux or macOS. If you are using Windows, you can create SSH-keys with PuTTYgen as described here. If your hosting provider does not need a public key before creation you can copy the public key with the ssh-copy-id tool: ssh-copy-id -i ~/.ssh/jupyter-cloud-key user@host Finally, you can connect to your server with: ssh -i ~/.ssh/id_rsa root@host where ~/.ssh/id_rsa is the path to your ssh private key and host is the host address or IP address of you server instance. In some servers you start off as a root user. It is considered bad practice to work directly with the root since it has a lot of privileges which can be destructive if some commands are done by accident. If you already have a user you can skip this section. Note that you can replace cloud-user in all the following commands with the user name you want. Start by creating a new user: adduser cloud-user This command will ask you a couple of questions including a password. Next, you’ll want to grant administrative privileges to this user. You can do this by typing: usermod -aG sudo cloud-user Now you are ready to switch to the new user with su cloud-user or by connecting to your server with ssh cloud-user@host. Optionally, you can add the SSH keys of the root user to the new user for additional security. Otherwise, you can skip to the next section on how to install Anaconda. Now, if you have existing SSH keys for the root user you can copy the public key from the root home folder to the users home folder like shown here: mkdir /home/cloud-user/.sshcp /root/.ssh/authorized_keys /home/cloud-user/.ssh/ Next, you need to change the permissions for both the folder and the public key: cd /home/user/chmod 700 .ssh/chmod 600 .ssh/authorized_keys If you are using a password for your user you need to update /etc/ssh/sshd_config: nano /etc/ssh/sshd_config There you want to find the line PasswordAuthentication no and change the no to a yes to allow password authentication. Finally you want to restart the SSH service by typing service ssh restart. For other distributions have a look into this guide, where you will also see how to set up a firewall. Anaconda is an open-source distribution of Python (and R) for scientific computing including package management and deployment. With it, you have most tooling that you need including Jupyter. To install Anaconda, go to the downloads for linux and copy the Linux installer link for the latest Python 3.x version. Then you can download the installer with wget: wget https://repo.anaconda.com/archive/Anaconda3-5.2.0-Linux-x86_64.sh Next you can install Anaconda by using bash as follows: bash Anaconda3-5.2.0-Linux-x86_64.sh During installation, it is important to type yes when the following prompt appears during the installation: Do you wish the installer to prepend the Anaconda3 install locationto PATH in your /home/user/.bashrc ? [yes|no] After you finished installing you want to initialize the conda command line tool and package manager by Anaconda with: source .bashrc conda update conda These two commands set up Anaconda on your server. If you have run the Anaconda bash file with sudo, you will get a Permission denied error. You can solve it as shown in this question by typing sudo chown -R $$USER:$$USER /home/user/anaconda3. This changes the owner of this folder to the current user with the chown command. Jupyter is installed with Anaconda, but we need to do some configuration in order to run it on the server. First, you’ll want to create a password for Jupyter notebook. You can do this by starting the IPython shell with ipython and generating a password hash: from IPython.lib import passwdpasswd() Save this resulting hash for now, we will need it in a moment. Next, you want to generate a configuration file which you can create by typing. jupyter-notebook --generate-config Now open the configuration file with sudo nano ~/.jupyter/jupyter_notebook_config.py and copy the following code into the file and replace the hash in this snippet with the one you have previously generated: c = get_config() # get the config object# do not open a browser window by default when using notebooksc.NotebookApp.open_browser = False# this is the password hash that we generated earlier.c.NotebookApp.password = 'sha1:073bb9acaa67:b367308802ab66cb1d7654b6684eafefbd61d004' Now you should be set up. Next, you can decide whether you want to use SSH tunneling or you want to use SSL encryption and access your jupyter notebook over your own domain name. You can tunnel to your server by adding the -L argument to the ssh command, which is responsible for port forwarding. The first 8888 is the port you will access on your local machine (if you already use this port for another juypter instance you can use port 8889 or a different open port). You can access this then on your browser with localhost:8888. The second part localhost:8888 specifies the jump server address accessed from the server. Since we want to run the notebook locally on the server, this is again localhost. This would mean that we access localhost:8888 from the server via port forwarding to localhost:8888 on our machine. Here is how the command would look like: ssh -L 8888:localhost:8888 cloud-user@host If you have another Jupyter notebook running on your local machine already you can change the port to e.g. 8889 which would result in the command: ssh -L 8889:localhost:8888 cloud-user@host Now, you can create a notebook folder for your projects on the server and run Jupyter notebook inside: mkdir notebookcd notebook/jupyter-notebook You can also use JupyterLab instead, which is a more powerful interface and it comes also pre-installed with Anaconda. You can start it by typing jupyter-lab instead of juypter-notebook. It is also possible to use SSL encryption for your jupyter notebook. This enables you to access your Jupyter notebooks through the internet which makes it handy to share results with your colleagues. To do this you can use Let’s Encrypt, which is a free Certificate Authority (CA) that provides an easy way for TLS/SSL certificates. This can be done fully automated with their certbot tool. To find the installation guide for your system have a look at this list. For Ubuntu 18.04 the installation looks as follows: sudo apt-get updatesudo apt-get install software-properties-commonsudo add-apt-repository universesudo add-apt-repository ppa:certbot/certbotsudo apt-get updatesudo apt-get install certbot python-certbot-apache Now, you can run certbot for the domain that you have: sudo certbot certonly -d example.com After going through the prompts, you should get to this output: IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/example.com/privkey.pem Your cert will expire on 2019-05-09. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le Great! You have your certificate and key file ready. Now you can use the certificate and key file in your jupyter notebook configuration file. Before you can do that, you need to change the owner of the certificate and key file with (change user with your own user name): sudo chown user /usr/local/etc/letsencrypt/livesudo chown user /usr/local/etc/letsencrypt/archive Next, you can add the following code to the ~/.jupyter/jupyter_notebook_config.py configuration file: # Path to the certificate c.NotebookApp.certfile = '/etc/letsencrypt/live/example.com/fullchain.pem' # Path to the certificate key we generatedc.NotebookApp.keyfile = '/etc/letsencrypt/live/example.com/privkey.pem' # Serve the notebooks for all IP addressesc.NotebookApp.ip = '0.0.0.0' Finally, you can access Jupyter notebooks securely over https://example.com:8888. Just make sure to use https:// instead of http://. If you made any mistakes, you can delete the certbot certificate with sudo certbot delete or sudo certbot delete --cert-name example.com. If you are using a firewall, make sure that port 8888 is open. Here is a good guide on using the Uncomplicated Firewall (UFW) firewall. You have learned how to set up Jupyter for a server from start to finish. This is a task that gets easier with every server set up that you do. Make sure to delve into the surrounding topics of Linux server administration since working with servers can be intimidating in the beginning. Using Jupyter you have access to a wide variety of kernels that enable you to use other languages. A list of all available kernels can be found here. I hope this was helpful and if you have any further questions or remarks, feel free to share them in the comments below. I covered in a previous tutorial how to work with virtual environments in Jupyter notebook. There is also an option to run Jupyter as a Docker container. You can use for example the jupyter/datascience-notebook container. You can read more on how to work with Jupyter and Docker in this guide. For further security considerations have a look at Security in the Jupyter notebook server. Here are further links that I have learned from and that might be useful for you too: Initial Server Setup Running a notebook server How To Set Up Jupyter Notebook for Python 3 How To Use Certbot Standalone Mode to Retrieve Let’s Encrypt SSL Certificates UFW Essentials: Common Firewall Rules and Commands Using Virtual Environments in Jupyter Notebook and Python Creating Slides with Jupyter Notebook How to use letsencrypt certificates in Jupyter and IPython Adding SSL and a domain name to Jupyter Hub
[ { "code": null, "e": 562, "s": 172, "text": "Jupyter Notebook is a powerful tool, but how can you use it in all its glory on a server? In this tutorial, you will see how to set up Jupyter notebook on a server like Digital Ocean, Hetzner, AWS or most other hosting providers available. Additionally, you will see how to use Jupyter notebooks over SSH tunneling or TLS/SSL with Let’s Encrypt. This article was originally published here." }, { "code": null, "e": 1164, "s": 562, "text": "Jupyter is an open source web application that enables interactive computing from the browser. You can create documents that feature live code, documentation with Markdown, equations, visualization and even widgets and other interesting capabilities. Jupyter comes from the three core languages that are supported: Julia, Python, and R. Jupyter connects to a kernel with a specific language, the most common being the IPython kernel. It supports a whole variety of kernels and you should find most languages you need. This tutorial was written in JupyterLab, the next developments of Jupyter notebook:" }, { "code": null, "e": 1590, "s": 1164, "text": "In this tutorial, we will be working with Ubuntu 18.04/20.04 servers, but most steps should be fairly similar for Debian 9/10 distributions. We will first go through creating SSH keys, adding a new user on the server, and installing Python and Jupyter with Anaconda. Next, you will set up Jupyter to run on the server. Finally, you can either choose to run Jupyter notebooks over SSH tunneling or over SSL with Let’s Encrypt." }, { "code": null, "e": 2058, "s": 1590, "text": "We are starting with a fresh server and in order to add more security when accessing your server, you should consider using SSH key pairs. These key pairs consist of a public key which is uploaded to the server and a private key that stays on your machine. Some hosting providers require you to upload the public key before creating the server instance. To create a new SSH key you can use the ssh-keygen tool. To create the key pairs you can simply type the command:" }, { "code": null, "e": 2069, "s": 2058, "text": "ssh-keygen" }, { "code": null, "e": 2553, "s": 2069, "text": "this will prompt you to add the file path and a passphrase if you want to. There are other arguments of options you can choose from like public key algorithm or file name. You can find a very good tutorial here on how to create a new SSH key with ssh-keygen for Linux or macOS. If you are using Windows, you can create SSH-keys with PuTTYgen as described here. If your hosting provider does not need a public key before creation you can copy the public key with the ssh-copy-id tool:" }, { "code": null, "e": 2603, "s": 2553, "text": "ssh-copy-id -i ~/.ssh/jupyter-cloud-key user@host" }, { "code": null, "e": 2649, "s": 2603, "text": "Finally, you can connect to your server with:" }, { "code": null, "e": 2680, "s": 2649, "text": "ssh -i ~/.ssh/id_rsa root@host" }, { "code": null, "e": 2803, "s": 2680, "text": "where ~/.ssh/id_rsa is the path to your ssh private key and host is the host address or IP address of you server instance." }, { "code": null, "e": 3187, "s": 2803, "text": "In some servers you start off as a root user. It is considered bad practice to work directly with the root since it has a lot of privileges which can be destructive if some commands are done by accident. If you already have a user you can skip this section. Note that you can replace cloud-user in all the following commands with the user name you want. Start by creating a new user:" }, { "code": null, "e": 3206, "s": 3187, "text": "adduser cloud-user" }, { "code": null, "e": 3370, "s": 3206, "text": "This command will ask you a couple of questions including a password. Next, you’ll want to grant administrative privileges to this user. You can do this by typing:" }, { "code": null, "e": 3398, "s": 3370, "text": "usermod -aG sudo cloud-user" }, { "code": null, "e": 3835, "s": 3398, "text": "Now you are ready to switch to the new user with su cloud-user or by connecting to your server with ssh cloud-user@host. Optionally, you can add the SSH keys of the root user to the new user for additional security. Otherwise, you can skip to the next section on how to install Anaconda. Now, if you have existing SSH keys for the root user you can copy the public key from the root home folder to the users home folder like shown here:" }, { "code": null, "e": 3915, "s": 3835, "text": "mkdir /home/cloud-user/.sshcp /root/.ssh/authorized_keys /home/cloud-user/.ssh/" }, { "code": null, "e": 3996, "s": 3915, "text": "Next, you need to change the permissions for both the folder and the public key:" }, { "code": null, "e": 4056, "s": 3996, "text": "cd /home/user/chmod 700 .ssh/chmod 600 .ssh/authorized_keys" }, { "code": null, "e": 4139, "s": 4056, "text": "If you are using a password for your user you need to update /etc/ssh/sshd_config:" }, { "code": null, "e": 4165, "s": 4139, "text": "nano /etc/ssh/sshd_config" }, { "code": null, "e": 4462, "s": 4165, "text": "There you want to find the line PasswordAuthentication no and change the no to a yes to allow password authentication. Finally you want to restart the SSH service by typing service ssh restart. For other distributions have a look into this guide, where you will also see how to set up a firewall." }, { "code": null, "e": 4821, "s": 4462, "text": "Anaconda is an open-source distribution of Python (and R) for scientific computing including package management and deployment. With it, you have most tooling that you need including Jupyter. To install Anaconda, go to the downloads for linux and copy the Linux installer link for the latest Python 3.x version. Then you can download the installer with wget:" }, { "code": null, "e": 4892, "s": 4821, "text": "wget https://repo.anaconda.com/archive/Anaconda3-5.2.0-Linux-x86_64.sh" }, { "code": null, "e": 4948, "s": 4892, "text": "Next you can install Anaconda by using bash as follows:" }, { "code": null, "e": 4985, "s": 4948, "text": "bash Anaconda3-5.2.0-Linux-x86_64.sh" }, { "code": null, "e": 5093, "s": 4985, "text": "During installation, it is important to type yes when the following prompt appears during the installation:" }, { "code": null, "e": 5206, "s": 5093, "text": "Do you wish the installer to prepend the Anaconda3 install locationto PATH in your /home/user/.bashrc ? [yes|no]" }, { "code": null, "e": 5325, "s": 5206, "text": "After you finished installing you want to initialize the conda command line tool and package manager by Anaconda with:" }, { "code": null, "e": 5359, "s": 5325, "text": "source .bashrc conda update conda" }, { "code": null, "e": 5685, "s": 5359, "text": "These two commands set up Anaconda on your server. If you have run the Anaconda bash file with sudo, you will get a Permission denied error. You can solve it as shown in this question by typing sudo chown -R $$USER:$$USER /home/user/anaconda3. This changes the owner of this folder to the current user with the chown command." }, { "code": null, "e": 5945, "s": 5685, "text": "Jupyter is installed with Anaconda, but we need to do some configuration in order to run it on the server. First, you’ll want to create a password for Jupyter notebook. You can do this by starting the IPython shell with ipython and generating a password hash:" }, { "code": null, "e": 5984, "s": 5945, "text": "from IPython.lib import passwdpasswd()" }, { "code": null, "e": 6127, "s": 5984, "text": "Save this resulting hash for now, we will need it in a moment. Next, you want to generate a configuration file which you can create by typing." }, { "code": null, "e": 6162, "s": 6127, "text": "jupyter-notebook --generate-config" }, { "code": null, "e": 6370, "s": 6162, "text": "Now open the configuration file with sudo nano ~/.jupyter/jupyter_notebook_config.py and copy the following code into the file and replace the hash in this snippet with the one you have previously generated:" }, { "code": null, "e": 6647, "s": 6370, "text": "c = get_config() # get the config object# do not open a browser window by default when using notebooksc.NotebookApp.open_browser = False# this is the password hash that we generated earlier.c.NotebookApp.password = 'sha1:073bb9acaa67:b367308802ab66cb1d7654b6684eafefbd61d004'" }, { "code": null, "e": 6826, "s": 6647, "text": "Now you should be set up. Next, you can decide whether you want to use SSH tunneling or you want to use SSL encryption and access your jupyter notebook over your own domain name." }, { "code": null, "e": 7509, "s": 6826, "text": "You can tunnel to your server by adding the -L argument to the ssh command, which is responsible for port forwarding. The first 8888 is the port you will access on your local machine (if you already use this port for another juypter instance you can use port 8889 or a different open port). You can access this then on your browser with localhost:8888. The second part localhost:8888 specifies the jump server address accessed from the server. Since we want to run the notebook locally on the server, this is again localhost. This would mean that we access localhost:8888 from the server via port forwarding to localhost:8888 on our machine. Here is how the command would look like:" }, { "code": null, "e": 7552, "s": 7509, "text": "ssh -L 8888:localhost:8888 cloud-user@host" }, { "code": null, "e": 7699, "s": 7552, "text": "If you have another Jupyter notebook running on your local machine already you can change the port to e.g. 8889 which would result in the command:" }, { "code": null, "e": 7742, "s": 7699, "text": "ssh -L 8889:localhost:8888 cloud-user@host" }, { "code": null, "e": 7845, "s": 7742, "text": "Now, you can create a notebook folder for your projects on the server and run Jupyter notebook inside:" }, { "code": null, "e": 7888, "s": 7845, "text": "mkdir notebookcd notebook/jupyter-notebook" }, { "code": null, "e": 8075, "s": 7888, "text": "You can also use JupyterLab instead, which is a more powerful interface and it comes also pre-installed with Anaconda. You can start it by typing jupyter-lab instead of juypter-notebook." }, { "code": null, "e": 8591, "s": 8075, "text": "It is also possible to use SSL encryption for your jupyter notebook. This enables you to access your Jupyter notebooks through the internet which makes it handy to share results with your colleagues. To do this you can use Let’s Encrypt, which is a free Certificate Authority (CA) that provides an easy way for TLS/SSL certificates. This can be done fully automated with their certbot tool. To find the installation guide for your system have a look at this list. For Ubuntu 18.04 the installation looks as follows:" }, { "code": null, "e": 8802, "s": 8591, "text": "sudo apt-get updatesudo apt-get install software-properties-commonsudo add-apt-repository universesudo add-apt-repository ppa:certbot/certbotsudo apt-get updatesudo apt-get install certbot python-certbot-apache" }, { "code": null, "e": 8857, "s": 8802, "text": "Now, you can run certbot for the domain that you have:" }, { "code": null, "e": 8894, "s": 8857, "text": "sudo certbot certonly -d example.com" }, { "code": null, "e": 8958, "s": 8894, "text": "After going through the prompts, you should get to this output:" }, { "code": null, "e": 9613, "s": 8958, "text": "IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/example.com/privkey.pem Your cert will expire on 2019-05-09. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the \"certonly\" option. To non-interactively renew *all* of your certificates, run \"certbot renew\" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le" }, { "code": null, "e": 9885, "s": 9613, "text": "Great! You have your certificate and key file ready. Now you can use the certificate and key file in your jupyter notebook configuration file. Before you can do that, you need to change the owner of the certificate and key file with (change user with your own user name):" }, { "code": null, "e": 9983, "s": 9885, "text": "sudo chown user /usr/local/etc/letsencrypt/livesudo chown user /usr/local/etc/letsencrypt/archive" }, { "code": null, "e": 10085, "s": 9983, "text": "Next, you can add the following code to the ~/.jupyter/jupyter_notebook_config.py configuration file:" }, { "code": null, "e": 10371, "s": 10085, "text": "# Path to the certificate c.NotebookApp.certfile = '/etc/letsencrypt/live/example.com/fullchain.pem' # Path to the certificate key we generatedc.NotebookApp.keyfile = '/etc/letsencrypt/live/example.com/privkey.pem' # Serve the notebooks for all IP addressesc.NotebookApp.ip = '0.0.0.0'" }, { "code": null, "e": 10778, "s": 10371, "text": "Finally, you can access Jupyter notebooks securely over https://example.com:8888. Just make sure to use https:// instead of http://. If you made any mistakes, you can delete the certbot certificate with sudo certbot delete or sudo certbot delete --cert-name example.com. If you are using a firewall, make sure that port 8888 is open. Here is a good guide on using the Uncomplicated Firewall (UFW) firewall." }, { "code": null, "e": 11336, "s": 10778, "text": "You have learned how to set up Jupyter for a server from start to finish. This is a task that gets easier with every server set up that you do. Make sure to delve into the surrounding topics of Linux server administration since working with servers can be intimidating in the beginning. Using Jupyter you have access to a wide variety of kernels that enable you to use other languages. A list of all available kernels can be found here. I hope this was helpful and if you have any further questions or remarks, feel free to share them in the comments below." }, { "code": null, "e": 11808, "s": 11336, "text": "I covered in a previous tutorial how to work with virtual environments in Jupyter notebook. There is also an option to run Jupyter as a Docker container. You can use for example the jupyter/datascience-notebook container. You can read more on how to work with Jupyter and Docker in this guide. For further security considerations have a look at Security in the Jupyter notebook server. Here are further links that I have learned from and that might be useful for you too:" }, { "code": null, "e": 11829, "s": 11808, "text": "Initial Server Setup" }, { "code": null, "e": 11855, "s": 11829, "text": "Running a notebook server" }, { "code": null, "e": 11899, "s": 11855, "text": "How To Set Up Jupyter Notebook for Python 3" }, { "code": null, "e": 11977, "s": 11899, "text": "How To Use Certbot Standalone Mode to Retrieve Let’s Encrypt SSL Certificates" }, { "code": null, "e": 12028, "s": 11977, "text": "UFW Essentials: Common Firewall Rules and Commands" }, { "code": null, "e": 12086, "s": 12028, "text": "Using Virtual Environments in Jupyter Notebook and Python" }, { "code": null, "e": 12124, "s": 12086, "text": "Creating Slides with Jupyter Notebook" }, { "code": null, "e": 12183, "s": 12124, "text": "How to use letsencrypt certificates in Jupyter and IPython" } ]
C++ Program for the Common Divisors of Two Numbers?
The common divisor of two numbers are the numbers that are divisors of both of them. For example, The divisors of 12 are 1, 2, 3, 4, 6, 12. The divisors of 18are 1, 2, 3, 6, 9, 18. Thus, the common divisors of 12 and 18 are 1, 2, 3, 6. The greatest among these is, perhaps unsurprisingly, called the greatest common divisor of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6. The greatest common divisor is important for many reasons. For example, it can be used to calculate the LCM of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as ab(a, b). For example, the least common multiple of 12 and 18 is 12·18(12, 18) =12 · 18.6 Input: a = 10, b = 20 Output: 1 2 5 10 // all common divisors are 1 2 5 10 Integers that can exactly divide both numbers (without a remainder). #include <iostream> using namespace std; int main() { int n1, n2, i; n1=10; n2=20; for(i=1; i <= n1 && i <= n2; ++i) { if(n1%i==0 && n2%i==0) { cout<<i<<"\t"; } } }
[ { "code": null, "e": 1147, "s": 1062, "text": "The common divisor of two numbers are the numbers that are divisors of both of them." }, { "code": null, "e": 1160, "s": 1147, "text": "For example," }, { "code": null, "e": 1202, "s": 1160, "text": "The divisors of 12 are 1, 2, 3, 4, 6, 12." }, { "code": null, "e": 1243, "s": 1202, "text": "The divisors of 18are 1, 2, 3, 6, 9, 18." }, { "code": null, "e": 1298, "s": 1243, "text": "Thus, the common divisors of 12 and 18 are 1, 2, 3, 6." }, { "code": null, "e": 1532, "s": 1298, "text": "The greatest among these is, perhaps unsurprisingly, called the greatest common divisor of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6." }, { "code": null, "e": 1809, "s": 1532, "text": "The greatest common divisor is important for many reasons. For example, it can be used to calculate the LCM of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as ab(a, b)." }, { "code": null, "e": 1889, "s": 1809, "text": "For example, the least common multiple of 12 and 18 is\n12·18(12, 18) =12 · 18.6" }, { "code": null, "e": 1964, "s": 1889, "text": "Input: a = 10, b = 20\nOutput: 1 2 5 10\n// all common divisors are 1 2 5 10" }, { "code": null, "e": 2033, "s": 1964, "text": "Integers that can exactly divide both numbers (without a remainder)." }, { "code": null, "e": 2234, "s": 2033, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int n1, n2, i;\n n1=10;\n n2=20;\n for(i=1; i <= n1 && i <= n2; ++i) {\n if(n1%i==0 && n2%i==0) {\n cout<<i<<\"\\t\";\n }\n }\n}" } ]
Estimating the number of dimensions with Exploratory Graph Analysis | by Rafael Valdece Sousa Bastos | Towards Data Science
In psychology, education, and behavioral sciences we use scales/instruments to measure a given construct (e.g., Anxiety; Happiness). For that, we usually have a questionnaire with an X number of items and wish to know the number of latent factors that arise from these items. This is usually made with Exploratory Factor Analysis (EFA), where the number of dimensions is usually estimated by examining the patterns of eigenvalues (see my guide on eigenvalues here). Two of the most common methods that use eigenvalues are Kaiser-Guttman eigenvalue greater than one rule and parallel analysis. However, a lot of critiques have been made with these methods' performance on estimating dimensionality. Because of those limitations, Golino & Epskamp (2017) proposed a new method for estimating the dimensionality of a scale, called Exploratory Graph Analysis (EGA). This article will be a brief summary of recent developments on EGA, aiming to the dissemination of this method. Network psychometrics methods have gained recent attention in the psychological sciences literature. This may be due to the shift in theoretical interpretation of the correlations observed in data. Traditionally, as done by EFA, psychometric models assume that latent causes explain the observed behavior (i.e., items). Emerging areas such as network psychometrics have promising models for psychology research because it supports theoretical perspectives on complexity, i.e., it considers psychological attributes as systems of observed behaviors that dynamically and mutually reinforce one another. There’s a relationship between a typical latent variable in the traditional psychometric and in network clusters. As said by Golino & Epskamp (2017): It can directly be seen that if a latent variable model is the true underlying causal model, we would expect indicators in a network model to feature strongly connected clusters for each latent variable. Since edges correspond to partial correlation coefficients between two variables after conditioning on all other variables in the network, and two indicators cannot become independent after conditioning on observed variables given that they are both caused by a latent variable, the edge strength between two indicators should not be zero. EGA is an exploratory method that does not rely on a priori assumptions, thus, they do not require any direction from the researcher. In EGA, nodes represent variables (i.e., items) and edges represent the relation (i.e., correlations) between two nodes. In the authors' first publication, the EGA is done as follows: It is estimated the correlation matrix of the observable variables.graphical least absolute shrinkage and selection operator (glasso) estimation is used to obtain the sparse inverse covariance matrix, with the regularization parameter defined via EBIC over 100 different values.The walktrap algorithm is used to find the number of clusters of the partial correlation matrix computed in the previous step.The number of clusters identified equals the number of latent factors in a given dataset. It is estimated the correlation matrix of the observable variables. graphical least absolute shrinkage and selection operator (glasso) estimation is used to obtain the sparse inverse covariance matrix, with the regularization parameter defined via EBIC over 100 different values. The walktrap algorithm is used to find the number of clusters of the partial correlation matrix computed in the previous step. The number of clusters identified equals the number of latent factors in a given dataset. Today, it is possible to estimate unidimensionality and multidimensionality; we are able to substitute glasso with Triangulated Maximally Filtered Graph (TMFG); and use an algorithm other than walktrap (i.e., louvain). Golino et al. (2020) showed that the EGA method performs as well as the best factor-analytic techniques. Being that EGA(TMFG) performed moderately good accuracy in both unidimensional and multidimensional structures, and EGA was one of the methods with higher accuracy in general. When estimating an EGA, one thing is important to consider. First, the number of dimensions that were identified in one study may vary on other studies with different samples and sample sizes. In addition, some items might be clustered in dimension A in one study and in dimension B in another. Because of that, Christensen & Golino (2019) created Bootstrap EGA. To do the analysis, we will use the R package EGAnet (CRAN; GitHub), made by Golino and Christensen. First, we have to install the package (we will use the GitHub version since it’s up to date). library(devtools)devtools::install_github('hfgolino/EGAnet') This will install the package on your device. We then will load the package with library(EGAnet) . We will be using Humor Styles Questionnaire data from the Open-Source Psychometrics Project. I added it to my GitHub so you can download it without much effort. data <- read.delim("https://raw.githubusercontent.com/rafavsbastos/data/main/HSQ.txt" We will run the EGA with the following code: ega.HSQ <- EGA( data, uni.method = "LE", corr = "cor_auto", model = "glasso", algorithm = "walktrap", plot.EGA = TRUE, plot.type = "qgraph" ) Where the first argument is the dataset (i.e., our items); the second represents what unidimensionality method should be used; the third is the type of the correlation matrix to compute; the fourth indicates the method to use; the fifth is the algorithm we used; the sixth if we want to plot the EGA; and the seventh what type of plot we wish. We have the following output: Where we can see a clear “extraction” of 4 dimensions, as expected. To calculate dimension stability, we will run the following code: bootdata <- bootEGA( data, iter= 1000, type = "resampling", ) Where the arguments are: the dataset.an integer with the number of replica samples to generate from the bootstrap analysis.Parametric or non-parametric approach. the dataset. an integer with the number of replica samples to generate from the bootstrap analysis. Parametric or non-parametric approach. Take care, since we are using some default arguments, we are not specifying it here. Look at the documentation of the package before doing your own analysis! Now we will see some useful information typing : bootdata$summary.table Where the output is: We can see the median number of dimensions (median.dim), the standard error (SE.dim), the confidence interval of the number of dimensions (CI.dim), the lower CI (Lower.CI) and upper Ci (Upper. CI), and the lower quantile of the number of dimensions (Lower.Quantile) and upper (Upper.Quantile). Based on this output, it is clear that the model with 4 dimensions is precise (SE = 0.27) and that 4 dimensions is most likely the structure of the scale (given the CI 3.47, 4.53). Now type bootdata$frequency. It gives you the following output: Where we can see that 4 factors were replicated 924 times, while 5 factors only 75 times and 6 factors one time. Now for item stability type: ic.HSQ <- itemStability(bootdata) . The output is an image: Where we can see that items replicated between 80% and 100% of the time in their given dimension. As shown by some of the analyses made so far and by recent papers, EGA can show us an accurate way of assessing the dimensionality of instruments that measures psychological attributes. In addition, the authors have implemented a bunch of functions in EGAnet that gives us useful information about dimensions and items. The package is still being updated, with results loading faster, and (probably) new functions are being made. Feel free to contact me by: LinkedIne-mail: rafavsbastos@gmail.comWebsite for consulting and partnerships H. F. Golino, and S. Epskamp, Exploratory graph analysis: A new approach for estimating the number of dimensions in psychological research, 2017, PloS one, 12(6), e0174035. H. F. Golino, D. Shi, A. P. Christensen, L. E. Garrido, M. D. Nieto, R. Sadana, ... and A. Martinez-Molina, Investigating the performance of exploratory graph analysis and traditional techniques to identify the number of latent factors: A simulation and tutorial, 2020, Psychological Methods. A. P. Christensen and H. F. Golino, Estimating the stability of the number of factors via Bootstrap Exploratory Graph Analysis: A tutorial, 2019.
[ { "code": null, "e": 870, "s": 172, "text": "In psychology, education, and behavioral sciences we use scales/instruments to measure a given construct (e.g., Anxiety; Happiness). For that, we usually have a questionnaire with an X number of items and wish to know the number of latent factors that arise from these items. This is usually made with Exploratory Factor Analysis (EFA), where the number of dimensions is usually estimated by examining the patterns of eigenvalues (see my guide on eigenvalues here). Two of the most common methods that use eigenvalues are Kaiser-Guttman eigenvalue greater than one rule and parallel analysis. However, a lot of critiques have been made with these methods' performance on estimating dimensionality." }, { "code": null, "e": 1145, "s": 870, "text": "Because of those limitations, Golino & Epskamp (2017) proposed a new method for estimating the dimensionality of a scale, called Exploratory Graph Analysis (EGA). This article will be a brief summary of recent developments on EGA, aiming to the dissemination of this method." }, { "code": null, "e": 1746, "s": 1145, "text": "Network psychometrics methods have gained recent attention in the psychological sciences literature. This may be due to the shift in theoretical interpretation of the correlations observed in data. Traditionally, as done by EFA, psychometric models assume that latent causes explain the observed behavior (i.e., items). Emerging areas such as network psychometrics have promising models for psychology research because it supports theoretical perspectives on complexity, i.e., it considers psychological attributes as systems of observed behaviors that dynamically and mutually reinforce one another." }, { "code": null, "e": 1896, "s": 1746, "text": "There’s a relationship between a typical latent variable in the traditional psychometric and in network clusters. As said by Golino & Epskamp (2017):" }, { "code": null, "e": 2440, "s": 1896, "text": "It can directly be seen that if a latent variable model is the true underlying causal model, we would expect indicators in a network model to feature strongly connected clusters for each latent variable. Since edges correspond to partial correlation coefficients between two variables after conditioning on all other variables in the network, and two indicators cannot become independent after conditioning on observed variables given that they are both caused by a latent variable, the edge strength between two indicators should not be zero." }, { "code": null, "e": 2695, "s": 2440, "text": "EGA is an exploratory method that does not rely on a priori assumptions, thus, they do not require any direction from the researcher. In EGA, nodes represent variables (i.e., items) and edges represent the relation (i.e., correlations) between two nodes." }, { "code": null, "e": 2758, "s": 2695, "text": "In the authors' first publication, the EGA is done as follows:" }, { "code": null, "e": 3252, "s": 2758, "text": "It is estimated the correlation matrix of the observable variables.graphical least absolute shrinkage and selection operator (glasso) estimation is used to obtain the sparse inverse covariance matrix, with the regularization parameter defined via EBIC over 100 different values.The walktrap algorithm is used to find the number of clusters of the partial correlation matrix computed in the previous step.The number of clusters identified equals the number of latent factors in a given dataset." }, { "code": null, "e": 3320, "s": 3252, "text": "It is estimated the correlation matrix of the observable variables." }, { "code": null, "e": 3532, "s": 3320, "text": "graphical least absolute shrinkage and selection operator (glasso) estimation is used to obtain the sparse inverse covariance matrix, with the regularization parameter defined via EBIC over 100 different values." }, { "code": null, "e": 3659, "s": 3532, "text": "The walktrap algorithm is used to find the number of clusters of the partial correlation matrix computed in the previous step." }, { "code": null, "e": 3749, "s": 3659, "text": "The number of clusters identified equals the number of latent factors in a given dataset." }, { "code": null, "e": 3968, "s": 3749, "text": "Today, it is possible to estimate unidimensionality and multidimensionality; we are able to substitute glasso with Triangulated Maximally Filtered Graph (TMFG); and use an algorithm other than walktrap (i.e., louvain)." }, { "code": null, "e": 4249, "s": 3968, "text": "Golino et al. (2020) showed that the EGA method performs as well as the best factor-analytic techniques. Being that EGA(TMFG) performed moderately good accuracy in both unidimensional and multidimensional structures, and EGA was one of the methods with higher accuracy in general." }, { "code": null, "e": 4612, "s": 4249, "text": "When estimating an EGA, one thing is important to consider. First, the number of dimensions that were identified in one study may vary on other studies with different samples and sample sizes. In addition, some items might be clustered in dimension A in one study and in dimension B in another. Because of that, Christensen & Golino (2019) created Bootstrap EGA." }, { "code": null, "e": 4713, "s": 4612, "text": "To do the analysis, we will use the R package EGAnet (CRAN; GitHub), made by Golino and Christensen." }, { "code": null, "e": 4807, "s": 4713, "text": "First, we have to install the package (we will use the GitHub version since it’s up to date)." }, { "code": null, "e": 4868, "s": 4807, "text": "library(devtools)devtools::install_github('hfgolino/EGAnet')" }, { "code": null, "e": 4967, "s": 4868, "text": "This will install the package on your device. We then will load the package with library(EGAnet) ." }, { "code": null, "e": 5128, "s": 4967, "text": "We will be using Humor Styles Questionnaire data from the Open-Source Psychometrics Project. I added it to my GitHub so you can download it without much effort." }, { "code": null, "e": 5214, "s": 5128, "text": "data <- read.delim(\"https://raw.githubusercontent.com/rafavsbastos/data/main/HSQ.txt\"" }, { "code": null, "e": 5259, "s": 5214, "text": "We will run the EGA with the following code:" }, { "code": null, "e": 5513, "s": 5259, "text": "ega.HSQ <- EGA( data, uni.method = \"LE\", corr = \"cor_auto\", model = \"glasso\", algorithm = \"walktrap\", plot.EGA = TRUE, plot.type = \"qgraph\" )" }, { "code": null, "e": 5857, "s": 5513, "text": "Where the first argument is the dataset (i.e., our items); the second represents what unidimensionality method should be used; the third is the type of the correlation matrix to compute; the fourth indicates the method to use; the fifth is the algorithm we used; the sixth if we want to plot the EGA; and the seventh what type of plot we wish." }, { "code": null, "e": 5887, "s": 5857, "text": "We have the following output:" }, { "code": null, "e": 5955, "s": 5887, "text": "Where we can see a clear “extraction” of 4 dimensions, as expected." }, { "code": null, "e": 6021, "s": 5955, "text": "To calculate dimension stability, we will run the following code:" }, { "code": null, "e": 6160, "s": 6021, "text": "bootdata <- bootEGA( data, iter= 1000, type = \"resampling\", )" }, { "code": null, "e": 6185, "s": 6160, "text": "Where the arguments are:" }, { "code": null, "e": 6322, "s": 6185, "text": "the dataset.an integer with the number of replica samples to generate from the bootstrap analysis.Parametric or non-parametric approach." }, { "code": null, "e": 6335, "s": 6322, "text": "the dataset." }, { "code": null, "e": 6422, "s": 6335, "text": "an integer with the number of replica samples to generate from the bootstrap analysis." }, { "code": null, "e": 6461, "s": 6422, "text": "Parametric or non-parametric approach." }, { "code": null, "e": 6619, "s": 6461, "text": "Take care, since we are using some default arguments, we are not specifying it here. Look at the documentation of the package before doing your own analysis!" }, { "code": null, "e": 6668, "s": 6619, "text": "Now we will see some useful information typing :" }, { "code": null, "e": 6691, "s": 6668, "text": "bootdata$summary.table" }, { "code": null, "e": 6712, "s": 6691, "text": "Where the output is:" }, { "code": null, "e": 7187, "s": 6712, "text": "We can see the median number of dimensions (median.dim), the standard error (SE.dim), the confidence interval of the number of dimensions (CI.dim), the lower CI (Lower.CI) and upper Ci (Upper. CI), and the lower quantile of the number of dimensions (Lower.Quantile) and upper (Upper.Quantile). Based on this output, it is clear that the model with 4 dimensions is precise (SE = 0.27) and that 4 dimensions is most likely the structure of the scale (given the CI 3.47, 4.53)." }, { "code": null, "e": 7251, "s": 7187, "text": "Now type bootdata$frequency. It gives you the following output:" }, { "code": null, "e": 7364, "s": 7251, "text": "Where we can see that 4 factors were replicated 924 times, while 5 factors only 75 times and 6 factors one time." }, { "code": null, "e": 7453, "s": 7364, "text": "Now for item stability type: ic.HSQ <- itemStability(bootdata) . The output is an image:" }, { "code": null, "e": 7551, "s": 7453, "text": "Where we can see that items replicated between 80% and 100% of the time in their given dimension." }, { "code": null, "e": 7981, "s": 7551, "text": "As shown by some of the analyses made so far and by recent papers, EGA can show us an accurate way of assessing the dimensionality of instruments that measures psychological attributes. In addition, the authors have implemented a bunch of functions in EGAnet that gives us useful information about dimensions and items. The package is still being updated, with results loading faster, and (probably) new functions are being made." }, { "code": null, "e": 8009, "s": 7981, "text": "Feel free to contact me by:" }, { "code": null, "e": 8087, "s": 8009, "text": "LinkedIne-mail: rafavsbastos@gmail.comWebsite for consulting and partnerships" }, { "code": null, "e": 8260, "s": 8087, "text": "H. F. Golino, and S. Epskamp, Exploratory graph analysis: A new approach for estimating the number of dimensions in psychological research, 2017, PloS one, 12(6), e0174035." }, { "code": null, "e": 8553, "s": 8260, "text": "H. F. Golino, D. Shi, A. P. Christensen, L. E. Garrido, M. D. Nieto, R. Sadana, ... and A. Martinez-Molina, Investigating the performance of exploratory graph analysis and traditional techniques to identify the number of latent factors: A simulation and tutorial, 2020, Psychological Methods." } ]
Keras - Quick Guide
Deep learning is one of the major subfield of machine learning framework. Machine learning is the study of design of algorithms, inspired from the model of human brain. Deep learning is becoming more popular in data science fields like robotics, artificial intelligence(AI), audio & video recognition and image recognition. Artificial neural network is the core of deep learning methodologies. Deep learning is supported by various libraries such as Theano, TensorFlow, Caffe, Mxnet etc., Keras is one of the most powerful and easy to use python library, which is built on top of popular deep learning libraries like TensorFlow, Theano, etc., for creating deep learning models. Keras runs on top of open source machine libraries like TensorFlow, Theano or Cognitive Toolkit (CNTK). Theano is a python library used for fast numerical computation tasks. TensorFlow is the most famous symbolic math library used for creating neural networks and deep learning models. TensorFlow is very flexible and the primary benefit is distributed computing. CNTK is deep learning framework developed by Microsoft. It uses libraries such as Python, C#, C++ or standalone machine learning toolkits. Theano and TensorFlow are very powerful libraries but difficult to understand for creating neural networks. Keras is based on minimal structure that provides a clean and easy way to create deep learning models based on TensorFlow or Theano. Keras is designed to quickly define deep learning models. Well, Keras is an optimal choice for deep learning applications. Keras leverages various optimization techniques to make high level neural network API easier and more performant. It supports the following features − Consistent, simple and extensible API. Consistent, simple and extensible API. Minimal structure - easy to achieve the result without any frills. Minimal structure - easy to achieve the result without any frills. It supports multiple platforms and backends. It supports multiple platforms and backends. It is user friendly framework which runs on both CPU and GPU. It is user friendly framework which runs on both CPU and GPU. Highly scalability of computation. Highly scalability of computation. Keras is highly powerful and dynamic framework and comes up with the following advantages − Larger community support. Larger community support. Easy to test. Easy to test. Keras neural networks are written in Python which makes things simpler. Keras neural networks are written in Python which makes things simpler. Keras supports both convolution and recurrent networks. Keras supports both convolution and recurrent networks. Deep learning models are discrete components, so that, you can combine into many ways. Deep learning models are discrete components, so that, you can combine into many ways. This chapter explains about how to install Keras on your machine. Before moving to installation, let us go through the basic requirements of Keras. You must satisfy the following requirements − Any kind of OS (Windows, Linux or Mac) Python version 3.5 or higher. Keras is python based neural network library so python must be installed on your machine. If python is properly installed on your machine, then open your terminal and type python, you could see the response similar as specified below, Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> As of now the latest version is ‘3.7.2’. If Python is not installed, then visit the official python link - www.python.org and download the latest version based on your OS and install it immediately on your system. Keras installation is quite easy. Follow below steps to properly install Keras on your system. Virtualenv is used to manage Python packages for different projects. This will be helpful to avoid breaking the packages installed in the other environments. So, it is always recommended to use a virtual environment while developing Python applications. Linux/Mac OS Linux or mac OS users, go to your project root directory and type the below command to create virtual environment, python3 -m venv kerasenv After executing the above command, “kerasenv” directory is created with bin,lib and include folders in your installation location. Windows Windows user can use the below command, py -m venv keras This step will configure python and pip executables in your shell path. Linux/Mac OS Now we have created a virtual environment named “kerasvenv”. Move to the folder and type the below command, $ cd kerasvenv kerasvenv $ source bin/activate Windows Windows users move inside the “kerasenv” folder and type the below command, .\env\Scripts\activate Keras depends on the following python libraries. Numpy Pandas Scikit-learn Matplotlib Scipy Seaborn Hopefully, you have installed all the above libraries on your system. If these libraries are not installed, then use the below command to install one by one. numpy pip install numpy you could see the following response, Collecting numpy Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ numpy-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s pandas pip install pandas We could see the following response, Collecting pandas Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ pandas-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s matplotlib pip install matplotlib We could see the following response, Collecting matplotlib Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ matplotlib-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s scipy pip install scipy We could see the following response, Collecting scipy Downloading https://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8 /scipy-3.1.1-cp36-cp36m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64. macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) |████████████████████████████████| 14.4MB 2.8MB/s scikit-learn It is an open source machine learning library. It is used for classification, regression and clustering algorithms. Before moving to the installation, it requires the following − Python version 3.5 or higher NumPy version 1.11.0 or higher SciPy version 0.17.0 or higher joblib 0.11 or higher. Now, we install scikit-learn using the below command − pip install -U scikit-learn Seaborn Seaborn is an amazing library that allows you to easily visualize your data. Use the below command to install − pip install seaborn You could see the message similar as specified below − Collecting seaborn Downloading https://files.pythonhosted.org/packages/a8/76/220ba4420459d9c4c9c9587c6ce607bf56c25b3d3d2de62056efe482dadc /seaborn-0.9.0-py3-none-any.whl (208kB) 100% |████████████████████████████████| 215kB 4.0MB/s Requirement already satisfied: numpy> = 1.9.3 in ./lib/python3.7/site-packages (from seaborn) (1.17.0) Collecting pandas> = 0.15.2 (from seaborn) Downloading https://files.pythonhosted.org/packages/39/b7/441375a152f3f9929ff8bc2915218ff1a063a59d7137ae0546db616749f9/ pandas-0.25.0-cp37-cp37m-macosx_10_9_x86_64. macosx_10_10_x86_64.whl (10.1MB) 100% |████████████████████████████████| 10.1MB 1.8MB/s Requirement already satisfied: scipy>=0.14.0 in ./lib/python3.7/site-packages (from seaborn) (1.3.0) Collecting matplotlib> = 1.4.3 (from seaborn) Downloading https://files.pythonhosted.org/packages/c3/8b/af9e0984f 5c0df06d3fab0bf396eb09cbf05f8452de4e9502b182f59c33b/ matplotlib-3.1.1-cp37-cp37m-macosx_10_6_intel. macosx_10_9_intel.macosx_10_9_x86_64 .macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) 100% |████████████████████████████████| 14.4MB 1.4MB/s ...................................... ...................................... Successfully installed cycler-0.10.0 kiwisolver-1.1.0 matplotlib-3.1.1 pandas-0.25.0 pyparsing-2.4.2 python-dateutil-2.8.0 pytz-2019.2 seaborn-0.9.0 As of now, we have completed basic requirements for the installtion of Kera. Now, install the Keras using same procedure as specified below − pip install keras After finishing all your changes in your project, then simply run the below command to quit the environment − deactivate We believe that you have installed anaconda cloud on your machine. If anaconda is not installed, then visit the official link, www.anaconda.com/distribution and choose download based on your OS. Launch anaconda prompt, this will open base Anaconda environment. Let us create a new conda environment. This process is similar to virtualenv. Type the below command in your conda terminal − conda create --name PythonCPU If you want, you can create and install modules using GPU also. In this tutorial, we follow CPU instructions. To activate the environment, use the below command − activate PythonCPU Spyder is an IDE for executing python applications. Let us install this IDE in our conda environment using the below command − conda install spyder We have already known the python libraries numpy, pandas, etc., needed for keras. You can install all the modules by using the below syntax − Syntax conda install -c anaconda <module-name> For example, you want to install pandas − conda install -c anaconda pandas Like the same method, try it yourself to install the remaining modules. Now, everything looks good so you can start keras installation using the below command − conda install -c anaconda keras Finally, launch spyder in your conda terminal using the below command − spyder To ensure everything was installed correctly, import all the modules, it will add everything and if anything went wrong, you will get module not found error message. This chapter explains Keras backend implementations TensorFlow and Theano in detail. Let us go through each implementation one by one. TensorFlow is an open source machine learning library used for numerical computational tasks developed by Google. Keras is a high level API built on top of TensorFlow or Theano. We know already how to install TensorFlow using pip. If it is not installed, you can install using the below command − pip install TensorFlow Once we execute keras, we could see the configuration file is located at your home directory inside and go to .keras/keras.json. { "image_data_format": "channels_last", "epsilon": 1e-07, "floatx": "float32", "backend": "tensorflow" } Here, image_data_format represent the data format. image_data_format represent the data format. epsilon represents numeric constant. It is used to avoid DivideByZero error. epsilon represents numeric constant. It is used to avoid DivideByZero error. floatx represent the default data type float32. You can also change it to float16 or float64 using set_floatx() method. floatx represent the default data type float32. You can also change it to float16 or float64 using set_floatx() method. image_data_format represent the data format. image_data_format represent the data format. Suppose, if the file is not created then move to the location and create using the below steps − > cd home > mkdir .keras > vi keras.json Remember, you should specify .keras as its folder name and add the above configuration inside keras.json file. We can perform some pre-defined operations to know backend functions. Theano is an open source deep learning library that allows you to evaluate multi-dimensional arrays effectively. We can easily install using the below command − pip install theano By default, keras uses TensorFlow backend. If you want to change backend configuration from TensorFlow to Theano, just change the backend = theano in keras.json file. It is described below − { "image_data_format": "channels_last", "epsilon": 1e-07, "floatx": "float32", "backend": "theano" } Now save your file, restart your terminal and start keras, your backend will be changed. >>> import keras as k using theano backend. Deep learning is an evolving subfield of machine learning. Deep learning involves analyzing the input in layer by layer manner, where each layer progressively extracts higher level information about the input. Let us take a simple scenario of analyzing an image. Let us assume that your input image is divided up into a rectangular grid of pixels. Now, the first layer abstracts the pixels. The second layer understands the edges in the image. The Next layer constructs nodes from the edges. Then, the next would find branches from the nodes. Finally, the output layer will detect the full object. Here, the feature extraction process goes from the output of one layer into the input of the next subsequent layer. By using this approach, we can process huge amount of features, which makes deep learning a very powerful tool. Deep learning algorithms are also useful for the analysis of unstructured data. Let us go through the basics of deep learning in this chapter. The most popular and primary approach of deep learning is using “Artificial neural network” (ANN). They are inspired from the model of human brain, which is the most complex organ of our body. The human brain is made up of more than 90 billion tiny cells called “Neurons”. Neurons are inter-connected through nerve fiber called “axons” and “Dendrites”. The main role of axon is to transmit information from one neuron to another to which it is connected. Similarly, the main role of dendrites is to receive the information being transmitted by the axons of another neuron to which it is connected. Each neuron processes a small information and then passes the result to another neuron and this process continues. This is the basic method used by our human brain to process huge about of information like speech, visual, etc., and extract useful information from it. Based on this model, the first Artificial Neural Network (ANN) was invented by psychologist Frank Rosenblatt, in the year of 1958. ANNs are made up of multiple nodes which is similar to neurons. Nodes are tightly interconnected and organized into different hidden layers. The input layer receives the input data and the data goes through one or more hidden layers sequentially and finally the output layer predict something useful about the input data. For example, the input may be an image and the output may be the thing identified in the image, say a “Cat”. A single neuron (called as perceptron in ANN) can be represented as below − Here, Multiple input along with weight represents dendrites. Multiple input along with weight represents dendrites. Sum of input along with activation function represents neurons. Sum actually means computed value of all inputs and activation function represent a function, which modify the Sum value into 0, 1 or 0 to 1. Sum of input along with activation function represents neurons. Sum actually means computed value of all inputs and activation function represent a function, which modify the Sum value into 0, 1 or 0 to 1. Actual output represent axon and the output will be received by neuron in next layer. Actual output represent axon and the output will be received by neuron in next layer. Let us understand different types of artificial neural networks in this section. Multi-Layer perceptron is the simplest form of ANN. It consists of a single input layer, one or more hidden layer and finally an output layer. A layer consists of a collection of perceptron. Input layer is basically one or more features of the input data. Every hidden layer consists of one or more neurons and process certain aspect of the feature and send the processed information into the next hidden layer. The output layer process receives the data from last hidden layer and finally output the result. Convolutional neural network is one of the most popular ANN. It is widely used in the fields of image and video recognition. It is based on the concept of convolution, a mathematical concept. It is almost similar to multi-layer perceptron except it contains series of convolution layer and pooling layer before the fully connected hidden neuron layer. It has three important layers − Convolution layer − It is the primary building block and perform computational tasks based on convolution function. Convolution layer − It is the primary building block and perform computational tasks based on convolution function. Pooling layer − It is arranged next to convolution layer and is used to reduce the size of inputs by removing unnecessary information so computation can be performed faster. Pooling layer − It is arranged next to convolution layer and is used to reduce the size of inputs by removing unnecessary information so computation can be performed faster. Fully connected layer − It is arranged to next to series of convolution and pooling layer and classify input into various categories. Fully connected layer − It is arranged to next to series of convolution and pooling layer and classify input into various categories. A simple CNN can be represented as below − Here, 2 series of Convolution and pooling layer is used and it receives and process the input (e.g. image). 2 series of Convolution and pooling layer is used and it receives and process the input (e.g. image). A single fully connected layer is used and it is used to output the data (e.g. classification of image) A single fully connected layer is used and it is used to output the data (e.g. classification of image) Recurrent Neural Networks (RNN) are useful to address the flaw in other ANN models. Well, Most of the ANN doesn’t remember the steps from previous situations and learned to make decisions based on context in training. Meanwhile, RNN stores the past information and all its decisions are taken from what it has learnt from the past. This approach is mainly useful in image classification. Sometimes, we may need to look into the future to fix the past. In this case bidirectional RNN is helpful to learn from the past and predict the future. For example, we have handwritten samples in multiple inputs. Suppose, we have confusion in one input then we need to check again other inputs to recognize the correct context which takes the decision from the past. Let us first understand the different phases of deep learning and then, learn how Keras helps in the process of deep learning. Deep learning requires lot of input data to successfully learn and predict the result. So, first collect as much data as possible. Analyze the data and acquire a good understanding of the data. The better understanding of the data is required to select the correct ANN algorithm. Choose an algorithm, which will best fit for the type of learning process (e.g image classification, text processing, etc.,) and the available input data. Algorithm is represented by Model in Keras. Algorithm includes one or more layers. Each layers in ANN can be represented by Keras Layer in Keras. Prepare data − Process, filter and select only the required information from the data. Prepare data − Process, filter and select only the required information from the data. Split data − Split the data into training and test data set. Test data will be used to evaluate the prediction of the algorithm / Model (once the machine learn) and to cross check the efficiency of the learning process. Split data − Split the data into training and test data set. Test data will be used to evaluate the prediction of the algorithm / Model (once the machine learn) and to cross check the efficiency of the learning process. Compile the model − Compile the algorithm / model, so that, it can be used further to learn by training and finally do to prediction. This step requires us to choose loss function and Optimizer. loss function and Optimizer are used in learning phase to find the error (deviation from actual output) and do optimization so that the error will be minimized. Compile the model − Compile the algorithm / model, so that, it can be used further to learn by training and finally do to prediction. This step requires us to choose loss function and Optimizer. loss function and Optimizer are used in learning phase to find the error (deviation from actual output) and do optimization so that the error will be minimized. Fit the model − The actual learning process will be done in this phase using the training data set. Fit the model − The actual learning process will be done in this phase using the training data set. Predict result for unknown value − Predict the output for the unknown input data (other than existing training and test data) Predict result for unknown value − Predict the output for the unknown input data (other than existing training and test data) Evaluate model − Evaluate the model by predicting the output for test data and cross-comparing the prediction with actual result of the test data. Evaluate model − Evaluate the model by predicting the output for test data and cross-comparing the prediction with actual result of the test data. Freeze, Modify or choose new algorithm − Check whether the evaluation of the model is successful. If yes, save the algorithm for future prediction purpose. If not, then modify or choose new algorithm / model and finally, again train, predict and evaluate the model. Repeat the process until the best algorithm (model) is found. Freeze, Modify or choose new algorithm − Check whether the evaluation of the model is successful. If yes, save the algorithm for future prediction purpose. If not, then modify or choose new algorithm / model and finally, again train, predict and evaluate the model. Repeat the process until the best algorithm (model) is found. The above steps can be represented using below flow chart − Keras provides a complete framework to create any type of neural networks. Keras is innovative as well as very easy to learn. It supports simple neural network to very large and complex neural network model. Let us understand the architecture of Keras framework and how Keras helps in deep learning in this chapter. Keras API can be divided into three main categories − Model Layer Core Modules In Keras, every ANN is represented by Keras Models. In turn, every Keras Model is composition of Keras Layers and represents ANN layers like input, hidden layer, output layers, convolution layer, pooling layer, etc., Keras model and layer access Keras modules for activation function, loss function, regularization function, etc., Using Keras model, Keras Layer, and Keras modules, any ANN algorithm (CNN, RNN, etc.,) can be represented in a simple and efficient manner. The following diagram depicts the relationship between model, layer and core modules − Let us see the overview of Keras models, Keras layers and Keras modules. Keras Models are of two types as mentioned below − Sequential Model − Sequential model is basically a linear composition of Keras Layers. Sequential model is easy, minimal as well as has the ability to represent nearly all available neural networks. A simple sequential model is as follows − from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) Where, Line 1 imports Sequential model from Keras models Line 1 imports Sequential model from Keras models Line 2 imports Dense layer and Activation module Line 2 imports Dense layer and Activation module Line 4 create a new sequential model using Sequential API Line 4 create a new sequential model using Sequential API Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Sequential model exposes Model class to create customized models as well. We can use sub-classing concept to create our own complex model. Functional API − Functional API is basically used to create complex models. Each Keras layer in the Keras model represent the corresponding layer (input layer, hidden layer and output layer) in the actual proposed neural network model. Keras provides a lot of pre-build layers so that any complex neural network can be easily created. Some of the important Keras layers are specified below, Core Layers Convolution Layers Pooling Layers Recurrent Layers A simple python code to represent a neural network model using sequential model is as follows − from keras.models import Sequential from keras.layers import Dense, Activation, Dropout model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation = 'softmax')) Where, Line 1 imports Sequential model from Keras models Line 1 imports Sequential model from Keras models Line 2 imports Dense layer and Activation module Line 2 imports Dense layer and Activation module Line 4 create a new sequential model using Sequential API Line 4 create a new sequential model using Sequential API Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 6 adds a dropout layer (Dropout API) to handle over-fitting. Line 6 adds a dropout layer (Dropout API) to handle over-fitting. Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function. Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function. Line 8 adds another dropout layer (Dropout API) to handle over-fitting. Line 8 adds another dropout layer (Dropout API) to handle over-fitting. Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function. Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function. Keras also provides options to create our own customized layers. Customized layer can be created by sub-classing the Keras.Layer class and it is similar to sub-classing Keras models. Keras also provides a lot of built-in neural network related functions to properly create the Keras model and Keras layers. Some of the function are as follows − Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc., Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc., Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc., Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc., Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc., Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc., Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc., Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc., Let us learn Keras modules in detail in the upcoming chapter. As we learned earlier, Keras modules contains pre-defined classes, functions and variables which are useful for deep learning algorithm. Let us learn the modules provided by Keras in this chapter. Let us first see the list of modules available in the Keras. Initializers − Provides a list of initializers function. We can learn it in details in Keras layer chapter. during model creation phase of machine learning. Initializers − Provides a list of initializers function. We can learn it in details in Keras layer chapter. during model creation phase of machine learning. Regularizers − Provides a list of regularizers function. We can learn it in details in Keras Layers chapter. Regularizers − Provides a list of regularizers function. We can learn it in details in Keras Layers chapter. Constraints − Provides a list of constraints function. We can learn it in details in Keras Layers chapter. Constraints − Provides a list of constraints function. We can learn it in details in Keras Layers chapter. Activations − Provides a list of activator function. We can learn it in details in Keras Layers chapter. Activations − Provides a list of activator function. We can learn it in details in Keras Layers chapter. Losses − Provides a list of loss function. We can learn it in details in Model Training chapter. Losses − Provides a list of loss function. We can learn it in details in Model Training chapter. Metrics − Provides a list of metrics function. We can learn it in details in Model Training chapter. Metrics − Provides a list of metrics function. We can learn it in details in Model Training chapter. Optimizers − Provides a list of optimizer function. We can learn it in details in Model Training chapter. Optimizers − Provides a list of optimizer function. We can learn it in details in Model Training chapter. Callback − Provides a list of callback function. We can use it during the training process to print the intermediate data as well as to stop the training itself (EarlyStopping method) based on some condition. Callback − Provides a list of callback function. We can use it during the training process to print the intermediate data as well as to stop the training itself (EarlyStopping method) based on some condition. Text processing − Provides functions to convert text into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning. Text processing − Provides functions to convert text into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning. Image processing − Provides functions to convert images into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning. Image processing − Provides functions to convert images into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning. Sequence processing − Provides functions to generate time based data from the given input data. We can use it in data preparation phase of machine learning. Sequence processing − Provides functions to generate time based data from the given input data. We can use it in data preparation phase of machine learning. Backend − Provides function of the backend library like TensorFlow and Theano. Backend − Provides function of the backend library like TensorFlow and Theano. Utilities − Provides lot of utility function useful in deep learning. Utilities − Provides lot of utility function useful in deep learning. Let us see backend module and utils model in this chapter. backend module is used for keras backend operations. By default, keras runs on top of TensorFlow backend. If you want, you can switch to other backends like Theano or CNTK. Defualt backend configuration is defined inside your root directory under .keras/keras.json file. Keras backend module can be imported using below code >>> from keras import backend as k If we are using default backend TensorFlow, then the below function returns TensorFlow based information as specified below − >>> k.backend() 'tensorflow' >>> k.epsilon() 1e-07 >>> k.image_data_format() 'channels_last' >>> k.floatx() 'float32' Let us understand some of the significant backend functions used for data analysis in brief − It is the identifier for the default graph. It is defined below − >>> k.get_uid(prefix='') 1 >>> k.get_uid(prefix='') 2 It is used resets the uid value. >>> k.reset_uids() Now, again execute the get_uid(). This will be reset and change again to 1. >>> k.get_uid(prefix='') 1 It is used instantiates a placeholder tensor. Simple placeholder to hold 3-D shape is shown below − >>> data = k.placeholder(shape = (1,3,3)) >>> data <tf.Tensor 'Placeholder_9:0' shape = (1, 3, 3) dtype = float32> If you use int_shape(), it will show the shape. >>> k.int_shape(data) (1, 3, 3) It is used to multiply two tensors. Consider a and b are two tensors and c will be the outcome of multiply of ab. Assume a shape is (4,2) and b shape is (2,3). It is defined below, >>> a = k.placeholder(shape = (4,2)) >>> b = k.placeholder(shape = (2,3)) >>> c = k.dot(a,b) >>> c <tf.Tensor 'MatMul_3:0' shape = (4, 3) dtype = float32> >>> It is used to initialize all as one value. >>> res = k.ones(shape = (2,2)) #print the value >>> k.eval(res) array([[1., 1.], [1., 1.]], dtype = float32) It is used to perform the product of two data in batches. Input dimension must be 2 or higher. It is shown below − >>> a_batch = k.ones(shape = (2,3)) >>> b_batch = k.ones(shape = (3,2)) >>> c_batch = k.batch_dot(a_batch,b_batch) >>> c_batch <tf.Tensor 'ExpandDims:0' shape = (2, 1) dtype = float32> It is used to initializes a variable. Let us perform simple transpose operation in this variable. >>> data = k.variable([[10,20,30,40],[50,60,70,80]]) #variable initialized here >>> result = k.transpose(data) >>> print(result) Tensor("transpose_6:0", shape = (4, 2), dtype = float32) >>> print(k.eval(result)) [[10. 50.] [20. 60.] [30. 70.] [40. 80.]] If you want to access from numpy − >>> data = np.array([[10,20,30,40],[50,60,70,80]]) >>> print(np.transpose(data)) [[10 50] [20 60] [30 70] [40 80]] >>> res = k.variable(value = data) >>> print(res) <tf.Variable 'Variable_7:0' shape = (2, 4) dtype = float32_ref> It is used to check whether the tensor is sparse or not. >>> a = k.placeholder((2, 2), sparse=True) >>> print(a) SparseTensor(indices = Tensor("Placeholder_8:0", shape = (?, 2), dtype = int64), values = Tensor("Placeholder_7:0", shape = (?,), dtype = float32), dense_shape = Tensor("Const:0", shape = (2,), dtype = int64)) >>> print(k.is_sparse(a)) True It is used to converts sparse into dense. >>> b = k.to_dense(a) >>> print(b) Tensor("SparseToDense:0", shape = (2, 2), dtype = float32) >>> print(k.is_sparse(b)) False It is used to initialize using uniform distribution concept. k.random_uniform_variable(shape, mean, scale) Here, shape − denotes the rows and columns in the format of tuples. shape − denotes the rows and columns in the format of tuples. mean − mean of uniform distribution. mean − mean of uniform distribution. scale − standard deviation of uniform distribution. scale − standard deviation of uniform distribution. Let us have a look at the below example usage − >>> a = k.random_uniform_variable(shape = (2, 3), low=0, high = 1) >>> b = k. random_uniform_variable(shape = (3,2), low = 0, high = 1) >>> c = k.dot(a, b) >>> k.int_shape(c) (2, 2) utils provides useful utilities function for deep learning. Some of the methods provided by the utils module is as follows − It is used to represent the input data in HDF5 format. from keras.utils import HDF5Matrix data = HDF5Matrix('data.hdf5', 'data') It is used to convert class vector into binary class matrix. >>> from keras.utils import to_categorical >>> labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> to_categorical(labels) array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]], dtype = float32) >>> from keras.utils import normalize >>> normalize([1, 2, 3, 4, 5]) array([[0.13483997, 0.26967994, 0.40451992, 0.53935989, 0.67419986]]) It is used to print the summary of the model. from keras.utils import print_summary print_summary(model) It is used to create the model representation in dot format and save it to file. from keras.utils import plot_model plot_model(model,to_file = 'image.png') This plot_model will generate an image to understand the performance of model. As learned earlier, Keras layers are the primary building block of Keras models. Each layer receives input information, do some computation and finally output the transformed information. The output of one layer will flow into the next layer as its input. Let us learn complete details about layers in this chapter. A Keras layer requires shape of the input (input_shape) to understand the structure of the input data, initializer to set the weight for each input and finally activators to transform the output to make it non-linear. In between, constraints restricts and specify the range in which the weight of input data to be generated and regularizer will try to optimize the layer (and the model) by dynamically applying the penalties on the weights during optimization process. To summarise, Keras layer requires below minimum details to create a complete layer. Shape of the input data Number of neurons / units in the layer Initializers Regularizers Constraints Activations Let us understand the basic concept in the next chapter. Before understanding the basic concept, let us create a simple Keras layer using Sequential model API to get the idea of how Keras model and layer works. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers from keras import regularizers from keras import constraints model = Sequential() model.add(Dense(32, input_shape=(16,), kernel_initializer = 'he_uniform', kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(8)) where, Line 1-5 imports the necessary modules. Line 1-5 imports the necessary modules. Line 7 creates a new model using Sequential API. Line 7 creates a new model using Sequential API. Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional. First parameter represents the number of units (neurons). input_shape represent the shape of input data. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. activation represent activation to be used. relu function is set as value. Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional. First parameter represents the number of units (neurons). First parameter represents the number of units (neurons). input_shape represent the shape of input data. input_shape represent the shape of input data. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_initializer represent initializer to be used. he_uniform function is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_regularizer represent regularizer to be used. None is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. kernel_constraint represent constraint to be used. MaxNorm function is set as value. activation represent activation to be used. relu function is set as value. activation represent activation to be used. relu function is set as value. Line 10 creates second Dense layer with 16 units and set relu as the activation function. Line 10 creates second Dense layer with 16 units and set relu as the activation function. Line 11 creates final Dense layer with 8 units. Line 11 creates final Dense layer with 8 units. Let us understand the basic concept of layer as well as how Keras supports each concept. In machine learning, all type of input data like text, images or videos will be first converted into array of numbers and then feed into the algorithm. Input numbers may be single dimensional array, two dimensional array (matrix) or multi-dimensional array. We can specify the dimensional information using shape, a tuple of integers. For example, (4,2) represent matrix with four rows and two columns. >>> import numpy as np >>> shape = (4, 2) >>> input = np.zeros(shape) >>> print(input) [ [0. 0.] [0. 0.] [0. 0.] [0. 0.] ] >>> Similarly, (3,4,2) three dimensional matrix having three collections of 4x2 matrix (two rows and four columns). >>> import numpy as np >>> shape = (3, 4, 2) >>> input = np.zeros(shape) >>> print(input) [ [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] ] >>> To create the first layer of the model (or input layer of the model), shape of the input data should be specified. In Machine Learning, weight will be assigned to all input data. Initializers module provides different functions to set these initial weight. Some of the Keras Initializer function are as follows − Generates 0 for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Zeros() model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Where, kernel_initializer represent the initializer for kernel of the model. Generates 1 for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Ones() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Generates a constant value (say, 5) specified by the user for all input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Constant(value = 0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) where, value represent the constant value Generates value using normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomNormal(mean=0.0, stddev = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, mean represent the mean of the random values to generate mean represent the mean of the random values to generate stddev represent the standard deviation of the random values to generate stddev represent the standard deviation of the random values to generate seed represent the values to generate random number seed represent the values to generate random number Generates value using uniform distribution of input data. from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, minval represent the lower bound of the random values to generate minval represent the lower bound of the random values to generate maxval represent the upper bound of the random values to generate maxval represent the upper bound of the random values to generate Generates value using truncated normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.TruncatedNormal(mean = 0.0, stddev = 0.05, seed = None model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) Generates value based on the input shape and output shape of the layer along with the specified scale. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.VarianceScaling( scale = 1.0, mode = 'fan_in', distribution = 'normal', seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), skernel_initializer = my_init)) where, scale represent the scaling factor scale represent the scaling factor mode represent any one of fan_in, fan_out and fan_avg values mode represent any one of fan_in, fan_out and fan_avg values distribution represent either of normal or uniform distribution represent either of normal or uniform It finds the stddev value for normal distribution using below formula and then find the weights using normal distribution, stddev = sqrt(scale / n) where n represent, number of input units for mode = fan_in number of input units for mode = fan_in number of out units for mode = fan_out number of out units for mode = fan_out average number of input and output units for mode = fan_avg average number of input and output units for mode = fan_avg Similarly, it finds the limit for uniform distribution using below formula and then find the weights using uniform distribution, limit = sqrt(3 * scale / n) Generates value using lecun normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the stddev using the below formula and then apply normal distribution stddev = sqrt(1 / fan_in) where, fan_in represent the number of input units. Generates value using lecun uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.lecun_uniform(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution limit = sqrt(3 / fan_in) where, fan_in represents the number of input units fan_in represents the number of input units fan_out represents the number of output units fan_out represents the number of output units Generates value using glorot normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.glorot_normal(seed=None) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) It finds the stddev using the below formula and then apply normal distribution stddev = sqrt(2 / (fan_in + fan_out)) where, fan_in represents the number of input units fan_in represents the number of input units fan_out represents the number of output units fan_out represents the number of output units Generates value using glorot uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.glorot_uniform(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution limit = sqrt(6 / (fan_in + fan_out)) where, fan_in represent the number of input units. fan_in represent the number of input units. fan_out represents the number of output units fan_out represents the number of output units Generates value using he normal distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the stddev using the below formula and then apply normal distribution. stddev = sqrt(2 / fan_in) where, fan_in represent the number of input units. Generates value using he uniform distribution of input data. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.he_normal(seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) It finds the limit using the below formula and then apply uniform distribution. limit = sqrt(6 / fan_in) where, fan_in represent the number of input units. Generates a random orthogonal matrix. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Orthogonal(gain = 1.0, seed = None) model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)) where, gain represent the multiplication factor of the matrix. Generates identity matrix. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Identity(gain = 1.0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) In machine learning, a constraint will be set on the parameter (weight) during optimization phase. <>Constraints module provides different functions to set the constraint on the layer. Some of the constraint functions are as follows. Constrains weights to be non-negative. from keras.models import Sequential from keras.layers import Activation, Dense from keras import initializers my_init = initializers.Identity(gain = 1.0) model.add( Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init) ) where, kernel_constraint represent the constraint to be used in the layer. Constrains weights to be unit norm. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.UnitNorm(axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) Constrains weight to norm less than or equals to the given value. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.MaxNorm(max_value = 2, axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) where, max_value represent the upper bound max_value represent the upper bound axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension Constrains weights to be norm between specified minimum and maximum values. from keras.models import Sequential from keras.layers import Activation, Dense from keras import constraints my_constrain = constraints.MinMaxNorm(min_value = 0.0, max_value = 1.0, rate = 1.0, axis = 0) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_constraint = my_constrain)) where, rate represent the rate at which the weight constrain is applied. In machine learning, regularizers are used in the optimization phase. It applies some penalties on the layer parameter during optimization. Keras regularization module provides below functions to set penalties on the layer. Regularization applies per-layer basis only. It provides L1 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l1(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) where, kernel_regularizer represent the rate at which the weight constrain is applied. It provides L2 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l2(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) It provides both L1 and L2 based regularization. from keras.models import Sequential from keras.layers import Activation, Dense from keras import regularizers my_regularizer = regularizers.l2(0.) model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,), kernel_regularizer = my_regularizer)) In machine learning, activation function is a special function used to find whether a specific neuron is activated or not. Basically, the activation function does a nonlinear transformation of the input data and thus enable the neurons to learn better. Output of a neuron depends on the activation function. As you recall the concept of single perception, the output of a perceptron (neuron) is simply the result of the activation function, which accepts the summation of all input multiplied with its corresponding weight plus overall bias, if any available. result = Activation(SUMOF(input * weight) + bias) So, activation function plays an important role in the successful learning of the model. Keras provides a lot of activation function in the activations module. Let us learn all the activations available in the module. Applies Linear function. Does nothing. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'linear', input_shape = (784,))) Where, activation refers the activation function of the layer. It can be specified simply by the name of the function and the layer will use corresponding activators. Applies Exponential linear unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'elu', input_shape = (784,))) Applies Scaled exponential linear unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'selu', input_shape = (784,))) Applies Rectified Linear Unit. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) Applies Softmax function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softmax', input_shape = (784,))) Applies Softplus function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softplus', input_shape = (784,))) Applies Softsign function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'softsign', input_shape = (784,))) Applies Hyperbolic tangent function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'tanh', input_shape = (784,))) Applies Sigmoid function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'sigmoid', input_shape = (784,))) Applies Hard Sigmoid function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'hard_sigmoid', input_shape = (784,))) Applies exponential function. from keras.models import Sequential from keras.layers import Activation, Dense model = Sequential() model.add(Dense(512, activation = 'exponential', input_shape = (784,))) Dense Layer Dense layer is the regular deeply connected neural network layer. Dropout Layers Dropout is one of the important concept in the machine learning. Flatten Layers Flatten is used to flatten the input. Reshape Layers Reshape is used to change the shape of the input. Permute Layers Permute is also used to change the shape of the input using pattern. RepeatVector Layers RepeatVector is used to repeat the input for set number, n of times. Lambda Layers Lambda is used to transform the input data using an expression or function. Convolution Layers Keras contains a lot of layers for creating Convolution based ANN, popularly called as Convolution Neural Network (CNN). Pooling Layer It is used to perform max pooling operations on temporal data. Locally connected layer Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared. Merge Layer It is used to merge a list of inputs. Embedding Layer It performs embedding operations in input layer. Keras allows to create our own customized layer. Once a new layer is created, it can be used in any model without any restriction. Let us learn how to create new layer in this chapter. Keras provides a base layer class, Layer which can sub-classed to create our own customized layer. Let us create a simple layer which will find weight based on normal distribution and then do the basic computation of finding the summation of the product of input and its weight during training. First, let us import the necessary modules − from keras import backend as K from keras.layers import Layer Here, backend is used to access the dot function. backend is used to access the dot function. Layer is the base class and we will be sub-classing it to create our layer Layer is the base class and we will be sub-classing it to create our layer Let us create a new class, MyCustomLayer by sub-classing Layer class − class MyCustomLayer(Layer): ... Let us initialize our new class as specified below − def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyCustomLayer, self).__init__(**kwargs) Here, Line 2 sets the output dimension. Line 2 sets the output dimension. Line 3 calls the base or super layer’s init function. Line 3 calls the base or super layer’s init function. build is the main method and its only purpose is to build the layer properly. It can do anything related to the inner working of the layer. Once the custom functionality is done, we can call the base class build function. Our custom build function is as follows − def build(self, input_shape): self.kernel = self.add_weight(name = 'kernel', shape = (input_shape[1], self.output_dim), initializer = 'normal', trainable = True) super(MyCustomLayer, self).build(input_shape) Here, Line 1 defines the build method with one argument, input_shape. Shape of the input data is referred by input_shape. Line 1 defines the build method with one argument, input_shape. Shape of the input data is referred by input_shape. Line 2 creates the weight corresponding to input shape and set it in the kernel. It is our custom functionality of the layer. It creates the weight using ‘normal’ initializer. Line 2 creates the weight corresponding to input shape and set it in the kernel. It is our custom functionality of the layer. It creates the weight using ‘normal’ initializer. Line 6 calls the base class, build method. Line 6 calls the base class, build method. call method does the exact working of the layer during training process. Our custom call method is as follows def call(self, input_data): return K.dot(input_data, self.kernel) Here, Line 1 defines the call method with one argument, input_data. input_data is the input data for our layer. Line 1 defines the call method with one argument, input_data. input_data is the input data for our layer. Line 2 return the dot product of the input data, input_data and our layer’s kernel, self.kernel Line 2 return the dot product of the input data, input_data and our layer’s kernel, self.kernel def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) Here, Line 1 defines compute_output_shape method with one argument input_shape Line 1 defines compute_output_shape method with one argument input_shape Line 2 computes the output shape using shape of input data and output dimension set while initializing the layer. Line 2 computes the output shape using shape of input data and output dimension set while initializing the layer. Implementing the build, call and compute_output_shape completes the creating a customized layer. The final and complete code is as follows from keras import backend as K from keras.layers import Layer class MyCustomLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyCustomLayer, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(name = 'kernel', shape = (input_shape[1], self.output_dim), initializer = 'normal', trainable = True) super(MyCustomLayer, self).build(input_shape) # Be sure to call this at the end def call(self, input_data): return K.dot(input_data, self.kernel) def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) Let us create a simple model using our customized layer as specified below − from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(MyCustomLayer(32, input_shape = (16,))) model.add(Dense(8, activation = 'softmax')) model.summary() Here, Our MyCustomLayer is added to the model using 32 units and (16,) as input shape Our MyCustomLayer is added to the model using 32 units and (16,) as input shape Running the application will print the model summary as below − Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param #================================================================ my_custom_layer_1 (MyCustomL (None, 32) 512 _________________________________________________________________ dense_1 (Dense) (None, 8) 264 ================================================================= Total params: 776 Trainable params: 776 Non-trainable params: 0 _________________________________________________________________ As learned earlier, Keras model represents the actual neural network model. Keras provides a two mode to create the model, simple and easy to use Sequential API as well as more flexible and advanced Functional API. Let us learn now to create model using both Sequential and Functional API in this chapter. The core idea of Sequential API is simply arranging the Keras layers in a sequential order and so, it is called Sequential API. Most of the ANN also has layers in sequential order and the data flows from one layer to another layer in the given order until the data finally reaches the output layer. A ANN model can be created by simply calling Sequential() API as specified below − from keras.models import Sequential model = Sequential() To add a layer, simply create a layer using Keras layer API and then pass the layer through add() function as specified below − from keras.models import Sequential model = Sequential() input_layer = Dense(32, input_shape=(8,)) model.add(input_layer) hidden_layer = Dense(64, activation='relu'); model.add(hidden_layer) output_layer = Dense(8) model.add(output_layer) Here, we have created one input layer, one hidden layer and one output layer. Keras provides few methods to get the model information like layers, input data and output data. They are as follows − model.layers − Returns all the layers of the model as list. model.layers − Returns all the layers of the model as list. >>> layers = model.layers >>> layers [ <keras.layers.core.Dense object at 0x000002C8C888B8D0>, <keras.layers.core.Dense object at 0x000002C8C888B7B8> <keras.layers.core.Dense object at 0x 000002C8C888B898> ] model.inputs − Returns all the input tensors of the model as list. model.inputs − Returns all the input tensors of the model as list. >>> inputs = model.inputs >>> inputs [<tf.Tensor 'dense_13_input:0' shape=(?, 8) dtype=float32>] model.outputs − Returns all the output tensors of the model as list. model.outputs − Returns all the output tensors of the model as list. >>> outputs = model.outputs >>> outputs <tf.Tensor 'dense_15/BiasAdd:0' shape=(?, 8) dtype=float32>] model.get_weights − Returns all the weights as NumPy arrays. model.get_weights − Returns all the weights as NumPy arrays. model.set_weights(weight_numpy_array) − Set the weights of the model. model.set_weights(weight_numpy_array) − Set the weights of the model. Keras provides methods to serialize the model into object as well as json and load it again later. They are as follows − get_config() − IReturns the model as an object. get_config() − IReturns the model as an object. config = model.get_config() from_config() − It accept the model configuration object as argument and create the model accordingly. from_config() − It accept the model configuration object as argument and create the model accordingly. new_model = Sequential.from_config(config) to_json() − Returns the model as an json object. to_json() − Returns the model as an json object. >>> json_string = model.to_json() >>> json_string '{"class_name": "Sequential", "config": {"name": "sequential_10", "layers": [{"class_name": "Dense", "config": {"name": "dense_13", "trainable": true, "batch_input_shape": [null, 8], "dtype": "float32", "units": 32, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "Vari anceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "conf ig": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {" class_name": "Dense", "config": {"name": "dense_14", "trainable": true, "dtype": "float32", "units": 64, "activation": "relu", "use_bias": true, "kern el_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initia lizer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint" : null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_15", "trainable": true, "dtype": "float32", "units": 8, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": " uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_r egularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, "keras_version": "2.2.5", "backend": "tensorflow"}' >>> model_from_json() − Accepts json representation of the model and create a new model. model_from_json() − Accepts json representation of the model and create a new model. from keras.models import model_from_json new_model = model_from_json(json_string) to_yaml() − Returns the model as a yaml string. to_yaml() − Returns the model as a yaml string. >>> yaml_string = model.to_yaml() >>> yaml_string 'backend: tensorflow\nclass_name: Sequential\nconfig:\n layers:\n - class_name: Dense\n config:\n activation: linear\n activity_regular izer: null\n batch_input_shape: !!python/tuple\n - null\n - 8\n bias_constraint: null\n bias_initializer:\n class_name : Zeros\n config: {}\n bias_regularizer: null\n dtype: float32\n kernel_constraint: null\n kernel_initializer:\n cla ss_name: VarianceScaling\n config:\n distribution: uniform\n mode: fan_avg\n scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense_13\n trainable: true\n units: 32\n use_bias: true\n - class_name: Dense\n config:\n activation: relu\n activity_regularizer: null\n bias_constraint: null\n bias_initializer:\n class_name: Zeros\n config : {}\n bias_regularizer: null\n dtype: float32\n kernel_constraint: null\n kernel_initializer:\n class_name: VarianceScalin g\n config:\n distribution: uniform\n mode: fan_avg\n scale: 1.0\n seed: null\n kernel_regularizer: nu ll\n name: dense_14\n trainable: true\n units: 64\n use_bias: true\n - class_name: Dense\n config:\n activation: linear\n activity_regularizer: null\n bias_constraint: null\n bias_initializer:\n class_name: Zeros\n config: {}\n bias_regu larizer: null\n dtype: float32\n kernel_constraint: null\n kernel_initializer:\n class_name: VarianceScaling\n config:\n distribution: uniform\n mode: fan_avg\n scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense _15\n trainable: true\n units: 8\n use_bias: true\n name: sequential_10\nkeras_version: 2.2.5\n' >>> model_from_yaml() − Accepts yaml representation of the model and create a new model. model_from_yaml() − Accepts yaml representation of the model and create a new model. from keras.models import model_from_yaml new_model = model_from_yaml(yaml_string) Understanding the model is very important phase to properly use it for training and prediction purposes. Keras provides a simple method, summary to get the full information about the model and its layers. A summary of the model created in the previous section is as follows − >>> model.summary() Model: "sequential_10" _________________________________________________________________ Layer (type) Output Shape Param #================================================================ dense_13 (Dense) (None, 32) 288 _________________________________________________________________ dense_14 (Dense) (None, 64) 2112 _________________________________________________________________ dense_15 (Dense) (None, 8) 520 ================================================================= Total params: 2,920 Trainable params: 2,920 Non-trainable params: 0 _________________________________________________________________ >>> Model provides function for training, evaluation and prediction process. They are as follows − compile − Configure the learning process of the model compile − Configure the learning process of the model fit − Train the model using the training data fit − Train the model using the training data evaluate − Evaluate the model using the test data evaluate − Evaluate the model using the test data predict − Predict the results for new input. predict − Predict the results for new input. Sequential API is used to create models layer-by-layer. Functional API is an alternative approach of creating more complex models. Functional model, you can define multiple input or output that share layers. First, we create an instance for model and connecting to the layers to access input and output to the model. This section explains about functional model in brief. Import an input layer using the below module − >>> from keras.layers import Input Now, create an input layer specifying input dimension shape for the model using the below code − >>> data = Input(shape=(2,3)) Define layer for the input using the below module − >>> from keras.layers import Dense Add Dense layer for the input using the below line of code − >>> layer = Dense(2)(data) >>> print(layer) Tensor("dense_1/add:0", shape =(?, 2, 2), dtype = float32) Define model using the below module − from keras.models import Model Create a model in functional way by specifying both input and output layer − model = Model(inputs = data, outputs = layer) The complete code to create a simple model is shown below − from keras.layers import Input from keras.models import Model from keras.layers import Dense data = Input(shape=(2,3)) layer = Dense(2)(data) model = Model(inputs=data,outputs=layer) model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 2, 3) 0 _________________________________________________________________ dense_2 (Dense) (None, 2, 2) 8 ================================================================= Total params: 8 Trainable params: 8 Non-trainable params: 0 _________________________________________________________________ Previously, we studied the basics of how to create model using Sequential and Functional API. This chapter explains about how to compile the model. The compilation is the final step in creating a model. Once the compilation is done, we can move on to training phase. Let us learn few concepts required to better understand the compilation process. In machine learning, Loss function is used to find error or deviation in the learning process. Keras requires loss function during model compilation process. Keras provides quite a few loss function in the losses module and they are as follows − mean_squared_error mean_absolute_error mean_absolute_percentage_error mean_squared_logarithmic_error squared_hinge hinge categorical_hinge logcosh huber_loss categorical_crossentropy sparse_categorical_crossentropy binary_crossentropy kullback_leibler_divergence poisson cosine_proximity is_categorical_crossentropy All above loss function accepts two arguments − y_true − true labels as tensors y_true − true labels as tensors y_pred − prediction with same shape as y_true y_pred − prediction with same shape as y_true Import the losses module before using loss function as specified below − from keras import losses In machine learning, Optimization is an important process which optimize the input weights by comparing the prediction and the loss function. Keras provides quite a few optimizer as a module, optimizers and they are as follows: SGD − Stochastic gradient descent optimizer. keras.optimizers.SGD(learning_rate = 0.01, momentum = 0.0, nesterov = False) RMSprop − RMSProp optimizer. keras.optimizers.RMSprop(learning_rate = 0.001, rho = 0.9) Adagrad − Adagrad optimizer. keras.optimizers.Adagrad(learning_rate = 0.01) Adadelta − Adadelta optimizer. keras.optimizers.Adadelta(learning_rate = 1.0, rho = 0.95) Adam − Adam optimizer. keras.optimizers.Adam( learning_rate = 0.001, beta_1 = 0.9, beta_2 = 0.999, amsgrad = False ) Adamax − Adamax optimizer from Adam. keras.optimizers.Adamax(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999) Nadam − Nesterov Adam optimizer. keras.optimizers.Nadam(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999) Import the optimizers module before using optimizers as specified below − from keras import optimizers In machine learning, Metrics is used to evaluate the performance of your model. It is similar to loss function, but not used in training process. Keras provides quite a few metrics as a module, metrics and they are as follows accuracy binary_accuracy categorical_accuracy sparse_categorical_accuracy top_k_categorical_accuracy sparse_top_k_categorical_accuracy cosine_proximity clone_metric Similar to loss function, metrics also accepts below two arguments − y_true − true labels as tensors y_true − true labels as tensors y_pred − prediction with same shape as y_true y_pred − prediction with same shape as y_true Import the metrics module before using metrics as specified below − from keras import metrics Keras model provides a method, compile() to compile the model. The argument and default value of the compile() method is as follows compile( optimizer, loss = None, metrics = None, loss_weights = None, sample_weight_mode = None, weighted_metrics = None, target_tensors = None ) The important arguments are as follows − loss function Optimizer metrics A sample code to compile the mode is as follows − from keras import losses from keras import optimizers from keras import metrics model.compile(loss = 'mean_squared_error', optimizer = 'sgd', metrics = [metrics.categorical_accuracy]) where, loss function is set as mean_squared_error loss function is set as mean_squared_error optimizer is set as sgd optimizer is set as sgd metrics is set as metrics.categorical_accuracy metrics is set as metrics.categorical_accuracy Models are trained by NumPy arrays using fit(). The main purpose of this fit function is used to evaluate your model on training. This can be also used for graphing model performance. It has the following syntax − model.fit(X, y, epochs = , batch_size = ) Here, X, y − It is a tuple to evaluate your data. X, y − It is a tuple to evaluate your data. epochs − no of times the model is needed to be evaluated during training. epochs − no of times the model is needed to be evaluated during training. batch_size − training instances. batch_size − training instances. Let us take a simple example of numpy random data to use this concept. Let us create a random data using numpy for x and y with the help of below mentioned command − import numpy as np x_train = np.random.random((100,4,8)) y_train = np.random.random((100,10)) Now, create random validation data, x_val = np.random.random((100,4,8)) y_val = np.random.random((100,10)) Let us create simple sequential model − from keras.models import Sequential model = Sequential() Create layers to add model − from keras.layers import LSTM, Dense # add a sequence of vectors of dimension 16 model.add(LSTM(16, return_sequences = True)) model.add(Dense(10, activation = 'softmax')) Now model is defined. You can compile using the below command − model.compile( loss = 'categorical_crossentropy', optimizer = 'sgd', metrics = ['accuracy'] ) Now we apply fit() function to train our data − model.fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = (x_val, y_val)) We have learned to create, compile and train the Keras models. Let us apply our learning and create a simple MPL based ANN. Before creating a model, we need to choose a problem, need to collect the required data and convert the data to NumPy array. Once data is collected, we can prepare the model and train it by using the collected data. Data collection is one of the most difficult phase of machine learning. Keras provides a special module, datasets to download the online machine learning data for training purposes. It fetches the data from online server, process the data and return the data as training and test set. Let us check the data provided by Keras dataset module. The data available in the module are as follows, CIFAR10 small image classification CIFAR100 small image classification IMDB Movie reviews sentiment classification Reuters newswire topics classification MNIST database of handwritten digits Fashion-MNIST database of fashion articles Boston housing price regression dataset Let us use the MNIST database of handwritten digits (or minst) as our input. minst is a collection of 60,000, 28x28 grayscale images. It contains 10 digits. It also contains 10,000 test images. Below code can be used to load the dataset − from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() where Line 1 imports minst from the keras dataset module. Line 1 imports minst from the keras dataset module. Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape. Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape. Other dataset can also be fetched using similar API and every API returns similar data as well except the shape of the data. The shape of the data depends on the type of data. Let us choose a simple multi-layer perceptron (MLP) as represented below and try to create the model using Keras. The core features of the model are as follows − Input layer consists of 784 values (28 x 28 = 784). Input layer consists of 784 values (28 x 28 = 784). First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function. First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function. Second hidden layer, Dropout has 0.2 as its value. Second hidden layer, Dropout has 0.2 as its value. Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function. Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function. Fourth hidden layer, Dropout has 0.2 as its value. Fourth hidden layer, Dropout has 0.2 as its value. Fifth and final layer consists of 10 neurons and ‘softmax’ activation function. Fifth and final layer consists of 10 neurons and ‘softmax’ activation function. Use categorical_crossentropy as loss function. Use categorical_crossentropy as loss function. Use RMSprop() as Optimizer. Use RMSprop() as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 128 as batch size. Use 128 as batch size. Use 20 as epochs. Use 20 as epochs. Step 1 − Import the modules Let us import the necessary modules. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import numpy as np Step 2 − Load data Let us import the mnist dataset. (x_train, y_train), (x_test, y_test) = mnist.load_data() Step 3 − Process the data Let us change the dataset according to our model, so that it can be feed into our model. x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) Where reshape is used to reshape the input from (28, 28) tuple to (784, ) reshape is used to reshape the input from (28, 28) tuple to (784, ) to_categorical is used to convert vector to binary matrix to_categorical is used to convert vector to binary matrix Step 4 − Create the model Let us create the actual model. model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation = 'softmax')) Step 5 − Compile the model Let us compile the model using selected loss function, optimizer and metrics. model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) Step 6 − Train the model Let us train the model using fit() method. history = model.fit( x_train, y_train, batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test) ) We have created the model, loaded the data and also trained the data to the model. We still need to evaluate the model and predict output for unknown input, which we learn in upcoming chapter. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import numpy as np (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) model = Sequential() model.add(Dense(512, activation='relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) history = model.fit(x_train, y_train, batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test)) Executing the application will give the below content as output − Train on 60000 samples, validate on 10000 samples Epoch 1/20 60000/60000 [==============================] - 7s 118us/step - loss: 0.2453 - acc: 0.9236 - val_loss: 0.1004 - val_acc: 0.9675 Epoch 2/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.1023 - acc: 0.9693 - val_loss: 0.0797 - val_acc: 0.9761 Epoch 3/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.0744 - acc: 0.9770 - val_loss: 0.0727 - val_acc: 0.9791 Epoch 4/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.0599 - acc: 0.9823 - val_loss: 0.0704 - val_acc: 0.9801 Epoch 5/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0504 - acc: 0.9853 - val_loss: 0.0714 - val_acc: 0.9817 Epoch 6/20 60000/60000 [==============================] - 7s 111us/step - loss: 0.0438 - acc: 0.9868 - val_loss: 0.0845 - val_acc: 0.9809 Epoch 7/20 60000/60000 [==============================] - 7s 114us/step - loss: 0.0391 - acc: 0.9887 - val_loss: 0.0823 - val_acc: 0.9802 Epoch 8/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0364 - acc: 0.9892 - val_loss: 0.0818 - val_acc: 0.9830 Epoch 9/20 60000/60000 [==============================] - 7s 113us/step - loss: 0.0308 - acc: 0.9905 - val_loss: 0.0833 - val_acc: 0.9829 Epoch 10/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0289 - acc: 0.9917 - val_loss: 0.0947 - val_acc: 0.9815 Epoch 11/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0279 - acc: 0.9921 - val_loss: 0.0818 - val_acc: 0.9831 Epoch 12/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0260 - acc: 0.9927 - val_loss: 0.0945 - val_acc: 0.9819 Epoch 13/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0257 - acc: 0.9931 - val_loss: 0.0952 - val_acc: 0.9836 Epoch 14/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0229 - acc: 0.9937 - val_loss: 0.0924 - val_acc: 0.9832 Epoch 15/20 60000/60000 [==============================] - 7s 115us/step - loss: 0.0235 - acc: 0.9937 - val_loss: 0.1004 - val_acc: 0.9823 Epoch 16/20 60000/60000 [==============================] - 7s 113us/step - loss: 0.0214 - acc: 0.9941 - val_loss: 0.0991 - val_acc: 0.9847 Epoch 17/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0219 - acc: 0.9943 - val_loss: 0.1044 - val_acc: 0.9837 Epoch 18/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0190 - acc: 0.9952 - val_loss: 0.1129 - val_acc: 0.9836 Epoch 19/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0197 - acc: 0.9953 - val_loss: 0.0981 - val_acc: 0.9841 Epoch 20/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0198 - acc: 0.9950 - val_loss: 0.1215 - val_acc: 0.9828 This chapter deals with the model evaluation and model prediction in Keras. Let us begin by understanding the model evaluation. Evaluation is a process during development of the model to check whether the model is best fit for the given problem and corresponding data. Keras model provides a function, evaluate which does the evaluation of the model. It has three main arguments, Test data Test data label verbose - true or false Let us evaluate the model, which we created in the previous chapter using test data. score = model.evaluate(x_test, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Executing the above code will output the below information. 0 The test accuracy is 98.28%. We have created a best model to identify the handwriting digits. On the positive side, we can still scope to improve our model. Prediction is the final step and our expected outcome of the model generation. Keras provides a method, predict to get the prediction of the trained model. The signature of the predict method is as follows, predict( x, batch_size = None, verbose = 0, steps = None, callbacks = None, max_queue_size = 10, workers = 1, use_multiprocessing = False ) Here, all arguments are optional except the first argument, which refers the unknown input data. The shape should be maintained to get the proper prediction. Let us do prediction for our MPL model created in previous chapter using below code − pred = model.predict(x_test) pred = np.argmax(pred, axis = 1)[:5] label = np.argmax(y_test,axis = 1)[:5] print(pred) print(label) Here, Line 1 call the predict function using test data. Line 1 call the predict function using test data. Line 2 gets the first five prediction Line 2 gets the first five prediction Line 3 gets the first five labels of the test data. Line 3 gets the first five labels of the test data. Line 5 - 6 prints the prediction and actual label. Line 5 - 6 prints the prediction and actual label. The output of the above application is as follows − [7 2 1 0 4] [7 2 1 0 4] The output of both array is identical and it indicate that our model predicts correctly the first five images. Let us modify the model from MPL to Convolution Neural Network (CNN) for our earlier digit identification problem. CNN can be represented as below − The core features of the model are as follows − Input layer consists of (1, 8, 28) values. Input layer consists of (1, 8, 28) values. First layer, Conv2D consists of 32 filters and ‘relu’ activation function with kernel size, (3,3). First layer, Conv2D consists of 32 filters and ‘relu’ activation function with kernel size, (3,3). Second layer, Conv2D consists of 64 filters and ‘relu’ activation function with kernel size, (3,3). Second layer, Conv2D consists of 64 filters and ‘relu’ activation function with kernel size, (3,3). Thrid layer, MaxPooling has pool size of (2, 2). Thrid layer, MaxPooling has pool size of (2, 2). Fifth layer, Flatten is used to flatten all its input into single dimension. Fifth layer, Flatten is used to flatten all its input into single dimension. Sixth layer, Dense consists of 128 neurons and ‘relu’ activation function. Sixth layer, Dense consists of 128 neurons and ‘relu’ activation function. Seventh layer, Dropout has 0.5 as its value. Seventh layer, Dropout has 0.5 as its value. Eighth and final layer consists of 10 neurons and ‘softmax’ activation function. Eighth and final layer consists of 10 neurons and ‘softmax’ activation function. Use categorical_crossentropy as loss function. Use categorical_crossentropy as loss function. Use Adadelta() as Optimizer. Use Adadelta() as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 128 as batch size. Use 128 as batch size. Use 20 as epochs. Use 20 as epochs. Step 1 − Import the modules Let us import the necessary modules. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K import numpy as np Step 2 − Load data Let us import the mnist dataset. (x_train, y_train), (x_test, y_test) = mnist.load_data() Step 3 − Process the data Let us change the dataset according to our model, so that it can be feed into our model. img_rows, img_cols = 28, 28 if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) The data processing is similar to MPL model except the shape of the input data and image format configuration. Step 4 − Create the model Let us create tha actual model. model = Sequential() model.add(Conv2D(32, kernel_size = (3, 3), activation = 'relu', input_shape = input_shape)) model.add(Conv2D(64, (3, 3), activation = 'relu')) model.add(MaxPooling2D(pool_size = (2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation = 'relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation = 'softmax')) Step 5 − Compile the model Let us compile the model using selected loss function, optimizer and metrics. model.compile(loss = keras.losses.categorical_crossentropy, optimizer = keras.optimizers.Adadelta(), metrics = ['accuracy']) Step 6 − Train the model Let us train the model using fit() method. model.fit( x_train, y_train, batch_size = 128, epochs = 12, verbose = 1, validation_data = (x_test, y_test) ) Executing the application will output the below information − Train on 60000 samples, validate on 10000 samples Epoch 1/12 60000/60000 [==============================] - 84s 1ms/step - loss: 0.2687 - acc: 0.9173 - val_loss: 0.0549 - val_acc: 0.9827 Epoch 2/12 60000/60000 [==============================] - 86s 1ms/step - loss: 0.0899 - acc: 0.9737 - val_loss: 0.0452 - val_acc: 0.9845 Epoch 3/12 60000/60000 [==============================] - 83s 1ms/step - loss: 0.0666 - acc: 0.9804 - val_loss: 0.0362 - val_acc: 0.9879 Epoch 4/12 60000/60000 [==============================] - 81s 1ms/step - loss: 0.0564 - acc: 0.9830 - val_loss: 0.0336 - val_acc: 0.9890 Epoch 5/12 60000/60000 [==============================] - 86s 1ms/step - loss: 0.0472 - acc: 0.9861 - val_loss: 0.0312 - val_acc: 0.9901 Epoch 6/12 60000/60000 [==============================] - 83s 1ms/step - loss: 0.0414 - acc: 0.9877 - val_loss: 0.0306 - val_acc: 0.9902 Epoch 7/12 60000/60000 [==============================] - 89s 1ms/step - loss: 0.0375 -acc: 0.9883 - val_loss: 0.0281 - val_acc: 0.9906 Epoch 8/12 60000/60000 [==============================] - 91s 2ms/step - loss: 0.0339 - acc: 0.9893 - val_loss: 0.0280 - val_acc: 0.9912 Epoch 9/12 60000/60000 [==============================] - 89s 1ms/step - loss: 0.0325 - acc: 0.9901 - val_loss: 0.0260 - val_acc: 0.9909 Epoch 10/12 60000/60000 [==============================] - 89s 1ms/step - loss: 0.0284 - acc: 0.9910 - val_loss: 0.0250 - val_acc: 0.9919 Epoch 11/12 60000/60000 [==============================] - 86s 1ms/step - loss: 0.0287 - acc: 0.9907 - val_loss: 0.0264 - val_acc: 0.9916 Epoch 12/12 60000/60000 [==============================] - 86s 1ms/step - loss: 0.0265 - acc: 0.9920 - val_loss: 0.0249 - val_acc: 0.9922 Step 7 − Evaluate the model Let us evaluate the model using test data. score = model.evaluate(x_test, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Executing the above code will output the below information − Test loss: 0.024936060590433316 Test accuracy: 0.9922 The test accuracy is 99.22%. We have created a best model to identify the handwriting digits. Step 8 − Predict Finally, predict the digit from images as below − pred = model.predict(x_test) pred = np.argmax(pred, axis = 1)[:5] label = np.argmax(y_test,axis = 1)[:5] print(pred) print(label) The output of the above application is as follows − [7 2 1 0 4] [7 2 1 0 4] The output of both array is identical and it indicate our model correctly predicts the first five images. In this chapter, let us write a simple MPL based ANN to do regression prediction. Till now, we have only done the classification based prediction. Now, we will try to predict the next possible value by analyzing the previous (continuous) values and its influencing factors. The Regression MPL can be represented as below − The core features of the model are as follows − Input layer consists of (13,) values. Input layer consists of (13,) values. First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer. First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer. Second layer, Dense consists of 64 units and ‘relu’ activation function. Second layer, Dense consists of 64 units and ‘relu’ activation function. Output layer, Dense consists of 1 unit. Output layer, Dense consists of 1 unit. Use mse as loss function. Use mse as loss function. Use RMSprop as Optimizer. Use RMSprop as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 128 as batch size. Use 128 as batch size. Use 500 as epochs. Use 500 as epochs. Step 1 − Import the modules Let us import the necessary modules. import keras from keras.datasets import boston_housing from keras.models import Sequential from keras.layers import Dense from keras.optimizers import RMSprop from keras.callbacks import EarlyStopping from sklearn import preprocessing from sklearn.preprocessing import scale Step 2 − Load data Let us import the Boston housing dataset. (x_train, y_train), (x_test, y_test) = boston_housing.load_data() Here, boston_housing is a dataset provided by Keras. It represents a collection of housing information in Boston area, each having 13 features. Step 3 − Process the data Let us change the dataset according to our model, so that, we can feed into our model. The data can be changed using below code − x_train_scaled = preprocessing.scale(x_train) scaler = preprocessing.StandardScaler().fit(x_train) x_test_scaled = scaler.transform(x_test) Here, we have normalized the training data using sklearn.preprocessing.scale function. preprocessing.StandardScaler().fit function returns a scalar with the normalized mean and standard deviation of the training data, which we can apply to the test data using scalar.transform function. This will normalize the test data as well with the same setting as that of training data. Step 4 − Create the model Let us create the actual model. model = Sequential() model.add(Dense(64, kernel_initializer = 'normal', activation = 'relu', input_shape = (13,))) model.add(Dense(64, activation = 'relu')) model.add(Dense(1)) Step 5 − Compile the model Let us compile the model using selected loss function, optimizer and metrics. model.compile( loss = 'mse', optimizer = RMSprop(), metrics = ['mean_absolute_error'] ) Step 6 − Train the model Let us train the model using fit() method. history = model.fit( x_train_scaled, y_train, batch_size=128, epochs = 500, verbose = 1, validation_split = 0.2, callbacks = [EarlyStopping(monitor = 'val_loss', patience = 20)] ) Here, we have used callback function, EarlyStopping. The purpose of this callback is to monitor the loss value during each epoch and compare it with previous epoch loss value to find the improvement in the training. If there is no improvement for the patience times, then the whole process will be stopped. Executing the application will give the below information as output − Train on 323 samples, validate on 81 samples Epoch 1/500 2019-09-24 01:07:03.889046: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not co mpiled to use: AVX2 323/323 [==============================] - 0s 515us/step - loss: 562.3129 - mean_absolute_error: 21.8575 - val_loss: 621.6523 - val_mean_absolute_erro r: 23.1730 Epoch 2/500 323/323 [==============================] - 0s 11us/step - loss: 545.1666 - mean_absolute_error: 21.4887 - val_loss: 605.1341 - val_mean_absolute_error : 22.8293 Epoch 3/500 323/323 [==============================] - 0s 12us/step - loss: 528.9944 - mean_absolute_error: 21.1328 - val_loss: 588.6594 - val_mean_absolute_error : 22.4799 Epoch 4/500 323/323 [==============================] - 0s 12us/step - loss: 512.2739 - mean_absolute_error: 20.7658 - val_loss: 570.3772 - val_mean_absolute_error : 22.0853 Epoch 5/500 323/323 [==============================] - 0s 9us/step - loss: 493.9775 - mean_absolute_error: 20.3506 - val_loss: 550.9548 - val_mean_absolute_error: 21.6547 .......... .......... .......... Epoch 143/500 323/323 [==============================] - 0s 15us/step - loss: 8.1004 - mean_absolute_error: 2.0002 - val_loss: 14.6286 - val_mean_absolute_error: 2. 5904 Epoch 144/500 323/323 [==============================] - 0s 19us/step - loss: 8.0300 - mean_absolute_error: 1.9683 - val_loss: 14.5949 - val_mean_absolute_error: 2. 5843 Epoch 145/500 323/323 [==============================] - 0s 12us/step - loss: 7.8704 - mean_absolute_error: 1.9313 - val_loss: 14.3770 - val_mean_absolute_error: 2. 4996 Step 7 − Evaluate the model Let us evaluate the model using test data. score = model.evaluate(x_test_scaled, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Executing the above code will output the below information − Test loss: 21.928471583946077 Test accuracy: 2.9599233234629914 Step 7 − Evaluate the model Let us evaluate the model using test data. score = model.evaluate(x_test_scaled, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Executing the above code will output the below information − Test loss: 21.928471583946077 Test accuracy: 2.9599233234629914 Step 8 − Predict Finally, predict using test data as below − prediction = model.predict(x_test_scaled) print(prediction.flatten()) print(y_test) The output of the above application is as follows − [ 7.5612316 17.583357 21.09344 31.859276 25.055613 18.673872 26.600405 22.403967 19.060272 22.264952 17.4191 17.00466 15.58924 41.624374 20.220217 18.985565 26.419338 19.837091 19.946192 36.43445 12.278508 16.330965 20.701359 14.345301 21.741161 25.050423 31.046402 27.738455 9.959419 20.93039 20.069063 14.518344 33.20235 24.735163 18.7274 9.148898 15.781284 18.556862 18.692865 26.045074 27.954073 28.106823 15.272034 40.879818 29.33896 23.714525 26.427515 16.483374 22.518442 22.425386 33.94826 18.831465 13.2501955 15.537227 34.639984 27.468002 13.474407 48.134598 34.39617 22.8503124.042334 17.747198 14.7837715 18.187277 23.655672 22.364983 13.858193 22.710032 14.371148 7.1272087 35.960033 28.247292 25.3014 14.477208 25.306196 17.891165 20.193708 23.585173 34.690193 12.200583 20.102983 38.45882 14.741723 14.408362 17.67158 18.418497 21.151712 21.157492 22.693687 29.809034 19.366991 20.072294 25.880817 40.814568 34.64087 19.43741 36.2591 50.73806 26.968863 43.91787 32.54908 20.248306 ] [ 7.2 18.8 19. 27. 22.2 24.5 31.2 22.9 20.5 23.2 18.6 14.5 17.8 50. 20.8 24.3 24.2 19.8 19.1 22.7 12. 10.2 20. 18.5 20.9 23. 27.5 30.1 9.5 22. 21.2 14.1 33.1 23.4 20.1 7.4 15.4 23.8 20.1 24.5 33. 28.4 14.1 46.7 32.5 29.6 28.4 19.8 20.2 25. 35.4 20.3 9.7 14.5 34.9 26.6 7.2 50. 32.4 21.6 29.8 13.1 27.5 21.2 23.1 21.9 13. 23.2 8.1 5.6 21.7 29.6 19.6 7. 26.4 18.9 20.9 28.1 35.4 10.2 24.3 43.1 17.6 15.4 16.2 27.1 21.4 21.5 22.4 25. 16.6 18.6 22. 42.8 35.1 21.5 36. 21.9 24.1 50. 26.7 25. ] The output of both array have around 10-30% difference and it indicate our model predicts with reasonable range. In this chapter, let us write a simple Long Short Term Memory (LSTM) based RNN to do sequence analysis. A sequence is a set of values where each value corresponds to a particular instance of time. Let us consider a simple example of reading a sentence. Reading and understanding a sentence involves reading the word in the given order and trying to understand each word and its meaning in the given context and finally understanding the sentence in a positive or negative sentiment. Here, the words are considered as values, and first value corresponds to first word, second value corresponds to second word, etc., and the order will be strictly maintained. Sequence Analysis is used frequently in natural language processing to find the sentiment analysis of the given text. Let us create a LSTM model to analyze the IMDB movie reviews and find its positive/negative sentiment. The model for the sequence analysis can be represented as below − The core features of the model are as follows − Input layer using Embedding layer with 128 features. Input layer using Embedding layer with 128 features. First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2. First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2. Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function. Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function. Use binary_crossentropy as loss function. Use binary_crossentropy as loss function. Use adam as Optimizer. Use adam as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 32 as batch size. Use 32 as batch size. Use 15 as epochs. Use 15 as epochs. Use 80 as the maximum length of the word. Use 80 as the maximum length of the word. Use 2000 as the maximum number of word in a given sentence. Use 2000 as the maximum number of word in a given sentence. Let us import the necessary modules. from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM from keras.datasets import imdb Let us import the imdb dataset. (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = 2000) Here, imdb is a dataset provided by Keras. It represents a collection of movies and its reviews. imdb is a dataset provided by Keras. It represents a collection of movies and its reviews. num_words represent the maximum number of words in the review. num_words represent the maximum number of words in the review. Let us change the dataset according to our model, so that it can be fed into our model. The data can be changed using the below code − x_train = sequence.pad_sequences(x_train, maxlen=80) x_test = sequence.pad_sequences(x_test, maxlen=80) Here, sequence.pad_sequences convert the list of input data with shape, (data) into 2D NumPy array of shape (data, timesteps). Basically, it adds timesteps concept into the given data. It generates the timesteps of length, maxlen. Let us create the actual model. model = Sequential() model.add(Embedding(2000, 128)) model.add(LSTM(128, dropout = 0.2, recurrent_dropout = 0.2)) model.add(Dense(1, activation = 'sigmoid')) Here, We have used Embedding layer as input layer and then added the LSTM layer. Finally, a Dense layer is used as output layer. Let us compile the model using selected loss function, optimizer and metrics. model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) LLet us train the model using fit() method. model.fit( x_train, y_train, batch_size = 32, epochs = 15, validation_data = (x_test, y_test) ) Executing the application will output the below information − Epoch 1/15 2019-09-24 01:19:01.151247: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not co mpiled to use: AVX2 25000/25000 [==============================] - 101s 4ms/step - loss: 0.4707 - acc: 0.7716 - val_loss: 0.3769 - val_acc: 0.8349 Epoch 2/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.3058 - acc: 0.8756 - val_loss: 0.3763 - val_acc: 0.8350 Epoch 3/15 25000/25000 [==============================] - 91s 4ms/step - loss: 0.2100 - acc: 0.9178 - val_loss: 0.5065 - val_acc: 0.8110 Epoch 4/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.1394 - acc: 0.9495 - val_loss: 0.6046 - val_acc: 0.8146 Epoch 5/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0973 - acc: 0.9652 - val_loss: 0.5969 - val_acc: 0.8147 Epoch 6/15 25000/25000 [==============================] - 98s 4ms/step - loss: 0.0759 - acc: 0.9730 - val_loss: 0.6368 - val_acc: 0.8208 Epoch 7/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0578 - acc: 0.9811 - val_loss: 0.6657 - val_acc: 0.8184 Epoch 8/15 25000/25000 [==============================] - 97s 4ms/step - loss: 0.0448 - acc: 0.9850 - val_loss: 0.7452 - val_acc: 0.8136 Epoch 9/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0324 - acc: 0.9894 - val_loss: 0.7616 - val_acc: 0.8162Epoch 10/15 25000/25000 [==============================] - 100s 4ms/step - loss: 0.0247 - acc: 0.9922 - val_loss: 0.9654 - val_acc: 0.8148 Epoch 11/15 25000/25000 [==============================] - 99s 4ms/step - loss: 0.0169 - acc: 0.9946 - val_loss: 1.0013 - val_acc: 0.8104 Epoch 12/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0154 - acc: 0.9948 - val_loss: 1.0316 - val_acc: 0.8100 Epoch 13/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0113 - acc: 0.9963 - val_loss: 1.1138 - val_acc: 0.8108 Epoch 14/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0106 - acc: 0.9971 - val_loss: 1.0538 - val_acc: 0.8102 Epoch 15/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0090 - acc: 0.9972 - val_loss: 1.1453 - val_acc: 0.8129 25000/25000 [==============================] - 10s 390us/step Let us evaluate the model using test data. score, acc = model.evaluate(x_test, y_test, batch_size = 32) print('Test score:', score) print('Test accuracy:', acc) Executing the above code will output the below information − Test score: 1.145306069601178 Test accuracy: 0.81292 Keras applications module is used to provide pre-trained model for deep neural networks. Keras models are used for prediction, feature extraction and fine tuning. This chapter explains about Keras applications in detail. Trained model consists of two parts model Architecture and model Weights. Model weights are large file so we have to download and extract the feature from ImageNet database. Some of the popular pre-trained models are listed below, ResNet VGG16 MobileNet InceptionResNetV2 InceptionV3 Keras pre-trained models can be easily loaded as specified below − import keras import numpy as np from keras.applications import vgg16, inception_v3, resnet50, mobilenet #Load the VGG model vgg_model = vgg16.VGG16(weights = 'imagenet') #Load the Inception_V3 model inception_model = inception_v3.InceptionV3(weights = 'imagenet') #Load the ResNet50 model resnet_model = resnet50.ResNet50(weights = 'imagenet') #Load the MobileNet model mobilenet_model = mobilenet.MobileNet(weights = 'imagenet') Once the model is loaded, we can immediately use it for prediction purpose. Let us check each pre-trained model in the upcoming chapters. ResNet is a pre-trained model. It is trained using ImageNet. ResNet model weights pre-trained on ImageNet. It has the following syntax − keras.applications.resnet.ResNet50 ( include_top = True, weights = 'imagenet', input_tensor = None, input_shape = None, pooling = None, classes = 1000 ) Here, include_top refers the fully-connected layer at the top of the network. include_top refers the fully-connected layer at the top of the network. weights refer pre-training on ImageNet. weights refer pre-training on ImageNet. input_tensor refers optional Keras tensor to use as image input for the model. input_tensor refers optional Keras tensor to use as image input for the model. input_shape refers optional shape tuple. The default input size for this model is 224x224. input_shape refers optional shape tuple. The default input size for this model is 224x224. classes refer optional number of classes to classify images. classes refer optional number of classes to classify images. Let us understand the model by writing a simple example − Let us load the necessary modules as specified below − >>> import PIL >>> from keras.preprocessing.image import load_img >>> from keras.preprocessing.image import img_to_array >>> from keras.applications.imagenet_utils import decode_predictions >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from keras.applications.resnet50 import ResNet50 >>> from keras.applications import resnet50 Let us choose an input image, Lotus as specified below − >>> filename = 'banana.jpg' >>> ## load an image in PIL format >>> original = load_img(filename, target_size = (224, 224)) >>> print('PIL image size',original.size) PIL image size (224, 224) >>> plt.imshow(original) <matplotlib.image.AxesImage object at 0x1304756d8> >>> plt.show() Here, we have loaded an image (banana.jpg) and displayed it. Let us convert our input, Banana into NumPy array, so that it can be passed into the model for the purpose of prediction. >>> #convert the PIL image to a numpy array >>> numpy_image = img_to_array(original) >>> plt.imshow(np.uint8(numpy_image)) <matplotlib.image.AxesImage object at 0x130475ac8> >>> print('numpy array size',numpy_image.shape) numpy array size (224, 224, 3) >>> # Convert the image / images into batch format >>> image_batch = np.expand_dims(numpy_image, axis = 0) >>> print('image batch size', image_batch.shape) image batch size (1, 224, 224, 3) >>> Let us feed our input into the model to get the predictions >>> prepare the image for the resnet50 model >>> >>> processed_image = resnet50.preprocess_input(image_batch.copy()) >>> # create resnet model >>>resnet_model = resnet50.ResNet50(weights = 'imagenet') >>> Downloavding data from https://github.com/fchollet/deep-learning-models/releas es/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5 102858752/102853048 [==============================] - 33s 0us/step >>> # get the predicted probabilities for each class >>> predictions = resnet_model.predict(processed_image) >>> # convert the probabilities to class labels >>> label = decode_predictions(predictions) Downloading data from https://storage.googleapis.com/download.tensorflow.org/ data/imagenet_class_index.json 40960/35363 [==================================] - 0s 0us/step >>> print(label) [ [ ('n07753592', 'banana', 0.99229723), ('n03532672', 'hook', 0.0014551596), ('n03970156', 'plunger', 0.0010738898), ('n07753113', 'fig', 0.0009359837) , ('n03109150', 'corkscrew', 0.00028538404) ] ] Here, the model predicted the images as banana correctly. In this chapter, we will learn about the pre-trained models in Keras. Let us begin with VGG16. VGG16 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows − keras.applications.vgg16.VGG16( include_top = True, weights = 'imagenet', input_tensor = None, input_shape = None, pooling = None, classes = 1000 ) The default input size for this model is 224x224. MobileNetV2 is another pre-trained model. It is also trained uing ImageNet. The syntax to load the model is as follows − keras.applications.mobilenet_v2.MobileNetV2 ( input_shape = None, alpha = 1.0, include_top = True, weights = 'imagenet', input_tensor = None, pooling = None, classes = 1000 ) Here, alpha controls the width of the network. If the value is below 1, decreases the number of filters in each layer. If the value is above 1, increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer. The default input size for this model is 224x224. InceptionResNetV2 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows − keras.applications.inception_resnet_v2.InceptionResNetV2 ( include_top = True, weights = 'imagenet', input_tensor = None, input_shape = None, pooling = None, classes = 1000) This model and can be built both with ‘channels_first’ data format (channels, height, width) or ‘channels_last’ data format (height, width, channels). The default input size for this model is 299x299. InceptionV3 is another pre-trained model. It is also trained uing ImageNet. The syntax to load the model is as follows − keras.applications.inception_v3.InceptionV3 ( include_top = True, weights = 'imagenet', input_tensor = None, input_shape = None, pooling = None, classes = 1000 ) Here, The default input size for this model is 299x299. Keras is very simple, extensible and easy to implement neural network API, which can be used to build deep learning applications with high level abstraction. Keras is an optimal choice for deep leaning models. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2729, "s": 2051, "text": "Deep learning is one of the major subfield of machine learning framework. Machine learning is the study of design of algorithms, inspired from the model of human brain. Deep learning is becoming more popular in data science fields like robotics, artificial intelligence(AI), audio & video recognition and image recognition. Artificial neural network is the core of deep learning methodologies. Deep learning is supported by various libraries such as Theano, TensorFlow, Caffe, Mxnet etc., Keras is one of the most powerful and easy to use python library, which is built on top of popular deep learning libraries like TensorFlow, Theano, etc., for creating deep learning models." }, { "code": null, "e": 3340, "s": 2729, "text": "Keras runs on top of open source machine libraries like TensorFlow, Theano or Cognitive Toolkit (CNTK). Theano is a python library used for fast numerical computation tasks. TensorFlow is the most famous symbolic math library used for creating neural networks and deep learning models. TensorFlow is very flexible and the primary benefit is distributed computing. CNTK is deep learning framework developed by Microsoft. It uses libraries such as Python, C#, C++ or standalone machine learning toolkits. Theano and TensorFlow are very powerful libraries but difficult to understand for creating neural networks." }, { "code": null, "e": 3596, "s": 3340, "text": "Keras is based on minimal structure that provides a clean and easy way to create deep learning models based on TensorFlow or Theano. Keras is designed to quickly define deep learning models. Well, Keras is an optimal choice for deep learning applications." }, { "code": null, "e": 3747, "s": 3596, "text": "Keras leverages various optimization techniques to make high level neural network API easier and more performant. It supports the following features −" }, { "code": null, "e": 3786, "s": 3747, "text": "Consistent, simple and extensible API." }, { "code": null, "e": 3825, "s": 3786, "text": "Consistent, simple and extensible API." }, { "code": null, "e": 3892, "s": 3825, "text": "Minimal structure - easy to achieve the result without any frills." }, { "code": null, "e": 3959, "s": 3892, "text": "Minimal structure - easy to achieve the result without any frills." }, { "code": null, "e": 4004, "s": 3959, "text": "It supports multiple platforms and backends." }, { "code": null, "e": 4049, "s": 4004, "text": "It supports multiple platforms and backends." }, { "code": null, "e": 4111, "s": 4049, "text": "It is user friendly framework which runs on both CPU and GPU." }, { "code": null, "e": 4173, "s": 4111, "text": "It is user friendly framework which runs on both CPU and GPU." }, { "code": null, "e": 4208, "s": 4173, "text": "Highly scalability of computation." }, { "code": null, "e": 4243, "s": 4208, "text": "Highly scalability of computation." }, { "code": null, "e": 4335, "s": 4243, "text": "Keras is highly powerful and dynamic framework and comes up with the following advantages −" }, { "code": null, "e": 4361, "s": 4335, "text": "Larger community support." }, { "code": null, "e": 4387, "s": 4361, "text": "Larger community support." }, { "code": null, "e": 4401, "s": 4387, "text": "Easy to test." }, { "code": null, "e": 4415, "s": 4401, "text": "Easy to test." }, { "code": null, "e": 4487, "s": 4415, "text": "Keras neural networks are written in Python which makes things simpler." }, { "code": null, "e": 4559, "s": 4487, "text": "Keras neural networks are written in Python which makes things simpler." }, { "code": null, "e": 4615, "s": 4559, "text": "Keras supports both convolution and recurrent networks." }, { "code": null, "e": 4671, "s": 4615, "text": "Keras supports both convolution and recurrent networks." }, { "code": null, "e": 4758, "s": 4671, "text": "Deep learning models are discrete components, so that, you can combine into many ways." }, { "code": null, "e": 4845, "s": 4758, "text": "Deep learning models are discrete components, so that, you can combine into many ways." }, { "code": null, "e": 4993, "s": 4845, "text": "This chapter explains about how to install Keras on your machine. Before moving to installation, let us go through the basic requirements of Keras." }, { "code": null, "e": 5039, "s": 4993, "text": "You must satisfy the following requirements −" }, { "code": null, "e": 5078, "s": 5039, "text": "Any kind of OS (Windows, Linux or Mac)" }, { "code": null, "e": 5108, "s": 5078, "text": "Python version 3.5 or higher." }, { "code": null, "e": 5343, "s": 5108, "text": "Keras is python based neural network library so python must be installed on your machine. If python is properly installed on your machine, then open your terminal and type python, you could see the response similar as specified below," }, { "code": null, "e": 5515, "s": 5343, "text": "Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) \n[MSC v.1900 64 bit (AMD64)] on win32 \nType \"help\", \"copyright\", \"credits\" or \"license\" for more information. \n>>>\n" }, { "code": null, "e": 5729, "s": 5515, "text": "As of now the latest version is ‘3.7.2’. If Python is not installed, then visit the official python link - www.python.org and download the latest version based on your OS and install it immediately on your system." }, { "code": null, "e": 5824, "s": 5729, "text": "Keras installation is quite easy. Follow below steps to properly install Keras on your system." }, { "code": null, "e": 6078, "s": 5824, "text": "Virtualenv is used to manage Python packages for different projects. This will be helpful to avoid breaking the packages installed in the other environments. So, it is always recommended to use a virtual environment while developing Python applications." }, { "code": null, "e": 6091, "s": 6078, "text": "Linux/Mac OS" }, { "code": null, "e": 6206, "s": 6091, "text": "Linux or mac OS users, go to your project root directory and type the below command to create virtual environment," }, { "code": null, "e": 6232, "s": 6206, "text": "python3 -m venv kerasenv\n" }, { "code": null, "e": 6363, "s": 6232, "text": "After executing the above command, “kerasenv” directory is created with bin,lib and include folders in your installation location." }, { "code": null, "e": 6371, "s": 6363, "text": "Windows" }, { "code": null, "e": 6411, "s": 6371, "text": "Windows user can use the below command," }, { "code": null, "e": 6429, "s": 6411, "text": "py -m venv keras\n" }, { "code": null, "e": 6501, "s": 6429, "text": "This step will configure python and pip executables in your shell path." }, { "code": null, "e": 6514, "s": 6501, "text": "Linux/Mac OS" }, { "code": null, "e": 6622, "s": 6514, "text": "Now we have created a virtual environment named “kerasvenv”. Move to the folder and type the below command," }, { "code": null, "e": 6670, "s": 6622, "text": "$ cd kerasvenv kerasvenv $ source bin/activate\n" }, { "code": null, "e": 6678, "s": 6670, "text": "Windows" }, { "code": null, "e": 6754, "s": 6678, "text": "Windows users move inside the “kerasenv” folder and type the below command," }, { "code": null, "e": 6778, "s": 6754, "text": ".\\env\\Scripts\\activate\n" }, { "code": null, "e": 6827, "s": 6778, "text": "Keras depends on the following python libraries." }, { "code": null, "e": 6833, "s": 6827, "text": "Numpy" }, { "code": null, "e": 6840, "s": 6833, "text": "Pandas" }, { "code": null, "e": 6853, "s": 6840, "text": "Scikit-learn" }, { "code": null, "e": 6864, "s": 6853, "text": "Matplotlib" }, { "code": null, "e": 6870, "s": 6864, "text": "Scipy" }, { "code": null, "e": 6878, "s": 6870, "text": "Seaborn" }, { "code": null, "e": 7036, "s": 6878, "text": "Hopefully, you have installed all the above libraries on your system. If these libraries are not installed, then use the below command to install one by one." }, { "code": null, "e": 7042, "s": 7036, "text": "numpy" }, { "code": null, "e": 7061, "s": 7042, "text": "pip install numpy\n" }, { "code": null, "e": 7099, "s": 7061, "text": "you could see the following response," }, { "code": null, "e": 7439, "s": 7099, "text": "Collecting numpy \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \n numpy-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 7446, "s": 7439, "text": "pandas" }, { "code": null, "e": 7466, "s": 7446, "text": "pip install pandas\n" }, { "code": null, "e": 7503, "s": 7466, "text": "We could see the following response," }, { "code": null, "e": 7842, "s": 7503, "text": "Collecting pandas \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \npandas-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 7853, "s": 7842, "text": "matplotlib" }, { "code": null, "e": 7877, "s": 7853, "text": "pip install matplotlib\n" }, { "code": null, "e": 7914, "s": 7877, "text": "We could see the following response," }, { "code": null, "e": 8261, "s": 7914, "text": "Collecting matplotlib \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8/ \nmatplotlib-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 8267, "s": 8261, "text": "scipy" }, { "code": null, "e": 8286, "s": 8267, "text": "pip install scipy\n" }, { "code": null, "e": 8323, "s": 8286, "text": "We could see the following response," }, { "code": null, "e": 8660, "s": 8323, "text": "Collecting scipy \n Downloading \nhttps://files.pythonhosted.org/packages/cf/a4/d5387a74204542a60ad1baa84cd2d3353c330e59be8cf2d47c0b11d3cde8 \n/scipy-3.1.1-cp36-cp36m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64. \n macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) \n |████████████████████████████████| 14.4MB 2.8MB/s\n" }, { "code": null, "e": 8673, "s": 8660, "text": "scikit-learn" }, { "code": null, "e": 8852, "s": 8673, "text": "It is an open source machine learning library. It is used for classification, regression and clustering algorithms. Before moving to the installation, it requires the following −" }, { "code": null, "e": 8881, "s": 8852, "text": "Python version 3.5 or higher" }, { "code": null, "e": 8912, "s": 8881, "text": "NumPy version 1.11.0 or higher" }, { "code": null, "e": 8943, "s": 8912, "text": "SciPy version 0.17.0 or higher" }, { "code": null, "e": 8966, "s": 8943, "text": "joblib 0.11 or higher." }, { "code": null, "e": 9021, "s": 8966, "text": "Now, we install scikit-learn using the below command −" }, { "code": null, "e": 9050, "s": 9021, "text": "pip install -U scikit-learn\n" }, { "code": null, "e": 9058, "s": 9050, "text": "Seaborn" }, { "code": null, "e": 9170, "s": 9058, "text": "Seaborn is an amazing library that allows you to easily visualize your data. Use the below command to install −" }, { "code": null, "e": 9191, "s": 9170, "text": "pip install seaborn\n" }, { "code": null, "e": 9246, "s": 9191, "text": "You could see the message similar as specified below −" }, { "code": null, "e": 10607, "s": 9246, "text": "Collecting seaborn \n Downloading \nhttps://files.pythonhosted.org/packages/a8/76/220ba4420459d9c4c9c9587c6ce607bf56c25b3d3d2de62056efe482dadc \n/seaborn-0.9.0-py3-none-any.whl (208kB) 100% \n |████████████████████████████████| 215kB 4.0MB/s \nRequirement already satisfied: numpy> = 1.9.3 in \n./lib/python3.7/site-packages (from seaborn) (1.17.0) \nCollecting pandas> = 0.15.2 (from seaborn) \n Downloading \nhttps://files.pythonhosted.org/packages/39/b7/441375a152f3f9929ff8bc2915218ff1a063a59d7137ae0546db616749f9/ \npandas-0.25.0-cp37-cp37m-macosx_10_9_x86_64.\nmacosx_10_10_x86_64.whl (10.1MB) 100% \n |████████████████████████████████| 10.1MB 1.8MB/s \nRequirement already satisfied: scipy>=0.14.0 in \n./lib/python3.7/site-packages (from seaborn) (1.3.0) \nCollecting matplotlib> = 1.4.3 (from seaborn) \n Downloading \nhttps://files.pythonhosted.org/packages/c3/8b/af9e0984f\n5c0df06d3fab0bf396eb09cbf05f8452de4e9502b182f59c33b/ \nmatplotlib-3.1.1-cp37-cp37m-macosx_10_6_intel.\nmacosx_10_9_intel.macosx_10_9_x86_64 \n.macosx_10_10_intel.macosx_10_10_x86_64.whl (14.4MB) 100% \n |████████████████████████████████| 14.4MB 1.4MB/s \n...................................... \n...................................... \nSuccessfully installed cycler-0.10.0 kiwisolver-1.1.0 \nmatplotlib-3.1.1 pandas-0.25.0 pyparsing-2.4.2 \npython-dateutil-2.8.0 pytz-2019.2 seaborn-0.9.0\n" }, { "code": null, "e": 10749, "s": 10607, "text": "As of now, we have completed basic requirements for the installtion of Kera. Now, install the Keras using same procedure as specified below −" }, { "code": null, "e": 10768, "s": 10749, "text": "pip install keras\n" }, { "code": null, "e": 10878, "s": 10768, "text": "After finishing all your changes in your project, then simply run the below command to quit the environment −" }, { "code": null, "e": 10890, "s": 10878, "text": "deactivate\n" }, { "code": null, "e": 11085, "s": 10890, "text": "We believe that you have installed anaconda cloud on your machine. If anaconda is not installed, then visit the official link, www.anaconda.com/distribution and choose download based on your OS." }, { "code": null, "e": 11277, "s": 11085, "text": "Launch anaconda prompt, this will open base Anaconda environment. Let us create a new conda environment. This process is similar to virtualenv. Type the below command in your conda terminal −" }, { "code": null, "e": 11308, "s": 11277, "text": "conda create --name PythonCPU\n" }, { "code": null, "e": 11418, "s": 11308, "text": "If you want, you can create and install modules using GPU also. In this tutorial, we follow CPU instructions." }, { "code": null, "e": 11471, "s": 11418, "text": "To activate the environment, use the below command −" }, { "code": null, "e": 11491, "s": 11471, "text": "activate PythonCPU\n" }, { "code": null, "e": 11618, "s": 11491, "text": "Spyder is an IDE for executing python applications. Let us install this IDE in our conda environment using the below command −" }, { "code": null, "e": 11640, "s": 11618, "text": "conda install spyder\n" }, { "code": null, "e": 11782, "s": 11640, "text": "We have already known the python libraries numpy, pandas, etc., needed for keras. You can install all the modules by using the below syntax −" }, { "code": null, "e": 11789, "s": 11782, "text": "Syntax" }, { "code": null, "e": 11830, "s": 11789, "text": "conda install -c anaconda <module-name>\n" }, { "code": null, "e": 11872, "s": 11830, "text": "For example, you want to install pandas −" }, { "code": null, "e": 11906, "s": 11872, "text": "conda install -c anaconda pandas\n" }, { "code": null, "e": 11978, "s": 11906, "text": "Like the same method, try it yourself to install the remaining modules." }, { "code": null, "e": 12067, "s": 11978, "text": "Now, everything looks good so you can start keras installation using the below command −" }, { "code": null, "e": 12100, "s": 12067, "text": "conda install -c anaconda keras\n" }, { "code": null, "e": 12172, "s": 12100, "text": "Finally, launch spyder in your conda terminal using the below command −" }, { "code": null, "e": 12180, "s": 12172, "text": "spyder\n" }, { "code": null, "e": 12346, "s": 12180, "text": "To ensure everything was installed correctly, import all the modules, it will add everything and if anything went wrong, you will get module not found error message." }, { "code": null, "e": 12481, "s": 12346, "text": "This chapter explains Keras backend implementations TensorFlow and Theano in detail. Let us go through each implementation one by one." }, { "code": null, "e": 12712, "s": 12481, "text": "TensorFlow is an open source machine learning library used for numerical computational tasks developed by Google. Keras is a high level API built on top of TensorFlow or Theano. We know already how to install TensorFlow using pip." }, { "code": null, "e": 12778, "s": 12712, "text": "If it is not installed, you can install using the below command −" }, { "code": null, "e": 12802, "s": 12778, "text": "pip install TensorFlow\n" }, { "code": null, "e": 12931, "s": 12802, "text": "Once we execute keras, we could see the configuration file is located at your home directory inside and go to .keras/keras.json." }, { "code": null, "e": 13046, "s": 12931, "text": "{ \n \"image_data_format\": \"channels_last\", \n \"epsilon\": 1e-07, \"floatx\": \"float32\", \"backend\": \"tensorflow\" \n}\n" }, { "code": null, "e": 13052, "s": 13046, "text": "Here," }, { "code": null, "e": 13097, "s": 13052, "text": "image_data_format represent the data format." }, { "code": null, "e": 13142, "s": 13097, "text": "image_data_format represent the data format." }, { "code": null, "e": 13219, "s": 13142, "text": "epsilon represents numeric constant. It is used to avoid DivideByZero error." }, { "code": null, "e": 13296, "s": 13219, "text": "epsilon represents numeric constant. It is used to avoid DivideByZero error." }, { "code": null, "e": 13416, "s": 13296, "text": "floatx represent the default data type float32. You can also change it to float16 or float64 using set_floatx() method." }, { "code": null, "e": 13536, "s": 13416, "text": "floatx represent the default data type float32. You can also change it to float16 or float64 using set_floatx() method." }, { "code": null, "e": 13581, "s": 13536, "text": "image_data_format represent the data format." }, { "code": null, "e": 13626, "s": 13581, "text": "image_data_format represent the data format." }, { "code": null, "e": 13723, "s": 13626, "text": "Suppose, if the file is not created then move to the location and create using the below steps −" }, { "code": null, "e": 13767, "s": 13723, "text": "> cd home \n> mkdir .keras \n> vi keras.json\n" }, { "code": null, "e": 13948, "s": 13767, "text": "Remember, you should specify .keras as its folder name and add the above configuration inside keras.json file. We can perform some pre-defined operations to know backend functions." }, { "code": null, "e": 14109, "s": 13948, "text": "Theano is an open source deep learning library that allows you to evaluate multi-dimensional arrays effectively. We can easily install using the below command −" }, { "code": null, "e": 14129, "s": 14109, "text": "pip install theano\n" }, { "code": null, "e": 14320, "s": 14129, "text": "By default, keras uses TensorFlow backend. If you want to change backend configuration from TensorFlow to Theano, just change the backend = theano in keras.json file. It is described below −" }, { "code": null, "e": 14439, "s": 14320, "text": "{ \n \"image_data_format\": \"channels_last\", \n \"epsilon\": 1e-07, \n \"floatx\": \"float32\", \n \"backend\": \"theano\" \n}\n" }, { "code": null, "e": 14528, "s": 14439, "text": "Now save your file, restart your terminal and start keras, your backend will be changed." }, { "code": null, "e": 14574, "s": 14528, "text": ">>> import keras as k \nusing theano backend.\n" }, { "code": null, "e": 14784, "s": 14574, "text": "Deep learning is an evolving subfield of machine learning. Deep learning involves analyzing the input in layer by layer manner, where each layer progressively extracts higher level information about the input." }, { "code": null, "e": 15288, "s": 14784, "text": "Let us take a simple scenario of analyzing an image. Let us assume that your input image is divided up into a rectangular grid of pixels. Now, the first layer abstracts the pixels. The second layer understands the edges in the image. The Next layer constructs nodes from the edges. Then, the next would find branches from the nodes. Finally, the output layer will detect the full object. Here, the feature extraction process goes from the output of one layer into the input of the next subsequent layer." }, { "code": null, "e": 15543, "s": 15288, "text": "By using this approach, we can process huge amount of features, which makes deep learning a very powerful tool. Deep learning algorithms are also useful for the analysis of unstructured data. Let us go through the basics of deep learning in this chapter." }, { "code": null, "e": 15998, "s": 15543, "text": "The most popular and primary approach of deep learning is using “Artificial neural network” (ANN). They are inspired from the model of human brain, which is the most complex organ of our body. The human brain is made up of more than 90 billion tiny cells called “Neurons”. Neurons are inter-connected through nerve fiber called “axons” and “Dendrites”. The main role of axon is to transmit information from one neuron to another to which it is connected." }, { "code": null, "e": 16409, "s": 15998, "text": "Similarly, the main role of dendrites is to receive the information being transmitted by the axons of another neuron to which it is connected. Each neuron processes a small information and then passes the result to another neuron and this process continues. This is the basic method used by our human brain to process huge about of information like speech, visual, etc., and extract useful information from it." }, { "code": null, "e": 16971, "s": 16409, "text": "Based on this model, the first Artificial Neural Network (ANN) was invented by psychologist Frank Rosenblatt, in the year of 1958. ANNs are made up of multiple nodes which is similar to neurons. Nodes are tightly interconnected and organized into different hidden layers. The input layer receives the input data and the data goes through one or more hidden layers sequentially and finally the output layer predict something useful about the input data. For example, the input may be an image and the output may be the thing identified in the image, say a “Cat”." }, { "code": null, "e": 17047, "s": 16971, "text": "A single neuron (called as perceptron in ANN) can be represented as below −" }, { "code": null, "e": 17053, "s": 17047, "text": "Here," }, { "code": null, "e": 17108, "s": 17053, "text": "Multiple input along with weight represents dendrites." }, { "code": null, "e": 17163, "s": 17108, "text": "Multiple input along with weight represents dendrites." }, { "code": null, "e": 17369, "s": 17163, "text": "Sum of input along with activation function represents neurons. Sum actually means computed value of all inputs and activation function represent a function, which modify the Sum value into 0, 1 or 0 to 1." }, { "code": null, "e": 17575, "s": 17369, "text": "Sum of input along with activation function represents neurons. Sum actually means computed value of all inputs and activation function represent a function, which modify the Sum value into 0, 1 or 0 to 1." }, { "code": null, "e": 17661, "s": 17575, "text": "Actual output represent axon and the output will be received by neuron in next layer." }, { "code": null, "e": 17747, "s": 17661, "text": "Actual output represent axon and the output will be received by neuron in next layer." }, { "code": null, "e": 17828, "s": 17747, "text": "Let us understand different types of artificial neural networks in this section." }, { "code": null, "e": 18337, "s": 17828, "text": "Multi-Layer perceptron is the simplest form of ANN. It consists of a single input layer, one or more hidden layer and finally an output layer. A layer consists of a collection of perceptron. Input layer is basically one or more features of the input data. Every hidden layer consists of one or more neurons and process certain aspect of the feature and send the processed information into the next hidden layer. The output layer process receives the data from last hidden layer and finally output the result." }, { "code": null, "e": 18721, "s": 18337, "text": "Convolutional neural network is one of the most popular ANN. It is widely used in the fields of image and video recognition. It is based on the concept of convolution, a mathematical concept. It is almost similar to multi-layer perceptron except it contains series of convolution layer and pooling layer before the fully connected hidden neuron layer. It has three important layers −" }, { "code": null, "e": 18837, "s": 18721, "text": "Convolution layer − It is the primary building block and perform computational tasks based on convolution function." }, { "code": null, "e": 18953, "s": 18837, "text": "Convolution layer − It is the primary building block and perform computational tasks based on convolution function." }, { "code": null, "e": 19127, "s": 18953, "text": "Pooling layer − It is arranged next to convolution layer and is used to reduce the size of inputs by removing unnecessary information so computation can be performed faster." }, { "code": null, "e": 19301, "s": 19127, "text": "Pooling layer − It is arranged next to convolution layer and is used to reduce the size of inputs by removing unnecessary information so computation can be performed faster." }, { "code": null, "e": 19435, "s": 19301, "text": "Fully connected layer − It is arranged to next to series of convolution and pooling layer and classify input into various categories." }, { "code": null, "e": 19569, "s": 19435, "text": "Fully connected layer − It is arranged to next to series of convolution and pooling layer and classify input into various categories." }, { "code": null, "e": 19612, "s": 19569, "text": "A simple CNN can be represented as below −" }, { "code": null, "e": 19618, "s": 19612, "text": "Here," }, { "code": null, "e": 19720, "s": 19618, "text": "2 series of Convolution and pooling layer is used and it receives and process the input (e.g. image)." }, { "code": null, "e": 19822, "s": 19720, "text": "2 series of Convolution and pooling layer is used and it receives and process the input (e.g. image)." }, { "code": null, "e": 19926, "s": 19822, "text": "A single fully connected layer is used and it is used to output the data (e.g. classification of image)" }, { "code": null, "e": 20030, "s": 19926, "text": "A single fully connected layer is used and it is used to output the data (e.g. classification of image)" }, { "code": null, "e": 20362, "s": 20030, "text": "Recurrent Neural Networks (RNN) are useful to address the flaw in other ANN models. Well, Most of the ANN doesn’t remember the steps from previous situations and learned to make decisions based on context in training. Meanwhile, RNN stores the past information and all its decisions are taken from what it has learnt from the past." }, { "code": null, "e": 20786, "s": 20362, "text": "This approach is mainly useful in image classification. Sometimes, we may need to look into the future to fix the past. In this case bidirectional RNN is helpful to learn from the past and predict the future. For example, we have handwritten samples in multiple inputs. Suppose, we have confusion in one input then we need to check again other inputs to recognize the correct context which takes the decision from the past." }, { "code": null, "e": 20913, "s": 20786, "text": "Let us first understand the different phases of deep learning and then, learn how Keras helps in the process of deep learning." }, { "code": null, "e": 21044, "s": 20913, "text": "Deep learning requires lot of input data to successfully learn and predict the result. So, first collect as much data as possible." }, { "code": null, "e": 21193, "s": 21044, "text": "Analyze the data and acquire a good understanding of the data. The better understanding of the data is required to select the correct ANN algorithm." }, { "code": null, "e": 21494, "s": 21193, "text": "Choose an algorithm, which will best fit for the type of learning process (e.g image classification, text processing, etc.,) and the available input data. Algorithm is represented by Model in Keras. Algorithm includes one or more layers. Each layers in ANN can be represented by Keras Layer in Keras." }, { "code": null, "e": 21581, "s": 21494, "text": "Prepare data − Process, filter and select only the required information from the data." }, { "code": null, "e": 21668, "s": 21581, "text": "Prepare data − Process, filter and select only the required information from the data." }, { "code": null, "e": 21888, "s": 21668, "text": "Split data − Split the data into training and test data set. Test data will be used to evaluate the prediction of the algorithm / Model (once the machine learn) and to cross check the efficiency of the learning process." }, { "code": null, "e": 22108, "s": 21888, "text": "Split data − Split the data into training and test data set. Test data will be used to evaluate the prediction of the algorithm / Model (once the machine learn) and to cross check the efficiency of the learning process." }, { "code": null, "e": 22464, "s": 22108, "text": "Compile the model − Compile the algorithm / model, so that, it can be used further to learn by training and finally do to prediction. This step requires us to choose loss function and Optimizer. loss function and Optimizer are used in learning phase to find the error (deviation from actual output) and do optimization so that the error will be minimized." }, { "code": null, "e": 22820, "s": 22464, "text": "Compile the model − Compile the algorithm / model, so that, it can be used further to learn by training and finally do to prediction. This step requires us to choose loss function and Optimizer. loss function and Optimizer are used in learning phase to find the error (deviation from actual output) and do optimization so that the error will be minimized." }, { "code": null, "e": 22920, "s": 22820, "text": "Fit the model − The actual learning process will be done in this phase using the training data set." }, { "code": null, "e": 23020, "s": 22920, "text": "Fit the model − The actual learning process will be done in this phase using the training data set." }, { "code": null, "e": 23146, "s": 23020, "text": "Predict result for unknown value − Predict the output for the unknown input data (other than existing training and test data)" }, { "code": null, "e": 23272, "s": 23146, "text": "Predict result for unknown value − Predict the output for the unknown input data (other than existing training and test data)" }, { "code": null, "e": 23419, "s": 23272, "text": "Evaluate model − Evaluate the model by predicting the output for test data and cross-comparing the prediction with actual result of the test data." }, { "code": null, "e": 23566, "s": 23419, "text": "Evaluate model − Evaluate the model by predicting the output for test data and cross-comparing the prediction with actual result of the test data." }, { "code": null, "e": 23894, "s": 23566, "text": "Freeze, Modify or choose new algorithm − Check whether the evaluation of the model is successful. If yes, save the algorithm for future prediction purpose. If not, then modify or choose new algorithm / model and finally, again train, predict and evaluate the model. Repeat the process until the best algorithm (model) is found." }, { "code": null, "e": 24222, "s": 23894, "text": "Freeze, Modify or choose new algorithm − Check whether the evaluation of the model is successful. If yes, save the algorithm for future prediction purpose. If not, then modify or choose new algorithm / model and finally, again train, predict and evaluate the model. Repeat the process until the best algorithm (model) is found." }, { "code": null, "e": 24282, "s": 24222, "text": "The above steps can be represented using below flow chart −" }, { "code": null, "e": 24598, "s": 24282, "text": "Keras provides a complete framework to create any type of neural networks. Keras is innovative as well as very easy to learn. It supports simple neural network to very large and complex neural network model. Let us understand the architecture of Keras framework and how Keras helps in deep learning in this chapter." }, { "code": null, "e": 24652, "s": 24598, "text": "Keras API can be divided into three main categories −" }, { "code": null, "e": 24658, "s": 24652, "text": "Model" }, { "code": null, "e": 24664, "s": 24658, "text": "Layer" }, { "code": null, "e": 24677, "s": 24664, "text": "Core Modules" }, { "code": null, "e": 25148, "s": 24677, "text": "In Keras, every ANN is represented by Keras Models. In turn, every Keras Model is composition of Keras Layers and represents ANN layers like input, hidden layer, output layers, convolution layer, pooling layer, etc., Keras model and layer access Keras modules for activation function, loss function, regularization function, etc., Using Keras model, Keras Layer, and Keras modules, any ANN algorithm (CNN, RNN, etc.,) can be represented in a simple and efficient manner." }, { "code": null, "e": 25235, "s": 25148, "text": "The following diagram depicts the relationship between model, layer and core modules −" }, { "code": null, "e": 25308, "s": 25235, "text": "Let us see the overview of Keras models, Keras layers and Keras modules." }, { "code": null, "e": 25359, "s": 25308, "text": "Keras Models are of two types as mentioned below −" }, { "code": null, "e": 25558, "s": 25359, "text": "Sequential Model − Sequential model is basically a linear composition of Keras Layers. Sequential model is easy, minimal as well as has the ability to represent nearly all available neural networks." }, { "code": null, "e": 25600, "s": 25558, "text": "A simple sequential model is as follows −" }, { "code": null, "e": 25771, "s": 25600, "text": "from keras.models import Sequential \nfrom keras.layers import Dense, Activation \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,)))\n" }, { "code": null, "e": 25778, "s": 25771, "text": "Where," }, { "code": null, "e": 25828, "s": 25778, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 25878, "s": 25828, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 25927, "s": 25878, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 25976, "s": 25927, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 26034, "s": 25976, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 26092, "s": 26034, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 26187, "s": 26092, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 26282, "s": 26187, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 26421, "s": 26282, "text": "Sequential model exposes Model class to create customized models as well. We can use sub-classing concept to create our own complex model." }, { "code": null, "e": 26497, "s": 26421, "text": "Functional API − Functional API is basically used to create complex models." }, { "code": null, "e": 26812, "s": 26497, "text": "Each Keras layer in the Keras model represent the corresponding layer (input layer, hidden layer and output layer) in the actual proposed neural network model. Keras provides a lot of pre-build layers so that any complex neural network can be easily created. Some of the important Keras layers are specified below," }, { "code": null, "e": 26824, "s": 26812, "text": "Core Layers" }, { "code": null, "e": 26843, "s": 26824, "text": "Convolution Layers" }, { "code": null, "e": 26858, "s": 26843, "text": "Pooling Layers" }, { "code": null, "e": 26875, "s": 26858, "text": "Recurrent Layers" }, { "code": null, "e": 26971, "s": 26875, "text": "A simple python code to represent a neural network model using sequential model is as follows −" }, { "code": null, "e": 27297, "s": 26971, "text": "from keras.models import Sequential \nfrom keras.layers import Dense, Activation, Dropout model = Sequential() \n\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) \nmodel.add(Dense(num_classes, activation = 'softmax'))\n" }, { "code": null, "e": 27304, "s": 27297, "text": "Where," }, { "code": null, "e": 27354, "s": 27304, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 27404, "s": 27354, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 27453, "s": 27404, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 27502, "s": 27453, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 27560, "s": 27502, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 27618, "s": 27560, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 27713, "s": 27618, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 27808, "s": 27713, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 27874, "s": 27808, "text": "Line 6 adds a dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 27940, "s": 27874, "text": "Line 6 adds a dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 28041, "s": 27940, "text": "Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 28142, "s": 28041, "text": "Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 28214, "s": 28142, "text": "Line 8 adds another dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 28286, "s": 28214, "text": "Line 8 adds another dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 28388, "s": 28286, "text": "Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function." }, { "code": null, "e": 28490, "s": 28388, "text": "Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function." }, { "code": null, "e": 28673, "s": 28490, "text": "Keras also provides options to create our own customized layers. Customized layer can be created by sub-classing the Keras.Layer class and it is similar to sub-classing Keras models." }, { "code": null, "e": 28835, "s": 28673, "text": "Keras also provides a lot of built-in neural network related functions to properly create the Keras model and Keras layers. Some of the function are as follows −" }, { "code": null, "e": 28990, "s": 28835, "text": "Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc.," }, { "code": null, "e": 29145, "s": 28990, "text": "Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc.," }, { "code": null, "e": 29256, "s": 29145, "text": "Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc.," }, { "code": null, "e": 29367, "s": 29256, "text": "Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc.," }, { "code": null, "e": 29453, "s": 29367, "text": "Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc.," }, { "code": null, "e": 29539, "s": 29453, "text": "Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc.," }, { "code": null, "e": 29635, "s": 29539, "text": "Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc.," }, { "code": null, "e": 29731, "s": 29635, "text": "Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc.," }, { "code": null, "e": 29793, "s": 29731, "text": "Let us learn Keras modules in detail in the upcoming chapter." }, { "code": null, "e": 29990, "s": 29793, "text": "As we learned earlier, Keras modules contains pre-defined classes, functions and variables which are useful for deep learning algorithm. Let us learn the modules provided by Keras in this chapter." }, { "code": null, "e": 30051, "s": 29990, "text": "Let us first see the list of modules available in the Keras." }, { "code": null, "e": 30208, "s": 30051, "text": "Initializers − Provides a list of initializers function. We can learn it in details in Keras layer chapter. during model creation phase of machine learning." }, { "code": null, "e": 30365, "s": 30208, "text": "Initializers − Provides a list of initializers function. We can learn it in details in Keras layer chapter. during model creation phase of machine learning." }, { "code": null, "e": 30474, "s": 30365, "text": "Regularizers − Provides a list of regularizers function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 30583, "s": 30474, "text": "Regularizers − Provides a list of regularizers function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 30690, "s": 30583, "text": "Constraints − Provides a list of constraints function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 30797, "s": 30690, "text": "Constraints − Provides a list of constraints function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 30902, "s": 30797, "text": "Activations − Provides a list of activator function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 31007, "s": 30902, "text": "Activations − Provides a list of activator function. We can learn it in details in Keras Layers chapter." }, { "code": null, "e": 31104, "s": 31007, "text": "Losses − Provides a list of loss function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31201, "s": 31104, "text": "Losses − Provides a list of loss function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31302, "s": 31201, "text": "Metrics − Provides a list of metrics function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31403, "s": 31302, "text": "Metrics − Provides a list of metrics function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31509, "s": 31403, "text": "Optimizers − Provides a list of optimizer function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31615, "s": 31509, "text": "Optimizers − Provides a list of optimizer function. We can learn it in details in Model Training chapter." }, { "code": null, "e": 31824, "s": 31615, "text": "Callback − Provides a list of callback function. We can use it during the training process to print the intermediate data as well as to stop the training itself (EarlyStopping method) based on some condition." }, { "code": null, "e": 32033, "s": 31824, "text": "Callback − Provides a list of callback function. We can use it during the training process to print the intermediate data as well as to stop the training itself (EarlyStopping method) based on some condition." }, { "code": null, "e": 32195, "s": 32033, "text": "Text processing − Provides functions to convert text into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 32357, "s": 32195, "text": "Text processing − Provides functions to convert text into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 32522, "s": 32357, "text": "Image processing − Provides functions to convert images into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 32687, "s": 32522, "text": "Image processing − Provides functions to convert images into NumPy array suitable for machine learning. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 32844, "s": 32687, "text": "Sequence processing − Provides functions to generate time based data from the given input data. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 33001, "s": 32844, "text": "Sequence processing − Provides functions to generate time based data from the given input data. We can use it in data preparation phase of machine learning." }, { "code": null, "e": 33080, "s": 33001, "text": "Backend − Provides function of the backend library like TensorFlow and Theano." }, { "code": null, "e": 33159, "s": 33080, "text": "Backend − Provides function of the backend library like TensorFlow and Theano." }, { "code": null, "e": 33229, "s": 33159, "text": "Utilities − Provides lot of utility function useful in deep learning." }, { "code": null, "e": 33299, "s": 33229, "text": "Utilities − Provides lot of utility function useful in deep learning." }, { "code": null, "e": 33358, "s": 33299, "text": "Let us see backend module and utils model in this chapter." }, { "code": null, "e": 33629, "s": 33358, "text": "backend module is used for keras backend operations. By default, keras runs on top of TensorFlow backend. If you want, you can switch to other backends like Theano or CNTK. Defualt backend configuration is defined inside your root directory under .keras/keras.json file." }, { "code": null, "e": 33683, "s": 33629, "text": "Keras backend module can be imported using below code" }, { "code": null, "e": 33719, "s": 33683, "text": ">>> from keras import backend as k\n" }, { "code": null, "e": 33845, "s": 33719, "text": "If we are using default backend TensorFlow, then the below function returns TensorFlow based information as specified below −" }, { "code": null, "e": 33967, "s": 33845, "text": ">>> k.backend() \n'tensorflow'\n>>> k.epsilon() \n1e-07\n>>> k.image_data_format() \n'channels_last'\n>>> k.floatx() \n'float32'" }, { "code": null, "e": 34061, "s": 33967, "text": "Let us understand some of the significant backend functions used for data analysis in brief −" }, { "code": null, "e": 34127, "s": 34061, "text": "It is the identifier for the default graph. It is defined below −" }, { "code": null, "e": 34184, "s": 34127, "text": ">>> k.get_uid(prefix='') \n1 \n>>> k.get_uid(prefix='') 2\n" }, { "code": null, "e": 34217, "s": 34184, "text": "It is used resets the uid value." }, { "code": null, "e": 34237, "s": 34217, "text": ">>> k.reset_uids()\n" }, { "code": null, "e": 34313, "s": 34237, "text": "Now, again execute the get_uid(). This will be reset and change again to 1." }, { "code": null, "e": 34342, "s": 34313, "text": ">>> k.get_uid(prefix='') \n1\n" }, { "code": null, "e": 34442, "s": 34342, "text": "It is used instantiates a placeholder tensor. Simple placeholder to hold 3-D shape is shown below −" }, { "code": null, "e": 34643, "s": 34442, "text": ">>> data = k.placeholder(shape = (1,3,3)) \n>>> data \n<tf.Tensor 'Placeholder_9:0' shape = (1, 3, 3) dtype = float32> \n\nIf you use int_shape(), it will show the shape. \n\n>>> k.int_shape(data) (1, 3, 3)" }, { "code": null, "e": 34824, "s": 34643, "text": "It is used to multiply two tensors. Consider a and b are two tensors and c will be the outcome of multiply of ab. Assume a shape is (4,2) and b shape is (2,3). It is defined below," }, { "code": null, "e": 34988, "s": 34824, "text": ">>> a = k.placeholder(shape = (4,2)) \n>>> b = k.placeholder(shape = (2,3)) \n>>> c = k.dot(a,b) \n>>> c \n<tf.Tensor 'MatMul_3:0' shape = (4, 3) dtype = float32> \n>>>" }, { "code": null, "e": 35031, "s": 34988, "text": "It is used to initialize all as one value." }, { "code": null, "e": 35146, "s": 35031, "text": ">>> res = k.ones(shape = (2,2)) \n\n#print the value \n\n>>> k.eval(res) \narray([[1., 1.], [1., 1.]], dtype = float32)" }, { "code": null, "e": 35261, "s": 35146, "text": "It is used to perform the product of two data in batches. Input dimension must be 2 or higher. It is shown below −" }, { "code": null, "e": 35450, "s": 35261, "text": ">>> a_batch = k.ones(shape = (2,3)) \n>>> b_batch = k.ones(shape = (3,2)) \n>>> c_batch = k.batch_dot(a_batch,b_batch) \n>>> c_batch \n<tf.Tensor 'ExpandDims:0' shape = (2, 1) dtype = float32>" }, { "code": null, "e": 35548, "s": 35450, "text": "It is used to initializes a variable. Let us perform simple transpose operation in this variable." }, { "code": null, "e": 35823, "s": 35548, "text": ">>> data = k.variable([[10,20,30,40],[50,60,70,80]]) \n#variable initialized here \n>>> result = k.transpose(data) \n>>> print(result) \nTensor(\"transpose_6:0\", shape = (4, 2), dtype = float32) \n>>> print(k.eval(result)) \n [[10. 50.] \n [20. 60.] \n [30. 70.] \n [40. 80.]]" }, { "code": null, "e": 35858, "s": 35823, "text": "If you want to access from numpy −" }, { "code": null, "e": 36109, "s": 35858, "text": ">>> data = np.array([[10,20,30,40],[50,60,70,80]]) \n\n>>> print(np.transpose(data)) \n [[10 50] \n [20 60] \n [30 70] \n [40 80]] \n\n>>> res = k.variable(value = data) \n>>> print(res) \n<tf.Variable 'Variable_7:0' shape = (2, 4) dtype = float32_ref>" }, { "code": null, "e": 36166, "s": 36109, "text": "It is used to check whether the tensor is sparse or not." }, { "code": null, "e": 36483, "s": 36166, "text": ">>> a = k.placeholder((2, 2), sparse=True) \n\n>>> print(a) SparseTensor(indices = \n Tensor(\"Placeholder_8:0\", \n shape = (?, 2), dtype = int64), \nvalues = Tensor(\"Placeholder_7:0\", shape = (?,), \ndtype = float32), dense_shape = Tensor(\"Const:0\", shape = (2,), dtype = int64)) \n\n>>> print(k.is_sparse(a)) True" }, { "code": null, "e": 36525, "s": 36483, "text": "It is used to converts sparse into dense." }, { "code": null, "e": 36653, "s": 36525, "text": ">>> b = k.to_dense(a) \n>>> print(b) Tensor(\"SparseToDense:0\", shape = (2, 2), dtype = float32) \n>>> print(k.is_sparse(b)) False" }, { "code": null, "e": 36714, "s": 36653, "text": "It is used to initialize using uniform distribution concept." }, { "code": null, "e": 36761, "s": 36714, "text": "k.random_uniform_variable(shape, mean, scale)\n" }, { "code": null, "e": 36767, "s": 36761, "text": "Here," }, { "code": null, "e": 36829, "s": 36767, "text": "shape − denotes the rows and columns in the format of tuples." }, { "code": null, "e": 36891, "s": 36829, "text": "shape − denotes the rows and columns in the format of tuples." }, { "code": null, "e": 36928, "s": 36891, "text": "mean − mean of uniform distribution." }, { "code": null, "e": 36965, "s": 36928, "text": "mean − mean of uniform distribution." }, { "code": null, "e": 37017, "s": 36965, "text": "scale − standard deviation of uniform distribution." }, { "code": null, "e": 37069, "s": 37017, "text": "scale − standard deviation of uniform distribution." }, { "code": null, "e": 37117, "s": 37069, "text": "Let us have a look at the below example usage −" }, { "code": null, "e": 37304, "s": 37117, "text": ">>> a = k.random_uniform_variable(shape = (2, 3), low=0, high = 1) \n>>> b = k. random_uniform_variable(shape = (3,2), low = 0, high = 1) \n>>> c = k.dot(a, b) \n>>> k.int_shape(c) \n(2, 2)\n" }, { "code": null, "e": 37429, "s": 37304, "text": "utils provides useful utilities function for deep learning. Some of the methods provided by the utils module is as follows −" }, { "code": null, "e": 37484, "s": 37429, "text": "It is used to represent the input data in HDF5 format." }, { "code": null, "e": 37559, "s": 37484, "text": "from keras.utils import HDF5Matrix data = HDF5Matrix('data.hdf5', 'data')\n" }, { "code": null, "e": 37620, "s": 37559, "text": "It is used to convert class vector into binary class matrix." }, { "code": null, "e": 38360, "s": 37620, "text": ">>> from keras.utils import to_categorical \n>>> labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] \n>>> to_categorical(labels) \narray([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], \n [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], \n [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], \n [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], \n [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], \n [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], \n [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], \n [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], \n [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], \n [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]], dtype = float32)\n>>> from keras.utils import normalize \n>>> normalize([1, 2, 3, 4, 5]) \narray([[0.13483997, 0.26967994, 0.40451992, 0.53935989, 0.67419986]])\n" }, { "code": null, "e": 38406, "s": 38360, "text": "It is used to print the summary of the model." }, { "code": null, "e": 38466, "s": 38406, "text": "from keras.utils import print_summary print_summary(model)\n" }, { "code": null, "e": 38547, "s": 38466, "text": "It is used to create the model representation in dot format and save it to file." }, { "code": null, "e": 38624, "s": 38547, "text": "from keras.utils import plot_model \nplot_model(model,to_file = 'image.png')\n" }, { "code": null, "e": 38703, "s": 38624, "text": "This plot_model will generate an image to understand the performance of model." }, { "code": null, "e": 39019, "s": 38703, "text": "As learned earlier, Keras layers are the primary building block of Keras models. Each layer receives input information, do some computation and finally output the transformed information. The output of one layer will flow into the next layer as its input. Let us learn complete details about layers in this chapter." }, { "code": null, "e": 39488, "s": 39019, "text": "A Keras layer requires shape of the input (input_shape) to understand the structure of the input data, initializer to set the weight for each input and finally activators to transform the output to make it non-linear. In between, constraints restricts and specify the range in which the weight of input data to be generated and regularizer will try to optimize the layer (and the model) by dynamically applying the penalties on the weights during optimization process." }, { "code": null, "e": 39573, "s": 39488, "text": "To summarise, Keras layer requires below minimum details to create a complete layer." }, { "code": null, "e": 39597, "s": 39573, "text": "Shape of the input data" }, { "code": null, "e": 39636, "s": 39597, "text": "Number of neurons / units in the layer" }, { "code": null, "e": 39649, "s": 39636, "text": "Initializers" }, { "code": null, "e": 39662, "s": 39649, "text": "Regularizers" }, { "code": null, "e": 39674, "s": 39662, "text": "Constraints" }, { "code": null, "e": 39686, "s": 39674, "text": "Activations" }, { "code": null, "e": 39897, "s": 39686, "text": "Let us understand the basic concept in the next chapter. Before understanding the basic concept, let us create a simple Keras layer using Sequential model API to get the idea of how Keras model and layer works." }, { "code": null, "e": 40319, "s": 39897, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \nfrom keras import regularizers \nfrom keras import constraints \n\nmodel = Sequential() \n\nmodel.add(Dense(32, input_shape=(16,), kernel_initializer = 'he_uniform', \n kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu')) \nmodel.add(Dense(16, activation = 'relu')) \nmodel.add(Dense(8))" }, { "code": null, "e": 40326, "s": 40319, "text": "where," }, { "code": null, "e": 40366, "s": 40326, "text": "Line 1-5 imports the necessary modules." }, { "code": null, "e": 40406, "s": 40366, "text": "Line 1-5 imports the necessary modules." }, { "code": null, "e": 40455, "s": 40406, "text": "Line 7 creates a new model using Sequential API." }, { "code": null, "e": 40504, "s": 40455, "text": "Line 7 creates a new model using Sequential API." }, { "code": null, "e": 41324, "s": 40504, "text": "Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional.\n\nFirst parameter represents the number of units (neurons).\ninput_shape represent the shape of input data.\nkernel_initializer represent initializer to be used. he_uniform function is set as value.\nkernel_regularizer represent regularizer to be used. None is set as value.\nkernel_constraint represent constraint to be used. MaxNorm function is set as value.\nactivation represent activation to be used. relu function is set as value.\n\n" }, { "code": null, "e": 41711, "s": 41324, "text": "Line 9 creates a new Dense layer and add it into the model. Dense is an entry level layer provided by Keras, which accepts the number of neurons or units (32) as its required parameter. If the layer is first layer, then we need to provide Input Shape, (16,) as well. Otherwise, the output of the previous layer will be used as input of the next layer. All other parameters are optional." }, { "code": null, "e": 41769, "s": 41711, "text": "First parameter represents the number of units (neurons)." }, { "code": null, "e": 41827, "s": 41769, "text": "First parameter represents the number of units (neurons)." }, { "code": null, "e": 41874, "s": 41827, "text": "input_shape represent the shape of input data." }, { "code": null, "e": 41921, "s": 41874, "text": "input_shape represent the shape of input data." }, { "code": null, "e": 42011, "s": 41921, "text": "kernel_initializer represent initializer to be used. he_uniform function is set as value." }, { "code": null, "e": 42101, "s": 42011, "text": "kernel_initializer represent initializer to be used. he_uniform function is set as value." }, { "code": null, "e": 42176, "s": 42101, "text": "kernel_regularizer represent regularizer to be used. None is set as value." }, { "code": null, "e": 42251, "s": 42176, "text": "kernel_regularizer represent regularizer to be used. None is set as value." }, { "code": null, "e": 42336, "s": 42251, "text": "kernel_constraint represent constraint to be used. MaxNorm function is set as value." }, { "code": null, "e": 42421, "s": 42336, "text": "kernel_constraint represent constraint to be used. MaxNorm function is set as value." }, { "code": null, "e": 42496, "s": 42421, "text": "activation represent activation to be used. relu function is set as value." }, { "code": null, "e": 42571, "s": 42496, "text": "activation represent activation to be used. relu function is set as value." }, { "code": null, "e": 42661, "s": 42571, "text": "Line 10 creates second Dense layer with 16 units and set relu as the activation function." }, { "code": null, "e": 42751, "s": 42661, "text": "Line 10 creates second Dense layer with 16 units and set relu as the activation function." }, { "code": null, "e": 42799, "s": 42751, "text": "Line 11 creates final Dense layer with 8 units." }, { "code": null, "e": 42847, "s": 42799, "text": "Line 11 creates final Dense layer with 8 units." }, { "code": null, "e": 42936, "s": 42847, "text": "Let us understand the basic concept of layer as well as how Keras supports each concept." }, { "code": null, "e": 43339, "s": 42936, "text": "In machine learning, all type of input data like text, images or videos will be first converted into array of numbers and then feed into the algorithm. Input numbers may be single dimensional array, two dimensional array (matrix) or multi-dimensional array. We can specify the dimensional information using shape, a tuple of integers. For example, (4,2) represent matrix with four rows and two columns." }, { "code": null, "e": 43486, "s": 43339, "text": ">>> import numpy as np \n>>> shape = (4, 2) \n>>> input = np.zeros(shape) \n>>> print(input) \n[\n [0. 0.] \n [0. 0.] \n [0. 0.] \n [0. 0.]\n] \n>>>" }, { "code": null, "e": 43598, "s": 43486, "text": "Similarly, (3,4,2) three dimensional matrix having three collections of 4x2 matrix (two rows and four columns)." }, { "code": null, "e": 43812, "s": 43598, "text": ">>> import numpy as np \n>>> shape = (3, 4, 2) \n>>> input = np.zeros(shape) \n>>> print(input)\n[\n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] \n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]] \n [[0. 0.] [0. 0.] [0. 0.] [0. 0.]]\n]\n>>>" }, { "code": null, "e": 43927, "s": 43812, "text": "To create the first layer of the model (or input layer of the model), shape of the input data should be specified." }, { "code": null, "e": 44125, "s": 43927, "text": "In Machine Learning, weight will be assigned to all input data. Initializers module provides different functions to set these initial weight. Some of the Keras Initializer function are as follows −" }, { "code": null, "e": 44157, "s": 44125, "text": "Generates 0 for all input data." }, { "code": null, "e": 44424, "s": 44157, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Zeros() \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 44501, "s": 44424, "text": "Where, kernel_initializer represent the initializer for kernel of the model." }, { "code": null, "e": 44533, "s": 44501, "text": "Generates 1 for all input data." }, { "code": null, "e": 44777, "s": 44533, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Ones() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 44855, "s": 44777, "text": "Generates a constant value (say, 5) specified by the user for all input data." }, { "code": null, "e": 45112, "s": 44855, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Constant(value = 0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 45154, "s": 45112, "text": "where, value represent the constant value" }, { "code": null, "e": 45211, "s": 45154, "text": "Generates value using normal distribution of input data." }, { "code": null, "e": 45500, "s": 45211, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomNormal(mean=0.0, \nstddev = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 45507, "s": 45500, "text": "where," }, { "code": null, "e": 45564, "s": 45507, "text": "mean represent the mean of the random values to generate" }, { "code": null, "e": 45621, "s": 45564, "text": "mean represent the mean of the random values to generate" }, { "code": null, "e": 45694, "s": 45621, "text": "stddev represent the standard deviation of the random values to generate" }, { "code": null, "e": 45767, "s": 45694, "text": "stddev represent the standard deviation of the random values to generate" }, { "code": null, "e": 45819, "s": 45767, "text": "seed represent the values to generate random number" }, { "code": null, "e": 45871, "s": 45819, "text": "seed represent the values to generate random number" }, { "code": null, "e": 45929, "s": 45871, "text": "Generates value using uniform distribution of input data." }, { "code": null, "e": 46143, "s": 45929, "text": "from keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 46150, "s": 46143, "text": "where," }, { "code": null, "e": 46216, "s": 46150, "text": "minval represent the lower bound of the random values to generate" }, { "code": null, "e": 46282, "s": 46216, "text": "minval represent the lower bound of the random values to generate" }, { "code": null, "e": 46348, "s": 46282, "text": "maxval represent the upper bound of the random values to generate" }, { "code": null, "e": 46414, "s": 46348, "text": "maxval represent the upper bound of the random values to generate" }, { "code": null, "e": 46481, "s": 46414, "text": "Generates value using truncated normal distribution of input data." }, { "code": null, "e": 46772, "s": 46481, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.TruncatedNormal(mean = 0.0, stddev = 0.05, seed = None\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 46875, "s": 46772, "text": "Generates value based on the input shape and output shape of the layer along with the specified scale." }, { "code": null, "e": 47201, "s": 46875, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.VarianceScaling(\n scale = 1.0, mode = 'fan_in', distribution = 'normal', seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n skernel_initializer = my_init))" }, { "code": null, "e": 47208, "s": 47201, "text": "where," }, { "code": null, "e": 47243, "s": 47208, "text": "scale represent the scaling factor" }, { "code": null, "e": 47278, "s": 47243, "text": "scale represent the scaling factor" }, { "code": null, "e": 47339, "s": 47278, "text": "mode represent any one of fan_in, fan_out and fan_avg values" }, { "code": null, "e": 47400, "s": 47339, "text": "mode represent any one of fan_in, fan_out and fan_avg values" }, { "code": null, "e": 47451, "s": 47400, "text": "distribution represent either of normal or uniform" }, { "code": null, "e": 47502, "s": 47451, "text": "distribution represent either of normal or uniform" }, { "code": null, "e": 47625, "s": 47502, "text": "It finds the stddev value for normal distribution using below formula and then find the weights using normal distribution," }, { "code": null, "e": 47651, "s": 47625, "text": "stddev = sqrt(scale / n)\n" }, { "code": null, "e": 47670, "s": 47651, "text": "where n represent," }, { "code": null, "e": 47710, "s": 47670, "text": "number of input units for mode = fan_in" }, { "code": null, "e": 47750, "s": 47710, "text": "number of input units for mode = fan_in" }, { "code": null, "e": 47789, "s": 47750, "text": "number of out units for mode = fan_out" }, { "code": null, "e": 47828, "s": 47789, "text": "number of out units for mode = fan_out" }, { "code": null, "e": 47888, "s": 47828, "text": "average number of input and output units for mode = fan_avg" }, { "code": null, "e": 47948, "s": 47888, "text": "average number of input and output units for mode = fan_avg" }, { "code": null, "e": 48077, "s": 47948, "text": "Similarly, it finds the limit for uniform distribution using below formula and then find the weights using uniform distribution," }, { "code": null, "e": 48106, "s": 48077, "text": "limit = sqrt(3 * scale / n)\n" }, { "code": null, "e": 48169, "s": 48106, "text": "Generates value using lecun normal distribution of input data." }, { "code": null, "e": 48463, "s": 48169, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None)\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 48542, "s": 48463, "text": "It finds the stddev using the below formula and then apply normal distribution" }, { "code": null, "e": 48569, "s": 48542, "text": "stddev = sqrt(1 / fan_in)\n" }, { "code": null, "e": 48620, "s": 48569, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 48684, "s": 48620, "text": "Generates value using lecun uniform distribution of input data." }, { "code": null, "e": 48948, "s": 48684, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.lecun_uniform(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 49027, "s": 48948, "text": "It finds the limit using the below formula and then apply uniform distribution" }, { "code": null, "e": 49053, "s": 49027, "text": "limit = sqrt(3 / fan_in)\n" }, { "code": null, "e": 49060, "s": 49053, "text": "where," }, { "code": null, "e": 49104, "s": 49060, "text": "fan_in represents the number of input units" }, { "code": null, "e": 49148, "s": 49104, "text": "fan_in represents the number of input units" }, { "code": null, "e": 49194, "s": 49148, "text": "fan_out represents the number of output units" }, { "code": null, "e": 49240, "s": 49194, "text": "fan_out represents the number of output units" }, { "code": null, "e": 49304, "s": 49240, "text": "Generates value using glorot normal distribution of input data." }, { "code": null, "e": 49566, "s": 49304, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.glorot_normal(seed=None) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 49645, "s": 49566, "text": "It finds the stddev using the below formula and then apply normal distribution" }, { "code": null, "e": 49684, "s": 49645, "text": "stddev = sqrt(2 / (fan_in + fan_out))\n" }, { "code": null, "e": 49691, "s": 49684, "text": "where," }, { "code": null, "e": 49735, "s": 49691, "text": "fan_in represents the number of input units" }, { "code": null, "e": 49779, "s": 49735, "text": "fan_in represents the number of input units" }, { "code": null, "e": 49825, "s": 49779, "text": "fan_out represents the number of output units" }, { "code": null, "e": 49871, "s": 49825, "text": "fan_out represents the number of output units" }, { "code": null, "e": 49936, "s": 49871, "text": "Generates value using glorot uniform distribution of input data." }, { "code": null, "e": 50201, "s": 49936, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.glorot_uniform(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 50280, "s": 50201, "text": "It finds the limit using the below formula and then apply uniform distribution" }, { "code": null, "e": 50318, "s": 50280, "text": "limit = sqrt(6 / (fan_in + fan_out))\n" }, { "code": null, "e": 50325, "s": 50318, "text": "where," }, { "code": null, "e": 50369, "s": 50325, "text": "fan_in represent the number of input units." }, { "code": null, "e": 50413, "s": 50369, "text": "fan_in represent the number of input units." }, { "code": null, "e": 50459, "s": 50413, "text": "fan_out represents the number of output units" }, { "code": null, "e": 50505, "s": 50459, "text": "fan_out represents the number of output units" }, { "code": null, "e": 50565, "s": 50505, "text": "Generates value using he normal distribution of input data." }, { "code": null, "e": 50860, "s": 50565, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.RandomUniform(minval = -0.05, maxval = 0.05, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 50940, "s": 50860, "text": "It finds the stddev using the below formula and then apply normal distribution." }, { "code": null, "e": 50967, "s": 50940, "text": "stddev = sqrt(2 / fan_in)\n" }, { "code": null, "e": 51018, "s": 50967, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 51079, "s": 51018, "text": "Generates value using he uniform distribution of input data." }, { "code": null, "e": 51339, "s": 51079, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.he_normal(seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 51419, "s": 51339, "text": "It finds the limit using the below formula and then apply uniform distribution." }, { "code": null, "e": 51445, "s": 51419, "text": "limit = sqrt(6 / fan_in)\n" }, { "code": null, "e": 51496, "s": 51445, "text": "where, fan_in represent the number of input units." }, { "code": null, "e": 51534, "s": 51496, "text": "Generates a random orthogonal matrix." }, { "code": null, "e": 51807, "s": 51534, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Orthogonal(gain = 1.0, seed = None) \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init))" }, { "code": null, "e": 51870, "s": 51807, "text": "where, gain represent the multiplication factor of the matrix." }, { "code": null, "e": 51897, "s": 51870, "text": "Generates identity matrix." }, { "code": null, "e": 52155, "s": 51897, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Identity(gain = 1.0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), kernel_initializer = my_init)\n)" }, { "code": null, "e": 52389, "s": 52155, "text": "In machine learning, a constraint will be set on the parameter (weight) during optimization phase. <>Constraints module provides different functions to set the constraint on the layer. Some of the constraint functions are as follows." }, { "code": null, "e": 52428, "s": 52389, "text": "Constrains weights to be non-negative." }, { "code": null, "e": 52690, "s": 52428, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import initializers \n\nmy_init = initializers.Identity(gain = 1.0) model.add(\n Dense(512, activation = 'relu', input_shape = (784,), \n kernel_initializer = my_init)\n)" }, { "code": null, "e": 52765, "s": 52690, "text": "where, kernel_constraint represent the constraint to be used in the layer." }, { "code": null, "e": 52801, "s": 52765, "text": "Constrains weights to be unit norm." }, { "code": null, "e": 53086, "s": 52801, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.UnitNorm(axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 53152, "s": 53086, "text": "Constrains weight to norm less than or equals to the given value." }, { "code": null, "e": 53451, "s": 53152, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.MaxNorm(max_value = 2, axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 53458, "s": 53451, "text": "where," }, { "code": null, "e": 53494, "s": 53458, "text": "max_value represent the upper bound" }, { "code": null, "e": 53530, "s": 53494, "text": "max_value represent the upper bound" }, { "code": null, "e": 53709, "s": 53530, "text": "axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension" }, { "code": null, "e": 53888, "s": 53709, "text": "axis represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension" }, { "code": null, "e": 53964, "s": 53888, "text": "Constrains weights to be norm between specified minimum and maximum values." }, { "code": null, "e": 54297, "s": 53964, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import constraints \n\nmy_constrain = constraints.MinMaxNorm(min_value = 0.0, max_value = 1.0, rate = 1.0, axis = 0) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_constraint = my_constrain))" }, { "code": null, "e": 54370, "s": 54297, "text": "where, rate represent the rate at which the weight constrain is applied." }, { "code": null, "e": 54639, "s": 54370, "text": "In machine learning, regularizers are used in the optimization phase. It applies some penalties on the layer parameter during optimization. Keras regularization module provides below functions to set penalties on the layer. Regularization applies per-layer basis only." }, { "code": null, "e": 54676, "s": 54639, "text": "It provides L1 based regularization." }, { "code": null, "e": 54957, "s": 54676, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l1(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_regularizer = my_regularizer))\n" }, { "code": null, "e": 55044, "s": 54957, "text": "where, kernel_regularizer represent the rate at which the weight constrain is applied." }, { "code": null, "e": 55081, "s": 55044, "text": "It provides L2 based regularization." }, { "code": null, "e": 55361, "s": 55081, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l2(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,), \n kernel_regularizer = my_regularizer))" }, { "code": null, "e": 55410, "s": 55361, "text": "It provides both L1 and L2 based regularization." }, { "code": null, "e": 55689, "s": 55410, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nfrom keras import regularizers \n\nmy_regularizer = regularizers.l2(0.) \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,),\n kernel_regularizer = my_regularizer))" }, { "code": null, "e": 55997, "s": 55689, "text": "In machine learning, activation function is a special function used to find whether a specific neuron is activated or not. Basically, the activation function does a nonlinear transformation of the input data and thus enable the neurons to learn better. Output of a neuron depends on the activation function." }, { "code": null, "e": 56249, "s": 55997, "text": "As you recall the concept of single perception, the output of a perceptron (neuron) is simply the result of the activation function, which accepts the summation of all input multiplied with its corresponding weight plus overall bias, if any available." }, { "code": null, "e": 56300, "s": 56249, "text": "result = Activation(SUMOF(input * weight) + bias)\n" }, { "code": null, "e": 56518, "s": 56300, "text": "So, activation function plays an important role in the successful learning of the model. Keras provides a lot of activation function in the activations module. Let us learn all the activations available in the module." }, { "code": null, "e": 56557, "s": 56518, "text": "Applies Linear function. Does nothing." }, { "code": null, "e": 56729, "s": 56557, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'linear', input_shape = (784,)))\n" }, { "code": null, "e": 56896, "s": 56729, "text": "Where, activation refers the activation function of the layer. It can be specified simply by the name of the function and the layer will use corresponding activators." }, { "code": null, "e": 56929, "s": 56896, "text": "Applies Exponential linear unit." }, { "code": null, "e": 57097, "s": 56929, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'elu', input_shape = (784,)))" }, { "code": null, "e": 57137, "s": 57097, "text": "Applies Scaled exponential linear unit." }, { "code": null, "e": 57306, "s": 57137, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'selu', input_shape = (784,)))" }, { "code": null, "e": 57337, "s": 57306, "text": "Applies Rectified Linear Unit." }, { "code": null, "e": 57506, "s": 57337, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,)))" }, { "code": null, "e": 57532, "s": 57506, "text": "Applies Softmax function." }, { "code": null, "e": 57704, "s": 57532, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softmax', input_shape = (784,)))" }, { "code": null, "e": 57731, "s": 57704, "text": "Applies Softplus function." }, { "code": null, "e": 57904, "s": 57731, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softplus', input_shape = (784,)))" }, { "code": null, "e": 57931, "s": 57904, "text": "Applies Softsign function." }, { "code": null, "e": 58104, "s": 57931, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'softsign', input_shape = (784,)))" }, { "code": null, "e": 58141, "s": 58104, "text": "Applies Hyperbolic tangent function." }, { "code": null, "e": 58309, "s": 58141, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \nmodel = Sequential() \nmodel.add(Dense(512, activation = 'tanh', input_shape = (784,)))" }, { "code": null, "e": 58335, "s": 58309, "text": "Applies Sigmoid function." }, { "code": null, "e": 58507, "s": 58335, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'sigmoid', input_shape = (784,)))" }, { "code": null, "e": 58538, "s": 58507, "text": "Applies Hard Sigmoid function." }, { "code": null, "e": 58715, "s": 58538, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'hard_sigmoid', input_shape = (784,)))" }, { "code": null, "e": 58745, "s": 58715, "text": "Applies exponential function." }, { "code": null, "e": 58921, "s": 58745, "text": "from keras.models import Sequential \nfrom keras.layers import Activation, Dense \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'exponential', input_shape = (784,)))" }, { "code": null, "e": 58933, "s": 58921, "text": "Dense Layer" }, { "code": null, "e": 58999, "s": 58933, "text": "Dense layer is the regular deeply connected neural network layer." }, { "code": null, "e": 59014, "s": 58999, "text": "Dropout Layers" }, { "code": null, "e": 59079, "s": 59014, "text": "Dropout is one of the important concept in the machine learning." }, { "code": null, "e": 59094, "s": 59079, "text": "Flatten Layers" }, { "code": null, "e": 59132, "s": 59094, "text": "Flatten is used to flatten the input." }, { "code": null, "e": 59147, "s": 59132, "text": "Reshape Layers" }, { "code": null, "e": 59197, "s": 59147, "text": "Reshape is used to change the shape of the input." }, { "code": null, "e": 59212, "s": 59197, "text": "Permute Layers" }, { "code": null, "e": 59281, "s": 59212, "text": "Permute is also used to change the shape of the input using pattern." }, { "code": null, "e": 59301, "s": 59281, "text": "RepeatVector Layers" }, { "code": null, "e": 59370, "s": 59301, "text": "RepeatVector is used to repeat the input for set number, n of times." }, { "code": null, "e": 59384, "s": 59370, "text": "Lambda Layers" }, { "code": null, "e": 59460, "s": 59384, "text": "Lambda is used to transform the input data using an expression or function." }, { "code": null, "e": 59479, "s": 59460, "text": "Convolution Layers" }, { "code": null, "e": 59600, "s": 59479, "text": "Keras contains a lot of layers for creating Convolution based ANN, popularly called as Convolution Neural Network (CNN)." }, { "code": null, "e": 59614, "s": 59600, "text": "Pooling Layer" }, { "code": null, "e": 59677, "s": 59614, "text": "It is used to perform max pooling operations on temporal data." }, { "code": null, "e": 59701, "s": 59677, "text": "Locally connected layer" }, { "code": null, "e": 59839, "s": 59701, "text": "Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared." }, { "code": null, "e": 59851, "s": 59839, "text": "Merge Layer" }, { "code": null, "e": 59889, "s": 59851, "text": "It is used to merge a list of inputs." }, { "code": null, "e": 59905, "s": 59889, "text": "Embedding Layer" }, { "code": null, "e": 59954, "s": 59905, "text": "It performs embedding operations in input layer." }, { "code": null, "e": 60139, "s": 59954, "text": "Keras allows to create our own customized layer. Once a new layer is created, it can be used in any model without any restriction. Let us learn how to create new layer in this chapter." }, { "code": null, "e": 60434, "s": 60139, "text": "Keras provides a base layer class, Layer which can sub-classed to create our own customized layer. Let us create a simple layer which will find weight based on normal distribution and then do the basic computation of finding the summation of the product of input and its weight during training." }, { "code": null, "e": 60479, "s": 60434, "text": "First, let us import the necessary modules −" }, { "code": null, "e": 60542, "s": 60479, "text": "from keras import backend as K \nfrom keras.layers import Layer" }, { "code": null, "e": 60548, "s": 60542, "text": "Here," }, { "code": null, "e": 60592, "s": 60548, "text": "backend is used to access the dot function." }, { "code": null, "e": 60636, "s": 60592, "text": "backend is used to access the dot function." }, { "code": null, "e": 60711, "s": 60636, "text": "Layer is the base class and we will be sub-classing it to create our layer" }, { "code": null, "e": 60786, "s": 60711, "text": "Layer is the base class and we will be sub-classing it to create our layer" }, { "code": null, "e": 60857, "s": 60786, "text": "Let us create a new class, MyCustomLayer by sub-classing Layer class −" }, { "code": null, "e": 60894, "s": 60857, "text": "class MyCustomLayer(Layer): \n ...\n" }, { "code": null, "e": 60947, "s": 60894, "text": "Let us initialize our new class as specified below −" }, { "code": null, "e": 61076, "s": 60947, "text": "def __init__(self, output_dim, **kwargs): \n self.output_dim = output_dim \n super(MyCustomLayer, self).__init__(**kwargs)\n" }, { "code": null, "e": 61082, "s": 61076, "text": "Here," }, { "code": null, "e": 61116, "s": 61082, "text": "Line 2 sets the output dimension." }, { "code": null, "e": 61150, "s": 61116, "text": "Line 2 sets the output dimension." }, { "code": null, "e": 61204, "s": 61150, "text": "Line 3 calls the base or super layer’s init function." }, { "code": null, "e": 61258, "s": 61204, "text": "Line 3 calls the base or super layer’s init function." }, { "code": null, "e": 61522, "s": 61258, "text": "build is the main method and its only purpose is to build the layer properly. It can do anything related to the inner working of the layer. Once the custom functionality is done, we can call the base class build function. Our custom build function is as follows −" }, { "code": null, "e": 61752, "s": 61522, "text": "def build(self, input_shape): \n self.kernel = self.add_weight(name = 'kernel', \n shape = (input_shape[1], self.output_dim), \n initializer = 'normal', trainable = True) \n super(MyCustomLayer, self).build(input_shape)" }, { "code": null, "e": 61758, "s": 61752, "text": "Here," }, { "code": null, "e": 61874, "s": 61758, "text": "Line 1 defines the build method with one argument, input_shape. Shape of the input data is referred by input_shape." }, { "code": null, "e": 61990, "s": 61874, "text": "Line 1 defines the build method with one argument, input_shape. Shape of the input data is referred by input_shape." }, { "code": null, "e": 62166, "s": 61990, "text": "Line 2 creates the weight corresponding to input shape and set it in the kernel. It is our custom functionality of the layer. It creates the weight using ‘normal’ initializer." }, { "code": null, "e": 62342, "s": 62166, "text": "Line 2 creates the weight corresponding to input shape and set it in the kernel. It is our custom functionality of the layer. It creates the weight using ‘normal’ initializer." }, { "code": null, "e": 62385, "s": 62342, "text": "Line 6 calls the base class, build method." }, { "code": null, "e": 62428, "s": 62385, "text": "Line 6 calls the base class, build method." }, { "code": null, "e": 62501, "s": 62428, "text": "call method does the exact working of the layer during training process." }, { "code": null, "e": 62538, "s": 62501, "text": "Our custom call method is as follows" }, { "code": null, "e": 62609, "s": 62538, "text": "def call(self, input_data): \n return K.dot(input_data, self.kernel)\n" }, { "code": null, "e": 62615, "s": 62609, "text": "Here," }, { "code": null, "e": 62721, "s": 62615, "text": "Line 1 defines the call method with one argument, input_data. input_data is the input data for our layer." }, { "code": null, "e": 62827, "s": 62721, "text": "Line 1 defines the call method with one argument, input_data. input_data is the input data for our layer." }, { "code": null, "e": 62923, "s": 62827, "text": "Line 2 return the dot product of the input data, input_data and our layer’s kernel, self.kernel" }, { "code": null, "e": 63019, "s": 62923, "text": "Line 2 return the dot product of the input data, input_data and our layer’s kernel, self.kernel" }, { "code": null, "e": 63106, "s": 63019, "text": "def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim)\n" }, { "code": null, "e": 63112, "s": 63106, "text": "Here," }, { "code": null, "e": 63185, "s": 63112, "text": "Line 1 defines compute_output_shape method with one argument input_shape" }, { "code": null, "e": 63258, "s": 63185, "text": "Line 1 defines compute_output_shape method with one argument input_shape" }, { "code": null, "e": 63372, "s": 63258, "text": "Line 2 computes the output shape using shape of input data and output dimension set while initializing the layer." }, { "code": null, "e": 63486, "s": 63372, "text": "Line 2 computes the output shape using shape of input data and output dimension set while initializing the layer." }, { "code": null, "e": 63625, "s": 63486, "text": "Implementing the build, call and compute_output_shape completes the creating a customized layer. The final and complete code is as follows" }, { "code": null, "e": 64291, "s": 63625, "text": "from keras import backend as K from keras.layers import Layer\nclass MyCustomLayer(Layer): \n def __init__(self, output_dim, **kwargs): \n self.output_dim = output_dim \n super(MyCustomLayer, self).__init__(**kwargs) \n def build(self, input_shape): self.kernel = \n self.add_weight(name = 'kernel', \n shape = (input_shape[1], self.output_dim), \n initializer = 'normal', trainable = True) \n super(MyCustomLayer, self).build(input_shape) # \n Be sure to call this at the end \n def call(self, input_data): return K.dot(input_data, self.kernel) \n def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim)" }, { "code": null, "e": 64368, "s": 64291, "text": "Let us create a simple model using our customized layer as specified below −" }, { "code": null, "e": 64571, "s": 64368, "text": "from keras.models import Sequential \nfrom keras.layers import Dense \n\nmodel = Sequential() \nmodel.add(MyCustomLayer(32, input_shape = (16,))) \nmodel.add(Dense(8, activation = 'softmax')) model.summary()" }, { "code": null, "e": 64577, "s": 64571, "text": "Here," }, { "code": null, "e": 64657, "s": 64577, "text": "Our MyCustomLayer is added to the model using 32 units and (16,) as input shape" }, { "code": null, "e": 64737, "s": 64657, "text": "Our MyCustomLayer is added to the model using 32 units and (16,) as input shape" }, { "code": null, "e": 64801, "s": 64737, "text": "Running the application will print the model summary as below −" }, { "code": null, "e": 65333, "s": 64801, "text": "Model: \"sequential_1\" \n_________________________________________________________________ \nLayer (type) Output Shape Param \n#================================================================ \nmy_custom_layer_1 (MyCustomL (None, 32) 512 \n_________________________________________________________________\ndense_1 (Dense) (None, 8) 264 \n================================================================= \nTotal params: 776 \nTrainable params: 776 \nNon-trainable params: 0 \n_________________________________________________________________" }, { "code": null, "e": 65639, "s": 65333, "text": "As learned earlier, Keras model represents the actual neural network model. Keras provides a two mode to create the model, simple and easy to use Sequential API as well as more flexible and advanced Functional API. Let us learn now to create model using both Sequential and Functional API in this chapter." }, { "code": null, "e": 65938, "s": 65639, "text": "The core idea of Sequential API is simply arranging the Keras layers in a sequential order and so, it is called Sequential API. Most of the ANN also has layers in sequential order and the data flows from one layer to another layer in the given order until the data finally reaches the output layer." }, { "code": null, "e": 66021, "s": 65938, "text": "A ANN model can be created by simply calling Sequential() API as specified below −" }, { "code": null, "e": 66080, "s": 66021, "text": "from keras.models import Sequential \nmodel = Sequential()\n" }, { "code": null, "e": 66208, "s": 66080, "text": "To add a layer, simply create a layer using Keras layer API and then pass the layer through add() function as specified below −" }, { "code": null, "e": 66453, "s": 66208, "text": "from keras.models import Sequential \n\nmodel = Sequential() \ninput_layer = Dense(32, input_shape=(8,)) model.add(input_layer) \nhidden_layer = Dense(64, activation='relu'); model.add(hidden_layer) \noutput_layer = Dense(8) \nmodel.add(output_layer)" }, { "code": null, "e": 66531, "s": 66453, "text": "Here, we have created one input layer, one hidden layer and one output layer." }, { "code": null, "e": 66650, "s": 66531, "text": "Keras provides few methods to get the model information like layers, input data and output data. They are as follows −" }, { "code": null, "e": 66710, "s": 66650, "text": "model.layers − Returns all the layers of the model as list." }, { "code": null, "e": 66770, "s": 66710, "text": "model.layers − Returns all the layers of the model as list." }, { "code": null, "e": 66990, "s": 66770, "text": ">>> layers = model.layers \n>>> layers \n[\n <keras.layers.core.Dense object at 0x000002C8C888B8D0>, \n <keras.layers.core.Dense object at 0x000002C8C888B7B8>\n <keras.layers.core.Dense object at 0x 000002C8C888B898>\n]" }, { "code": null, "e": 67057, "s": 66990, "text": "model.inputs − Returns all the input tensors of the model as list." }, { "code": null, "e": 67124, "s": 67057, "text": "model.inputs − Returns all the input tensors of the model as list." }, { "code": null, "e": 67223, "s": 67124, "text": ">>> inputs = model.inputs \n>>> inputs \n[<tf.Tensor 'dense_13_input:0' shape=(?, 8) dtype=float32>]" }, { "code": null, "e": 67292, "s": 67223, "text": "model.outputs − Returns all the output tensors of the model as list." }, { "code": null, "e": 67361, "s": 67292, "text": "model.outputs − Returns all the output tensors of the model as list." }, { "code": null, "e": 67464, "s": 67361, "text": ">>> outputs = model.outputs \n>>> outputs \n<tf.Tensor 'dense_15/BiasAdd:0' shape=(?, 8) dtype=float32>]" }, { "code": null, "e": 67525, "s": 67464, "text": "model.get_weights − Returns all the weights as NumPy arrays." }, { "code": null, "e": 67586, "s": 67525, "text": "model.get_weights − Returns all the weights as NumPy arrays." }, { "code": null, "e": 67656, "s": 67586, "text": "model.set_weights(weight_numpy_array) − Set the weights of the model." }, { "code": null, "e": 67726, "s": 67656, "text": "model.set_weights(weight_numpy_array) − Set the weights of the model." }, { "code": null, "e": 67847, "s": 67726, "text": "Keras provides methods to serialize the model into object as well as json and load it again later. They are as follows −" }, { "code": null, "e": 67895, "s": 67847, "text": "get_config() − IReturns the model as an object." }, { "code": null, "e": 67943, "s": 67895, "text": "get_config() − IReturns the model as an object." }, { "code": null, "e": 67972, "s": 67943, "text": "config = model.get_config()\n" }, { "code": null, "e": 68075, "s": 67972, "text": "from_config() − It accept the model configuration object as argument and create the model accordingly." }, { "code": null, "e": 68178, "s": 68075, "text": "from_config() − It accept the model configuration object as argument and create the model accordingly." }, { "code": null, "e": 68222, "s": 68178, "text": "new_model = Sequential.from_config(config)\n" }, { "code": null, "e": 68271, "s": 68222, "text": "to_json() − Returns the model as an json object." }, { "code": null, "e": 68320, "s": 68271, "text": "to_json() − Returns the model as an json object." }, { "code": null, "e": 70035, "s": 68320, "text": ">>> json_string = model.to_json() \n>>> json_string '{\"class_name\": \"Sequential\", \"config\": \n{\"name\": \"sequential_10\", \"layers\": \n[{\"class_name\": \"Dense\", \"config\": \n{\"name\": \"dense_13\", \"trainable\": true, \"batch_input_shape\": \n[null, 8], \"dtype\": \"float32\", \"units\": 32, \"activation\": \"linear\", \n\"use_bias\": true, \"kernel_initializer\": \n{\"class_name\": \"Vari anceScaling\", \"config\": \n{\"scale\": 1.0, \"mode\": \"fan_avg\", \"distribution\": \"uniform\", \"seed\": null}},\n\"bias_initializer\": {\"class_name\": \"Zeros\", \"conf \nig\": {}}, \"kernel_regularizer\": null, \"bias_regularizer\": null, \n\"activity_regularizer\": null, \"kernel_constraint\": null, \"bias_constraint\": null}}, \n{\" class_name\": \"Dense\", \"config\": {\"name\": \"dense_14\", \"trainable\": true, \n\"dtype\": \"float32\", \"units\": 64, \"activation\": \"relu\", \"use_bias\": true, \n\"kern el_initializer\": {\"class_name\": \"VarianceScaling\", \"config\": \n{\"scale\": 1.0, \"mode\": \"fan_avg\", \"distribution\": \"uniform\", \"seed\": null}}, \n\"bias_initia lizer\": {\"class_name\": \"Zeros\", \n\"config\": {}}, \"kernel_regularizer\": null, \"bias_regularizer\": null, \n\"activity_regularizer\": null, \"kernel_constraint\" : null, \"bias_constraint\": null}}, \n{\"class_name\": \"Dense\", \"config\": {\"name\": \"dense_15\", \"trainable\": true, \n\"dtype\": \"float32\", \"units\": 8, \"activation\": \"linear\", \"use_bias\": true, \n\"kernel_initializer\": {\"class_name\": \"VarianceScaling\", \"config\": \n{\"scale\": 1.0, \"mode\": \"fan_avg\", \"distribution\": \" uniform\", \"seed\": null}}, \n\"bias_initializer\": {\"class_name\": \"Zeros\", \"config\": {}}, \n\"kernel_regularizer\": null, \"bias_regularizer\": null, \"activity_r egularizer\": \nnull, \"kernel_constraint\": null, \"bias_constraint\": \nnull}}]}, \"keras_version\": \"2.2.5\", \"backend\": \"tensorflow\"}' \n>>>" }, { "code": null, "e": 70120, "s": 70035, "text": "model_from_json() − Accepts json representation of the model and create a new model." }, { "code": null, "e": 70205, "s": 70120, "text": "model_from_json() − Accepts json representation of the model and create a new model." }, { "code": null, "e": 70289, "s": 70205, "text": "from keras.models import model_from_json \nnew_model = model_from_json(json_string)\n" }, { "code": null, "e": 70337, "s": 70289, "text": "to_yaml() − Returns the model as a yaml string." }, { "code": null, "e": 70385, "s": 70337, "text": "to_yaml() − Returns the model as a yaml string." }, { "code": null, "e": 71971, "s": 70385, "text": ">>> yaml_string = model.to_yaml() \n>>> yaml_string 'backend: tensorflow\\nclass_name: \nSequential\\nconfig:\\n layers:\\n - class_name: Dense\\n config:\\n \nactivation: linear\\n activity_regular izer: null\\n batch_input_shape: \n!!python/tuple\\n - null\\n - 8\\n bias_constraint: null\\n bias_initializer:\\n \nclass_name : Zeros\\n config: {}\\n bias_regularizer: null\\n dtype: \nfloat32\\n kernel_constraint: null\\n \nkernel_initializer:\\n cla ss_name: VarianceScaling\\n config:\\n \ndistribution: uniform\\n mode: fan_avg\\n \nscale: 1.0\\n seed: null\\n kernel_regularizer: null\\n name: dense_13\\n \ntrainable: true\\n units: 32\\n \nuse_bias: true\\n - class_name: Dense\\n config:\\n activation: relu\\n activity_regularizer: null\\n \nbias_constraint: null\\n bias_initializer:\\n class_name: Zeros\\n \nconfig : {}\\n bias_regularizer: null\\n dtype: float32\\n \nkernel_constraint: null\\n kernel_initializer:\\n class_name: VarianceScalin g\\n \nconfig:\\n distribution: uniform\\n mode: fan_avg\\n scale: 1.0\\n \nseed: null\\n kernel_regularizer: nu ll\\n name: dense_14\\n trainable: true\\n \nunits: 64\\n use_bias: true\\n - class_name: Dense\\n config:\\n \nactivation: linear\\n activity_regularizer: null\\n \nbias_constraint: null\\n bias_initializer:\\n \nclass_name: Zeros\\n config: {}\\n bias_regu larizer: null\\n \ndtype: float32\\n kernel_constraint: null\\n \nkernel_initializer:\\n class_name: VarianceScaling\\n config:\\n \ndistribution: uniform\\n mode: fan_avg\\n \nscale: 1.0\\n seed: null\\n kernel_regularizer: null\\n name: dense _15\\n \ntrainable: true\\n units: 8\\n \nuse_bias: true\\n name: sequential_10\\nkeras_version: 2.2.5\\n' \n>>>" }, { "code": null, "e": 72056, "s": 71971, "text": "model_from_yaml() − Accepts yaml representation of the model and create a new model." }, { "code": null, "e": 72141, "s": 72056, "text": "model_from_yaml() − Accepts yaml representation of the model and create a new model." }, { "code": null, "e": 72224, "s": 72141, "text": "from keras.models import model_from_yaml \nnew_model = model_from_yaml(yaml_string)" }, { "code": null, "e": 72429, "s": 72224, "text": "Understanding the model is very important phase to properly use it for training and prediction purposes. Keras provides a simple method, summary to get the full information about the model and its layers." }, { "code": null, "e": 72500, "s": 72429, "text": "A summary of the model created in the previous section is as follows −" }, { "code": null, "e": 73153, "s": 72500, "text": ">>> model.summary() Model: \"sequential_10\" \n_________________________________________________________________ \nLayer (type) Output Shape Param \n#================================================================ \ndense_13 (Dense) (None, 32) 288 \n_________________________________________________________________ \ndense_14 (Dense) (None, 64) 2112 \n_________________________________________________________________ \ndense_15 (Dense) (None, 8) 520 \n================================================================= \nTotal params: 2,920 \nTrainable params: 2,920 \nNon-trainable params: 0 \n_________________________________________________________________ \n>>>" }, { "code": null, "e": 73248, "s": 73153, "text": "Model provides function for training, evaluation and prediction process. They are as follows −" }, { "code": null, "e": 73302, "s": 73248, "text": "compile − Configure the learning process of the model" }, { "code": null, "e": 73356, "s": 73302, "text": "compile − Configure the learning process of the model" }, { "code": null, "e": 73402, "s": 73356, "text": "fit − Train the model using the training data" }, { "code": null, "e": 73448, "s": 73402, "text": "fit − Train the model using the training data" }, { "code": null, "e": 73498, "s": 73448, "text": "evaluate − Evaluate the model using the test data" }, { "code": null, "e": 73548, "s": 73498, "text": "evaluate − Evaluate the model using the test data" }, { "code": null, "e": 73593, "s": 73548, "text": "predict − Predict the results for new input." }, { "code": null, "e": 73638, "s": 73593, "text": "predict − Predict the results for new input." }, { "code": null, "e": 74010, "s": 73638, "text": "Sequential API is used to create models layer-by-layer. Functional API is an alternative approach of creating more complex models. Functional model, you can define multiple input or output that share layers. First, we create an instance for model and connecting to the layers to access input and output to the model. This section explains about functional model in brief." }, { "code": null, "e": 74057, "s": 74010, "text": "Import an input layer using the below module −" }, { "code": null, "e": 74093, "s": 74057, "text": ">>> from keras.layers import Input\n" }, { "code": null, "e": 74190, "s": 74093, "text": "Now, create an input layer specifying input dimension shape for the model using the below code −" }, { "code": null, "e": 74221, "s": 74190, "text": ">>> data = Input(shape=(2,3))\n" }, { "code": null, "e": 74273, "s": 74221, "text": "Define layer for the input using the below module −" }, { "code": null, "e": 74309, "s": 74273, "text": ">>> from keras.layers import Dense\n" }, { "code": null, "e": 74370, "s": 74309, "text": "Add Dense layer for the input using the below line of code −" }, { "code": null, "e": 74475, "s": 74370, "text": ">>> layer = Dense(2)(data) \n>>> print(layer) \nTensor(\"dense_1/add:0\", shape =(?, 2, 2), dtype = float32)" }, { "code": null, "e": 74513, "s": 74475, "text": "Define model using the below module −" }, { "code": null, "e": 74545, "s": 74513, "text": "from keras.models import Model\n" }, { "code": null, "e": 74622, "s": 74545, "text": "Create a model in functional way by specifying both input and output layer −" }, { "code": null, "e": 74669, "s": 74622, "text": "model = Model(inputs = data, outputs = layer)\n" }, { "code": null, "e": 74729, "s": 74669, "text": "The complete code to create a simple model is shown below −" }, { "code": null, "e": 75509, "s": 74729, "text": "from keras.layers import Input \nfrom keras.models import Model \nfrom keras.layers import Dense \n\ndata = Input(shape=(2,3)) \nlayer = Dense(2)(data) model = \nModel(inputs=data,outputs=layer) model.summary() \n_________________________________________________________________ \nLayer (type) Output Shape Param # \n================================================================= \ninput_2 (InputLayer) (None, 2, 3) 0 \n_________________________________________________________________ \ndense_2 (Dense) (None, 2, 2) 8 \n================================================================= \nTotal params: 8 \nTrainable params: 8 \nNon-trainable params: 0 \n_________________________________________________________________" }, { "code": null, "e": 75776, "s": 75509, "text": "Previously, we studied the basics of how to create model using Sequential and Functional API. This chapter explains about how to compile the model. The compilation is the final step in creating a model. Once the compilation is done, we can move on to training phase." }, { "code": null, "e": 75857, "s": 75776, "text": "Let us learn few concepts required to better understand the compilation process." }, { "code": null, "e": 76015, "s": 75857, "text": "In machine learning, Loss function is used to find error or deviation in the learning process. Keras requires loss function during model compilation process." }, { "code": null, "e": 76103, "s": 76015, "text": "Keras provides quite a few loss function in the losses module and they are as follows −" }, { "code": null, "e": 76122, "s": 76103, "text": "mean_squared_error" }, { "code": null, "e": 76142, "s": 76122, "text": "mean_absolute_error" }, { "code": null, "e": 76173, "s": 76142, "text": "mean_absolute_percentage_error" }, { "code": null, "e": 76204, "s": 76173, "text": "mean_squared_logarithmic_error" }, { "code": null, "e": 76218, "s": 76204, "text": "squared_hinge" }, { "code": null, "e": 76224, "s": 76218, "text": "hinge" }, { "code": null, "e": 76242, "s": 76224, "text": "categorical_hinge" }, { "code": null, "e": 76250, "s": 76242, "text": "logcosh" }, { "code": null, "e": 76261, "s": 76250, "text": "huber_loss" }, { "code": null, "e": 76286, "s": 76261, "text": "categorical_crossentropy" }, { "code": null, "e": 76318, "s": 76286, "text": "sparse_categorical_crossentropy" }, { "code": null, "e": 76338, "s": 76318, "text": "binary_crossentropy" }, { "code": null, "e": 76366, "s": 76338, "text": "kullback_leibler_divergence" }, { "code": null, "e": 76374, "s": 76366, "text": "poisson" }, { "code": null, "e": 76391, "s": 76374, "text": "cosine_proximity" }, { "code": null, "e": 76419, "s": 76391, "text": "is_categorical_crossentropy" }, { "code": null, "e": 76467, "s": 76419, "text": "All above loss function accepts two arguments −" }, { "code": null, "e": 76499, "s": 76467, "text": "y_true − true labels as tensors" }, { "code": null, "e": 76531, "s": 76499, "text": "y_true − true labels as tensors" }, { "code": null, "e": 76577, "s": 76531, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 76623, "s": 76577, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 76696, "s": 76623, "text": "Import the losses module before using loss function as specified below −" }, { "code": null, "e": 76722, "s": 76696, "text": "from keras import losses\n" }, { "code": null, "e": 76950, "s": 76722, "text": "In machine learning, Optimization is an important process which optimize the input weights by comparing the prediction and the loss function. Keras provides quite a few optimizer as a module, optimizers and they are as follows:" }, { "code": null, "e": 76995, "s": 76950, "text": "SGD − Stochastic gradient descent optimizer." }, { "code": null, "e": 77073, "s": 76995, "text": "keras.optimizers.SGD(learning_rate = 0.01, momentum = 0.0, nesterov = False)\n" }, { "code": null, "e": 77102, "s": 77073, "text": "RMSprop − RMSProp optimizer." }, { "code": null, "e": 77162, "s": 77102, "text": "keras.optimizers.RMSprop(learning_rate = 0.001, rho = 0.9)\n" }, { "code": null, "e": 77191, "s": 77162, "text": "Adagrad − Adagrad optimizer." }, { "code": null, "e": 77239, "s": 77191, "text": "keras.optimizers.Adagrad(learning_rate = 0.01)\n" }, { "code": null, "e": 77270, "s": 77239, "text": "Adadelta − Adadelta optimizer." }, { "code": null, "e": 77330, "s": 77270, "text": "keras.optimizers.Adadelta(learning_rate = 1.0, rho = 0.95)\n" }, { "code": null, "e": 77353, "s": 77330, "text": "Adam − Adam optimizer." }, { "code": null, "e": 77450, "s": 77353, "text": "keras.optimizers.Adam(\n learning_rate = 0.001, beta_1 = 0.9, beta_2 = 0.999, amsgrad = False\n)" }, { "code": null, "e": 77487, "s": 77450, "text": "Adamax − Adamax optimizer from Adam." }, { "code": null, "e": 77565, "s": 77487, "text": "keras.optimizers.Adamax(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999)\n" }, { "code": null, "e": 77598, "s": 77565, "text": "Nadam − Nesterov Adam optimizer." }, { "code": null, "e": 77675, "s": 77598, "text": "keras.optimizers.Nadam(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999)\n" }, { "code": null, "e": 77749, "s": 77675, "text": "Import the optimizers module before using optimizers as specified below −" }, { "code": null, "e": 77779, "s": 77749, "text": "from keras import optimizers\n" }, { "code": null, "e": 78005, "s": 77779, "text": "In machine learning, Metrics is used to evaluate the performance of your model. It is similar to loss function, but not used in training process. Keras provides quite a few metrics as a module, metrics and they are as follows" }, { "code": null, "e": 78014, "s": 78005, "text": "accuracy" }, { "code": null, "e": 78030, "s": 78014, "text": "binary_accuracy" }, { "code": null, "e": 78051, "s": 78030, "text": "categorical_accuracy" }, { "code": null, "e": 78079, "s": 78051, "text": "sparse_categorical_accuracy" }, { "code": null, "e": 78106, "s": 78079, "text": "top_k_categorical_accuracy" }, { "code": null, "e": 78140, "s": 78106, "text": "sparse_top_k_categorical_accuracy" }, { "code": null, "e": 78157, "s": 78140, "text": "cosine_proximity" }, { "code": null, "e": 78170, "s": 78157, "text": "clone_metric" }, { "code": null, "e": 78239, "s": 78170, "text": "Similar to loss function, metrics also accepts below two arguments −" }, { "code": null, "e": 78271, "s": 78239, "text": "y_true − true labels as tensors" }, { "code": null, "e": 78303, "s": 78271, "text": "y_true − true labels as tensors" }, { "code": null, "e": 78349, "s": 78303, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 78395, "s": 78349, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 78463, "s": 78395, "text": "Import the metrics module before using metrics as specified below −" }, { "code": null, "e": 78490, "s": 78463, "text": "from keras import metrics\n" }, { "code": null, "e": 78622, "s": 78490, "text": "Keras model provides a method, compile() to compile the model. The argument and default value of the compile() method is as follows" }, { "code": null, "e": 78796, "s": 78622, "text": "compile(\n optimizer, \n loss = None, \n metrics = None, \n loss_weights = None, \n sample_weight_mode = None, \n weighted_metrics = None, \n target_tensors = None\n)\n" }, { "code": null, "e": 78837, "s": 78796, "text": "The important arguments are as follows −" }, { "code": null, "e": 78851, "s": 78837, "text": "loss function" }, { "code": null, "e": 78861, "s": 78851, "text": "Optimizer" }, { "code": null, "e": 78869, "s": 78861, "text": "metrics" }, { "code": null, "e": 78919, "s": 78869, "text": "A sample code to compile the mode is as follows −" }, { "code": null, "e": 79112, "s": 78919, "text": "from keras import losses \nfrom keras import optimizers \nfrom keras import metrics \n\nmodel.compile(loss = 'mean_squared_error', \n optimizer = 'sgd', metrics = [metrics.categorical_accuracy])" }, { "code": null, "e": 79119, "s": 79112, "text": "where," }, { "code": null, "e": 79162, "s": 79119, "text": "loss function is set as mean_squared_error" }, { "code": null, "e": 79205, "s": 79162, "text": "loss function is set as mean_squared_error" }, { "code": null, "e": 79229, "s": 79205, "text": "optimizer is set as sgd" }, { "code": null, "e": 79253, "s": 79229, "text": "optimizer is set as sgd" }, { "code": null, "e": 79300, "s": 79253, "text": "metrics is set as metrics.categorical_accuracy" }, { "code": null, "e": 79347, "s": 79300, "text": "metrics is set as metrics.categorical_accuracy" }, { "code": null, "e": 79561, "s": 79347, "text": "Models are trained by NumPy arrays using fit(). The main purpose of this fit function is used to evaluate your model on training. This can be also used for graphing model performance. It has the following syntax −" }, { "code": null, "e": 79604, "s": 79561, "text": "model.fit(X, y, epochs = , batch_size = )\n" }, { "code": null, "e": 79610, "s": 79604, "text": "Here," }, { "code": null, "e": 79654, "s": 79610, "text": "X, y − It is a tuple to evaluate your data." }, { "code": null, "e": 79698, "s": 79654, "text": "X, y − It is a tuple to evaluate your data." }, { "code": null, "e": 79772, "s": 79698, "text": "epochs − no of times the model is needed to be evaluated during training." }, { "code": null, "e": 79846, "s": 79772, "text": "epochs − no of times the model is needed to be evaluated during training." }, { "code": null, "e": 79879, "s": 79846, "text": "batch_size − training instances." }, { "code": null, "e": 79912, "s": 79879, "text": "batch_size − training instances." }, { "code": null, "e": 79983, "s": 79912, "text": "Let us take a simple example of numpy random data to use this concept." }, { "code": null, "e": 80078, "s": 79983, "text": "Let us create a random data using numpy for x and y with the help of below mentioned command −" }, { "code": null, "e": 80175, "s": 80078, "text": "import numpy as np \n\nx_train = np.random.random((100,4,8)) \ny_train = np.random.random((100,10))" }, { "code": null, "e": 80211, "s": 80175, "text": "Now, create random validation data," }, { "code": null, "e": 80284, "s": 80211, "text": "x_val = np.random.random((100,4,8)) \ny_val = np.random.random((100,10))\n" }, { "code": null, "e": 80324, "s": 80284, "text": "Let us create simple sequential model −" }, { "code": null, "e": 80382, "s": 80324, "text": "from keras.models import Sequential model = Sequential()\n" }, { "code": null, "e": 80411, "s": 80382, "text": "Create layers to add model −" }, { "code": null, "e": 80587, "s": 80411, "text": "from keras.layers import LSTM, Dense \n\n# add a sequence of vectors of dimension 16 \nmodel.add(LSTM(16, return_sequences = True)) \nmodel.add(Dense(10, activation = 'softmax'))\n" }, { "code": null, "e": 80651, "s": 80587, "text": "Now model is defined. You can compile using the below command −" }, { "code": null, "e": 80749, "s": 80651, "text": "model.compile(\n loss = 'categorical_crossentropy', optimizer = 'sgd', metrics = ['accuracy']\n)\n" }, { "code": null, "e": 80797, "s": 80749, "text": "Now we apply fit() function to train our data −" }, { "code": null, "e": 80889, "s": 80797, "text": "model.fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = (x_val, y_val))\n" }, { "code": null, "e": 80952, "s": 80889, "text": "We have learned to create, compile and train the Keras models." }, { "code": null, "e": 81013, "s": 80952, "text": "Let us apply our learning and create a simple MPL based ANN." }, { "code": null, "e": 81619, "s": 81013, "text": "Before creating a model, we need to choose a problem, need to collect the required data and convert the data to NumPy array. Once data is collected, we can prepare the model and train it by using the collected data. Data collection is one of the most difficult phase of machine learning. Keras provides a special module, datasets to download the online machine learning data for training purposes. It fetches the data from online server, process the data and return the data as training and test set. Let us check the data provided by Keras dataset module. The data available in the module are as follows," }, { "code": null, "e": 81654, "s": 81619, "text": "CIFAR10 small image classification" }, { "code": null, "e": 81690, "s": 81654, "text": "CIFAR100 small image classification" }, { "code": null, "e": 81734, "s": 81690, "text": "IMDB Movie reviews sentiment classification" }, { "code": null, "e": 81773, "s": 81734, "text": "Reuters newswire topics classification" }, { "code": null, "e": 81810, "s": 81773, "text": "MNIST database of handwritten digits" }, { "code": null, "e": 81853, "s": 81810, "text": "Fashion-MNIST database of fashion articles" }, { "code": null, "e": 81893, "s": 81853, "text": "Boston housing price regression dataset" }, { "code": null, "e": 82087, "s": 81893, "text": "Let us use the MNIST database of handwritten digits (or minst) as our input. minst is a collection of 60,000, 28x28 grayscale images. It contains 10 digits. It also contains 10,000 test images." }, { "code": null, "e": 82132, "s": 82087, "text": "Below code can be used to load the dataset −" }, { "code": null, "e": 82224, "s": 82132, "text": "from keras.datasets import mnist \n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()" }, { "code": null, "e": 82230, "s": 82224, "text": "where" }, { "code": null, "e": 82282, "s": 82230, "text": "Line 1 imports minst from the keras dataset module." }, { "code": null, "e": 82334, "s": 82282, "text": "Line 1 imports minst from the keras dataset module." }, { "code": null, "e": 82665, "s": 82334, "text": "Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape." }, { "code": null, "e": 82996, "s": 82665, "text": "Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape." }, { "code": null, "e": 83172, "s": 82996, "text": "Other dataset can also be fetched using similar API and every API returns similar data as well except the shape of the data. The shape of the data depends on the type of data." }, { "code": null, "e": 83286, "s": 83172, "text": "Let us choose a simple multi-layer perceptron (MLP) as represented below and try to create the model using Keras." }, { "code": null, "e": 83334, "s": 83286, "text": "The core features of the model are as follows −" }, { "code": null, "e": 83386, "s": 83334, "text": "Input layer consists of 784 values (28 x 28 = 784)." }, { "code": null, "e": 83438, "s": 83386, "text": "Input layer consists of 784 values (28 x 28 = 784)." }, { "code": null, "e": 83520, "s": 83438, "text": "First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 83602, "s": 83520, "text": "First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 83653, "s": 83602, "text": "Second hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 83704, "s": 83653, "text": "Second hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 83792, "s": 83704, "text": "Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 83880, "s": 83792, "text": "Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 83931, "s": 83880, "text": "Fourth hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 83982, "s": 83931, "text": "Fourth hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 84062, "s": 83982, "text": "Fifth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 84142, "s": 84062, "text": "Fifth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 84189, "s": 84142, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 84236, "s": 84189, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 84264, "s": 84236, "text": "Use RMSprop() as Optimizer." }, { "code": null, "e": 84292, "s": 84264, "text": "Use RMSprop() as Optimizer." }, { "code": null, "e": 84317, "s": 84292, "text": "Use accuracy as metrics." }, { "code": null, "e": 84342, "s": 84317, "text": "Use accuracy as metrics." }, { "code": null, "e": 84365, "s": 84342, "text": "Use 128 as batch size." }, { "code": null, "e": 84388, "s": 84365, "text": "Use 128 as batch size." }, { "code": null, "e": 84406, "s": 84388, "text": "Use 20 as epochs." }, { "code": null, "e": 84424, "s": 84406, "text": "Use 20 as epochs." }, { "code": null, "e": 84452, "s": 84424, "text": "Step 1 − Import the modules" }, { "code": null, "e": 84489, "s": 84452, "text": "Let us import the necessary modules." }, { "code": null, "e": 84672, "s": 84489, "text": "import keras \nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Dropout \nfrom keras.optimizers import RMSprop \nimport numpy as np" }, { "code": null, "e": 84691, "s": 84672, "text": "Step 2 − Load data" }, { "code": null, "e": 84724, "s": 84691, "text": "Let us import the mnist dataset." }, { "code": null, "e": 84782, "s": 84724, "text": "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n" }, { "code": null, "e": 84808, "s": 84782, "text": "Step 3 − Process the data" }, { "code": null, "e": 84897, "s": 84808, "text": "Let us change the dataset according to our model, so that it can be feed into our model." }, { "code": null, "e": 85176, "s": 84897, "text": "x_train = x_train.reshape(60000, 784) \nx_test = x_test.reshape(10000, 784) \nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32') \nx_train /= 255 \nx_test /= 255 \n\ny_train = keras.utils.to_categorical(y_train, 10) \ny_test = keras.utils.to_categorical(y_test, 10)" }, { "code": null, "e": 85182, "s": 85176, "text": "Where" }, { "code": null, "e": 85250, "s": 85182, "text": "reshape is used to reshape the input from (28, 28) tuple to (784, )" }, { "code": null, "e": 85318, "s": 85250, "text": "reshape is used to reshape the input from (28, 28) tuple to (784, )" }, { "code": null, "e": 85376, "s": 85318, "text": "to_categorical is used to convert vector to binary matrix" }, { "code": null, "e": 85434, "s": 85376, "text": "to_categorical is used to convert vector to binary matrix" }, { "code": null, "e": 85460, "s": 85434, "text": "Step 4 − Create the model" }, { "code": null, "e": 85492, "s": 85460, "text": "Let us create the actual model." }, { "code": null, "e": 85718, "s": 85492, "text": "model = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu'))\nmodel.add(Dropout(0.2)) \nmodel.add(Dense(10, activation = 'softmax'))" }, { "code": null, "e": 85745, "s": 85718, "text": "Step 5 − Compile the model" }, { "code": null, "e": 85823, "s": 85745, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 85931, "s": 85823, "text": "model.compile(loss = 'categorical_crossentropy', \n optimizer = RMSprop(), \n metrics = ['accuracy'])" }, { "code": null, "e": 85956, "s": 85931, "text": "Step 6 − Train the model" }, { "code": null, "e": 85999, "s": 85956, "text": "Let us train the model using fit() method." }, { "code": null, "e": 86138, "s": 85999, "text": "history = model.fit(\n x_train, y_train, \n batch_size = 128, \n epochs = 20, \n verbose = 1, \n validation_data = (x_test, y_test)\n)" }, { "code": null, "e": 86331, "s": 86138, "text": "We have created the model, loaded the data and also trained the data to the model. We still need to evaluate the model and predict output for unknown input, which we learn in upcoming chapter." }, { "code": null, "e": 87308, "s": 86331, "text": "import keras \nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Dropout \nfrom keras.optimizers import RMSprop \nimport numpy as np \n\n(x_train, y_train), (x_test, y_test) = mnist.load_data() \n\nx_train = x_train.reshape(60000, 784) \nx_test = x_test.reshape(10000, 784) \nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32') \nx_train /= 255 \nx_test /= 255 \n\ny_train = keras.utils.to_categorical(y_train, 10) \ny_test = keras.utils.to_categorical(y_test, 10) \n\nmodel = Sequential() \nmodel.add(Dense(512, activation='relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) \nmodel.add(Dense(10, activation = 'softmax'))\nmodel.compile(loss = 'categorical_crossentropy', \n optimizer = RMSprop(), \n metrics = ['accuracy']) \n\nhistory = model.fit(x_train, y_train, \n batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test))" }, { "code": null, "e": 87374, "s": 87308, "text": "Executing the application will give the below content as output −" }, { "code": null, "e": 90234, "s": 87374, "text": "Train on 60000 samples, validate on 10000 samples Epoch 1/20 \n60000/60000 [==============================] - 7s 118us/step - loss: 0.2453 \n- acc: 0.9236 - val_loss: 0.1004 - val_acc: 0.9675 Epoch 2/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.1023 \n- acc: 0.9693 - val_loss: 0.0797 - val_acc: 0.9761 Epoch 3/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.0744 \n- acc: 0.9770 - val_loss: 0.0727 - val_acc: 0.9791 Epoch 4/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.0599 \n- acc: 0.9823 - val_loss: 0.0704 - val_acc: 0.9801 Epoch 5/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0504 \n- acc: 0.9853 - val_loss: 0.0714 - val_acc: 0.9817 Epoch 6/20 \n60000/60000 [==============================] - 7s 111us/step - loss: 0.0438 \n- acc: 0.9868 - val_loss: 0.0845 - val_acc: 0.9809 Epoch 7/20 \n60000/60000 [==============================] - 7s 114us/step - loss: 0.0391 \n- acc: 0.9887 - val_loss: 0.0823 - val_acc: 0.9802 Epoch 8/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0364 \n- acc: 0.9892 - val_loss: 0.0818 - val_acc: 0.9830 Epoch 9/20 \n60000/60000 [==============================] - 7s 113us/step - loss: 0.0308 \n- acc: 0.9905 - val_loss: 0.0833 - val_acc: 0.9829 Epoch 10/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0289 \n- acc: 0.9917 - val_loss: 0.0947 - val_acc: 0.9815 Epoch 11/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0279 \n- acc: 0.9921 - val_loss: 0.0818 - val_acc: 0.9831 Epoch 12/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0260 \n- acc: 0.9927 - val_loss: 0.0945 - val_acc: 0.9819 Epoch 13/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0257 \n- acc: 0.9931 - val_loss: 0.0952 - val_acc: 0.9836 Epoch 14/20\n60000/60000 [==============================] - 7s 112us/step - loss: 0.0229 \n- acc: 0.9937 - val_loss: 0.0924 - val_acc: 0.9832 Epoch 15/20 \n60000/60000 [==============================] - 7s 115us/step - loss: 0.0235 \n- acc: 0.9937 - val_loss: 0.1004 - val_acc: 0.9823 Epoch 16/20 \n60000/60000 [==============================] - 7s 113us/step - loss: 0.0214 \n- acc: 0.9941 - val_loss: 0.0991 - val_acc: 0.9847 Epoch 17/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0219 \n- acc: 0.9943 - val_loss: 0.1044 - val_acc: 0.9837 Epoch 18/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0190 \n- acc: 0.9952 - val_loss: 0.1129 - val_acc: 0.9836 Epoch 19/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0197 \n- acc: 0.9953 - val_loss: 0.0981 - val_acc: 0.9841 Epoch 20/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0198 \n- acc: 0.9950 - val_loss: 0.1215 - val_acc: 0.9828" }, { "code": null, "e": 90310, "s": 90234, "text": "This chapter deals with the model evaluation and model prediction in Keras." }, { "code": null, "e": 90362, "s": 90310, "text": "Let us begin by understanding the model evaluation." }, { "code": null, "e": 90614, "s": 90362, "text": "Evaluation is a process during development of the model to check whether the model is best fit for the given problem and corresponding data. Keras model provides a function, evaluate which does the evaluation of the model. It has three main arguments," }, { "code": null, "e": 90624, "s": 90614, "text": "Test data" }, { "code": null, "e": 90640, "s": 90624, "text": "Test data label" }, { "code": null, "e": 90664, "s": 90640, "text": "verbose - true or false" }, { "code": null, "e": 90749, "s": 90664, "text": "Let us evaluate the model, which we created in the previous chapter using test data." }, { "code": null, "e": 90868, "s": 90749, "text": "score = model.evaluate(x_test, y_test, verbose = 0) \n\nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])" }, { "code": null, "e": 90928, "s": 90868, "text": "Executing the above code will output the below information." }, { "code": null, "e": 90931, "s": 90928, "text": "0\n" }, { "code": null, "e": 91088, "s": 90931, "text": "The test accuracy is 98.28%. We have created a best model to identify the handwriting digits. On the positive side, we can still scope to improve our model." }, { "code": null, "e": 91295, "s": 91088, "text": "Prediction is the final step and our expected outcome of the model generation. Keras provides a method, predict to get the prediction of the trained model. The signature of the predict method is as follows," }, { "code": null, "e": 91466, "s": 91295, "text": "predict(\n x, \n batch_size = None, \n verbose = 0, \n steps = None, \n callbacks = None, \n max_queue_size = 10, \n workers = 1, \n use_multiprocessing = False\n)" }, { "code": null, "e": 91624, "s": 91466, "text": "Here, all arguments are optional except the first argument, which refers the unknown input data. The shape should be maintained to get the proper prediction." }, { "code": null, "e": 91710, "s": 91624, "text": "Let us do prediction for our MPL model created in previous chapter using below code −" }, { "code": null, "e": 91845, "s": 91710, "text": "pred = model.predict(x_test) \npred = np.argmax(pred, axis = 1)[:5] \nlabel = np.argmax(y_test,axis = 1)[:5] \n\nprint(pred) \nprint(label)" }, { "code": null, "e": 91851, "s": 91845, "text": "Here," }, { "code": null, "e": 91901, "s": 91851, "text": "Line 1 call the predict function using test data." }, { "code": null, "e": 91951, "s": 91901, "text": "Line 1 call the predict function using test data." }, { "code": null, "e": 91989, "s": 91951, "text": "Line 2 gets the first five prediction" }, { "code": null, "e": 92027, "s": 91989, "text": "Line 2 gets the first five prediction" }, { "code": null, "e": 92079, "s": 92027, "text": "Line 3 gets the first five labels of the test data." }, { "code": null, "e": 92131, "s": 92079, "text": "Line 3 gets the first five labels of the test data." }, { "code": null, "e": 92182, "s": 92131, "text": "Line 5 - 6 prints the prediction and actual label." }, { "code": null, "e": 92233, "s": 92182, "text": "Line 5 - 6 prints the prediction and actual label." }, { "code": null, "e": 92285, "s": 92233, "text": "The output of the above application is as follows −" }, { "code": null, "e": 92311, "s": 92285, "text": "[7 2 1 0 4] \n[7 2 1 0 4]\n" }, { "code": null, "e": 92422, "s": 92311, "text": "The output of both array is identical and it indicate that our model predicts correctly the first five images." }, { "code": null, "e": 92537, "s": 92422, "text": "Let us modify the model from MPL to Convolution Neural Network (CNN) for our earlier digit identification problem." }, { "code": null, "e": 92571, "s": 92537, "text": "CNN can be represented as below −" }, { "code": null, "e": 92619, "s": 92571, "text": "The core features of the model are as follows −" }, { "code": null, "e": 92662, "s": 92619, "text": "Input layer consists of (1, 8, 28) values." }, { "code": null, "e": 92705, "s": 92662, "text": "Input layer consists of (1, 8, 28) values." }, { "code": null, "e": 92804, "s": 92705, "text": "First layer, Conv2D consists of 32 filters and ‘relu’ activation function with kernel size, (3,3)." }, { "code": null, "e": 92903, "s": 92804, "text": "First layer, Conv2D consists of 32 filters and ‘relu’ activation function with kernel size, (3,3)." }, { "code": null, "e": 93003, "s": 92903, "text": "Second layer, Conv2D consists of 64 filters and ‘relu’ activation function with kernel size, (3,3)." }, { "code": null, "e": 93103, "s": 93003, "text": "Second layer, Conv2D consists of 64 filters and ‘relu’ activation function with kernel size, (3,3)." }, { "code": null, "e": 93152, "s": 93103, "text": "Thrid layer, MaxPooling has pool size of (2, 2)." }, { "code": null, "e": 93201, "s": 93152, "text": "Thrid layer, MaxPooling has pool size of (2, 2)." }, { "code": null, "e": 93278, "s": 93201, "text": "Fifth layer, Flatten is used to flatten all its input into single dimension." }, { "code": null, "e": 93355, "s": 93278, "text": "Fifth layer, Flatten is used to flatten all its input into single dimension." }, { "code": null, "e": 93430, "s": 93355, "text": "Sixth layer, Dense consists of 128 neurons and ‘relu’ activation function." }, { "code": null, "e": 93505, "s": 93430, "text": "Sixth layer, Dense consists of 128 neurons and ‘relu’ activation function." }, { "code": null, "e": 93550, "s": 93505, "text": "Seventh layer, Dropout has 0.5 as its value." }, { "code": null, "e": 93595, "s": 93550, "text": "Seventh layer, Dropout has 0.5 as its value." }, { "code": null, "e": 93676, "s": 93595, "text": "Eighth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 93757, "s": 93676, "text": "Eighth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 93804, "s": 93757, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 93851, "s": 93804, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 93880, "s": 93851, "text": "Use Adadelta() as Optimizer." }, { "code": null, "e": 93909, "s": 93880, "text": "Use Adadelta() as Optimizer." }, { "code": null, "e": 93934, "s": 93909, "text": "Use accuracy as metrics." }, { "code": null, "e": 93959, "s": 93934, "text": "Use accuracy as metrics." }, { "code": null, "e": 93982, "s": 93959, "text": "Use 128 as batch size." }, { "code": null, "e": 94005, "s": 93982, "text": "Use 128 as batch size." }, { "code": null, "e": 94023, "s": 94005, "text": "Use 20 as epochs." }, { "code": null, "e": 94041, "s": 94023, "text": "Use 20 as epochs." }, { "code": null, "e": 94069, "s": 94041, "text": "Step 1 − Import the modules" }, { "code": null, "e": 94106, "s": 94069, "text": "Let us import the necessary modules." }, { "code": null, "e": 94339, "s": 94106, "text": "import keras \nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Dropout, Flatten \nfrom keras.layers import Conv2D, MaxPooling2D \nfrom keras import backend as K \nimport numpy as np" }, { "code": null, "e": 94358, "s": 94339, "text": "Step 2 − Load data" }, { "code": null, "e": 94391, "s": 94358, "text": "Let us import the mnist dataset." }, { "code": null, "e": 94449, "s": 94391, "text": "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n" }, { "code": null, "e": 94475, "s": 94449, "text": "Step 3 − Process the data" }, { "code": null, "e": 94564, "s": 94475, "text": "Let us change the dataset according to our model, so that it can be feed into our model." }, { "code": null, "e": 95217, "s": 94564, "text": "img_rows, img_cols = 28, 28 \n\nif K.image_data_format() == 'channels_first': \n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) \n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) \n input_shape = (1, img_rows, img_cols) \nelse: \n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) \n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) \n input_shape = (img_rows, img_cols, 1) \n \nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32') \nx_train /= 255 \nx_test /= 255 \n\ny_train = keras.utils.to_categorical(y_train, 10) \ny_test = keras.utils.to_categorical(y_test, 10)" }, { "code": null, "e": 95328, "s": 95217, "text": "The data processing is similar to MPL model except the shape of the input data and image format configuration." }, { "code": null, "e": 95354, "s": 95328, "text": "Step 4 − Create the model" }, { "code": null, "e": 95386, "s": 95354, "text": "Let us create tha actual model." }, { "code": null, "e": 95764, "s": 95386, "text": "model = Sequential() \nmodel.add(Conv2D(32, kernel_size = (3, 3), \n activation = 'relu', input_shape = input_shape)) \nmodel.add(Conv2D(64, (3, 3), activation = 'relu')) \nmodel.add(MaxPooling2D(pool_size = (2, 2))) \nmodel.add(Dropout(0.25)) model.add(Flatten()) \nmodel.add(Dense(128, activation = 'relu')) \nmodel.add(Dropout(0.5)) \nmodel.add(Dense(10, activation = 'softmax'))" }, { "code": null, "e": 95791, "s": 95764, "text": "Step 5 − Compile the model" }, { "code": null, "e": 95869, "s": 95791, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 95998, "s": 95869, "text": "model.compile(loss = keras.losses.categorical_crossentropy, \n optimizer = keras.optimizers.Adadelta(), metrics = ['accuracy'])" }, { "code": null, "e": 96023, "s": 95998, "text": "Step 6 − Train the model" }, { "code": null, "e": 96066, "s": 96023, "text": "Let us train the model using fit() method." }, { "code": null, "e": 96195, "s": 96066, "text": "model.fit(\n x_train, y_train, \n batch_size = 128, \n epochs = 12, \n verbose = 1, \n validation_data = (x_test, y_test)\n)" }, { "code": null, "e": 96257, "s": 96195, "text": "Executing the application will output the below information −" }, { "code": null, "e": 97978, "s": 96257, "text": "Train on 60000 samples, validate on 10000 samples Epoch 1/12 \n60000/60000 [==============================] - 84s 1ms/step - loss: 0.2687 \n- acc: 0.9173 - val_loss: 0.0549 - val_acc: 0.9827 Epoch 2/12 \n60000/60000 [==============================] - 86s 1ms/step - loss: 0.0899 \n- acc: 0.9737 - val_loss: 0.0452 - val_acc: 0.9845 Epoch 3/12 \n60000/60000 [==============================] - 83s 1ms/step - loss: 0.0666 \n- acc: 0.9804 - val_loss: 0.0362 - val_acc: 0.9879 Epoch 4/12 \n60000/60000 [==============================] - 81s 1ms/step - loss: 0.0564 \n- acc: 0.9830 - val_loss: 0.0336 - val_acc: 0.9890 Epoch 5/12 \n60000/60000 [==============================] - 86s 1ms/step - loss: 0.0472 \n- acc: 0.9861 - val_loss: 0.0312 - val_acc: 0.9901 Epoch 6/12 \n60000/60000 [==============================] - 83s 1ms/step - loss: 0.0414 \n- acc: 0.9877 - val_loss: 0.0306 - val_acc: 0.9902 Epoch 7/12 \n60000/60000 [==============================] - 89s 1ms/step - loss: 0.0375 \n-acc: 0.9883 - val_loss: 0.0281 - val_acc: 0.9906 Epoch 8/12 \n60000/60000 [==============================] - 91s 2ms/step - loss: 0.0339 \n- acc: 0.9893 - val_loss: 0.0280 - val_acc: 0.9912 Epoch 9/12 \n60000/60000 [==============================] - 89s 1ms/step - loss: 0.0325 \n- acc: 0.9901 - val_loss: 0.0260 - val_acc: 0.9909 Epoch 10/12 \n60000/60000 [==============================] - 89s 1ms/step - loss: 0.0284 \n- acc: 0.9910 - val_loss: 0.0250 - val_acc: 0.9919 Epoch 11/12 \n60000/60000 [==============================] - 86s 1ms/step - loss: 0.0287 \n- acc: 0.9907 - val_loss: 0.0264 - val_acc: 0.9916 Epoch 12/12 \n60000/60000 [==============================] - 86s 1ms/step - loss: 0.0265 \n- acc: 0.9920 - val_loss: 0.0249 - val_acc: 0.9922\n" }, { "code": null, "e": 98006, "s": 97978, "text": "Step 7 − Evaluate the model" }, { "code": null, "e": 98049, "s": 98006, "text": "Let us evaluate the model using test data." }, { "code": null, "e": 98168, "s": 98049, "text": "score = model.evaluate(x_test, y_test, verbose = 0) \n\nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])" }, { "code": null, "e": 98229, "s": 98168, "text": "Executing the above code will output the below information −" }, { "code": null, "e": 98285, "s": 98229, "text": "Test loss: 0.024936060590433316 \nTest accuracy: 0.9922\n" }, { "code": null, "e": 98379, "s": 98285, "text": "The test accuracy is 99.22%. We have created a best model to identify the handwriting digits." }, { "code": null, "e": 98396, "s": 98379, "text": "Step 8 − Predict" }, { "code": null, "e": 98446, "s": 98396, "text": "Finally, predict the digit from images as below −" }, { "code": null, "e": 98581, "s": 98446, "text": "pred = model.predict(x_test) \npred = np.argmax(pred, axis = 1)[:5] \nlabel = np.argmax(y_test,axis = 1)[:5] \n\nprint(pred) \nprint(label)" }, { "code": null, "e": 98633, "s": 98581, "text": "The output of the above application is as follows −" }, { "code": null, "e": 98659, "s": 98633, "text": "[7 2 1 0 4] \n[7 2 1 0 4]\n" }, { "code": null, "e": 98765, "s": 98659, "text": "The output of both array is identical and it indicate our model correctly predicts the first five images." }, { "code": null, "e": 99039, "s": 98765, "text": "In this chapter, let us write a simple MPL based ANN to do regression prediction. Till now, we have only done the classification based prediction. Now, we will try to predict the next possible value by analyzing the previous (continuous) values and its influencing factors." }, { "code": null, "e": 99088, "s": 99039, "text": "The Regression MPL can be represented as below −" }, { "code": null, "e": 99136, "s": 99088, "text": "The core features of the model are as follows −" }, { "code": null, "e": 99174, "s": 99136, "text": "Input layer consists of (13,) values." }, { "code": null, "e": 99212, "s": 99174, "text": "Input layer consists of (13,) values." }, { "code": null, "e": 99317, "s": 99212, "text": "First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer." }, { "code": null, "e": 99422, "s": 99317, "text": "First layer, Dense consists of 64 units and ‘relu’ activation function with ‘normal’ kernel initializer." }, { "code": null, "e": 99495, "s": 99422, "text": "Second layer, Dense consists of 64 units and ‘relu’ activation function." }, { "code": null, "e": 99568, "s": 99495, "text": "Second layer, Dense consists of 64 units and ‘relu’ activation function." }, { "code": null, "e": 99608, "s": 99568, "text": "Output layer, Dense consists of 1 unit." }, { "code": null, "e": 99648, "s": 99608, "text": "Output layer, Dense consists of 1 unit." }, { "code": null, "e": 99674, "s": 99648, "text": "Use mse as loss function." }, { "code": null, "e": 99700, "s": 99674, "text": "Use mse as loss function." }, { "code": null, "e": 99726, "s": 99700, "text": "Use RMSprop as Optimizer." }, { "code": null, "e": 99752, "s": 99726, "text": "Use RMSprop as Optimizer." }, { "code": null, "e": 99777, "s": 99752, "text": "Use accuracy as metrics." }, { "code": null, "e": 99802, "s": 99777, "text": "Use accuracy as metrics." }, { "code": null, "e": 99825, "s": 99802, "text": "Use 128 as batch size." }, { "code": null, "e": 99848, "s": 99825, "text": "Use 128 as batch size." }, { "code": null, "e": 99867, "s": 99848, "text": "Use 500 as epochs." }, { "code": null, "e": 99886, "s": 99867, "text": "Use 500 as epochs." }, { "code": null, "e": 99914, "s": 99886, "text": "Step 1 − Import the modules" }, { "code": null, "e": 99951, "s": 99914, "text": "Let us import the necessary modules." }, { "code": null, "e": 100234, "s": 99951, "text": "import keras \n\nfrom keras.datasets import boston_housing \nfrom keras.models import Sequential \nfrom keras.layers import Dense \nfrom keras.optimizers import RMSprop \nfrom keras.callbacks import EarlyStopping \nfrom sklearn import preprocessing \nfrom sklearn.preprocessing import scale" }, { "code": null, "e": 100253, "s": 100234, "text": "Step 2 − Load data" }, { "code": null, "e": 100295, "s": 100253, "text": "Let us import the Boston housing dataset." }, { "code": null, "e": 100362, "s": 100295, "text": "(x_train, y_train), (x_test, y_test) = boston_housing.load_data()\n" }, { "code": null, "e": 100368, "s": 100362, "text": "Here," }, { "code": null, "e": 100506, "s": 100368, "text": "boston_housing is a dataset provided by Keras. It represents a collection of housing information in Boston area, each having 13 features." }, { "code": null, "e": 100532, "s": 100506, "text": "Step 3 − Process the data" }, { "code": null, "e": 100662, "s": 100532, "text": "Let us change the dataset according to our model, so that, we can feed into our model. The data can be changed using below code −" }, { "code": null, "e": 100804, "s": 100662, "text": "x_train_scaled = preprocessing.scale(x_train) \nscaler = preprocessing.StandardScaler().fit(x_train) \nx_test_scaled = scaler.transform(x_test)" }, { "code": null, "e": 101181, "s": 100804, "text": "Here, we have normalized the training data using sklearn.preprocessing.scale function. preprocessing.StandardScaler().fit function returns a scalar with the normalized mean and standard deviation of the training data, which we can apply to the test data using scalar.transform function. This will normalize the test data as well with the same setting as that of training data." }, { "code": null, "e": 101207, "s": 101181, "text": "Step 4 − Create the model" }, { "code": null, "e": 101239, "s": 101207, "text": "Let us create the actual model." }, { "code": null, "e": 101418, "s": 101239, "text": "model = Sequential() \nmodel.add(Dense(64, kernel_initializer = 'normal', activation = 'relu',\ninput_shape = (13,))) \nmodel.add(Dense(64, activation = 'relu')) model.add(Dense(1))" }, { "code": null, "e": 101445, "s": 101418, "text": "Step 5 − Compile the model" }, { "code": null, "e": 101523, "s": 101445, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 101622, "s": 101523, "text": "model.compile(\n loss = 'mse', \n optimizer = RMSprop(), \n metrics = ['mean_absolute_error']\n)" }, { "code": null, "e": 101647, "s": 101622, "text": "Step 6 − Train the model" }, { "code": null, "e": 101690, "s": 101647, "text": "Let us train the model using fit() method." }, { "code": null, "e": 101896, "s": 101690, "text": "history = model.fit(\n x_train_scaled, y_train, \n batch_size=128, \n epochs = 500, \n verbose = 1, \n validation_split = 0.2, \n callbacks = [EarlyStopping(monitor = 'val_loss', patience = 20)]\n)" }, { "code": null, "e": 102203, "s": 101896, "text": "Here, we have used callback function, EarlyStopping. The purpose of this callback is to monitor the loss value during each epoch and compare it with previous epoch loss value to find the improvement in the training. If there is no improvement for the patience times, then the whole process will be stopped." }, { "code": null, "e": 102273, "s": 102203, "text": "Executing the application will give the below information as output −" }, { "code": null, "e": 103925, "s": 102273, "text": "Train on 323 samples, validate on 81 samples Epoch 1/500 2019-09-24 01:07:03.889046: I \ntensorflow/core/platform/cpu_feature_guard.cc:142] \nYour CPU supports instructions that this \nTensorFlow binary was not co mpiled to use: AVX2 323/323 \n[==============================] - 0s 515us/step - loss: 562.3129 \n- mean_absolute_error: 21.8575 - val_loss: 621.6523 - val_mean_absolute_erro \nr: 23.1730 Epoch 2/500 \n323/323 [==============================] - 0s 11us/step - loss: 545.1666 \n- mean_absolute_error: 21.4887 - val_loss: 605.1341 - val_mean_absolute_error \n: 22.8293 Epoch 3/500 \n323/323 [==============================] - 0s 12us/step - loss: 528.9944 \n- mean_absolute_error: 21.1328 - val_loss: 588.6594 - val_mean_absolute_error \n: 22.4799 Epoch 4/500 \n323/323 [==============================] - 0s 12us/step - loss: 512.2739 \n- mean_absolute_error: 20.7658 - val_loss: 570.3772 - val_mean_absolute_error \n: 22.0853 Epoch 5/500\n323/323 [==============================] - 0s 9us/step - loss: 493.9775 \n- mean_absolute_error: 20.3506 - val_loss: 550.9548 - val_mean_absolute_error: 21.6547 \n.......... \n.......... \n.......... \nEpoch 143/500 \n323/323 [==============================] - 0s 15us/step - loss: 8.1004 \n- mean_absolute_error: 2.0002 - val_loss: 14.6286 - val_mean_absolute_error: \n2. 5904 Epoch 144/500 \n323/323 [==============================] - 0s 19us/step - loss: 8.0300 \n- mean_absolute_error: 1.9683 - val_loss: 14.5949 - val_mean_absolute_error: \n2. 5843 Epoch 145/500 \n323/323 [==============================] - 0s 12us/step - loss: 7.8704 \n- mean_absolute_error: 1.9313 - val_loss: 14.3770 - val_mean_absolute_error: 2. 4996\n" }, { "code": null, "e": 103953, "s": 103925, "text": "Step 7 − Evaluate the model" }, { "code": null, "e": 103996, "s": 103953, "text": "Let us evaluate the model using test data." }, { "code": null, "e": 104121, "s": 103996, "text": "score = model.evaluate(x_test_scaled, y_test, verbose = 0) \nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])" }, { "code": null, "e": 104182, "s": 104121, "text": "Executing the above code will output the below information −" }, { "code": null, "e": 104247, "s": 104182, "text": "Test loss: 21.928471583946077 Test accuracy: 2.9599233234629914\n" }, { "code": null, "e": 104275, "s": 104247, "text": "Step 7 − Evaluate the model" }, { "code": null, "e": 104318, "s": 104275, "text": "Let us evaluate the model using test data." }, { "code": null, "e": 104443, "s": 104318, "text": "score = model.evaluate(x_test_scaled, y_test, verbose = 0) \nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])" }, { "code": null, "e": 104504, "s": 104443, "text": "Executing the above code will output the below information −" }, { "code": null, "e": 104570, "s": 104504, "text": "Test loss: 21.928471583946077 \nTest accuracy: 2.9599233234629914\n" }, { "code": null, "e": 104587, "s": 104570, "text": "Step 8 − Predict" }, { "code": null, "e": 104631, "s": 104587, "text": "Finally, predict using test data as below −" }, { "code": null, "e": 104717, "s": 104631, "text": "prediction = model.predict(x_test_scaled) \nprint(prediction.flatten()) \nprint(y_test)" }, { "code": null, "e": 104769, "s": 104717, "text": "The output of the above application is as follows −" }, { "code": null, "e": 106271, "s": 104769, "text": "[ 7.5612316 17.583357 21.09344 31.859276 25.055613 18.673872 26.600405 22.403967 19.060272 22.264952 \n17.4191 17.00466 15.58924 41.624374 20.220217 18.985565 26.419338 19.837091 19.946192 36.43445 \n12.278508 16.330965 20.701359 14.345301 21.741161 25.050423 31.046402 27.738455 9.959419 20.93039 \n20.069063 14.518344 33.20235 24.735163 18.7274 9.148898 15.781284 18.556862 18.692865 26.045074 \n27.954073 28.106823 15.272034 40.879818 29.33896 23.714525 26.427515 16.483374 22.518442 22.425386 \n33.94826 18.831465 13.2501955 15.537227 34.639984 27.468002 13.474407 48.134598 34.39617 \n22.8503124.042334 17.747198 14.7837715 18.187277 23.655672 22.364983 13.858193 22.710032 14.371148 \n7.1272087 35.960033 28.247292 25.3014 14.477208 25.306196 17.891165 20.193708 23.585173 34.690193 \n12.200583 20.102983 38.45882 14.741723 14.408362 17.67158 18.418497 21.151712 21.157492 22.693687 \n29.809034 19.366991 20.072294 25.880817 40.814568 34.64087 19.43741 36.2591 50.73806 26.968863 43.91787 \n32.54908 20.248306 ] [ 7.2 18.8 19. 27. 22.2 24.5 31.2 22.9 20.5 23.2 18.6 14.5 17.8 50. 20.8 24.3 24.2 \n19.8 19.1 22.7 12. 10.2 20. 18.5 20.9 23. 27.5 30.1 9.5 22. 21.2 14.1 33.1 23.4 20.1 7.4 15.4 23.8 20.1 \n24.5 33. 28.4 14.1 46.7 32.5 29.6 28.4 19.8 20.2 25. 35.4 20.3 9.7 14.5 34.9 26.6 7.2 50. 32.4 21.6 29.8 \n13.1 27.5 21.2 23.1 21.9 13. 23.2 8.1 5.6 21.7 29.6 19.6 7. 26.4 18.9 20.9 28.1 35.4 10.2 24.3 43.1 17.6 \n15.4 16.2 27.1 21.4 21.5 22.4 25. 16.6 18.6 22. 42.8 35.1 21.5 36. 21.9 24.1 50. 26.7 25. ]\n" }, { "code": null, "e": 106384, "s": 106271, "text": "The output of both array have around 10-30% difference and it indicate our model predicts with reasonable range." }, { "code": null, "e": 106867, "s": 106384, "text": "In this chapter, let us write a simple Long Short Term Memory (LSTM) based RNN to do sequence analysis. A sequence is a set of values where each value corresponds to a particular instance of time. Let us consider a simple example of reading a sentence. Reading and understanding a sentence involves reading the word in the given order and trying to understand each word and its meaning in the given context and finally understanding the sentence in a positive or negative sentiment." }, { "code": null, "e": 107160, "s": 106867, "text": "Here, the words are considered as values, and first value corresponds to first word, second value corresponds to second word, etc., and the order will be strictly maintained. Sequence Analysis is used frequently in natural language processing to find the sentiment analysis of the given text." }, { "code": null, "e": 107263, "s": 107160, "text": "Let us create a LSTM model to analyze the IMDB movie reviews and find its positive/negative sentiment." }, { "code": null, "e": 107329, "s": 107263, "text": "The model for the sequence analysis can be represented as below −" }, { "code": null, "e": 107377, "s": 107329, "text": "The core features of the model are as follows −" }, { "code": null, "e": 107430, "s": 107377, "text": "Input layer using Embedding layer with 128 features." }, { "code": null, "e": 107483, "s": 107430, "text": "Input layer using Embedding layer with 128 features." }, { "code": null, "e": 107578, "s": 107483, "text": "First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2." }, { "code": null, "e": 107673, "s": 107578, "text": "First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2." }, { "code": null, "e": 107747, "s": 107673, "text": "Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function." }, { "code": null, "e": 107821, "s": 107747, "text": "Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function." }, { "code": null, "e": 107863, "s": 107821, "text": "Use binary_crossentropy as loss function." }, { "code": null, "e": 107905, "s": 107863, "text": "Use binary_crossentropy as loss function." }, { "code": null, "e": 107928, "s": 107905, "text": "Use adam as Optimizer." }, { "code": null, "e": 107951, "s": 107928, "text": "Use adam as Optimizer." }, { "code": null, "e": 107976, "s": 107951, "text": "Use accuracy as metrics." }, { "code": null, "e": 108001, "s": 107976, "text": "Use accuracy as metrics." }, { "code": null, "e": 108023, "s": 108001, "text": "Use 32 as batch size." }, { "code": null, "e": 108045, "s": 108023, "text": "Use 32 as batch size." }, { "code": null, "e": 108063, "s": 108045, "text": "Use 15 as epochs." }, { "code": null, "e": 108081, "s": 108063, "text": "Use 15 as epochs." }, { "code": null, "e": 108123, "s": 108081, "text": "Use 80 as the maximum length of the word." }, { "code": null, "e": 108165, "s": 108123, "text": "Use 80 as the maximum length of the word." }, { "code": null, "e": 108225, "s": 108165, "text": "Use 2000 as the maximum number of word in a given sentence." }, { "code": null, "e": 108285, "s": 108225, "text": "Use 2000 as the maximum number of word in a given sentence." }, { "code": null, "e": 108322, "s": 108285, "text": "Let us import the necessary modules." }, { "code": null, "e": 108507, "s": 108322, "text": "from keras.preprocessing import sequence \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Embedding \nfrom keras.layers import LSTM \nfrom keras.datasets import imdb" }, { "code": null, "e": 108539, "s": 108507, "text": "Let us import the imdb dataset." }, { "code": null, "e": 108612, "s": 108539, "text": "(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = 2000)\n" }, { "code": null, "e": 108618, "s": 108612, "text": "Here," }, { "code": null, "e": 108709, "s": 108618, "text": "imdb is a dataset provided by Keras. It represents a collection of movies and its reviews." }, { "code": null, "e": 108800, "s": 108709, "text": "imdb is a dataset provided by Keras. It represents a collection of movies and its reviews." }, { "code": null, "e": 108863, "s": 108800, "text": "num_words represent the maximum number of words in the review." }, { "code": null, "e": 108926, "s": 108863, "text": "num_words represent the maximum number of words in the review." }, { "code": null, "e": 109061, "s": 108926, "text": "Let us change the dataset according to our model, so that it can be fed into our model. The data can be changed using the below code −" }, { "code": null, "e": 109166, "s": 109061, "text": "x_train = sequence.pad_sequences(x_train, maxlen=80) \nx_test = sequence.pad_sequences(x_test, maxlen=80)" }, { "code": null, "e": 109172, "s": 109166, "text": "Here," }, { "code": null, "e": 109397, "s": 109172, "text": "sequence.pad_sequences convert the list of input data with shape, (data) into 2D NumPy array of shape (data, timesteps). Basically, it adds timesteps concept into the given data. It generates the timesteps of length, maxlen." }, { "code": null, "e": 109429, "s": 109397, "text": "Let us create the actual model." }, { "code": null, "e": 109590, "s": 109429, "text": "model = Sequential() \nmodel.add(Embedding(2000, 128)) \nmodel.add(LSTM(128, dropout = 0.2, recurrent_dropout = 0.2)) \nmodel.add(Dense(1, activation = 'sigmoid'))" }, { "code": null, "e": 109596, "s": 109590, "text": "Here," }, { "code": null, "e": 109719, "s": 109596, "text": "We have used Embedding layer as input layer and then added the LSTM layer. Finally, a Dense layer is used as output layer." }, { "code": null, "e": 109797, "s": 109719, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 109889, "s": 109797, "text": "model.compile(loss = 'binary_crossentropy', \n optimizer = 'adam', metrics = ['accuracy'])" }, { "code": null, "e": 109933, "s": 109889, "text": "LLet us train the model using fit() method." }, { "code": null, "e": 110044, "s": 109933, "text": "model.fit(\n x_train, y_train, \n batch_size = 32, \n epochs = 15, \n validation_data = (x_test, y_test)\n)" }, { "code": null, "e": 110106, "s": 110044, "text": "Executing the application will output the below information −" }, { "code": null, "e": 112436, "s": 110106, "text": "Epoch 1/15 2019-09-24 01:19:01.151247: I \ntensorflow/core/platform/cpu_feature_guard.cc:142] \nYour CPU supports instructions that this \nTensorFlow binary was not co mpiled to use: AVX2 \n25000/25000 [==============================] - 101s 4ms/step - loss: 0.4707 \n- acc: 0.7716 - val_loss: 0.3769 - val_acc: 0.8349 Epoch 2/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.3058 \n- acc: 0.8756 - val_loss: 0.3763 - val_acc: 0.8350 Epoch 3/15 \n25000/25000 [==============================] - 91s 4ms/step - loss: 0.2100 \n- acc: 0.9178 - val_loss: 0.5065 - val_acc: 0.8110 Epoch 4/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.1394 \n- acc: 0.9495 - val_loss: 0.6046 - val_acc: 0.8146 Epoch 5/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.0973 \n- acc: 0.9652 - val_loss: 0.5969 - val_acc: 0.8147 Epoch 6/15 \n25000/25000 [==============================] - 98s 4ms/step - loss: 0.0759 \n- acc: 0.9730 - val_loss: 0.6368 - val_acc: 0.8208 Epoch 7/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.0578 \n- acc: 0.9811 - val_loss: 0.6657 - val_acc: 0.8184 Epoch 8/15 \n25000/25000 [==============================] - 97s 4ms/step - loss: 0.0448 \n- acc: 0.9850 - val_loss: 0.7452 - val_acc: 0.8136 Epoch 9/15 \n25000/25000 [==============================] - 95s 4ms/step - loss: 0.0324 \n- acc: 0.9894 - val_loss: 0.7616 - val_acc: 0.8162Epoch 10/15 \n25000/25000 [==============================] - 100s 4ms/step - loss: 0.0247 \n- acc: 0.9922 - val_loss: 0.9654 - val_acc: 0.8148 Epoch 11/15 \n25000/25000 [==============================] - 99s 4ms/step - loss: 0.0169 \n- acc: 0.9946 - val_loss: 1.0013 - val_acc: 0.8104 Epoch 12/15 \n25000/25000 [==============================] - 90s 4ms/step - loss: 0.0154 \n- acc: 0.9948 - val_loss: 1.0316 - val_acc: 0.8100 Epoch 13/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0113 \n- acc: 0.9963 - val_loss: 1.1138 - val_acc: 0.8108 Epoch 14/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0106 \n- acc: 0.9971 - val_loss: 1.0538 - val_acc: 0.8102 Epoch 15/15 \n25000/25000 [==============================] - 89s 4ms/step - loss: 0.0090 \n- acc: 0.9972 - val_loss: 1.1453 - val_acc: 0.8129 \n25000/25000 [==============================] - 10s 390us/step\n" }, { "code": null, "e": 112479, "s": 112436, "text": "Let us evaluate the model using test data." }, { "code": null, "e": 112603, "s": 112479, "text": "score, acc = model.evaluate(x_test, y_test, batch_size = 32) \n \nprint('Test score:', score) \nprint('Test accuracy:', acc)" }, { "code": null, "e": 112664, "s": 112603, "text": "Executing the above code will output the below information −" }, { "code": null, "e": 112719, "s": 112664, "text": "Test score: 1.145306069601178 \nTest accuracy: 0.81292\n" }, { "code": null, "e": 112940, "s": 112719, "text": "Keras applications module is used to provide pre-trained model for deep neural networks. Keras models are used for prediction, feature extraction and fine tuning. This chapter explains about Keras applications in detail." }, { "code": null, "e": 113171, "s": 112940, "text": "Trained model consists of two parts model Architecture and model Weights. Model weights are large file so we have to download and extract the feature from ImageNet database. Some of the popular pre-trained models are listed below," }, { "code": null, "e": 113178, "s": 113171, "text": "ResNet" }, { "code": null, "e": 113184, "s": 113178, "text": "VGG16" }, { "code": null, "e": 113194, "s": 113184, "text": "MobileNet" }, { "code": null, "e": 113212, "s": 113194, "text": "InceptionResNetV2" }, { "code": null, "e": 113224, "s": 113212, "text": "InceptionV3" }, { "code": null, "e": 113291, "s": 113224, "text": "Keras pre-trained models can be easily loaded as specified below −" }, { "code": null, "e": 113735, "s": 113291, "text": "import keras \nimport numpy as np \n\nfrom keras.applications import vgg16, inception_v3, resnet50, mobilenet \n\n#Load the VGG model \nvgg_model = vgg16.VGG16(weights = 'imagenet') \n\n#Load the Inception_V3 model \ninception_model = inception_v3.InceptionV3(weights = 'imagenet') \n\n#Load the ResNet50 model \nresnet_model = resnet50.ResNet50(weights = 'imagenet') \n\n#Load the MobileNet model mobilenet_model = mobilenet.MobileNet(weights = 'imagenet')" }, { "code": null, "e": 113873, "s": 113735, "text": "Once the model is loaded, we can immediately use it for prediction purpose. Let us check each pre-trained model in the upcoming chapters." }, { "code": null, "e": 114010, "s": 113873, "text": "ResNet is a pre-trained model. It is trained using ImageNet. ResNet model weights pre-trained on ImageNet. It has the following syntax −" }, { "code": null, "e": 114186, "s": 114010, "text": "keras.applications.resnet.ResNet50 (\n include_top = True, \n weights = 'imagenet', \n input_tensor = None, \n input_shape = None, \n pooling = None, \n classes = 1000\n)" }, { "code": null, "e": 114192, "s": 114186, "text": "Here," }, { "code": null, "e": 114264, "s": 114192, "text": "include_top refers the fully-connected layer at the top of the network." }, { "code": null, "e": 114336, "s": 114264, "text": "include_top refers the fully-connected layer at the top of the network." }, { "code": null, "e": 114376, "s": 114336, "text": "weights refer pre-training on ImageNet." }, { "code": null, "e": 114416, "s": 114376, "text": "weights refer pre-training on ImageNet." }, { "code": null, "e": 114495, "s": 114416, "text": "input_tensor refers optional Keras tensor to use as image input for the model." }, { "code": null, "e": 114574, "s": 114495, "text": "input_tensor refers optional Keras tensor to use as image input for the model." }, { "code": null, "e": 114665, "s": 114574, "text": "input_shape refers optional shape tuple. The default input size for this model is 224x224." }, { "code": null, "e": 114756, "s": 114665, "text": "input_shape refers optional shape tuple. The default input size for this model is 224x224." }, { "code": null, "e": 114817, "s": 114756, "text": "classes refer optional number of classes to classify images." }, { "code": null, "e": 114878, "s": 114817, "text": "classes refer optional number of classes to classify images." }, { "code": null, "e": 114936, "s": 114878, "text": "Let us understand the model by writing a simple example −" }, { "code": null, "e": 114991, "s": 114936, "text": "Let us load the necessary modules as specified below −" }, { "code": null, "e": 115344, "s": 114991, "text": ">>> import PIL \n>>> from keras.preprocessing.image import load_img \n>>> from keras.preprocessing.image import img_to_array \n>>> from keras.applications.imagenet_utils import decode_predictions \n>>> import matplotlib.pyplot as plt \n>>> import numpy as np \n>>> from keras.applications.resnet50 import ResNet50 \n>>> from keras.applications import resnet50" }, { "code": null, "e": 115401, "s": 115344, "text": "Let us choose an input image, Lotus as specified below −" }, { "code": null, "e": 115689, "s": 115401, "text": ">>> filename = 'banana.jpg' \n>>> ## load an image in PIL format \n>>> original = load_img(filename, target_size = (224, 224)) \n>>> print('PIL image size',original.size)\nPIL image size (224, 224) \n>>> plt.imshow(original) \n<matplotlib.image.AxesImage object at 0x1304756d8> \n>>> plt.show()" }, { "code": null, "e": 115750, "s": 115689, "text": "Here, we have loaded an image (banana.jpg) and displayed it." }, { "code": null, "e": 115872, "s": 115750, "text": "Let us convert our input, Banana into NumPy array, so that it can be passed into the model for the purpose of prediction." }, { "code": null, "e": 116333, "s": 115872, "text": ">>> #convert the PIL image to a numpy array \n>>> numpy_image = img_to_array(original) \n\n>>> plt.imshow(np.uint8(numpy_image)) \n<matplotlib.image.AxesImage object at 0x130475ac8> \n\n>>> print('numpy array size',numpy_image.shape) \nnumpy array size (224, 224, 3) \n\n>>> # Convert the image / images into batch format \n>>> image_batch = np.expand_dims(numpy_image, axis = 0) \n\n>>> print('image batch size', image_batch.shape) \nimage batch size (1, 224, 224, 3)\n>>> " }, { "code": null, "e": 116393, "s": 116333, "text": "Let us feed our input into the model to get the predictions" }, { "code": null, "e": 117215, "s": 116393, "text": ">>> prepare the image for the resnet50 model >>> \n>>> processed_image = resnet50.preprocess_input(image_batch.copy()) \n\n>>> # create resnet model \n>>>resnet_model = resnet50.ResNet50(weights = 'imagenet') \n>>> Downloavding data from https://github.com/fchollet/deep-learning-models/releas\nes/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5 \n102858752/102853048 [==============================] - 33s 0us/step \n\n>>> # get the predicted probabilities for each class \n>>> predictions = resnet_model.predict(processed_image) \n\n>>> # convert the probabilities to class labels \n>>> label = decode_predictions(predictions) \nDownloading data from https://storage.googleapis.com/download.tensorflow.org/\ndata/imagenet_class_index.json \n40960/35363 [==================================] - 0s 0us/step \n\n>>> print(label)" }, { "code": null, "e": 117457, "s": 117215, "text": "[\n [\n ('n07753592', 'banana', 0.99229723), \n ('n03532672', 'hook', 0.0014551596), \n ('n03970156', 'plunger', 0.0010738898), \n ('n07753113', 'fig', 0.0009359837) , \n ('n03109150', 'corkscrew', 0.00028538404)\n ]\n]\n" }, { "code": null, "e": 117515, "s": 117457, "text": "Here, the model predicted the images as banana correctly." }, { "code": null, "e": 117610, "s": 117515, "text": "In this chapter, we will learn about the pre-trained models in Keras. Let us begin with VGG16." }, { "code": null, "e": 117726, "s": 117610, "text": "VGG16 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows −" }, { "code": null, "e": 117897, "s": 117726, "text": "keras.applications.vgg16.VGG16(\n include_top = True, \n weights = 'imagenet', \n input_tensor = None, \n input_shape = None, \n pooling = None, \n classes = 1000\n)" }, { "code": null, "e": 117947, "s": 117897, "text": "The default input size for this model is 224x224." }, { "code": null, "e": 118023, "s": 117947, "text": "MobileNetV2 is another pre-trained model. It is also trained uing ImageNet." }, { "code": null, "e": 118068, "s": 118023, "text": "The syntax to load the model is as follows −" }, { "code": null, "e": 118270, "s": 118068, "text": "keras.applications.mobilenet_v2.MobileNetV2 (\n input_shape = None, \n alpha = 1.0, \n include_top = True, \n weights = 'imagenet', \n input_tensor = None, \n pooling = None, \n classes = 1000\n)" }, { "code": null, "e": 118276, "s": 118270, "text": "Here," }, { "code": null, "e": 118540, "s": 118276, "text": "alpha controls the width of the network. If the value is below 1, decreases the number of filters in each layer. If the value is above 1, increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer." }, { "code": null, "e": 118590, "s": 118540, "text": "The default input size for this model is 224x224." }, { "code": null, "e": 118718, "s": 118590, "text": "InceptionResNetV2 is another pre-trained model. It is also trained using ImageNet. The syntax to load the model is as follows −" }, { "code": null, "e": 118914, "s": 118718, "text": "keras.applications.inception_resnet_v2.InceptionResNetV2 (\n include_top = True, \n weights = 'imagenet',\n input_tensor = None, \n input_shape = None, \n pooling = None, \n classes = 1000)" }, { "code": null, "e": 119065, "s": 118914, "text": "This model and can be built both with ‘channels_first’ data format (channels, height, width) or ‘channels_last’ data format (height, width, channels)." }, { "code": null, "e": 119115, "s": 119065, "text": "The default input size for this model is 299x299." }, { "code": null, "e": 119236, "s": 119115, "text": "InceptionV3 is another pre-trained model. It is also trained uing ImageNet. The syntax to load the model is as follows −" }, { "code": null, "e": 119422, "s": 119236, "text": "keras.applications.inception_v3.InceptionV3 (\n include_top = True, \n weights = 'imagenet', \n input_tensor = None, \n input_shape = None, \n pooling = None, \n classes = 1000\n)\n" }, { "code": null, "e": 119428, "s": 119422, "text": "Here," }, { "code": null, "e": 119478, "s": 119428, "text": "The default input size for this model is 299x299." }, { "code": null, "e": 119688, "s": 119478, "text": "Keras is very simple, extensible and easy to implement neural network API, which can be used to build deep learning applications with high level abstraction. Keras is an optimal choice for deep leaning models." }, { "code": null, "e": 119722, "s": 119688, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 119739, "s": 119722, "text": " Abhilash Nelson" }, { "code": null, "e": 119772, "s": 119739, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 119794, "s": 119772, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 119827, "s": 119794, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 119849, "s": 119827, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 119882, "s": 119849, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 119904, "s": 119882, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 119937, "s": 119904, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 119959, "s": 119937, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 119992, "s": 119959, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 120003, "s": 119992, "text": " Mike West" }, { "code": null, "e": 120010, "s": 120003, "text": " Print" }, { "code": null, "e": 120021, "s": 120010, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Text shadow with blur effect
[]
basic_string c_str function in C++ STL - GeeksforGeeks
17 Jul, 2018 The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end. Syntax: const CharT* c_str() const Parameter: The function does not accept any parameter. Return Value : The function returns a constant Null terminated pointer to the character array storage of the string. Below is the implementation of the above function: Program 1: // C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std; int main(){ // declare a example string string s1 = "GeeksForGeeks"; // check if the size of the string is same as the // size of character pointer given by c_str if (s1.size() == strlen(s1.c_str())) { cout << "s1.size is equal to strlen(s1.c_str()) " << endl; } else { cout << "s1.size is not equal to strlen(s1.c_str())" << endl; } // print the string printf("%s \n", s1.c_str());} s1.size is equal to strlen(s1.c_str()) GeeksForGeeks Program 2: // C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std; int main(){ // declare a example string string s1 = "Aditya"; // print the characters of the string for (int i = 0; i < s1.length(); i++) { cout << "The " << i + 1 << "th character of string " << s1 << " is " << s1.c_str()[i] << endl; }} The 1th character of string Aditya is A The 2th character of string Aditya is d The 3th character of string Aditya is i The 4th character of string Aditya is t The 5th character of string Aditya is y The 6th character of string Aditya is a CPP-Functions cpp-string STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Destructors in C++
[ { "code": null, "e": 25919, "s": 25891, "text": "\n17 Jul, 2018" }, { "code": null, "e": 26284, "s": 25919, "text": "The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end." }, { "code": null, "e": 26292, "s": 26284, "text": "Syntax:" }, { "code": null, "e": 26320, "s": 26292, "text": "const CharT* c_str() const\n" }, { "code": null, "e": 26375, "s": 26320, "text": "Parameter: The function does not accept any parameter." }, { "code": null, "e": 26492, "s": 26375, "text": "Return Value : The function returns a constant Null terminated pointer to the character array storage of the string." }, { "code": null, "e": 26543, "s": 26492, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 26554, "s": 26543, "text": "Program 1:" }, { "code": "// C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std; int main(){ // declare a example string string s1 = \"GeeksForGeeks\"; // check if the size of the string is same as the // size of character pointer given by c_str if (s1.size() == strlen(s1.c_str())) { cout << \"s1.size is equal to strlen(s1.c_str()) \" << endl; } else { cout << \"s1.size is not equal to strlen(s1.c_str())\" << endl; } // print the string printf(\"%s \\n\", s1.c_str());}", "e": 27111, "s": 26554, "text": null }, { "code": null, "e": 27167, "s": 27111, "text": "s1.size is equal to strlen(s1.c_str()) \nGeeksForGeeks \n" }, { "code": null, "e": 27178, "s": 27167, "text": "Program 2:" }, { "code": "// C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std; int main(){ // declare a example string string s1 = \"Aditya\"; // print the characters of the string for (int i = 0; i < s1.length(); i++) { cout << \"The \" << i + 1 << \"th character of string \" << s1 << \" is \" << s1.c_str()[i] << endl; }}", "e": 27577, "s": 27178, "text": null }, { "code": null, "e": 27819, "s": 27577, "text": "The 1th character of string Aditya is A\nThe 2th character of string Aditya is d\nThe 3th character of string Aditya is i\nThe 4th character of string Aditya is t\nThe 5th character of string Aditya is y\nThe 6th character of string Aditya is a\n\n" }, { "code": null, "e": 27833, "s": 27819, "text": "CPP-Functions" }, { "code": null, "e": 27844, "s": 27833, "text": "cpp-string" }, { "code": null, "e": 27848, "s": 27844, "text": "STL" }, { "code": null, "e": 27852, "s": 27848, "text": "C++" }, { "code": null, "e": 27856, "s": 27852, "text": "STL" }, { "code": null, "e": 27860, "s": 27856, "text": "CPP" }, { "code": null, "e": 27958, "s": 27860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27986, "s": 27958, "text": "Operator Overloading in C++" }, { "code": null, "e": 28006, "s": 27986, "text": "Polymorphism in C++" }, { "code": null, "e": 28039, "s": 28006, "text": "Friend class and function in C++" }, { "code": null, "e": 28063, "s": 28039, "text": "Sorting a vector in C++" }, { "code": null, "e": 28088, "s": 28063, "text": "std::string class in C++" }, { "code": null, "e": 28112, "s": 28088, "text": "Inline Functions in C++" }, { "code": null, "e": 28156, "s": 28112, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28209, "s": 28156, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 28245, "s": 28209, "text": "Convert string to char array in C++" } ]
Python | Pandas Index.dropna() - GeeksforGeeks
12 Jan, 2022 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.dropna() function return Index without NA/NaN values. All the missing values are removed and a new object is returned which does not have any NaN values present in it. Syntax: Index.dropna(how=’any’) Parameters :how : {‘any’, ‘all’}, default ‘any’If the Index is a MultiIndex, drop the value when any or all levels are NaN. Returns : valid : Index Example #1: Use Index.dropna() function to remove all missing values from the given Index containing datetime data. Python3 # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', None, '2014-02-11']) # Print the Indexidx Output : Let’s drop all the NaN values from the Index. Python3 # drop all missing values.idx.dropna(how ='all') Output : As we can see in the output, the Index.dropna() function has removed all the missing values. Example #2: Use Index.dropna() function to delete all the missing values in the Index. Index contains string type data. Python3 # importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', None, 'May', 'Jun', None, 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx Output : Let’s drop all the missing values. Python3 # drop the missing valuesidx.dropna(how ='any') Output :As we can see in the output all missing values of months has been removed. surindertarika1234 Python pandas-indexing Python-pandas Technical Scripter 2018 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 Enumerate() in Python Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python
[ { "code": null, "e": 24786, "s": 24758, "text": "\n12 Jan, 2022" }, { "code": null, "e": 25000, "s": 24786, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25181, "s": 25000, "text": "Pandas Index.dropna() function return Index without NA/NaN values. All the missing values are removed and a new object is returned which does not have any NaN values present in it." }, { "code": null, "e": 25213, "s": 25181, "text": "Syntax: Index.dropna(how=’any’)" }, { "code": null, "e": 25337, "s": 25213, "text": "Parameters :how : {‘any’, ‘all’}, default ‘any’If the Index is a MultiIndex, drop the value when any or all levels are NaN." }, { "code": null, "e": 25361, "s": 25337, "text": "Returns : valid : Index" }, { "code": null, "e": 25477, "s": 25361, "text": "Example #1: Use Index.dropna() function to remove all missing values from the given Index containing datetime data." }, { "code": null, "e": 25485, "s": 25477, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', None, '2014-02-11']) # Print the Indexidx", "e": 25700, "s": 25485, "text": null }, { "code": null, "e": 25709, "s": 25700, "text": "Output :" }, { "code": null, "e": 25755, "s": 25709, "text": "Let’s drop all the NaN values from the Index." }, { "code": null, "e": 25763, "s": 25755, "text": "Python3" }, { "code": "# drop all missing values.idx.dropna(how ='all')", "e": 25812, "s": 25763, "text": null }, { "code": null, "e": 25821, "s": 25812, "text": "Output :" }, { "code": null, "e": 26034, "s": 25821, "text": "As we can see in the output, the Index.dropna() function has removed all the missing values. Example #2: Use Index.dropna() function to delete all the missing values in the Index. Index contains string type data." }, { "code": null, "e": 26042, "s": 26034, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', None, 'May', 'Jun', None, 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) # Print the Indexidx", "e": 26243, "s": 26042, "text": null }, { "code": null, "e": 26252, "s": 26243, "text": "Output :" }, { "code": null, "e": 26287, "s": 26252, "text": "Let’s drop all the missing values." }, { "code": null, "e": 26295, "s": 26287, "text": "Python3" }, { "code": "# drop the missing valuesidx.dropna(how ='any')", "e": 26343, "s": 26295, "text": null }, { "code": null, "e": 26426, "s": 26343, "text": "Output :As we can see in the output all missing values of months has been removed." }, { "code": null, "e": 26445, "s": 26426, "text": "surindertarika1234" }, { "code": null, "e": 26468, "s": 26445, "text": "Python pandas-indexing" }, { "code": null, "e": 26482, "s": 26468, "text": "Python-pandas" }, { "code": null, "e": 26506, "s": 26482, "text": "Technical Scripter 2018" }, { "code": null, "e": 26513, "s": 26506, "text": "Python" }, { "code": null, "e": 26611, "s": 26513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26629, "s": 26611, "text": "Python Dictionary" }, { "code": null, "e": 26664, "s": 26629, "text": "Read a file line by line in Python" }, { "code": null, "e": 26696, "s": 26664, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26738, "s": 26696, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26760, "s": 26738, "text": "Enumerate() in Python" }, { "code": null, "e": 26790, "s": 26760, "text": "Iterate over a list in Python" }, { "code": null, "e": 26816, "s": 26790, "text": "Python String | replace()" }, { "code": null, "e": 26860, "s": 26816, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26897, "s": 26860, "text": "Create a Pandas DataFrame from Lists" } ]
C++ | Inheritance | Question 1 - GeeksforGeeks
28 Jun, 2021 #include<iostream> using namespace std;class Base1 { public: Base1() { cout << " Base1's constructor called" << endl; }}; class Base2 { public: Base2() { cout << "Base2's constructor called" << endl; }}; class Derived: public Base1, public Base2 { public: Derived() { cout << "Derived's constructor called" << endl; }}; int main(){ Derived d; return 0;} (A) Compiler Dependent(B) Base1′s constructor calledBase2′s constructor calledDerived’s constructor called(C) Base2′s constructor calledBase1′s constructor calledDerived’s constructor called(D) Compiler ErrorAnswer: (B)Explanation: When a class inherits from multiple classes, constructors of base classes are called in the same order as they are specified in inheritance.Quiz of this Question C++-Inheritance Inheritance C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C C++ | new and delete | Question 4 C++ | new and delete | Question 1 C++ | References | Question 4 C++ | Virtual Functions | Question 12 C++ | Virtual Functions | Question 2
[ { "code": null, "e": 25597, "s": 25569, "text": "\n28 Jun, 2021" }, { "code": "#include<iostream> using namespace std;class Base1 { public: Base1() { cout << \" Base1's constructor called\" << endl; }}; class Base2 { public: Base2() { cout << \"Base2's constructor called\" << endl; }}; class Derived: public Base1, public Base2 { public: Derived() { cout << \"Derived's constructor called\" << endl; }}; int main(){ Derived d; return 0;}", "e": 25993, "s": 25597, "text": null }, { "code": null, "e": 26387, "s": 25993, "text": "(A) Compiler Dependent(B) Base1′s constructor calledBase2′s constructor calledDerived’s constructor called(C) Base2′s constructor calledBase1′s constructor calledDerived’s constructor called(D) Compiler ErrorAnswer: (B)Explanation: When a class inherits from multiple classes, constructors of base classes are called in the same order as they are specified in inheritance.Quiz of this Question" }, { "code": null, "e": 26403, "s": 26387, "text": "C++-Inheritance" }, { "code": null, "e": 26415, "s": 26403, "text": "Inheritance" }, { "code": null, "e": 26426, "s": 26415, "text": "C Language" }, { "code": null, "e": 26435, "s": 26426, "text": "C++ Quiz" }, { "code": null, "e": 26533, "s": 26435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26555, "s": 26533, "text": "Function Pointer in C" }, { "code": null, "e": 26572, "s": 26555, "text": "Substring in C++" }, { "code": null, "e": 26584, "s": 26572, "text": "fork() in C" }, { "code": null, "e": 26609, "s": 26584, "text": "std::string class in C++" }, { "code": null, "e": 26636, "s": 26609, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 26670, "s": 26636, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 26704, "s": 26670, "text": "C++ | new and delete | Question 1" }, { "code": null, "e": 26734, "s": 26704, "text": "C++ | References | Question 4" }, { "code": null, "e": 26772, "s": 26734, "text": "C++ | Virtual Functions | Question 12" } ]
Lex program to find the Length of a String
30 Apr, 2019 Problem: Write a Lex program to find the Length of a String Explanation:FLEX (Fast Lexical Analyzer Generator) is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Examples: Input: geeksforgeeks Output: length of given string is : 13 Input: geeks Output: length of given string is : 5 Implementation: /*lex program to find the length of a string*/ %{ #include<stdio.h> int length;%} /* Rules Section*/%% [a-z A-Z 0-9]+ {length=yyleng; }%% int main() { yylex(); printf("length of given string is : %d", length); return 0; } Output: Lex program C Programs Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Apr, 2019" }, { "code": null, "e": 113, "s": 53, "text": "Problem: Write a Lex program to find the Length of a String" }, { "code": null, "e": 402, "s": 113, "text": "Explanation:FLEX (Fast Lexical Analyzer Generator) is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language." }, { "code": null, "e": 412, "s": 402, "text": "Examples:" }, { "code": null, "e": 525, "s": 412, "text": "Input: geeksforgeeks\nOutput: length of given string is : 13\n\nInput: geeks\nOutput: length of given string is : 5 " }, { "code": null, "e": 541, "s": 525, "text": "Implementation:" }, { "code": "/*lex program to find the length of a string*/ %{ #include<stdio.h> int length;%} /* Rules Section*/%% [a-z A-Z 0-9]+ {length=yyleng; }%% int main() { yylex(); printf(\"length of given string is : %d\", length); return 0; }", "e": 774, "s": 541, "text": null }, { "code": null, "e": 782, "s": 774, "text": "Output:" }, { "code": null, "e": 794, "s": 782, "text": "Lex program" }, { "code": null, "e": 805, "s": 794, "text": "C Programs" }, { "code": null, "e": 821, "s": 805, "text": "Compiler Design" } ]
Lodash _.difference() Function
12 May, 2021 The _.difference() function is used to remove a single element or the array of elements from the original array. This function works pretty much same as the core function of JavaScript i.e filter. Syntax : _.difference(array, [values]); Parameters: This function accept two parameters as mentioned above and described below: array: It is the array from which different elements are to be removed. values: It is the array of values that are to be removed from the original array. Note: We can use single value or the array of values. But if only single Integer is given then it will not effect the original array. Please install the library before going further using npm install lodash. Below examples illustrate the _.difference() function in Lodash: Example 1: When array of values is given. Javascript // Requiring the lodash librarylet lodash = require("lodash"); // Original arraylet array = ["a", 2, 3]; // Values to be removed from// the original arraylet values = [2, 3]let newArray = lodash.difference(array, values);console.log("Before: ", array); // Printing arrayconsole.log("After: ", newArray); Output: Example 2: When an empty array is given, there will be no change in the origin a array. Javascript // Requiring the lodash librarylet lodash = require("lodash"); // Original arraylet array = ["a", 2, 3]; // Values to be removed from// the original arraylet values = []let newArray = lodash.difference(array, values);console.log("Before: ", array); // Printing arrayconsole.log("After: ", newArray); Output: Note: This function returns the original array if the value array is single value, empty array or object of arrays. simmytarika5 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 225, "s": 28, "text": "The _.difference() function is used to remove a single element or the array of elements from the original array. This function works pretty much same as the core function of JavaScript i.e filter." }, { "code": null, "e": 234, "s": 225, "text": "Syntax :" }, { "code": null, "e": 265, "s": 234, "text": "_.difference(array, [values]);" }, { "code": null, "e": 353, "s": 265, "text": "Parameters: This function accept two parameters as mentioned above and described below:" }, { "code": null, "e": 425, "s": 353, "text": "array: It is the array from which different elements are to be removed." }, { "code": null, "e": 507, "s": 425, "text": "values: It is the array of values that are to be removed from the original array." }, { "code": null, "e": 514, "s": 507, "text": "Note: " }, { "code": null, "e": 642, "s": 514, "text": "We can use single value or the array of values. But if only single Integer is given then it will not effect the original array." }, { "code": null, "e": 716, "s": 642, "text": "Please install the library before going further using npm install lodash." }, { "code": null, "e": 781, "s": 716, "text": "Below examples illustrate the _.difference() function in Lodash:" }, { "code": null, "e": 824, "s": 781, "text": "Example 1: When array of values is given. " }, { "code": null, "e": 835, "s": 824, "text": "Javascript" }, { "code": "// Requiring the lodash librarylet lodash = require(\"lodash\"); // Original arraylet array = [\"a\", 2, 3]; // Values to be removed from// the original arraylet values = [2, 3]let newArray = lodash.difference(array, values);console.log(\"Before: \", array); // Printing arrayconsole.log(\"After: \", newArray);", "e": 1139, "s": 835, "text": null }, { "code": null, "e": 1147, "s": 1139, "text": "Output:" }, { "code": null, "e": 1235, "s": 1147, "text": "Example 2: When an empty array is given, there will be no change in the origin a array." }, { "code": null, "e": 1246, "s": 1235, "text": "Javascript" }, { "code": "// Requiring the lodash librarylet lodash = require(\"lodash\"); // Original arraylet array = [\"a\", 2, 3]; // Values to be removed from// the original arraylet values = []let newArray = lodash.difference(array, values);console.log(\"Before: \", array); // Printing arrayconsole.log(\"After: \", newArray);", "e": 1546, "s": 1246, "text": null }, { "code": null, "e": 1554, "s": 1546, "text": "Output:" }, { "code": null, "e": 1670, "s": 1554, "text": "Note: This function returns the original array if the value array is single value, empty array or object of arrays." }, { "code": null, "e": 1683, "s": 1670, "text": "simmytarika5" }, { "code": null, "e": 1701, "s": 1683, "text": "JavaScript-Lodash" }, { "code": null, "e": 1712, "s": 1701, "text": "JavaScript" }, { "code": null, "e": 1729, "s": 1712, "text": "Web Technologies" }, { "code": null, "e": 1827, "s": 1729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1888, "s": 1827, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1960, "s": 1888, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2000, "s": 1960, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2053, "s": 2000, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2094, "s": 2053, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2127, "s": 2094, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2189, "s": 2127, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2250, "s": 2189, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2300, "s": 2250, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Nested printf (printf inside printf) in C
13 Dec, 2018 Predict the output of the following C program with a printf inside printf. #include<stdio.h> int main(){ int x = 1987; printf("%d", printf("%d", printf("%d", x))); return(0);} Output : 198741 Explanation :1. Firstly, the innermost printf is executed which results in printing 1987 2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces to : printf("%d", printf("%d", 4)); 3. The second printf then prints 4 and returns the total number of digits in 4 i.e 1 (4 is single digit number ). 4. Finally, the whole statement simply reduces to : printf("%d", 1); 5. It simply prints 1 and output will be : Output: 198741 So, when multiple printf’s appear inside another printf, the inner printf prints its output and returns length of the string printed on the screen to the outer printf. This article is contributed by Rishav Raj. 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. C-Input and Output Quiz c-input-output C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2018" }, { "code": null, "e": 127, "s": 52, "text": "Predict the output of the following C program with a printf inside printf." }, { "code": "#include<stdio.h> int main(){ int x = 1987; printf(\"%d\", printf(\"%d\", printf(\"%d\", x))); return(0);}", "e": 236, "s": 127, "text": null }, { "code": null, "e": 245, "s": 236, "text": "Output :" }, { "code": null, "e": 253, "s": 245, "text": "198741\n" }, { "code": null, "e": 342, "s": 253, "text": "Explanation :1. Firstly, the innermost printf is executed which results in printing 1987" }, { "code": null, "e": 506, "s": 342, "text": "2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces to :" }, { "code": "printf(\"%d\", printf(\"%d\", 4));", "e": 537, "s": 506, "text": null }, { "code": null, "e": 651, "s": 537, "text": "3. The second printf then prints 4 and returns the total number of digits in 4 i.e 1 (4 is single digit number )." }, { "code": null, "e": 703, "s": 651, "text": "4. Finally, the whole statement simply reduces to :" }, { "code": "printf(\"%d\", 1);", "e": 720, "s": 703, "text": null }, { "code": null, "e": 763, "s": 720, "text": "5. It simply prints 1 and output will be :" }, { "code": null, "e": 771, "s": 763, "text": "Output:" }, { "code": null, "e": 779, "s": 771, "text": "198741\n" }, { "code": null, "e": 947, "s": 779, "text": "So, when multiple printf’s appear inside another printf, the inner printf prints its output and returns length of the string printed on the screen to the outer printf." }, { "code": null, "e": 1245, "s": 947, "text": "This article is contributed by Rishav Raj. 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": 1370, "s": 1245, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1394, "s": 1370, "text": "C-Input and Output Quiz" }, { "code": null, "e": 1409, "s": 1394, "text": "c-input-output" }, { "code": null, "e": 1420, "s": 1409, "text": "C Language" } ]
Building Tooltip using CSS
02 Jan, 2019 A Tooltip is used to provide interactive textual hints that gives the user an idea about the element when mouse pointer moves over. For Example, in the below image GeeksForGeeks is a button and when user hovers over it, the additional information “A computer Science Portal” pops-up. Positions of Tooltip: Depending on the values set to top, bottom, left and right, Tooltip can be positioned at any degree. There are mainly four position which are widely used while building Tooltips for better representation and for good user experience: Right Tooltip: The Left and Top property of CSS are used to place the tooltip right to the hoverable text. The value of Left should be to set (100+x)% to make it appear to the right of the container element (if x=0 then tooltip will touch the hoverable text) and the value of top should be set to (0+y)% to adjust the distance from top of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; min-width:100px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; left: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip"> GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button> </body></html> Output: Below program illustrate the above approach: <!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; min-width:100px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; left: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip"> GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button> </body></html> Output: Left Tooltip: The Right and Top properties of CSS are used to place the tooltip left to the hoverable text. The value of Right should be to set (100+x)% to make it appear to the left of the container element (if x=0 then tooltip will touch the hoverable text) and the value of top should be set to (0+y)% to adjust the distance from top end of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; right: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip"> GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button> </body></html> Output: Below program illustrate the above approach: <!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; right: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip"> GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button> </body></html> Output: Top Tooltip: The Bottom and Left properties of CSS are used to place the tooltip top to the hoverable text. The value of Bottom should be to set (100+x)% to make it appear to the top of the container element (if x=0 then tooltip will touch the hoverable text) and the value of left should be set to (0+y)% to adjust the distance from left end of the container element.Below programs illustrate the above approach:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style="text-align:center;"> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Below programs illustrate the above approach: <!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style="text-align:center;"> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Bottom Tooltip: The Top and Left properties of CSS are used to place the tooltip bottom to the hoverable text. The value of Top should be to set (100+x)% to make it appear to the bottom of the container element (if x=0 then tooltip will touch the hoverable text) and the value of left should be set to (0+y)% to adjust the distance from left end of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Below program illustrate the above approach: <!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Bottom Arrow: Top and Left are used to place the arrow at the bottom of the tooltip. The value of Top should be to set (100+x)% to make it appear to the bottom of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of left should be set to (0+y)% to adjust the distance from left end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: black transparent transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Program: <!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: black transparent transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Top Arrow: Bottom and Left are used to place the arrow at the top of the tooltip. The value of Bottom should be to set (100+x)% to make it appear to the top of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of left should be set to (0+y)% to adjust the distance from left end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; bottom: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent black transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Program: <!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; bottom: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent black transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Left Arrow: Top and Right are used to place the arrow at the left of the tooltip. The value of Right should be to set (100+x)% to make it appear to the left of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of top should be set to (0+y)% to adjust the distance from top end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; left: 115%; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 50%; right: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent black transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"><br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Program: <!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; left: 115%; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 50%; right: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent black transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style="text-align:center;"><br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Right Arrow: Top and Left are used to place the arrow at the right of the tooltip. The value of Left should be to set (100+x)% to make it appear to the right of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of top should be set to (0+y)% to adjust the distance from top end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html><head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; right: 115%; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 50%; left: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent transparent black; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: Program: <!DOCTYPE html><html><head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; right: 115%; } .gfg_tooltip .gfg_text::after { content: ""; position: absolute; top: 50%; left: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent transparent black; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style="text-align:center;"> <br><br> <button class="gfg_tooltip">GeeksforGeeks <span class="gfg_text"> A Computer science portal </span> </button></body></html> Output: CSS-Misc Picked Technical Scripter 2018 CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? 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? CSS to put icon inside an input element in a form Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jan, 2019" }, { "code": null, "e": 338, "s": 54, "text": "A Tooltip is used to provide interactive textual hints that gives the user an idea about the element when mouse pointer moves over. For Example, in the below image GeeksForGeeks is a button and when user hovers over it, the additional information “A computer Science Portal” pops-up." }, { "code": null, "e": 594, "s": 338, "text": "Positions of Tooltip: Depending on the values set to top, bottom, left and right, Tooltip can be positioned at any degree. There are mainly four position which are widely used while building Tooltips for better representation and for good user experience:" }, { "code": null, "e": 2202, "s": 594, "text": "Right Tooltip: The Left and Top property of CSS are used to place the tooltip right to the hoverable text. The value of Left should be to set (100+x)% to make it appear to the right of the container element (if x=0 then tooltip will touch the hoverable text) and the value of top should be set to (0+y)% to adjust the distance from top of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; min-width:100px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; left: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\"> GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button> </body></html> Output:" }, { "code": null, "e": 2247, "s": 2202, "text": "Below program illustrate the above approach:" }, { "code": "<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; min-width:100px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; left: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\"> GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button> </body></html> ", "e": 3443, "s": 2247, "text": null }, { "code": null, "e": 3451, "s": 3443, "text": "Output:" }, { "code": null, "e": 5046, "s": 3451, "text": "Left Tooltip: The Right and Top properties of CSS are used to place the tooltip left to the hoverable text. The value of Right should be to set (100+x)% to make it appear to the left of the container element (if x=0 then tooltip will touch the hoverable text) and the value of top should be set to (0+y)% to adjust the distance from top end of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; right: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\"> GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button> </body></html> Output:" }, { "code": null, "e": 5091, "s": 5046, "text": "Below program illustrate the above approach:" }, { "code": "<!DOCTYPE html><html> <head> <title>tooltip in CSS</title> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 25%; right: 105%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\"> GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button> </body></html> ", "e": 6269, "s": 5091, "text": null }, { "code": null, "e": 6277, "s": 6269, "text": "Output:" }, { "code": null, "e": 7800, "s": 6277, "text": "Top Tooltip: The Bottom and Left properties of CSS are used to place the tooltip top to the hoverable text. The value of Bottom should be to set (100+x)% to make it appear to the top of the container element (if x=0 then tooltip will touch the hoverable text) and the value of left should be set to (0+y)% to adjust the distance from left end of the container element.Below programs illustrate the above approach:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 7846, "s": 7800, "text": "Below programs illustrate the above approach:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 8949, "s": 7846, "text": null }, { "code": null, "e": 8957, "s": 8949, "text": "Output:" }, { "code": null, "e": 10499, "s": 8957, "text": "Bottom Tooltip: The Top and Left properties of CSS are used to place the tooltip bottom to the hoverable text. The value of Top should be to set (100+x)% to make it appear to the bottom of the container element (if x=0 then tooltip will touch the hoverable text) and the value of left should be set to (0+y)% to adjust the distance from left end of the container element.Below program illustrate the above approach:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 10544, "s": 10499, "text": "Below program illustrate the above approach:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 105%; left: 10%; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 11664, "s": 10544, "text": null }, { "code": null, "e": 11672, "s": 11664, "text": "Output:" }, { "code": null, "e": 13674, "s": 11672, "text": "Bottom Arrow: Top and Left are used to place the arrow at the bottom of the tooltip. The value of Top should be to set (100+x)% to make it appear to the bottom of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of left should be set to (0+y)% to adjust the distance from left end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: black transparent transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 13683, "s": 13674, "text": "Program:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; bottom: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: black transparent transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 15296, "s": 13683, "text": null }, { "code": null, "e": 15304, "s": 15296, "text": "Output:" }, { "code": null, "e": 17303, "s": 15304, "text": "Top Arrow: Bottom and Left are used to place the arrow at the top of the tooltip. The value of Bottom should be to set (100+x)% to make it appear to the top of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of left should be set to (0+y)% to adjust the distance from left end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; bottom: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent black transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 17312, "s": 17303, "text": "Program:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 115%; left: 50%; margin-left: -60px; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; bottom: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent black transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 18925, "s": 17312, "text": null }, { "code": null, "e": 18933, "s": 18925, "text": "Output:" }, { "code": null, "e": 20885, "s": 18933, "text": "Left Arrow: Top and Right are used to place the arrow at the left of the tooltip. The value of Right should be to set (100+x)% to make it appear to the left of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of top should be set to (0+y)% to adjust the distance from top end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; left: 115%; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 50%; right: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent black transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"><br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 20894, "s": 20885, "text": "Program:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; left: 115%; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 50%; right: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent black transparent transparent; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style> </head> <body style=\"text-align:center;\"><br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 22462, "s": 20894, "text": null }, { "code": null, "e": 22470, "s": 22462, "text": "Output:" }, { "code": null, "e": 24203, "s": 22470, "text": "Right Arrow: Top and Left are used to place the arrow at the right of the tooltip. The value of Left should be to set (100+x)% to make it appear to the right of the tooltip (if x=0 then the arrow will touch the tooltip) and the value of top should be set to (0+y)% to adjust the distance from top end of the tooltip (if y=50 then arrow will be in the middle of tooltip).Program:<!DOCTYPE html><html><head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; right: 115%; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 50%; left: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent transparent black; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> Output:" }, { "code": null, "e": 24212, "s": 24203, "text": "Program:" }, { "code": "<!DOCTYPE html><html><head> <style> .gfg_tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; background-color: green; color: black; padding: 15px; text-align: center; display: inline-block; font-size: 16px; } .gfg_tooltip .gfg_text { visibility: hidden; width: 120px; background-color: green; color: black; text-align: center; border-radius: 6px; padding: 5px 0; position: absolute; z-index: 1; top: 5%; right: 115%; } .gfg_tooltip .gfg_text::after { content: \"\"; position: absolute; top: 50%; left: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent transparent black; } .gfg_tooltip:hover .gfg_text { visibility: visible; } </style></head> <body style=\"text-align:center;\"> <br><br> <button class=\"gfg_tooltip\">GeeksforGeeks <span class=\"gfg_text\"> A Computer science portal </span> </button></body></html> ", "e": 25560, "s": 24212, "text": null }, { "code": null, "e": 25568, "s": 25560, "text": "Output:" }, { "code": null, "e": 25577, "s": 25568, "text": "CSS-Misc" }, { "code": null, "e": 25584, "s": 25577, "text": "Picked" }, { "code": null, "e": 25608, "s": 25584, "text": "Technical Scripter 2018" }, { "code": null, "e": 25612, "s": 25608, "text": "CSS" }, { "code": null, "e": 25631, "s": 25612, "text": "Technical Scripter" }, { "code": null, "e": 25648, "s": 25631, "text": "Web Technologies" }, { "code": null, "e": 25746, "s": 25648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25794, "s": 25746, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25856, "s": 25794, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25906, "s": 25856, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25964, "s": 25906, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26014, "s": 25964, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26047, "s": 26014, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26109, "s": 26047, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26170, "s": 26109, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26220, "s": 26170, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
SimpleDateFormat(“hh:mm:ss a”) in Java
The following format displays time from − hh:mm:ss The following format displays time with AM/ PM marker − hh:mm:ss a Here, we are using the SimpleDateFormat class to display date and time. Let us set it for the format we want i.e time and AM/PM Marker − Format f = new SimpleDateFormat("hh:mm:ss a"); String strResult = f.format(new Date()); System.out.println("Time = "+strResult); The following is an example − Live Demo import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { // displaying current date and time Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s zzzz"); System.out.println("Today's date = "+simpleformat.format(cal.getTime())); // current time Format f = new SimpleDateFormat("hh:mm:ss a"); String strResult = f.format(new Date()); System.out.println("Time = "+strResult); // displaying hour f = new SimpleDateFormat("H"); String strHour = f.format(new Date()); System.out.println("Current Hour = "+strHour); // displaying minutes f = new SimpleDateFormat("mm"); String strMinute = f.format(new Date()); System.out.println("Current Minutes = "+strMinute); // displaying seconds f = new SimpleDateFormat("ss"); String strSeconds = f.format(new Date()); System.out.println("Current Seconds = "+strSeconds); } } Today's date = 26/November/2018 08:27:34 Coordinated Universal Time Time = 08:27:34 AM Current Hour = 8 Current Minutes = 27 Current Seconds = 34
[ { "code": null, "e": 1229, "s": 1187, "text": "The following format displays time from −" }, { "code": null, "e": 1238, "s": 1229, "text": "hh:mm:ss" }, { "code": null, "e": 1294, "s": 1238, "text": "The following format displays time with AM/ PM marker −" }, { "code": null, "e": 1305, "s": 1294, "text": "hh:mm:ss a" }, { "code": null, "e": 1442, "s": 1305, "text": "Here, we are using the SimpleDateFormat class to display date and time. Let us set it for the format we want i.e time and AM/PM Marker −" }, { "code": null, "e": 1571, "s": 1442, "text": "Format f = new SimpleDateFormat(\"hh:mm:ss a\");\nString strResult = f.format(new Date());\nSystem.out.println(\"Time = \"+strResult);" }, { "code": null, "e": 1601, "s": 1571, "text": "The following is an example −" }, { "code": null, "e": 1612, "s": 1601, "text": " Live Demo" }, { "code": null, "e": 2739, "s": 1612, "text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy hh:mm:s zzzz\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // current time\n Format f = new SimpleDateFormat(\"hh:mm:ss a\");\n String strResult = f.format(new Date());\n System.out.println(\"Time = \"+strResult);\n // displaying hour\n f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n }\n}" }, { "code": null, "e": 2885, "s": 2739, "text": "Today's date = 26/November/2018 08:27:34 Coordinated Universal Time\nTime = 08:27:34 AM\nCurrent Hour = 8\nCurrent Minutes = 27\nCurrent Seconds = 34" } ]
Initialize Matrix in Python
In this article, we will learn about how we can initialize matrix using two dimensional list in Python 3.x. Or earlier. Let’s see the intuitive way to initialize a matrix that only python language offers. Here we take advantage of List comprehension. we initialise the inner list and then extend to multiple rows using the list comprehension. # input the number of rows N = 3 # input the number of columns M = 3 # initializing the matrix res = [ [ i*j for i in range(N) ] for j in range(M) ] # printing the matrix on screen row by row in a single line print("Inline representation:") [ [ print(res[i][j] ,end =" ") for i in range(N) ] for j in range(M) ] print("") # printing in multiple lines print("Multiline representation") for i in range(N): for j in range(M): print(res[i][j] ,end =" ") print("") Inline representation: 0 0 0 0 1 2 0 2 4 Multiline representation 0 0 0 0 1 2 0 2 4 Now let's see the general way which can be implemented in any language. This is the standard way of creating a matrix or multidimensional-array # input the number of rows N = 3 # input the number of columns M = 3 lis=[[0,0,0],[0,0,0],[0,0,0]] # initializing the matrix for i in range(N): for j in range(M): lis[i][j]=i # multiline representation for i in range(N): for j in range(M): print(lis[i][j],end=" ") print("") 0 0 0 0 1 2 0 2 4 In this article, we learned how to implement logic gates in Python 3.x. Or earlier. We also learned about two universal gates i.e. NAND and NOR gates.
[ { "code": null, "e": 1307, "s": 1187, "text": "In this article, we will learn about how we can initialize matrix using two dimensional list in Python 3.x. Or earlier." }, { "code": null, "e": 1530, "s": 1307, "text": "Let’s see the intuitive way to initialize a matrix that only python language offers. Here we take advantage of List comprehension. we initialise the inner list and then extend to multiple rows using the list comprehension." }, { "code": null, "e": 2003, "s": 1530, "text": "# input the number of rows\nN = 3\n# input the number of columns\nM = 3\n# initializing the matrix\nres = [ [ i*j for i in range(N) ] for j in range(M) ]\n\n# printing the matrix on screen row by row in a single line\nprint(\"Inline representation:\")\n[ [ print(res[i][j] ,end =\" \") for i in range(N) ] for j in range(M) ]\nprint(\"\")\n# printing in multiple lines\nprint(\"Multiline representation\")\nfor i in range(N):\n for j in range(M):\n print(res[i][j] ,end =\" \")\n print(\"\")" }, { "code": null, "e": 2087, "s": 2003, "text": "Inline representation:\n0 0 0 0 1 2 0 2 4\nMultiline representation\n0 0 0\n0 1 2\n0 2 4" }, { "code": null, "e": 2231, "s": 2087, "text": "Now let's see the general way which can be implemented in any language. This is the standard way of creating a matrix or multidimensional-array" }, { "code": null, "e": 2527, "s": 2231, "text": "# input the number of rows\nN = 3\n# input the number of columns\nM = 3\nlis=[[0,0,0],[0,0,0],[0,0,0]]\n# initializing the matrix\nfor i in range(N):\n for j in range(M):\n lis[i][j]=i\n# multiline representation\nfor i in range(N):\n for j in range(M):\n print(lis[i][j],end=\" \")\n print(\"\")" }, { "code": null, "e": 2545, "s": 2527, "text": "0 0 0\n0 1 2\n0 2 4" }, { "code": null, "e": 2696, "s": 2545, "text": "In this article, we learned how to implement logic gates in Python 3.x. Or\nearlier. We also learned about two universal gates i.e. NAND and NOR gates." } ]
PHP program to fetch data from localhost server database using XAMPP
06 Jun, 2022 In this article, we will see how we can display the records by fetching them from the MySQL database using PHP. Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the XAMPP server. XAMPP is a free and open-source cross-platform web server solution stack package developed by Apache which allows a web application to be easily tested on a local web server. Here, we can manually create a relational database and store data in tabular form by going to this link. But to operate on localhost or for storing data first we have to start Apache and MySQL from the XAMPP control panel. Let, for example, the database name is server, the table name is user_info having column name as ID, First Name, Username and Password and we have to fetch the data stored there. So, below is the PHP program whose task is to fetch data. Follow the steps to fetch data from the Database using PHP: 1. Create Database: Create a database using PHPMyAdmin, the database is named “geeksforgeeks” here. You can give any name to your database. create database “geeksforgeeks” 2. Create Table: Create a table named ‘user_info’. The table contains four fields: id – int(11) – primary key – auto increment first_name – varchar(100) last_name – varchar(100) gfg_username – varchar(100) Your table structure should look like this: the table structure of “user_info” Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin. CREATE TABLE IF NOT EXISTS `user_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(100) NOT NULL, `last_name` varchar(100) NOT NULL, `gfg_username` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; To do this from the SQL panel refer to the following screenshot: create a table ‘user_info” from the SQL panel Insert records: We will now insert some records into our table. Here we are inserting 4 records. You can add multiple records. records in our table Copy and paste the following code into the SQL panel to insert records into the table. INSERT INTO `user_info` (`first_name`, `last_name`, `gfg_username`) VALUES ('Rohit', 'Kumar', 'rohitk987'), ('Nisha', 'Jadhav', 'nishajadhav001'), ('Aayush', 'Joshi', 'geeky1aayush'), ('Shweta', 'Pawar', 'shwetap12gfg'); inserting records Creating folder and files: We will now create our project folder named “GeeksforGeeks”. Create index.php and database.php files. Keep your main project folder (for example here.. GeeksforGeeks) in the “C://xampp/htdocs/”, if you are using XAMPP or “C://wamp64/www/” folder if you are using the WAMP server respectively. The folder structure should look like this: folder structure database.php: Code for connection with the database. PHP <?php// this php script is for connecting with database// data has to be fetched from local server // Username is root$user = 'root';$password = ''; // Database name is geeksforgeeks$database = 'geeksforgeeks'; // Server is localhost with// port number 3306$servername='localhost:3306';$mysqli = new mysqli($servername, $user, $password, $database); // Checking for connectionsif (!$mysqli){ echo "Connection Unsuccessful!!!";} ?> index.php: Code for displaying the records. PHP <?php// going to use above coderequire 'database.php'; // printing column name above the dataecho 'ID'.' '.'First Name'.' '.'Last Name'.' '.'GFG Username'.'<br>'; // sql query to fetch all the data$query = "SELECT * FROM `user_info`";// mysql_query will execute the query to fetch dataif ($is_query_run = mysql_query($query)){ // echo "Query Executed"; // loop will iterate until all data is fetched while ($query_executed = mysql_fetch_assoc ($is_query_run)) { // these four line is for four column echo $query_executed['ID'].' '; echo $query_executed['first_ame'].' '; echo $query_executed['last_name'].' '; echo $query_executed['gfg_username'].'<br>'; }}else{ echo "Error in execution!";}?> Output: ID First Name Last Name GFG Username 1 Rohit Kumar rohitk987 2 Nisha Jadhav nishajadhav001 3 Aayush Joshi geeky1aayush 4 Shweta Pawar shwetap12gfg PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. sanjyotpanure GBlog PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge How to Learn Data Science in 10 weeks? What is Hashing | A Complete Tutorial How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to delete an array element based on key in PHP? How to convert array to string in PHP ?
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2022" }, { "code": null, "e": 165, "s": 52, "text": "In this article, we will see how we can display the records by fetching them from the MySQL database using PHP. " }, { "code": null, "e": 303, "s": 165, "text": "Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the XAMPP server." }, { "code": null, "e": 939, "s": 303, "text": "XAMPP is a free and open-source cross-platform web server solution stack package developed by Apache which allows a web application to be easily tested on a local web server. Here, we can manually create a relational database and store data in tabular form by going to this link. But to operate on localhost or for storing data first we have to start Apache and MySQL from the XAMPP control panel. Let, for example, the database name is server, the table name is user_info having column name as ID, First Name, Username and Password and we have to fetch the data stored there. So, below is the PHP program whose task is to fetch data. " }, { "code": null, "e": 999, "s": 939, "text": "Follow the steps to fetch data from the Database using PHP:" }, { "code": null, "e": 1140, "s": 999, "text": "1. Create Database: Create a database using PHPMyAdmin, the database is named “geeksforgeeks” here. You can give any name to your database. " }, { "code": null, "e": 1172, "s": 1140, "text": "create database “geeksforgeeks”" }, { "code": null, "e": 1255, "s": 1172, "text": "2. Create Table: Create a table named ‘user_info’. The table contains four fields:" }, { "code": null, "e": 1299, "s": 1255, "text": "id – int(11) – primary key – auto increment" }, { "code": null, "e": 1325, "s": 1299, "text": "first_name – varchar(100)" }, { "code": null, "e": 1350, "s": 1325, "text": "last_name – varchar(100)" }, { "code": null, "e": 1378, "s": 1350, "text": "gfg_username – varchar(100)" }, { "code": null, "e": 1422, "s": 1378, "text": "Your table structure should look like this:" }, { "code": null, "e": 1457, "s": 1422, "text": "the table structure of “user_info”" }, { "code": null, "e": 1564, "s": 1457, "text": "Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin." }, { "code": null, "e": 1811, "s": 1564, "text": "CREATE TABLE IF NOT EXISTS `user_info` (\n`id` int(11) NOT NULL AUTO_INCREMENT,\n`first_name` varchar(100) NOT NULL,\n`last_name` varchar(100) NOT NULL,\n`gfg_username` varchar(100) NOT NULL,\nPRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;" }, { "code": null, "e": 1876, "s": 1811, "text": "To do this from the SQL panel refer to the following screenshot:" }, { "code": null, "e": 1922, "s": 1876, "text": "create a table ‘user_info” from the SQL panel" }, { "code": null, "e": 2049, "s": 1922, "text": "Insert records: We will now insert some records into our table. Here we are inserting 4 records. You can add multiple records." }, { "code": null, "e": 2070, "s": 2049, "text": "records in our table" }, { "code": null, "e": 2157, "s": 2070, "text": "Copy and paste the following code into the SQL panel to insert records into the table." }, { "code": null, "e": 2379, "s": 2157, "text": "INSERT INTO `user_info` (`first_name`, `last_name`, `gfg_username`) VALUES ('Rohit', 'Kumar', 'rohitk987'), \n('Nisha', 'Jadhav', 'nishajadhav001'), ('Aayush', 'Joshi', 'geeky1aayush'), ('Shweta', 'Pawar', 'shwetap12gfg');" }, { "code": null, "e": 2397, "s": 2379, "text": "inserting records" }, { "code": null, "e": 2424, "s": 2397, "text": "Creating folder and files:" }, { "code": null, "e": 2761, "s": 2424, "text": "We will now create our project folder named “GeeksforGeeks”. Create index.php and database.php files. Keep your main project folder (for example here.. GeeksforGeeks) in the “C://xampp/htdocs/”, if you are using XAMPP or “C://wamp64/www/” folder if you are using the WAMP server respectively. The folder structure should look like this:" }, { "code": null, "e": 2778, "s": 2761, "text": "folder structure" }, { "code": null, "e": 2831, "s": 2778, "text": "database.php: Code for connection with the database." }, { "code": null, "e": 2835, "s": 2831, "text": "PHP" }, { "code": "<?php// this php script is for connecting with database// data has to be fetched from local server // Username is root$user = 'root';$password = ''; // Database name is geeksforgeeks$database = 'geeksforgeeks'; // Server is localhost with// port number 3306$servername='localhost:3306';$mysqli = new mysqli($servername, $user, $password, $database); // Checking for connectionsif (!$mysqli){ echo \"Connection Unsuccessful!!!\";} ?>", "e": 3284, "s": 2835, "text": null }, { "code": null, "e": 3328, "s": 3284, "text": "index.php: Code for displaying the records." }, { "code": null, "e": 3332, "s": 3328, "text": "PHP" }, { "code": "<?php// going to use above coderequire 'database.php'; // printing column name above the dataecho 'ID'.' '.'First Name'.' '.'Last Name'.' '.'GFG Username'.'<br>'; // sql query to fetch all the data$query = \"SELECT * FROM `user_info`\";// mysql_query will execute the query to fetch dataif ($is_query_run = mysql_query($query)){ // echo \"Query Executed\"; // loop will iterate until all data is fetched while ($query_executed = mysql_fetch_assoc ($is_query_run)) { // these four line is for four column echo $query_executed['ID'].' '; echo $query_executed['first_ame'].' '; echo $query_executed['last_name'].' '; echo $query_executed['gfg_username'].'<br>'; }}else{ echo \"Error in execution!\";}?>", "e": 4079, "s": 3332, "text": null }, { "code": null, "e": 4087, "s": 4079, "text": "Output:" }, { "code": null, "e": 4238, "s": 4087, "text": "ID First Name Last Name GFG Username\n1 Rohit Kumar rohitk987\n2 Nisha Jadhav nishajadhav001\n3 Aayush Joshi geeky1aayush\n4 Shweta Pawar shwetap12gfg" }, { "code": null, "e": 4407, "s": 4238, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 4421, "s": 4407, "text": "sanjyotpanure" }, { "code": null, "e": 4427, "s": 4421, "text": "GBlog" }, { "code": null, "e": 4431, "s": 4427, "text": "PHP" }, { "code": null, "e": 4448, "s": 4431, "text": "Web Technologies" }, { "code": null, "e": 4452, "s": 4448, "text": "PHP" }, { "code": null, "e": 4550, "s": 4452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4575, "s": 4550, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 4630, "s": 4575, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 4667, "s": 4630, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 4706, "s": 4667, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 4744, "s": 4706, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 4789, "s": 4744, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 4839, "s": 4789, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4863, "s": 4839, "text": "PHP in_array() Function" }, { "code": null, "e": 4915, "s": 4863, "text": "How to delete an array element based on key in PHP?" } ]
Perl | Operators | Set – 2
14 Jan, 2022 Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set – 1. Remaining operators will be discussed in this article: Quote Like Operators String Manipulation Operators Range Operator Auto Increment & Decrement Operator Arrow Operator In these operators, {} will represent a pair of delimiters that user choose. In this category there are three operators as follows: q{ } : It will encloses a string in single quotes(”) and cannot interpolate the string variable. For Example: q{geek} gives ‘geek’. qq{ }: It will encloses a string in double quotes(“”) and can interpolate the string variable. For Example: qq{geek} gives “geek”. qx{ } : It will encloses a string in invert quotes(“). For Example: qq{geek} gives `geek`. Example: Perl # Perl program to demonstrate the Quote# Like Operators #!/usr/local/bin/perl # taking a string variable$g = "Geek"; # using single quote Operators# this operator will not # interpolate the string variable$r = q{$g}; print "Value of g is = $r\n"; # using double quote Operators# this operator will interpolate# the string variable$r = qq{$g}; print "Value of g is = $r\n"; # Executing unix date command$d = qx{date}; print "Value of qx{date} = $d"; Output: Value of g is = $g Value of g is = Geek Value of qx{date} = Sun Aug 12 14:19:43 UTC 2018 String Manipulation Operators String are scalar variables and start with ($) sign in Perl. The String is defined by the user within a single quote(”) or double quote(“”). There are different types of string operators in Perl, as follows: Concatenation Operator (.) : Perl strings are concatenated with a Dot(.) symbol. The Dot(.) sign is used instead of (+) sign in Perl. Repetition Operator (x): The x operator accepts a string on its left-hand side and a number on its right-hand side. It will return the string on the left-hand side repeated as many times as the value on the right-hand side. Example: Perl # Perl program to demonstrate the# string operators #!/usr/bin/perl # Input first string $first_string = "Geeks"; # Input second string $second_string = "forGeeks"; # Implement Concatenation operator(.) $concat_string = $first_string.$second_string; # displaying concatenation string resultprint "Result of Concatenation Operator = $concat_string\n"; # Input a string $string = "GeeksforGeeks "; # Using Repetition operator(x)$str_result = $string x 4; # Display output# print string 4 times print "Result of Repetition Operator = $str_result"; Output: Result of Concatenation Operator = GeeksforGeeks Result of Repetition Operator = GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Note: To know more about string operators in Perl, you can refer to Perl String Operators article. In Perl, range operator is used for creating the specified sequence range of specified elements. So this operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.Example: Perl # Perl program to demonstrate the# Range operators #!/usr/bin/perl # using range operator @res = (1..4); # Display outputprint "Result of Range Operator = @res"; Output: Result of Range Operator = 1 2 3 4 Auto Increment(++): Increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++$x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, $x++.Auto Decrement Operator(–): Decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –$x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, $x–.Note: The increment and decrement operators are called unary operators as they work with a single operand.Example: Perl # Perl program to demonstrate the Auto # Increment and Decrement Operator #!/usr/local/bin/perl # taking a variable$g = 10; # using pre Increment$res = ++$g; print "Value of res is = $res\n";print "Value of g is = $g\n"; # taking a variable$g1 = 15; # using post Increment$res1 = $g1++; print "Value of res1 is = $res1\n";print "Value of g1 is = $g1\n"; # taking a variable$g2 = 20; # using pre Decrement$res2 = --$g2; print "Value of res2 is = $res2\n";print "Value of g2 is = $g2\n"; # taking a variable$g3 = 25; # using post Decrement$res3 = $g3--; print "Value of res3 is = $res3\n";print "Value of g3 is = $g3\n"; Output: Value of res is = 11 Value of g is = 11 Value of res1 is = 15 Value of g1 is = 16 Value of res2 is = 19 Value of g2 is = 19 Value of res3 is = 25 Value of g3 is = 24 This operator is used for dereferencing a Variable or a Method from a class or an object. Example: $ob->$x is an example to access variable $x from object $ob. Mostly this operator is used as a reference to a hash or an array to access the elements of the hash or the array.Example: Perl # Perl program to demonstrate the Arrow Operator #!/usr/local/bin/perl use strict;use warnings; # reference to arraymy $arr1 = [4,5,6]; # array inside arraymy $arr2 = [4,5,[6,7]]; # reference to hashmy $has1 = {'a'=>1,'b'=>2}; # hash inside hashmy $has2 = {'a'=>1,'b'=>2,'c'=>[1,2],'d'=>{'x'=>3,'y'=>4}}; # using arrow operatorprint "$arr1->[0]\n";print "$arr2->[1]\n";print "$arr2->[2][0]\n";print "$has2->{'a'}\n";print $has2->{'d'}->{'x'},"\n";print $has2->{'c'}->[0],"\n"; Output: 4 5 6 1 3 1 Points to Remember: Operator Associativity: It is used to decide whether equation or expression will evaluate from left to right or right to left. The order of evaluation is very important. Sometimes it may look same from both the sides but it can produce a lot of difference.Perl Arity: The arity can be defined as the number of operands on which an operator operates. Nullary operator: These operator operates on zero operand.Unary operator: Theses operators operates on one operand.Binary operator: These operators operates on two operands.Listary operator: These operators operates on a list of operands.Perl Fixity: It can be defined as operator’s position relative to its operands. Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3.Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x.Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..])Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} Operator Associativity: It is used to decide whether equation or expression will evaluate from left to right or right to left. The order of evaluation is very important. Sometimes it may look same from both the sides but it can produce a lot of difference. Perl Arity: The arity can be defined as the number of operands on which an operator operates. Nullary operator: These operator operates on zero operand.Unary operator: Theses operators operates on one operand.Binary operator: These operators operates on two operands.Listary operator: These operators operates on a list of operands. Nullary operator: These operator operates on zero operand. Unary operator: Theses operators operates on one operand. Binary operator: These operators operates on two operands. Listary operator: These operators operates on a list of operands. Perl Fixity: It can be defined as operator’s position relative to its operands. Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3.Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x.Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..])Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8 Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3. Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x. Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..]) Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} sagarbardhan791 anikaseth98 saurabh1990aror simmytarika5 perl-basics perl-operators Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Subroutines or Functions Perl | ne operator
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jan, 2022" }, { "code": null, "e": 429, "s": 52, "text": "Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Perl Operators Set – 1. Remaining operators will be discussed in this article: " }, { "code": null, "e": 450, "s": 429, "text": "Quote Like Operators" }, { "code": null, "e": 480, "s": 450, "text": "String Manipulation Operators" }, { "code": null, "e": 495, "s": 480, "text": "Range Operator" }, { "code": null, "e": 531, "s": 495, "text": "Auto Increment & Decrement Operator" }, { "code": null, "e": 547, "s": 531, "text": "Arrow Operator " }, { "code": null, "e": 680, "s": 547, "text": "In these operators, {} will represent a pair of delimiters that user choose. In this category there are three operators as follows: " }, { "code": null, "e": 812, "s": 680, "text": "q{ } : It will encloses a string in single quotes(”) and cannot interpolate the string variable. For Example: q{geek} gives ‘geek’." }, { "code": null, "e": 943, "s": 812, "text": "qq{ }: It will encloses a string in double quotes(“”) and can interpolate the string variable. For Example: qq{geek} gives “geek”." }, { "code": null, "e": 1034, "s": 943, "text": "qx{ } : It will encloses a string in invert quotes(“). For Example: qq{geek} gives `geek`." }, { "code": null, "e": 1043, "s": 1034, "text": "Example:" }, { "code": null, "e": 1048, "s": 1043, "text": "Perl" }, { "code": "# Perl program to demonstrate the Quote# Like Operators #!/usr/local/bin/perl # taking a string variable$g = \"Geek\"; # using single quote Operators# this operator will not # interpolate the string variable$r = q{$g}; print \"Value of g is = $r\\n\"; # using double quote Operators# this operator will interpolate# the string variable$r = qq{$g}; print \"Value of g is = $r\\n\"; # Executing unix date command$d = qx{date}; print \"Value of qx{date} = $d\";", "e": 1505, "s": 1048, "text": null }, { "code": null, "e": 1515, "s": 1505, "text": "Output: " }, { "code": null, "e": 1604, "s": 1515, "text": "Value of g is = $g\nValue of g is = Geek\nValue of qx{date} = Sun Aug 12 14:19:43 UTC 2018" }, { "code": null, "e": 1634, "s": 1604, "text": "String Manipulation Operators" }, { "code": null, "e": 1844, "s": 1634, "text": "String are scalar variables and start with ($) sign in Perl. The String is defined by the user within a single quote(”) or double quote(“”). There are different types of string operators in Perl, as follows: " }, { "code": null, "e": 1978, "s": 1844, "text": "Concatenation Operator (.) : Perl strings are concatenated with a Dot(.) symbol. The Dot(.) sign is used instead of (+) sign in Perl." }, { "code": null, "e": 2202, "s": 1978, "text": "Repetition Operator (x): The x operator accepts a string on its left-hand side and a number on its right-hand side. It will return the string on the left-hand side repeated as many times as the value on the right-hand side." }, { "code": null, "e": 2211, "s": 2202, "text": "Example:" }, { "code": null, "e": 2216, "s": 2211, "text": "Perl" }, { "code": "# Perl program to demonstrate the# string operators #!/usr/bin/perl # Input first string $first_string = \"Geeks\"; # Input second string $second_string = \"forGeeks\"; # Implement Concatenation operator(.) $concat_string = $first_string.$second_string; # displaying concatenation string resultprint \"Result of Concatenation Operator = $concat_string\\n\"; # Input a string $string = \"GeeksforGeeks \"; # Using Repetition operator(x)$str_result = $string x 4; # Display output# print string 4 times print \"Result of Repetition Operator = $str_result\";", "e": 2773, "s": 2216, "text": null }, { "code": null, "e": 2783, "s": 2773, "text": "Output: " }, { "code": null, "e": 2921, "s": 2783, "text": "Result of Concatenation Operator = GeeksforGeeks\nResult of Repetition Operator = GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks " }, { "code": null, "e": 3021, "s": 2921, "text": "Note: To know more about string operators in Perl, you can refer to Perl String Operators article. " }, { "code": null, "e": 3315, "s": 3021, "text": "In Perl, range operator is used for creating the specified sequence range of specified elements. So this operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.Example:" }, { "code": null, "e": 3320, "s": 3315, "text": "Perl" }, { "code": "# Perl program to demonstrate the# Range operators #!/usr/bin/perl # using range operator @res = (1..4); # Display outputprint \"Result of Range Operator = @res\";", "e": 3486, "s": 3320, "text": null }, { "code": null, "e": 3496, "s": 3486, "text": "Output: " }, { "code": null, "e": 3531, "s": 3496, "text": "Result of Range Operator = 1 2 3 4" }, { "code": null, "e": 4503, "s": 3531, "text": "Auto Increment(++): Increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++$x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, $x++.Auto Decrement Operator(–): Decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –$x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, $x–.Note: The increment and decrement operators are called unary operators as they work with a single operand.Example: " }, { "code": null, "e": 4508, "s": 4503, "text": "Perl" }, { "code": "# Perl program to demonstrate the Auto # Increment and Decrement Operator #!/usr/local/bin/perl # taking a variable$g = 10; # using pre Increment$res = ++$g; print \"Value of res is = $res\\n\";print \"Value of g is = $g\\n\"; # taking a variable$g1 = 15; # using post Increment$res1 = $g1++; print \"Value of res1 is = $res1\\n\";print \"Value of g1 is = $g1\\n\"; # taking a variable$g2 = 20; # using pre Decrement$res2 = --$g2; print \"Value of res2 is = $res2\\n\";print \"Value of g2 is = $g2\\n\"; # taking a variable$g3 = 25; # using post Decrement$res3 = $g3--; print \"Value of res3 is = $res3\\n\";print \"Value of g3 is = $g3\\n\";", "e": 5144, "s": 4508, "text": null }, { "code": null, "e": 5154, "s": 5144, "text": "Output: " }, { "code": null, "e": 5320, "s": 5154, "text": "Value of res is = 11\nValue of g is = 11\nValue of res1 is = 15\nValue of g1 is = 16\nValue of res2 is = 19\nValue of g2 is = 19\nValue of res3 is = 25\nValue of g3 is = 24" }, { "code": null, "e": 5604, "s": 5320, "text": "This operator is used for dereferencing a Variable or a Method from a class or an object. Example: $ob->$x is an example to access variable $x from object $ob. Mostly this operator is used as a reference to a hash or an array to access the elements of the hash or the array.Example: " }, { "code": null, "e": 5609, "s": 5604, "text": "Perl" }, { "code": "# Perl program to demonstrate the Arrow Operator #!/usr/local/bin/perl use strict;use warnings; # reference to arraymy $arr1 = [4,5,6]; # array inside arraymy $arr2 = [4,5,[6,7]]; # reference to hashmy $has1 = {'a'=>1,'b'=>2}; # hash inside hashmy $has2 = {'a'=>1,'b'=>2,'c'=>[1,2],'d'=>{'x'=>3,'y'=>4}}; # using arrow operatorprint \"$arr1->[0]\\n\";print \"$arr2->[1]\\n\";print \"$arr2->[2][0]\\n\";print \"$has2->{'a'}\\n\";print $has2->{'d'}->{'x'},\"\\n\";print $has2->{'c'}->[0],\"\\n\";", "e": 6093, "s": 5609, "text": null }, { "code": null, "e": 6103, "s": 6093, "text": "Output: " }, { "code": null, "e": 6115, "s": 6103, "text": "4\n5\n6\n1\n3\n1" }, { "code": null, "e": 6135, "s": 6115, "text": "Points to Remember:" }, { "code": null, "e": 7456, "s": 6135, "text": "Operator Associativity: It is used to decide whether equation or expression will evaluate from left to right or right to left. The order of evaluation is very important. Sometimes it may look same from both the sides but it can produce a lot of difference.Perl Arity: The arity can be defined as the number of operands on which an operator operates. Nullary operator: These operator operates on zero operand.Unary operator: Theses operators operates on one operand.Binary operator: These operators operates on two operands.Listary operator: These operators operates on a list of operands.Perl Fixity: It can be defined as operator’s position relative to its operands. Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3.Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x.Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..])Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} " }, { "code": null, "e": 7713, "s": 7456, "text": "Operator Associativity: It is used to decide whether equation or expression will evaluate from left to right or right to left. The order of evaluation is very important. Sometimes it may look same from both the sides but it can produce a lot of difference." }, { "code": null, "e": 8046, "s": 7713, "text": "Perl Arity: The arity can be defined as the number of operands on which an operator operates. Nullary operator: These operator operates on zero operand.Unary operator: Theses operators operates on one operand.Binary operator: These operators operates on two operands.Listary operator: These operators operates on a list of operands." }, { "code": null, "e": 8105, "s": 8046, "text": "Nullary operator: These operator operates on zero operand." }, { "code": null, "e": 8163, "s": 8105, "text": "Unary operator: Theses operators operates on one operand." }, { "code": null, "e": 8222, "s": 8163, "text": "Binary operator: These operators operates on two operands." }, { "code": null, "e": 8288, "s": 8222, "text": "Listary operator: These operators operates on a list of operands." }, { "code": null, "e": 9021, "s": 8288, "text": "Perl Fixity: It can be defined as operator’s position relative to its operands. Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3.Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x.Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..])Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} " }, { "code": null, "e": 9153, "s": 9021, "text": "Infix operator: These operators comes between its operands. For Example, 5 + 8, Here, + operator comes between the operands 5 and 8" }, { "code": null, "e": 9296, "s": 9153, "text": "Prefix operator: These operators comes before its operands. For Example, ! $g, – 7, Here, ! and – operator comes before the operands $a and 3." }, { "code": null, "e": 9427, "s": 9296, "text": "Postfix operator: These operators appears after its operands. For Example, $y ++, Here, ++ operator appears after the operands $x." }, { "code": null, "e": 9556, "s": 9427, "text": "Circumfix operators: These operators enclosed its operands like as hash constructor and quoting operators. For Example, (qq[..])" }, { "code": null, "e": 9678, "s": 9556, "text": "Postcircumfix operators: These operators follow some certain operands and surround some operands. For Example, $hash{$y} " }, { "code": null, "e": 9694, "s": 9678, "text": "sagarbardhan791" }, { "code": null, "e": 9706, "s": 9694, "text": "anikaseth98" }, { "code": null, "e": 9722, "s": 9706, "text": "saurabh1990aror" }, { "code": null, "e": 9735, "s": 9722, "text": "simmytarika5" }, { "code": null, "e": 9747, "s": 9735, "text": "perl-basics" }, { "code": null, "e": 9762, "s": 9747, "text": "perl-operators" }, { "code": null, "e": 9767, "s": 9762, "text": "Perl" }, { "code": null, "e": 9772, "s": 9767, "text": "Perl" }, { "code": null, "e": 9870, "s": 9772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9894, "s": 9870, "text": "Perl | split() Function" }, { "code": null, "e": 9917, "s": 9894, "text": "Perl | push() Function" }, { "code": null, "e": 9941, "s": 9917, "text": "Perl | chomp() Function" }, { "code": null, "e": 9966, "s": 9941, "text": "Perl | substr() function" }, { "code": null, "e": 9989, "s": 9966, "text": "Perl | grep() Function" }, { "code": null, "e": 10014, "s": 9989, "text": "Perl | exists() Function" }, { "code": null, "e": 10055, "s": 10014, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 10080, "s": 10055, "text": "Perl | length() Function" }, { "code": null, "e": 10112, "s": 10080, "text": "Perl | Subroutines or Functions" } ]
Sum of k smallest elements in BST
06 Jul, 2022 Given Binary Search Tree. The task is to find sum of all elements smaller than and equal to Kth smallest element. Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 17 Explanation : Kth smallest element is 8 so sum of all element smaller than or equal to 8 are 2 + 7 + 8 Input : K = 5 8 / \ 5 11 / \ 2 7 \ 3 Output : 25 Method 1 (Does not changes BST node structure): The idea is to traverse BST in inorder traversal. Note that Inorder traversal of BST accesses elements in sorted (or increasing) order. While traversing, we keep track of count of visited Nodes and keep adding Nodes until the count becomes k. Implementation: C++ Java Python3 C# Javascript // c++ program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BST#include <bits/stdc++.h>using namespace std; /* Binary tree Node */struct Node{ int data; Node* left, * right;}; // utility function new Node of BSTstruct Node *createNode(int data){ Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; return new_Node;} // A utility function to insert a new Node// with given key in BST and also maintain lcount ,Sumstruct Node * insert(Node *root, int key){ // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) root->left = insert(root->left, key); else if (root->data < key) root->right = insert(root->right, key); // return the (unchanged) Node pointer return root;} // function return sum of all element smaller than// and equal to Kth smallest elementint ksmallestElementSumRec(Node *root, int k, int &count){ // Base cases if (root == NULL) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root->left, k, count); if (count >= k) return res; // Add root's data res += root->data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root->right, k, count);} // Wrapper over ksmallestElementSumRec()int ksmallestElementSum(struct Node *root, int k){ int count = 0; ksmallestElementSumRec(root, k, count);} /* Driver program to test above functions */int main(){ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) <<endl; return 0;} // Java program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BSTimport java.util.*;class GFG{ /* Binary tree Node */ static class Node { int data; Node left, right; }; // utility function new Node of BST static Node createNode(int data) { Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum static Node insert(Node root, int key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } static int count = 0; // function return sum of all element smaller than // and equal to Kth smallest element static int ksmallestElementSumRec(Node root, int k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() static int ksmallestElementSum(Node root, int k) { int res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ public static void main(String[] args) { /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; int count = ksmallestElementSum(root, k); System.out.println(count); }} // This code is contributed by aashish1995 # Python3 program to find Sum Of All# Elements smaller than or equal to# Kth Smallest Element In BST INT_MAX = 2147483647 # Binary Tree Node""" utility that allocates a newNodewith the given key """class createNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # A utility function to insert a new# Node with given key in BST and also# maintain lcount ,Sumdef insert(root, key) : # If the tree is empty, return a new Node if (root == None) : return createNode(key) # Otherwise, recur down the tree if (root.data > key) : root.left = insert(root.left, key) else if (root.data < key): root.right = insert(root.right, key) # return the (unchanged) Node pointer return root # function return sum of all element smaller# than and equal to Kth smallest elementdef ksmallestElementSumRec(root, k, count) : # Base cases if (root == None) : return 0 if (count[0] > k[0]) : return 0 # Compute sum of elements in left subtree res = ksmallestElementSumRec(root.left, k, count) if (count[0] >= k[0]) : return res # Add root's data res += root.data # Add current Node count[0] += 1 if (count[0] >= k[0]) : return res # If count is less than k, return # right subtree Nodes return res + ksmallestElementSumRec(root.right, k, count) # Wrapper over ksmallestElementSumRec()def ksmallestElementSum(root, k): count = [0] return ksmallestElementSumRec(root, k, count) # Driver Codeif __name__ == '__main__': """ 20 / \ 8 22 / \ 4 12 / \ 10 14 """ root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = [3] print(ksmallestElementSum(root, k)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BSTusing System; public class GFG{ /* Binary tree Node */ public class Node { public int data; public Node left, right; }; // utility function new Node of BST static Node createNode(int data) { Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum static Node insert(Node root, int key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } static int count = 0; // function return sum of all element smaller than // and equal to Kth smallest element static int ksmallestElementSumRec(Node root, int k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() static int ksmallestElementSum(Node root, int k) { int res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ public static void Main(String[] args) { /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; int count = ksmallestElementSum(root, k); Console.WriteLine(count); }} // This code is contributed by aashish1995 <script> // JavaScript program to find// Sum Of All Elements smaller// than or equal to Kth Smallest Element In BST /* Binary tree Node */class Node { constructor() { this.data = 0; this.left = null; this.right = null; }} // utility function new Node of BST function createNode(data) { var new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum function insert(root , key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } var count = 0; // function return sum of all element smaller than // and equal to Kth smallest element function ksmallestElementSumRec(root , k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree var res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() function ksmallestElementSum(root , k) { var res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ var root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); var k = 3; var count = ksmallestElementSum(root, k); document.write(count); // This code is contributed by todaysgaurav </script> Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 22 Time complexity : O(k) Method 2 (Efficient and changes structure of BST): We can find the required sum in O(h) time where h is height of BST. Idea is similar to Kth-th smallest element in BST . Here we use augmented tree data structure to solve this problem efficiently in O(h) time [ h is height of BST ] . Algorithm : BST Node contain to extra fields : Lcount , Sum For each Node of BST lCount : store how many left child it has Sum : store sum of all left child it has Find Kth smallest element [ temp_sum store sum of all element less than equal to K ] ksmallestElementSumRec(root, K, temp_sum) IF root -> lCount == K + 1 temp_sum += root->data + root->sum; break; ELSE IF k > root->lCount // Goto right sub-tree temp_sum += root->data + root-> sum; ksmallestElementSumRec(root->right, K-root->lcount+1, temp_sum) ELSE // Goto left sun-tree ksmallestElementSumRec( root->left, K, temp_sum) Below is implementation of above algo : C++ Java Python3 C# Javascript // C++ program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BST#include <bits/stdc++.h>using namespace std; /* Binary tree Node */struct Node{ int data; int lCount; int Sum ; Node* left; Node* right;}; //utility function new Node of BSTstruct Node *createNode(int data){ Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; new_Node->lCount = 0 ; new_Node->Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstruct Node * insert(Node *root, int key){ // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) { // increment lCount of current Node root->lCount++; // increment current Node sum by adding // key into it root->Sum += key; root->left= insert(root->left , key); } else if (root->data < key ) root->right= insert (root->right , key ); // return the (unchanged) Node pointer return root;} // function return sum of all element smaller than and equal// to Kth smallest elementvoid ksmallestElementSumRec(Node *root, int k , int &temp_sum){ if (root == NULL) return ; // if we fount k smallest element then break the function if ((root->lCount + 1) == k) { temp_sum += root->data + root->Sum ; return ; } else if (k > root->lCount) { // store sum of all element smaller than current root ; temp_sum += root->data + root->Sum; // decremented k and call right sub-tree k = k -( root->lCount + 1); ksmallestElementSumRec(root->right , k , temp_sum); } else // call left sub-tree ksmallestElementSumRec(root->left , k , temp_sum );} // Wrapper over ksmallestElementSumRec()int ksmallestElementSum(struct Node *root, int k){ int sum = 0; ksmallestElementSumRec(root, k, sum); return sum;} /* Driver program to test above functions */int main(){ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) << endl; return 0;} // Java program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BST import java.util.*; class GFG{ /* Binary tree Node */static class Node{ int data; int lCount; int Sum ; Node left; Node right;}; //utility function new Node of BSTstatic Node createNode(int data){ Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0 ; new_Node.Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstatic Node insert(Node root, int key){ // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left= insert(root.left , key); } else if (root.data < key ) root.right= insert (root.right , key ); // return the (unchanged) Node pointer return root;} static int temp_sum;// function return sum of all element smaller than and equal// to Kth smallest elementstatic void ksmallestElementSumRec(Node root, int k ){ if (root == null) return ; // if we fount k smallest element then break the function if ((root.lCount + 1) == k) { temp_sum += root.data + root.Sum ; return ; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k -( root.lCount + 1); ksmallestElementSumRec(root.right , k ); } else // call left sub-tree ksmallestElementSumRec(root.left , k );} // Wrapper over ksmallestElementSumRec()static void ksmallestElementSum(Node root, int k){ temp_sum = 0; ksmallestElementSumRec(root, k);} /* Driver program to test above functions */public static void main(String[] args){ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; ksmallestElementSum(root, k); System.out.println(temp_sum);}} // This code is contributed by gauravrajput1 # Python3 program to find Sum Of All Elements# smaller than or equal t Kth Smallest Element In BST # utility function new Node of BSTclass createNode: # Constructor to create a new node def __init__(self, data): self.data = data self.lCount = 0 self.Sum = 0 self.left = None self.right = None # A utility function to insert a new Node with# given key in BST and also maintain lcount ,Sumdef insert(root, key): # If the tree is empty, return a new Node if root == None: return createNode(key) # Otherwise, recur down the tree if root.data > key: # increment lCount of current Node root.lCount += 1 # increment current Node sum by # adding key into it root.Sum += key root.left= insert(root.left , key) else if root.data < key: root.right= insert (root.right , key) # return the (unchanged) Node pointer return root # function return sum of all element smaller# than and equal to Kth smallest elementdef ksmallestElementSumRec(root, k , temp_sum): if root == None: return # if we fount k smallest element # then break the function if (root.lCount + 1) == k: temp_sum[0] += root.data + root.Sum return else if k > root.lCount: # store sum of all element smaller # than current root ; temp_sum[0] += root.data + root.Sum # decremented k and call right sub-tree k = k -( root.lCount + 1) ksmallestElementSumRec(root.right, k, temp_sum) else: # call left sub-tree ksmallestElementSumRec(root.left, k, temp_sum) # Wrapper over ksmallestElementSumRec()def ksmallestElementSum(root, k): Sum = [0] ksmallestElementSumRec(root, k, Sum) return Sum[0] # Driver Codeif __name__ == '__main__': # 20 # / \ # 8 22 # / \ #4 12 # / \ # 10 14 # root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = 3 print(ksmallestElementSum(root, k)) # This code is contributed by PranchalK // C# program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BSTusing System;public class GFG{ /* Binary tree Node */public class Node{ public int data; public int lCount; public int Sum ; public Node left; public Node right;}; // utility function new Node of BSTstatic Node createNode(int data){ Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0 ; new_Node.Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstatic Node insert(Node root, int key){ // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left = insert(root.left , key); } else if (root.data < key ) root.right = insert (root.right , key ); // return the (unchanged) Node pointer return root;} static int temp_sum; // function return sum of all element smaller than and equal// to Kth smallest elementstatic void ksmallestElementSumRec(Node root, int k ){ if (root == null) return ; // if we fount k smallest element then break the function if ((root.lCount + 1) == k) { temp_sum += root.data + root.Sum ; return ; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k -( root.lCount + 1); ksmallestElementSumRec(root.right , k ); } else // call left sub-tree ksmallestElementSumRec(root.left , k );} // Wrapper over ksmallestElementSumRec()static void ksmallestElementSum(Node root, int k){ temp_sum = 0; ksmallestElementSumRec(root, k);} /* Driver program to test above functions */public static void Main(String[] args){ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; ksmallestElementSum(root, k); Console.WriteLine(temp_sum);}} // This code is contributed by gauravrajput1 <script> // JavaScript program to find Sum Of All Elements smaller // than or equal t Kth Smallest Element In BST /* Binary tree Node */ class Node { constructor() { this.data = 0; this.lCount = 0; this.Sum = 0; this.left = null; this.right = null; } } // utility function new Node of BST function createNode(data) { var new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0; new_Node.Sum = 0; return new_Node; } // A utility function to insert a new Node with // given key in BST and also maintain lcount ,Sum function insert(root, key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left = insert(root.left, key); } else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } var temp_sum = 0; // function return sum of all element smaller than and equal // to Kth smallest element function ksmallestElementSumRec(root, k) { if (root == null) return; // if we fount k smallest element then break the function if (root.lCount + 1 == k) { temp_sum += root.data + root.Sum; return; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k - (root.lCount + 1); ksmallestElementSumRec(root.right, k); } // call left sub-tree else ksmallestElementSumRec(root.left, k); } // Wrapper over ksmallestElementSumRec() function ksmallestElementSum(root, k) { temp_sum = 0; ksmallestElementSumRec(root, k); } /* Driver program to test above functions */ /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ var root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); var k = 3; ksmallestElementSum(root, k); document.write(temp_sum); </script> 22 Time Complexity: O(h) where h is height of tree. Playlist : Trees | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks This article is contributed by Nishant 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. PranchalKatiyar SHUBHAMSINGH10 aashish1995 GauravRajput1 todaysgaurav rdtank surinderdawra388 simmytarika5 kothavvsaakash hardikkoriintern Amazon Order-Statistics Binary Search Tree Amazon Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 168, "s": 54, "text": "Given Binary Search Tree. The task is to find sum of all elements smaller than and equal to Kth smallest element." }, { "code": null, "e": 179, "s": 168, "text": "Examples: " }, { "code": null, "e": 549, "s": 179, "text": "Input : K = 3\n 8\n / \\\n 7 10\n / / \\\n 2 9 13\nOutput : 17\nExplanation : Kth smallest element is 8 so sum of all\n element smaller than or equal to 8 are\n 2 + 7 + 8\n\nInput : K = 5\n 8\n / \\\n 5 11\n / \\\n 2 7\n \\\n 3\nOutput : 25" }, { "code": null, "e": 841, "s": 549, "text": "Method 1 (Does not changes BST node structure): The idea is to traverse BST in inorder traversal. Note that Inorder traversal of BST accesses elements in sorted (or increasing) order. While traversing, we keep track of count of visited Nodes and keep adding Nodes until the count becomes k. " }, { "code": null, "e": 857, "s": 841, "text": "Implementation:" }, { "code": null, "e": 861, "s": 857, "text": "C++" }, { "code": null, "e": 866, "s": 861, "text": "Java" }, { "code": null, "e": 874, "s": 866, "text": "Python3" }, { "code": null, "e": 877, "s": 874, "text": "C#" }, { "code": null, "e": 888, "s": 877, "text": "Javascript" }, { "code": "// c++ program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BST#include <bits/stdc++.h>using namespace std; /* Binary tree Node */struct Node{ int data; Node* left, * right;}; // utility function new Node of BSTstruct Node *createNode(int data){ Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; return new_Node;} // A utility function to insert a new Node// with given key in BST and also maintain lcount ,Sumstruct Node * insert(Node *root, int key){ // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) root->left = insert(root->left, key); else if (root->data < key) root->right = insert(root->right, key); // return the (unchanged) Node pointer return root;} // function return sum of all element smaller than// and equal to Kth smallest elementint ksmallestElementSumRec(Node *root, int k, int &count){ // Base cases if (root == NULL) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root->left, k, count); if (count >= k) return res; // Add root's data res += root->data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root->right, k, count);} // Wrapper over ksmallestElementSumRec()int ksmallestElementSum(struct Node *root, int k){ int count = 0; ksmallestElementSumRec(root, k, count);} /* Driver program to test above functions */int main(){ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) <<endl; return 0;}", "e": 3015, "s": 888, "text": null }, { "code": "// Java program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BSTimport java.util.*;class GFG{ /* Binary tree Node */ static class Node { int data; Node left, right; }; // utility function new Node of BST static Node createNode(int data) { Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum static Node insert(Node root, int key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } static int count = 0; // function return sum of all element smaller than // and equal to Kth smallest element static int ksmallestElementSumRec(Node root, int k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() static int ksmallestElementSum(Node root, int k) { int res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ public static void main(String[] args) { /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; int count = ksmallestElementSum(root, k); System.out.println(count); }} // This code is contributed by aashish1995", "e": 5250, "s": 3015, "text": null }, { "code": "# Python3 program to find Sum Of All# Elements smaller than or equal to# Kth Smallest Element In BST INT_MAX = 2147483647 # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\"class createNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # A utility function to insert a new# Node with given key in BST and also# maintain lcount ,Sumdef insert(root, key) : # If the tree is empty, return a new Node if (root == None) : return createNode(key) # Otherwise, recur down the tree if (root.data > key) : root.left = insert(root.left, key) else if (root.data < key): root.right = insert(root.right, key) # return the (unchanged) Node pointer return root # function return sum of all element smaller# than and equal to Kth smallest elementdef ksmallestElementSumRec(root, k, count) : # Base cases if (root == None) : return 0 if (count[0] > k[0]) : return 0 # Compute sum of elements in left subtree res = ksmallestElementSumRec(root.left, k, count) if (count[0] >= k[0]) : return res # Add root's data res += root.data # Add current Node count[0] += 1 if (count[0] >= k[0]) : return res # If count is less than k, return # right subtree Nodes return res + ksmallestElementSumRec(root.right, k, count) # Wrapper over ksmallestElementSumRec()def ksmallestElementSum(root, k): count = [0] return ksmallestElementSumRec(root, k, count) # Driver Codeif __name__ == '__main__': \"\"\" 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 \"\"\" root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = [3] print(ksmallestElementSum(root, k)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 7293, "s": 5250, "text": null }, { "code": "// C# program to find Sum Of All Elements smaller// than or equal to Kth Smallest Element In BSTusing System; public class GFG{ /* Binary tree Node */ public class Node { public int data; public Node left, right; }; // utility function new Node of BST static Node createNode(int data) { Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum static Node insert(Node root, int key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } static int count = 0; // function return sum of all element smaller than // and equal to Kth smallest element static int ksmallestElementSumRec(Node root, int k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() static int ksmallestElementSum(Node root, int k) { int res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ public static void Main(String[] args) { /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; int count = ksmallestElementSum(root, k); Console.WriteLine(count); }} // This code is contributed by aashish1995", "e": 9538, "s": 7293, "text": null }, { "code": "<script> // JavaScript program to find// Sum Of All Elements smaller// than or equal to Kth Smallest Element In BST /* Binary tree Node */class Node { constructor() { this.data = 0; this.left = null; this.right = null; }} // utility function new Node of BST function createNode(data) { var new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum function insert(root , key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) root.left = insert(root.left, key); else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } var count = 0; // function return sum of all element smaller than // and equal to Kth smallest element function ksmallestElementSumRec(root , k) { // Base cases if (root == null) return 0; if (count > k) return 0; // Compute sum of elements in left subtree var res = ksmallestElementSumRec(root.left, k); if (count >= k) return res; // Add root's data res += root.data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root.right, k); } // Wrapper over ksmallestElementSumRec() function ksmallestElementSum(root , k) { var res = ksmallestElementSumRec(root, k); return res; } /* Driver program to test above functions */ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ var root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); var k = 3; var count = ksmallestElementSum(root, k); document.write(count); // This code is contributed by todaysgaurav </script>", "e": 11724, "s": 9538, "text": null }, { "code": null, "e": 11733, "s": 11724, "text": "Chapters" }, { "code": null, "e": 11760, "s": 11733, "text": "descriptions off, selected" }, { "code": null, "e": 11810, "s": 11760, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 11833, "s": 11810, "text": "captions off, selected" }, { "code": null, "e": 11841, "s": 11833, "text": "English" }, { "code": null, "e": 11865, "s": 11841, "text": "This is a modal window." }, { "code": null, "e": 11934, "s": 11865, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 11956, "s": 11934, "text": "End of dialog window." }, { "code": null, "e": 11959, "s": 11956, "text": "22" }, { "code": null, "e": 12034, "s": 11959, "text": "Time complexity : O(k) Method 2 (Efficient and changes structure of BST):" }, { "code": null, "e": 12268, "s": 12034, "text": "We can find the required sum in O(h) time where h is height of BST. Idea is similar to Kth-th smallest element in BST . Here we use augmented tree data structure to solve this problem efficiently in O(h) time [ h is height of BST ] ." }, { "code": null, "e": 12281, "s": 12268, "text": "Algorithm : " }, { "code": null, "e": 12923, "s": 12281, "text": "BST Node contain to extra fields : Lcount , Sum\n\nFor each Node of BST\nlCount : store how many left child it has\nSum : store sum of all left child it has\n\nFind Kth smallest element\n[ temp_sum store sum of all element less than equal to K ]\n\nksmallestElementSumRec(root, K, temp_sum)\n\n IF root -> lCount == K + 1\n temp_sum += root->data + root->sum;\n break;\n ELSE\n IF k > root->lCount // Goto right sub-tree\n temp_sum += root->data + root-> sum;\n ksmallestElementSumRec(root->right, K-root->lcount+1, temp_sum)\n ELSE\n // Goto left sun-tree\n ksmallestElementSumRec( root->left, K, temp_sum)" }, { "code": null, "e": 12964, "s": 12923, "text": "Below is implementation of above algo : " }, { "code": null, "e": 12968, "s": 12964, "text": "C++" }, { "code": null, "e": 12973, "s": 12968, "text": "Java" }, { "code": null, "e": 12981, "s": 12973, "text": "Python3" }, { "code": null, "e": 12984, "s": 12981, "text": "C#" }, { "code": null, "e": 12995, "s": 12984, "text": "Javascript" }, { "code": "// C++ program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BST#include <bits/stdc++.h>using namespace std; /* Binary tree Node */struct Node{ int data; int lCount; int Sum ; Node* left; Node* right;}; //utility function new Node of BSTstruct Node *createNode(int data){ Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; new_Node->lCount = 0 ; new_Node->Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstruct Node * insert(Node *root, int key){ // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) { // increment lCount of current Node root->lCount++; // increment current Node sum by adding // key into it root->Sum += key; root->left= insert(root->left , key); } else if (root->data < key ) root->right= insert (root->right , key ); // return the (unchanged) Node pointer return root;} // function return sum of all element smaller than and equal// to Kth smallest elementvoid ksmallestElementSumRec(Node *root, int k , int &temp_sum){ if (root == NULL) return ; // if we fount k smallest element then break the function if ((root->lCount + 1) == k) { temp_sum += root->data + root->Sum ; return ; } else if (k > root->lCount) { // store sum of all element smaller than current root ; temp_sum += root->data + root->Sum; // decremented k and call right sub-tree k = k -( root->lCount + 1); ksmallestElementSumRec(root->right , k , temp_sum); } else // call left sub-tree ksmallestElementSumRec(root->left , k , temp_sum );} // Wrapper over ksmallestElementSumRec()int ksmallestElementSum(struct Node *root, int k){ int sum = 0; ksmallestElementSumRec(root, k, sum); return sum;} /* Driver program to test above functions */int main(){ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) << endl; return 0;}", "e": 15501, "s": 12995, "text": null }, { "code": "// Java program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BST import java.util.*; class GFG{ /* Binary tree Node */static class Node{ int data; int lCount; int Sum ; Node left; Node right;}; //utility function new Node of BSTstatic Node createNode(int data){ Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0 ; new_Node.Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstatic Node insert(Node root, int key){ // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left= insert(root.left , key); } else if (root.data < key ) root.right= insert (root.right , key ); // return the (unchanged) Node pointer return root;} static int temp_sum;// function return sum of all element smaller than and equal// to Kth smallest elementstatic void ksmallestElementSumRec(Node root, int k ){ if (root == null) return ; // if we fount k smallest element then break the function if ((root.lCount + 1) == k) { temp_sum += root.data + root.Sum ; return ; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k -( root.lCount + 1); ksmallestElementSumRec(root.right , k ); } else // call left sub-tree ksmallestElementSumRec(root.left , k );} // Wrapper over ksmallestElementSumRec()static void ksmallestElementSum(Node root, int k){ temp_sum = 0; ksmallestElementSumRec(root, k);} /* Driver program to test above functions */public static void main(String[] args){ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; ksmallestElementSum(root, k); System.out.println(temp_sum);}} // This code is contributed by gauravrajput1", "e": 18024, "s": 15501, "text": null }, { "code": "# Python3 program to find Sum Of All Elements# smaller than or equal t Kth Smallest Element In BST # utility function new Node of BSTclass createNode: # Constructor to create a new node def __init__(self, data): self.data = data self.lCount = 0 self.Sum = 0 self.left = None self.right = None # A utility function to insert a new Node with# given key in BST and also maintain lcount ,Sumdef insert(root, key): # If the tree is empty, return a new Node if root == None: return createNode(key) # Otherwise, recur down the tree if root.data > key: # increment lCount of current Node root.lCount += 1 # increment current Node sum by # adding key into it root.Sum += key root.left= insert(root.left , key) else if root.data < key: root.right= insert (root.right , key) # return the (unchanged) Node pointer return root # function return sum of all element smaller# than and equal to Kth smallest elementdef ksmallestElementSumRec(root, k , temp_sum): if root == None: return # if we fount k smallest element # then break the function if (root.lCount + 1) == k: temp_sum[0] += root.data + root.Sum return else if k > root.lCount: # store sum of all element smaller # than current root ; temp_sum[0] += root.data + root.Sum # decremented k and call right sub-tree k = k -( root.lCount + 1) ksmallestElementSumRec(root.right, k, temp_sum) else: # call left sub-tree ksmallestElementSumRec(root.left, k, temp_sum) # Wrapper over ksmallestElementSumRec()def ksmallestElementSum(root, k): Sum = [0] ksmallestElementSumRec(root, k, Sum) return Sum[0] # Driver Codeif __name__ == '__main__': # 20 # / \\ # 8 22 # / \\ #4 12 # / \\ # 10 14 # root = None root = insert(root, 20) root = insert(root, 8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 10) root = insert(root, 14) root = insert(root, 22) k = 3 print(ksmallestElementSum(root, k)) # This code is contributed by PranchalK", "e": 20291, "s": 18024, "text": null }, { "code": "// C# program to find Sum Of All Elements smaller// than or equal t Kth Smallest Element In BSTusing System;public class GFG{ /* Binary tree Node */public class Node{ public int data; public int lCount; public int Sum ; public Node left; public Node right;}; // utility function new Node of BSTstatic Node createNode(int data){ Node new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0 ; new_Node.Sum = 0; return new_Node;} // A utility function to insert a new Node with// given key in BST and also maintain lcount ,Sumstatic Node insert(Node root, int key){ // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left = insert(root.left , key); } else if (root.data < key ) root.right = insert (root.right , key ); // return the (unchanged) Node pointer return root;} static int temp_sum; // function return sum of all element smaller than and equal// to Kth smallest elementstatic void ksmallestElementSumRec(Node root, int k ){ if (root == null) return ; // if we fount k smallest element then break the function if ((root.lCount + 1) == k) { temp_sum += root.data + root.Sum ; return ; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k -( root.lCount + 1); ksmallestElementSumRec(root.right , k ); } else // call left sub-tree ksmallestElementSumRec(root.left , k );} // Wrapper over ksmallestElementSumRec()static void ksmallestElementSum(Node root, int k){ temp_sum = 0; ksmallestElementSumRec(root, k);} /* Driver program to test above functions */public static void Main(String[] args){ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ Node root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; ksmallestElementSum(root, k); Console.WriteLine(temp_sum);}} // This code is contributed by gauravrajput1", "e": 22862, "s": 20291, "text": null }, { "code": "<script> // JavaScript program to find Sum Of All Elements smaller // than or equal t Kth Smallest Element In BST /* Binary tree Node */ class Node { constructor() { this.data = 0; this.lCount = 0; this.Sum = 0; this.left = null; this.right = null; } } // utility function new Node of BST function createNode(data) { var new_Node = new Node(); new_Node.left = null; new_Node.right = null; new_Node.data = data; new_Node.lCount = 0; new_Node.Sum = 0; return new_Node; } // A utility function to insert a new Node with // given key in BST and also maintain lcount ,Sum function insert(root, key) { // If the tree is empty, return a new Node if (root == null) return createNode(key); // Otherwise, recur down the tree if (root.data > key) { // increment lCount of current Node root.lCount++; // increment current Node sum by adding // key into it root.Sum += key; root.left = insert(root.left, key); } else if (root.data < key) root.right = insert(root.right, key); // return the (unchanged) Node pointer return root; } var temp_sum = 0; // function return sum of all element smaller than and equal // to Kth smallest element function ksmallestElementSumRec(root, k) { if (root == null) return; // if we fount k smallest element then break the function if (root.lCount + 1 == k) { temp_sum += root.data + root.Sum; return; } else if (k > root.lCount) { // store sum of all element smaller than current root ; temp_sum += root.data + root.Sum; // decremented k and call right sub-tree k = k - (root.lCount + 1); ksmallestElementSumRec(root.right, k); } // call left sub-tree else ksmallestElementSumRec(root.left, k); } // Wrapper over ksmallestElementSumRec() function ksmallestElementSum(root, k) { temp_sum = 0; ksmallestElementSumRec(root, k); } /* Driver program to test above functions */ /* 20 / \\ 8 22 / \\ 4 12 / \\ 10 14 */ var root = null; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); var k = 3; ksmallestElementSum(root, k); document.write(temp_sum); </script>", "e": 25541, "s": 22862, "text": null }, { "code": null, "e": 25544, "s": 25541, "text": "22" }, { "code": null, "e": 25594, "s": 25544, "text": "Time Complexity: O(h) where h is height of tree. " }, { "code": null, "e": 25682, "s": 25594, "text": "Playlist : Trees | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks" }, { "code": null, "e": 25980, "s": 25682, "text": " This article is contributed by Nishant 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." }, { "code": null, "e": 25996, "s": 25980, "text": "PranchalKatiyar" }, { "code": null, "e": 26011, "s": 25996, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 26023, "s": 26011, "text": "aashish1995" }, { "code": null, "e": 26037, "s": 26023, "text": "GauravRajput1" }, { "code": null, "e": 26050, "s": 26037, "text": "todaysgaurav" }, { "code": null, "e": 26057, "s": 26050, "text": "rdtank" }, { "code": null, "e": 26074, "s": 26057, "text": "surinderdawra388" }, { "code": null, "e": 26087, "s": 26074, "text": "simmytarika5" }, { "code": null, "e": 26102, "s": 26087, "text": "kothavvsaakash" }, { "code": null, "e": 26119, "s": 26102, "text": "hardikkoriintern" }, { "code": null, "e": 26126, "s": 26119, "text": "Amazon" }, { "code": null, "e": 26143, "s": 26126, "text": "Order-Statistics" }, { "code": null, "e": 26162, "s": 26143, "text": "Binary Search Tree" }, { "code": null, "e": 26169, "s": 26162, "text": "Amazon" }, { "code": null, "e": 26188, "s": 26169, "text": "Binary Search Tree" } ]
Java Stream | Collectors toCollection() in Java
06 Dec, 2018 Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) where:- Collection : The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. Collector<T, A, R> : A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T : The type of input elements to the reduction operation.A : The mutable accumulation type of the reduction operation.R : The result type of the reduction operation. T : The type of input elements to the reduction operation. A : The mutable accumulation type of the reduction operation. R : The result type of the reduction operation. Supplier : A functional interface and can therefore be used as the assignment target for a lambda expression or method reference. collectionFactory : A Supplier which returns a new, empty Collection of the appropriate type. Parameters: This method takes a mandatory parameter collectionFactory of type Supplier which returns a new, empty Collection of the appropriate type. Return Value: This method returns a collector which collects all the input elements into a Collection, in encounter order. Below given are some examples to illustrate the implementation of toCollection() in a better way: Example 1: // Java code to demonstrate Collectors// toCollection(Supplier collectionFactory) method import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a string stream Stream<String> s = Stream.of("Geeks", "for", "GeeksClasses"); // Using toCollection() method // to create a collection Collection<String> names = s .collect(Collectors .toCollection(TreeSet::new)); // Printing the elements System.out.println(names); }} [Geeks, GeeksClasses, for] Example 2: // Java code to demonstrate Collectors// toCollection(Supplier collectionFactory) method import java.util.Collection;import java.util.TreeSet;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a string stream Stream<String> s = Stream.of("2.5", "6", "4"); // Using Collectors toCollection() Collection<String> names = s .collect(Collectors .toCollection(TreeSet::new)); // Printing the elements System.out.println(names); }} [2.5, 4, 6] Java - util package Java-Collectors Java-Functions java-stream Java-Stream-Collectors Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 267, "s": 28, "text": "Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed." }, { "code": null, "e": 275, "s": 267, "text": "Syntax:" }, { "code": null, "e": 388, "s": 275, "text": "public static <T, C extends Collection<T>> Collector<T, ?, C>\n toCollection(Supplier<C> collectionFactory)\n" }, { "code": null, "e": 396, "s": 388, "text": "where:-" }, { "code": null, "e": 624, "s": 396, "text": "Collection : The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered." }, { "code": null, "e": 1101, "s": 624, "text": "Collector<T, A, R> : A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T : The type of input elements to the reduction operation.A : The mutable accumulation type of the reduction operation.R : The result type of the reduction operation." }, { "code": null, "e": 1160, "s": 1101, "text": "T : The type of input elements to the reduction operation." }, { "code": null, "e": 1222, "s": 1160, "text": "A : The mutable accumulation type of the reduction operation." }, { "code": null, "e": 1270, "s": 1222, "text": "R : The result type of the reduction operation." }, { "code": null, "e": 1400, "s": 1270, "text": "Supplier : A functional interface and can therefore be used as the assignment target for a lambda expression or method reference." }, { "code": null, "e": 1494, "s": 1400, "text": "collectionFactory : A Supplier which returns a new, empty Collection of the appropriate type." }, { "code": null, "e": 1644, "s": 1494, "text": "Parameters: This method takes a mandatory parameter collectionFactory of type Supplier which returns a new, empty Collection of the appropriate type." }, { "code": null, "e": 1767, "s": 1644, "text": "Return Value: This method returns a collector which collects all the input elements into a Collection, in encounter order." }, { "code": null, "e": 1865, "s": 1767, "text": "Below given are some examples to illustrate the implementation of toCollection() in a better way:" }, { "code": null, "e": 1876, "s": 1865, "text": "Example 1:" }, { "code": "// Java code to demonstrate Collectors// toCollection(Supplier collectionFactory) method import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a string stream Stream<String> s = Stream.of(\"Geeks\", \"for\", \"GeeksClasses\"); // Using toCollection() method // to create a collection Collection<String> names = s .collect(Collectors .toCollection(TreeSet::new)); // Printing the elements System.out.println(names); }}", "e": 2560, "s": 1876, "text": null }, { "code": null, "e": 2588, "s": 2560, "text": "[Geeks, GeeksClasses, for]\n" }, { "code": null, "e": 2599, "s": 2588, "text": "Example 2:" }, { "code": "// Java code to demonstrate Collectors// toCollection(Supplier collectionFactory) method import java.util.Collection;import java.util.TreeSet;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a string stream Stream<String> s = Stream.of(\"2.5\", \"6\", \"4\"); // Using Collectors toCollection() Collection<String> names = s .collect(Collectors .toCollection(TreeSet::new)); // Printing the elements System.out.println(names); }}", "e": 3273, "s": 2599, "text": null }, { "code": null, "e": 3286, "s": 3273, "text": "[2.5, 4, 6]\n" }, { "code": null, "e": 3306, "s": 3286, "text": "Java - util package" }, { "code": null, "e": 3322, "s": 3306, "text": "Java-Collectors" }, { "code": null, "e": 3337, "s": 3322, "text": "Java-Functions" }, { "code": null, "e": 3349, "s": 3337, "text": "java-stream" }, { "code": null, "e": 3372, "s": 3349, "text": "Java-Stream-Collectors" }, { "code": null, "e": 3377, "s": 3372, "text": "Java" }, { "code": null, "e": 3382, "s": 3377, "text": "Java" }, { "code": null, "e": 3480, "s": 3382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3495, "s": 3480, "text": "Stream In Java" }, { "code": null, "e": 3516, "s": 3495, "text": "Introduction to Java" }, { "code": null, "e": 3537, "s": 3516, "text": "Constructors in Java" }, { "code": null, "e": 3556, "s": 3537, "text": "Exceptions in Java" }, { "code": null, "e": 3573, "s": 3556, "text": "Generics in Java" }, { "code": null, "e": 3603, "s": 3573, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3629, "s": 3603, "text": "Java Programming Examples" }, { "code": null, "e": 3645, "s": 3629, "text": "Strings in Java" }, { "code": null, "e": 3682, "s": 3645, "text": "Differences between JDK, JRE and JVM" } ]
Creating and updating PowerPoint Presentations in Python using python – pptx
18 Aug, 2020 python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won’t work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let’s see some of its usage: Example 1: Creating new PowerPoint file with title and subtitle slide. Python3 # import Presentation class# from pptx libraryfrom pptx import Presentation # Creating presentation objectroot = Presentation() # Creating slide layoutfirst_slide_layout = root.slide_layouts[0] """ Ref for slide types: 0 -> title and subtitle1 -> title and content2 -> section header3 -> two content4 -> Comparison5 -> Title only 6 -> Blank7 -> Content with caption8 -> Pic with caption""" # Creating slide object to add # in ppt i.e. Attaching slides # with Presentation i.e. pptslide = root.slides.add_slide(first_slide_layout) # Adding title and subtitle in # slide i.e. first page of slide slide.shapes.title.text = " Created By python-pptx" # We have different formats of # subtitles in ppts, for simple# subtitle this method should # implemented, you can change# 0 to 1 for different designslide.placeholders[1].text = " This is 2nd way" # Saving fileroot.save("Output.pptx") print("done") Output: Example 2: Adding Text-Box in PowerPoint. Python3 # import required thingsfrom pptx import Presentation from pptx.util import Inches, Pt # Creating Objectppt = Presentation() # To create blank slide layout# We have to use 6 as an argument# of slide_layouts blank_slide_layout = ppt.slide_layouts[6] # Attaching slide obj to slideslide = ppt.slides.add_slide(blank_slide_layout) # For adjusting the Margins in inches left = top = width = height = Inches(1) # creating textBoxtxBox = slide.shapes.add_textbox(left, top, width, height) # creating textFramestf = txBox.text_frametf.text = "This is text inside a textbox" # adding Paragraphsp = tf.add_paragraph() # adding textp.text = "This is a second paragraph that's bold and italic" # font p.font.bold = Truep.font.italic = True p = tf.add_paragraph()p.text = "This is a third paragraph that's big " p.font.size = Pt(40) # save fileppt.save('test_2.pptx') print("done") Output: Example 3: PowerPoint (.pptx) file to Text (.txt) file conversion. Python3 # import Presentation class# from pptx libraryfrom pptx import Presentation # creating an objectppt = Presentation("sample.pptx") # open file in write modeFile_to_write_data = open("File_To_Extract_ppt.txt", "w") # write text from powerpoint# file into .txt filefor slide in ppt.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: File_to_write_data.write(run.text) # close the file File_to_write_data.close() print("Done") Output: Example 4: Inserting image into the PowerPoint file. Python3 from pptx import Presentation from pptx.util import Inches # Giving Image path img_path = 'bg_bg.png' # Creating an Presentation objectppt = Presentation() # Selecting blank slideblank_slide_layout = ppt.slide_layouts[6] # Attaching slide to pptslide = ppt.slides.add_slide(blank_slide_layout) # For marginsleft = top = Inches(1) # adding imagespic = slide.shapes.add_picture(img_path, left, top) left = Inches(1) height = Inches(1) pic = slide.shapes.add_picture(img_path, left, top, height = height)# save fileppt.save('test_4.pptx') print("Done") Output: Example 5: Adding Charts to the PowerPoint file. Python3 # import required classes/functions/methodfrom pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches # Create presentation objectppt = Presentation() # Adding slide with specific layoutslide = ppt.slides.add_slide(ppt.slide_layouts[6]) # Define chart data # Creating object of chartchart_data = CategoryChartData() # Adding categories to chartchart_data.categories = ['East', 'West', 'Midwest'] # Adding serieschart_data.add_series('Series 1', (int(input("Enter Value:")), int(input("Enter Value:")), int(input("Enter Value:")))) x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) slide.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data ) # Saving fileppt.save('chart-Tutorial.pptx') print("done") Output: Example 6: Adding tables to the PowerPoint file. Python3 # importingfrom pptx import Presentation from pptx.util import Inches # create a Presentation objectppt = Presentation() # Adding a blank slide in out pptslide = ppt.slides.add_slide(ppt.slide_layouts[6]) # Adjusting the width ! x, y, cx, cy = Inches(2), Inches(2), Inches(4), Inches(1.5) # Adding tablesshape = slide.shapes.add_table(3, 4, x, y, cx, cy) # Saving the fileppt.save("Tabel_Tutorial.pptx") print("done") Output: python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 245, "s": 28, "text": "python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won’t work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library." }, { "code": null, "e": 329, "s": 245, "text": "Installation: Open the command prompt on your system and write given below command:" }, { "code": null, "e": 354, "s": 329, "text": "pip install python-pptx\n" }, { "code": null, "e": 383, "s": 354, "text": "Let’s see some of its usage:" }, { "code": null, "e": 454, "s": 383, "text": "Example 1: Creating new PowerPoint file with title and subtitle slide." }, { "code": null, "e": 462, "s": 454, "text": "Python3" }, { "code": "# import Presentation class# from pptx libraryfrom pptx import Presentation # Creating presentation objectroot = Presentation() # Creating slide layoutfirst_slide_layout = root.slide_layouts[0] \"\"\" Ref for slide types: 0 -> title and subtitle1 -> title and content2 -> section header3 -> two content4 -> Comparison5 -> Title only 6 -> Blank7 -> Content with caption8 -> Pic with caption\"\"\" # Creating slide object to add # in ppt i.e. Attaching slides # with Presentation i.e. pptslide = root.slides.add_slide(first_slide_layout) # Adding title and subtitle in # slide i.e. first page of slide slide.shapes.title.text = \" Created By python-pptx\" # We have different formats of # subtitles in ppts, for simple# subtitle this method should # implemented, you can change# 0 to 1 for different designslide.placeholders[1].text = \" This is 2nd way\" # Saving fileroot.save(\"Output.pptx\") print(\"done\")", "e": 1381, "s": 462, "text": null }, { "code": null, "e": 1389, "s": 1381, "text": "Output:" }, { "code": null, "e": 1431, "s": 1389, "text": "Example 2: Adding Text-Box in PowerPoint." }, { "code": null, "e": 1439, "s": 1431, "text": "Python3" }, { "code": "# import required thingsfrom pptx import Presentation from pptx.util import Inches, Pt # Creating Objectppt = Presentation() # To create blank slide layout# We have to use 6 as an argument# of slide_layouts blank_slide_layout = ppt.slide_layouts[6] # Attaching slide obj to slideslide = ppt.slides.add_slide(blank_slide_layout) # For adjusting the Margins in inches left = top = width = height = Inches(1) # creating textBoxtxBox = slide.shapes.add_textbox(left, top, width, height) # creating textFramestf = txBox.text_frametf.text = \"This is text inside a textbox\" # adding Paragraphsp = tf.add_paragraph() # adding textp.text = \"This is a second paragraph that's bold and italic\" # font p.font.bold = Truep.font.italic = True p = tf.add_paragraph()p.text = \"This is a third paragraph that's big \" p.font.size = Pt(40) # save fileppt.save('test_2.pptx') print(\"done\")", "e": 2360, "s": 1439, "text": null }, { "code": null, "e": 2368, "s": 2360, "text": "Output:" }, { "code": null, "e": 2435, "s": 2368, "text": "Example 3: PowerPoint (.pptx) file to Text (.txt) file conversion." }, { "code": null, "e": 2443, "s": 2435, "text": "Python3" }, { "code": "# import Presentation class# from pptx libraryfrom pptx import Presentation # creating an objectppt = Presentation(\"sample.pptx\") # open file in write modeFile_to_write_data = open(\"File_To_Extract_ppt.txt\", \"w\") # write text from powerpoint# file into .txt filefor slide in ppt.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: File_to_write_data.write(run.text) # close the file File_to_write_data.close() print(\"Done\")", "e": 3040, "s": 2443, "text": null }, { "code": null, "e": 3048, "s": 3040, "text": "Output:" }, { "code": null, "e": 3101, "s": 3048, "text": "Example 4: Inserting image into the PowerPoint file." }, { "code": null, "e": 3109, "s": 3101, "text": "Python3" }, { "code": "from pptx import Presentation from pptx.util import Inches # Giving Image path img_path = 'bg_bg.png' # Creating an Presentation objectppt = Presentation() # Selecting blank slideblank_slide_layout = ppt.slide_layouts[6] # Attaching slide to pptslide = ppt.slides.add_slide(blank_slide_layout) # For marginsleft = top = Inches(1) # adding imagespic = slide.shapes.add_picture(img_path, left, top) left = Inches(1) height = Inches(1) pic = slide.shapes.add_picture(img_path, left, top, height = height)# save fileppt.save('test_4.pptx') print(\"Done\")", "e": 3735, "s": 3109, "text": null }, { "code": null, "e": 3743, "s": 3735, "text": "Output:" }, { "code": null, "e": 3792, "s": 3743, "text": "Example 5: Adding Charts to the PowerPoint file." }, { "code": null, "e": 3800, "s": 3792, "text": "Python3" }, { "code": "# import required classes/functions/methodfrom pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches # Create presentation objectppt = Presentation() # Adding slide with specific layoutslide = ppt.slides.add_slide(ppt.slide_layouts[6]) # Define chart data # Creating object of chartchart_data = CategoryChartData() # Adding categories to chartchart_data.categories = ['East', 'West', 'Midwest'] # Adding serieschart_data.add_series('Series 1', (int(input(\"Enter Value:\")), int(input(\"Enter Value:\")), int(input(\"Enter Value:\")))) x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) slide.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data ) # Saving fileppt.save('chart-Tutorial.pptx') print(\"done\")", "e": 4728, "s": 3800, "text": null }, { "code": null, "e": 4736, "s": 4728, "text": "Output:" }, { "code": null, "e": 4785, "s": 4736, "text": "Example 6: Adding tables to the PowerPoint file." }, { "code": null, "e": 4793, "s": 4785, "text": "Python3" }, { "code": "# importingfrom pptx import Presentation from pptx.util import Inches # create a Presentation objectppt = Presentation() # Adding a blank slide in out pptslide = ppt.slides.add_slide(ppt.slide_layouts[6]) # Adjusting the width ! x, y, cx, cy = Inches(2), Inches(2), Inches(4), Inches(1.5) # Adding tablesshape = slide.shapes.add_table(3, 4, x, y, cx, cy) # Saving the fileppt.save(\"Tabel_Tutorial.pptx\") print(\"done\")", "e": 5251, "s": 4793, "text": null }, { "code": null, "e": 5259, "s": 5251, "text": "Output:" }, { "code": null, "e": 5274, "s": 5259, "text": "python-modules" }, { "code": null, "e": 5289, "s": 5274, "text": "python-utility" }, { "code": null, "e": 5296, "s": 5289, "text": "Python" } ]
PHP | Sum of digits of a number
09 Mar, 2018 This is a simple PHP program where we need to calculate the sum of all digits of a number.Examples: Input : 711 Output : 9 Input : 14785 Output : 25 In this program, we will try to accept a number in the form of a string and then iterate through the length of the string. While iterating we will extract the digit from each position and then add them to the previously extracted digit, thus getting the sum. <?php// PHP program to calculate the sum of digitsfunction sum($num) { $sum = 0; for ($i = 0; $i < strlen($num); $i++){ $sum += $num[$i]; } return $sum;} // Driver Code$num = "711";echo sum($num);?> Output: 9 PHP-basics PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2018" }, { "code": null, "e": 128, "s": 28, "text": "This is a simple PHP program where we need to calculate the sum of all digits of a number.Examples:" }, { "code": null, "e": 180, "s": 128, "text": "Input : 711 \nOutput : 9\n\nInput : 14785\nOutput : 25\n" }, { "code": null, "e": 439, "s": 180, "text": "In this program, we will try to accept a number in the form of a string and then iterate through the length of the string. While iterating we will extract the digit from each position and then add them to the previously extracted digit, thus getting the sum." }, { "code": "<?php// PHP program to calculate the sum of digitsfunction sum($num) { $sum = 0; for ($i = 0; $i < strlen($num); $i++){ $sum += $num[$i]; } return $sum;} // Driver Code$num = \"711\";echo sum($num);?>", "e": 658, "s": 439, "text": null }, { "code": null, "e": 666, "s": 658, "text": "Output:" }, { "code": null, "e": 669, "s": 666, "text": "9\n" }, { "code": null, "e": 680, "s": 669, "text": "PHP-basics" }, { "code": null, "e": 684, "s": 680, "text": "PHP" }, { "code": null, "e": 701, "s": 684, "text": "Web Technologies" }, { "code": null, "e": 705, "s": 701, "text": "PHP" }, { "code": null, "e": 803, "s": 705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 853, "s": 803, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 893, "s": 853, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 954, "s": 893, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1004, "s": 954, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 1049, "s": 1004, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 1082, "s": 1049, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1144, "s": 1082, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1205, "s": 1144, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1255, "s": 1205, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Program for Topological Sorting
23 Feb, 2022 Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges). Topological sorting can be implemented recursively and non-recursively. First, we show the clearer recursive version, then provide the non-recursive version with analysis. Python3 #Python program to print topological sorting of a DAGfrom collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,visited,stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Push current vertex to stack which stores result stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Print contents of stack print (stack) g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1); print ("Following is a Topological Sort of the given graph")g.topologicalSort()#This code is contributed by Neelam Yadav Output: Following is a Topological Sort of the given graph 5 4 2 3 1 0 The way topological sorting is solved is by processing a node after all of its children are processed. Each time a node is processed, it is pushed into a stack in order to save the final result. This non-recursive solution builds on the same concept of DFS with a little tweak which can be understood above and in this article. However, unlike the recursive solution, which saves the order of the nodes in the stack after all the neighboring elements have been pushed to the program stack, this solution replaces the program stack with a working stack. If a node has a neighbor that has not been visited, the current node and the neighbor are pushed to the working stack to be processed until there are no more neighbors available to be visited.After all the nodes have been visited, what remains is the final result which is found by printing the stack result in reverse. Python3 #Python program to print topological sorting of a DAGfrom collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # neighbors lazy generator given key def neighbor_gen(self,v): for k in self.graph[v]: yield k # non recursive topological sort def nonRecursiveTopologicalSortUtil(self, v, visited,stack): # working stack contains key and the corresponding current generator working_stack = [(v,self.neighbor_gen(v))] while len(working_stack) > 0: # get last element in stack v, gen = working_stack[-1] visited[v] = True # delete it from stack working_stack.pop() # run through neighbor generator until its empty continue_flag = True while continue_flag: next_neighbor = next(gen,None) # if generator has returned all neighbors if next_neighbor is None: continue_flag = False # Save current key into the result stack stack.append(v) continue # if new neighbor push current key and neighbor into stack if not(visited[next_neighbor]): working_stack.append((v,gen)) working_stack.append((next_neighbor,self.neighbor_gen(next_neighbor))) continue_flag = False # The function to do Topological Sort. def nonRecursiveTopologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V # result stack stack = [] # Call the helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if not(visited[i]): self.nonRecursiveTopologicalSortUtil(i, visited,stack) # Print contents of the stack in reverse print(stack[::-1]) g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1); print("The following is a Topological Sort of the given graph")g.nonRecursiveTopologicalSort()# The following code was based of Neelam Yadav's code and is modified by Suhail Alnahari Output: Following is a Topological Sort of the given graph 5 4 2 3 1 0 Time Complexity: O(V + E): The above algorithm is simply DFS with a working stack and a result stack. Unlike the recursive solution, recursion depth is not an issue here. Auxiliary space: O(V): The extra space is needed for the 2 stacks used. Please refer complete article on Topological Sorting for more details. alnaharisuhail amartyaghoshgfg simmytarika5 python sorting-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert a list to dictionary Iterate over characters of a string in Python Python Program for Fibonacci numbers Python | Convert set into a list Python Program for Binary Search (Recursive and Iterative) Python program to add two numbers Python Program for factorial of a number Appending to list in Python dictionary Python program to check whether a number is Prime or not Python | Check if a variable is string
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Feb, 2022" }, { "code": null, "e": 625, "s": 52, "text": "Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph. For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a vertex with in-degree as 0 (a vertex with no in-coming edges). " }, { "code": null, "e": 798, "s": 625, "text": "Topological sorting can be implemented recursively and non-recursively. First, we show the clearer recursive version, then provide the non-recursive version with analysis. " }, { "code": null, "e": 806, "s": 798, "text": "Python3" }, { "code": "#Python program to print topological sorting of a DAGfrom collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,visited,stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Push current vertex to stack which stores result stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Print contents of stack print (stack) g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1); print (\"Following is a Topological Sort of the given graph\")g.topologicalSort()#This code is contributed by Neelam Yadav", "e": 2357, "s": 806, "text": null }, { "code": null, "e": 2366, "s": 2357, "text": "Output: " }, { "code": null, "e": 2429, "s": 2366, "text": "Following is a Topological Sort of the given graph\n5 4 2 3 1 0" }, { "code": null, "e": 3304, "s": 2431, "text": "The way topological sorting is solved is by processing a node after all of its children are processed. Each time a node is processed, it is pushed into a stack in order to save the final result. This non-recursive solution builds on the same concept of DFS with a little tweak which can be understood above and in this article. However, unlike the recursive solution, which saves the order of the nodes in the stack after all the neighboring elements have been pushed to the program stack, this solution replaces the program stack with a working stack. If a node has a neighbor that has not been visited, the current node and the neighbor are pushed to the working stack to be processed until there are no more neighbors available to be visited.After all the nodes have been visited, what remains is the final result which is found by printing the stack result in reverse." }, { "code": null, "e": 3312, "s": 3304, "text": "Python3" }, { "code": "#Python program to print topological sorting of a DAGfrom collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # neighbors lazy generator given key def neighbor_gen(self,v): for k in self.graph[v]: yield k # non recursive topological sort def nonRecursiveTopologicalSortUtil(self, v, visited,stack): # working stack contains key and the corresponding current generator working_stack = [(v,self.neighbor_gen(v))] while len(working_stack) > 0: # get last element in stack v, gen = working_stack[-1] visited[v] = True # delete it from stack working_stack.pop() # run through neighbor generator until its empty continue_flag = True while continue_flag: next_neighbor = next(gen,None) # if generator has returned all neighbors if next_neighbor is None: continue_flag = False # Save current key into the result stack stack.append(v) continue # if new neighbor push current key and neighbor into stack if not(visited[next_neighbor]): working_stack.append((v,gen)) working_stack.append((next_neighbor,self.neighbor_gen(next_neighbor))) continue_flag = False # The function to do Topological Sort. def nonRecursiveTopologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V # result stack stack = [] # Call the helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if not(visited[i]): self.nonRecursiveTopologicalSortUtil(i, visited,stack) # Print contents of the stack in reverse print(stack[::-1]) g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1); print(\"The following is a Topological Sort of the given graph\")g.nonRecursiveTopologicalSort()# The following code was based of Neelam Yadav's code and is modified by Suhail Alnahari", "e": 5887, "s": 3312, "text": null }, { "code": null, "e": 5896, "s": 5887, "text": "Output: " }, { "code": null, "e": 5959, "s": 5896, "text": "Following is a Topological Sort of the given graph\n5 4 2 3 1 0" }, { "code": null, "e": 6130, "s": 5959, "text": "Time Complexity: O(V + E): The above algorithm is simply DFS with a working stack and a result stack. Unlike the recursive solution, recursion depth is not an issue here." }, { "code": null, "e": 6202, "s": 6130, "text": "Auxiliary space: O(V): The extra space is needed for the 2 stacks used." }, { "code": null, "e": 6274, "s": 6202, "text": "Please refer complete article on Topological Sorting for more details. " }, { "code": null, "e": 6289, "s": 6274, "text": "alnaharisuhail" }, { "code": null, "e": 6305, "s": 6289, "text": "amartyaghoshgfg" }, { "code": null, "e": 6318, "s": 6305, "text": "simmytarika5" }, { "code": null, "e": 6343, "s": 6318, "text": "python sorting-exercises" }, { "code": null, "e": 6359, "s": 6343, "text": "Python Programs" }, { "code": null, "e": 6457, "s": 6359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6495, "s": 6457, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 6541, "s": 6495, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 6578, "s": 6541, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 6611, "s": 6578, "text": "Python | Convert set into a list" }, { "code": null, "e": 6670, "s": 6611, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 6704, "s": 6670, "text": "Python program to add two numbers" }, { "code": null, "e": 6745, "s": 6704, "text": "Python Program for factorial of a number" }, { "code": null, "e": 6784, "s": 6745, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 6841, "s": 6784, "text": "Python program to check whether a number is Prime or not" } ]
Merge two Pandas DataFrames on certain columns
12 Oct, 2021 We can merge two Pandas DataFrames on certain columns using the merge function by simply specifying the certain columns for merge. Syntax: DataFrame.merge(right, how=’inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, copy=True, indicator=False, validate=None) Example1: Let’s create a Dataframe and then merge them into a single dataframe. Creating a Dataframe: Python3 # importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2) Output: df1 df2 Now merge the dataframe: Python3 # applying mergedf1.merge(df2[['Name', 'Grade', 'Rank']]) Output: Merged Dataframe The resultant dataframe contains all the columns of df1 but certain specified columns of df2 with key column Name i.e. the resultant column contains Name, Marks, Grade, Rank column. Both dataframes has the different number of values but only common values in both the dataframes are displayed after merge. Example 2: In the resultant dataframe Grade column of df2 is merged with df1 based on key column Name with merge type left i.e. all the values of left dataframe (df1) will be displayed. Python3 # importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2) # applying merge with more parametersdf1.merge(df2[['Grade', 'Name']], on = 'Name', how = 'left') Output: df1 df2 Merged Dataframe Example 3: In this example, we have merged df1 with df2. The Marks column of df1 is merged with df2 and only the common values based on key column Name in both the dataframes are displayed here. Python3 # importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2) # applying merge with more parametersdf2.merge(df1[['Marks', 'Name']]) Output: df1 df2 Merged Dataframe anikakapoor Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Oct, 2021" }, { "code": null, "e": 184, "s": 52, "text": "We can merge two Pandas DataFrames on certain columns using the merge function by simply specifying the certain columns for merge. " }, { "code": null, "e": 358, "s": 184, "text": "Syntax: DataFrame.merge(right, how=’inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, copy=True, indicator=False, validate=None)" }, { "code": null, "e": 438, "s": 358, "text": "Example1: Let’s create a Dataframe and then merge them into a single dataframe." }, { "code": null, "e": 460, "s": 438, "text": "Creating a Dataframe:" }, { "code": null, "e": 468, "s": 460, "text": "Python3" }, { "code": "# importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2)", "e": 974, "s": 468, "text": null }, { "code": null, "e": 982, "s": 974, "text": "Output:" }, { "code": null, "e": 986, "s": 982, "text": "df1" }, { "code": null, "e": 990, "s": 986, "text": "df2" }, { "code": null, "e": 1015, "s": 990, "text": "Now merge the dataframe:" }, { "code": null, "e": 1023, "s": 1015, "text": "Python3" }, { "code": "# applying mergedf1.merge(df2[['Name', 'Grade', 'Rank']])", "e": 1081, "s": 1023, "text": null }, { "code": null, "e": 1089, "s": 1081, "text": "Output:" }, { "code": null, "e": 1106, "s": 1089, "text": "Merged Dataframe" }, { "code": null, "e": 1412, "s": 1106, "text": "The resultant dataframe contains all the columns of df1 but certain specified columns of df2 with key column Name i.e. the resultant column contains Name, Marks, Grade, Rank column. Both dataframes has the different number of values but only common values in both the dataframes are displayed after merge." }, { "code": null, "e": 1599, "s": 1412, "text": "Example 2: In the resultant dataframe Grade column of df2 is merged with df1 based on key column Name with merge type left i.e. all the values of left dataframe (df1) will be displayed. " }, { "code": null, "e": 1607, "s": 1599, "text": "Python3" }, { "code": "# importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2) # applying merge with more parametersdf1.merge(df2[['Grade', 'Name']], on = 'Name', how = 'left')", "e": 2212, "s": 1607, "text": null }, { "code": null, "e": 2220, "s": 2212, "text": "Output:" }, { "code": null, "e": 2224, "s": 2220, "text": "df1" }, { "code": null, "e": 2228, "s": 2224, "text": "df2" }, { "code": null, "e": 2245, "s": 2228, "text": "Merged Dataframe" }, { "code": null, "e": 2440, "s": 2245, "text": "Example 3: In this example, we have merged df1 with df2. The Marks column of df1 is merged with df2 and only the common values based on key column Name in both the dataframes are displayed here." }, { "code": null, "e": 2448, "s": 2440, "text": "Python3" }, { "code": "# importing modulesimport pandas as pd # creating a dataframedf1 = pd.DataFrame({'Name':['Raju', 'Rani', 'Geeta', 'Sita', 'Sohit'], 'Marks':[80, 90, 75, 88, 59]}) # creating another dataframe with different datadf2 = pd.DataFrame({'Name':['Raju', 'Divya', 'Geeta', 'Sita'], 'Grade':['A', 'A', 'B', 'A'], 'Rank':[3, 1, 4, 2 ], 'Gender':['Male', 'Female', 'Female', 'Female']})# display df1display(df1) # display df2display(df2) # applying merge with more parametersdf2.merge(df1[['Marks', 'Name']])", "e": 3026, "s": 2448, "text": null }, { "code": null, "e": 3034, "s": 3026, "text": "Output:" }, { "code": null, "e": 3038, "s": 3034, "text": "df1" }, { "code": null, "e": 3042, "s": 3038, "text": "df2" }, { "code": null, "e": 3059, "s": 3042, "text": "Merged Dataframe" }, { "code": null, "e": 3071, "s": 3059, "text": "anikakapoor" }, { "code": null, "e": 3078, "s": 3071, "text": "Picked" }, { "code": null, "e": 3102, "s": 3078, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3125, "s": 3102, "text": "Python Pandas-exercise" }, { "code": null, "e": 3139, "s": 3125, "text": "Python-pandas" }, { "code": null, "e": 3146, "s": 3139, "text": "Python" }, { "code": null, "e": 3244, "s": 3146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3276, "s": 3244, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3303, "s": 3276, "text": "Python Classes and Objects" }, { "code": null, "e": 3324, "s": 3303, "text": "Python OOPs Concepts" }, { "code": null, "e": 3347, "s": 3324, "text": "Introduction To PYTHON" }, { "code": null, "e": 3403, "s": 3347, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3434, "s": 3403, "text": "Python | os.path.join() method" }, { "code": null, "e": 3476, "s": 3434, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3518, "s": 3476, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3557, "s": 3518, "text": "Python | datetime.timedelta() function" } ]
ProcessPoolExecutor Class in Python
08 Oct, 2021 Prerequisite – Multiprocessing It allows parallelism of code and the Python language has two ways to achieve its 1st is via multiprocessing module and 2nd is via multithreading module. From Python 3.2 onwards a new class called ProcessPoolExecutor was introduced in python in concurrent. The futures module to efficiently manage and create Process. But wait, if python already had a multiprocessing module inbuilt then why a new module was introduced. Let me answer this first. Spawning a new process on the fly is not a problem when the number of processes is less, but it becomes really cumbersome to manage processes if we are dealing with many processes. Apart from this, it is computationally inefficient to create so many processes which will lead to a decline in throughput. An approach to keep up the throughput is to create & instantiate a pool of idle Processes beforehand and reuse the Processes from this pool until all the Processes are exhausted. This way the overhead of creating new Processes is reduced. Also, the pool keeps track and manages the Process lifecycle and schedules them on the programmer’s behalf thus making the code much simpler and less buggy. Syntax: concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=”, initializer=None, initargs=()) Parameters: max_workers: It is number of Process aka size of pool. If the value is None, then on Windows by default 61 process are created even if number of cores available is more than that. mp_context: It is the multiprocessing context, If None or empty then the default multiprocessing context is used. It allows user to control starting method. initializer: initializer takes a callable which is invoked on start of each worker Process. initargs: It’s a tuple of arguments passed to initializer. ProcessPoolExecutor Methods: ProcessPoolExecutor class exposes the following methods to execute Process asynchronously. A detailed explanation is given below. submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method. map(fn, *iterables, timeout=None, chunksize=1): It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor . If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor . shutdown(wait=True, *, cancel_futures=False):It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start. It signals the executor to free up all resources when the futures are done executing. It must be called before executor.submit() and executor.map() method else it would throw RuntimeError. wait=True makes the method not to return until execution of all threads is done and resources are freed up. cancel_futures=True then the executor will cancel all the future threads that are yet to start. Cancel(): It Attempts to cancel the call, if the call cannot be canceled then it returns False, else True. cancelled(): returns True if the call is canceled. running(): return True if the process is running and cannot be canceled. done(): returns True if the process has finished executing. result(timeout=None): returns the value which is returned by the process, if the process is still in execution then it waits for the timeout specified else raises a TimeoutError, if None is specified it will wait forever for the process to finish. add_done_callback(fn): Attaches a callback function which is called when the process finishes its execution. The below code demonstrates the use of ProcessPoolExecutor, notice unlike with the multiprocessing module we do not have to explicitly call using a loop, keeping a track of the process using a list or wait for the process using join for synchronization, or releasing the resources after the Process are finished everything is taken under the hood by the constructor itself making the code compact and bug-free. Python3 from concurrent.futures import ProcessPoolExecutorfrom time import sleep values = [3,4,5,6]def cube(x): print(f'Cube of {x}:{x*x*x}') if __name__ == '__main__': result =[] with ProcessPoolExecutor(max_workers=5) as exe: exe.submit(cube,2) # Maps the method 'cube' with a iterable result = exe.map(cube,values) for r in result: print(r) Output: Cube of 2:8 Cube of 3:27 Cube of 6:216 Cube of 4:64 Cube of 5:125 The below code is fetching images over the internet by making an HTTP request, I am using the request library for the same. The first section of the code makes a one-to-one call to the API and i.e the download is slow, whereas the second section of the code makes a parallel request using multiple Processes to fetch API. You can try all various parameters discussed above to see how it tunes the speedup for example if I make a Process pool of 6 instead of 3 the speedup is more significant. Python3 import requestsimport timeimport osimport concurrent.futures img_urls = [ 'https://media.geeksforgeeks.org/wp-content/uploads/20190623210949/download21.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211125/d11.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211655/d31.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212213/d4.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212607/d5.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623235904/d6.jpg',] t1 = time.time()print("Downloading images with single process")def download_image(img_url): img_bytes = requests.get(img_url).content print("Downloading..") for img in img_urls: download_image(img) t2 = time.time()print(f'Single Process Code Took :{t2-t1} seconds')print('*'*50) t1 = time.time()print("Downloading images with Multiprocess") def download_image(img_url): img_bytes = requests.get(img_url).content print(f"[Process ID]:{os.getpid()} Downloading..") with concurrent.futures.ProcessPoolExecutor(3) as exe: exe.map(download_image, img_urls) t2 = time.time()print(f'Multiprocess Code Took:{t2-t1} seconds') Output: Downloading images with single process Downloading.. Downloading.. Downloading.. Downloading.. Downloading.. Downloading.. Single Process Code Took :1.2382981777191162 seconds ************************************************** Downloading images with Multiprocess [Process ID]:118741 Downloading.. [Process ID]:118742 Downloading.. [Process ID]:118740 Downloading.. [Process ID]:118741 Downloading.. [Process ID]:118742 Downloading.. [Process ID]:118740 Downloading.. Multiprocess Code Took:0.8398590087890625 seconds ruhelaa48 adnanirshad158 Python-multithreading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 59, "s": 28, "text": "Prerequisite – Multiprocessing" }, { "code": null, "e": 506, "s": 59, "text": "It allows parallelism of code and the Python language has two ways to achieve its 1st is via multiprocessing module and 2nd is via multithreading module. From Python 3.2 onwards a new class called ProcessPoolExecutor was introduced in python in concurrent. The futures module to efficiently manage and create Process. But wait, if python already had a multiprocessing module inbuilt then why a new module was introduced. Let me answer this first." }, { "code": null, "e": 1049, "s": 506, "text": "Spawning a new process on the fly is not a problem when the number of processes is less, but it becomes really cumbersome to manage processes if we are dealing with many processes. Apart from this, it is computationally inefficient to create so many processes which will lead to a decline in throughput. An approach to keep up the throughput is to create & instantiate a pool of idle Processes beforehand and reuse the Processes from this pool until all the Processes are exhausted. This way the overhead of creating new Processes is reduced." }, { "code": null, "e": 1206, "s": 1049, "text": "Also, the pool keeps track and manages the Process lifecycle and schedules them on the programmer’s behalf thus making the code much simpler and less buggy." }, { "code": null, "e": 1214, "s": 1206, "text": "Syntax:" }, { "code": null, "e": 1316, "s": 1214, "text": "concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=”, initializer=None, initargs=())" }, { "code": null, "e": 1328, "s": 1316, "text": "Parameters:" }, { "code": null, "e": 1508, "s": 1328, "text": "max_workers: It is number of Process aka size of pool. If the value is None, then on Windows by default 61 process are created even if number of cores available is more than that." }, { "code": null, "e": 1665, "s": 1508, "text": "mp_context: It is the multiprocessing context, If None or empty then the default multiprocessing context is used. It allows user to control starting method." }, { "code": null, "e": 1757, "s": 1665, "text": "initializer: initializer takes a callable which is invoked on start of each worker Process." }, { "code": null, "e": 1816, "s": 1757, "text": "initargs: It’s a tuple of arguments passed to initializer." }, { "code": null, "e": 1975, "s": 1816, "text": "ProcessPoolExecutor Methods: ProcessPoolExecutor class exposes the following methods to execute Process asynchronously. A detailed explanation is given below." }, { "code": null, "e": 2111, "s": 1975, "text": "submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method." }, { "code": null, "e": 2449, "s": 2111, "text": "map(fn, *iterables, timeout=None, chunksize=1): It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor ." }, { "code": null, "e": 2578, "s": 2449, "text": "If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor ." }, { "code": null, "e": 3013, "s": 2578, "text": "shutdown(wait=True, *, cancel_futures=False):It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start." }, { "code": null, "e": 3099, "s": 3013, "text": "It signals the executor to free up all resources when the futures are done executing." }, { "code": null, "e": 3202, "s": 3099, "text": "It must be called before executor.submit() and executor.map() method else it would throw RuntimeError." }, { "code": null, "e": 3310, "s": 3202, "text": "wait=True makes the method not to return until execution of all threads is done and resources are freed up." }, { "code": null, "e": 3406, "s": 3310, "text": "cancel_futures=True then the executor will cancel all the future threads that are yet to start." }, { "code": null, "e": 3513, "s": 3406, "text": "Cancel(): It Attempts to cancel the call, if the call cannot be canceled then it returns False, else True." }, { "code": null, "e": 3564, "s": 3513, "text": "cancelled(): returns True if the call is canceled." }, { "code": null, "e": 3637, "s": 3564, "text": "running(): return True if the process is running and cannot be canceled." }, { "code": null, "e": 3697, "s": 3637, "text": "done(): returns True if the process has finished executing." }, { "code": null, "e": 3945, "s": 3697, "text": "result(timeout=None): returns the value which is returned by the process, if the process is still in execution then it waits for the timeout specified else raises a TimeoutError, if None is specified it will wait forever for the process to finish." }, { "code": null, "e": 4054, "s": 3945, "text": "add_done_callback(fn): Attaches a callback function which is called when the process finishes its execution." }, { "code": null, "e": 4465, "s": 4054, "text": "The below code demonstrates the use of ProcessPoolExecutor, notice unlike with the multiprocessing module we do not have to explicitly call using a loop, keeping a track of the process using a list or wait for the process using join for synchronization, or releasing the resources after the Process are finished everything is taken under the hood by the constructor itself making the code compact and bug-free." }, { "code": null, "e": 4473, "s": 4465, "text": "Python3" }, { "code": "from concurrent.futures import ProcessPoolExecutorfrom time import sleep values = [3,4,5,6]def cube(x): print(f'Cube of {x}:{x*x*x}') if __name__ == '__main__': result =[] with ProcessPoolExecutor(max_workers=5) as exe: exe.submit(cube,2) # Maps the method 'cube' with a iterable result = exe.map(cube,values) for r in result: print(r)", "e": 4862, "s": 4473, "text": null }, { "code": null, "e": 4870, "s": 4862, "text": "Output:" }, { "code": null, "e": 4936, "s": 4870, "text": "Cube of 2:8\nCube of 3:27\nCube of 6:216\nCube of 4:64\nCube of 5:125" }, { "code": null, "e": 5258, "s": 4936, "text": "The below code is fetching images over the internet by making an HTTP request, I am using the request library for the same. The first section of the code makes a one-to-one call to the API and i.e the download is slow, whereas the second section of the code makes a parallel request using multiple Processes to fetch API." }, { "code": null, "e": 5429, "s": 5258, "text": "You can try all various parameters discussed above to see how it tunes the speedup for example if I make a Process pool of 6 instead of 3 the speedup is more significant." }, { "code": null, "e": 5437, "s": 5429, "text": "Python3" }, { "code": "import requestsimport timeimport osimport concurrent.futures img_urls = [ 'https://media.geeksforgeeks.org/wp-content/uploads/20190623210949/download21.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211125/d11.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211655/d31.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212213/d4.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212607/d5.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623235904/d6.jpg',] t1 = time.time()print(\"Downloading images with single process\")def download_image(img_url): img_bytes = requests.get(img_url).content print(\"Downloading..\") for img in img_urls: download_image(img) t2 = time.time()print(f'Single Process Code Took :{t2-t1} seconds')print('*'*50) t1 = time.time()print(\"Downloading images with Multiprocess\") def download_image(img_url): img_bytes = requests.get(img_url).content print(f\"[Process ID]:{os.getpid()} Downloading..\") with concurrent.futures.ProcessPoolExecutor(3) as exe: exe.map(download_image, img_urls) t2 = time.time()print(f'Multiprocess Code Took:{t2-t1} seconds')", "e": 6643, "s": 5437, "text": null }, { "code": null, "e": 6651, "s": 6643, "text": "Output:" }, { "code": null, "e": 7169, "s": 6651, "text": "Downloading images with single process\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nSingle Process Code Took :1.2382981777191162 seconds\n**************************************************\nDownloading images with Multiprocess\n[Process ID]:118741 Downloading..\n[Process ID]:118742 Downloading..\n[Process ID]:118740 Downloading..\n[Process ID]:118741 Downloading..\n[Process ID]:118742 Downloading..\n[Process ID]:118740 Downloading..\nMultiprocess Code Took:0.8398590087890625 seconds" }, { "code": null, "e": 7181, "s": 7171, "text": "ruhelaa48" }, { "code": null, "e": 7196, "s": 7181, "text": "adnanirshad158" }, { "code": null, "e": 7218, "s": 7196, "text": "Python-multithreading" }, { "code": null, "e": 7225, "s": 7218, "text": "Python" } ]
Talking to Python from Javascript: Flask and the fetch API | by Daniel Ellis | Towards Data Science
Within the field of data science, it is common to be required to use a selection of tools, each specific to their job. A role requiring visualisation using a web interface, but processing of a Python script, it is often better to build a bespoke visualisation in d3 or THREE.js to display it and then fetch data as required. This article covers the creation of a simple flask app that can serve data to a web interface using the Fetch API. We start by building a repository containing an empty templates folder and an app.py file. Our app.pyfile contains the data required to create a web interface. To do this we use the flask ( pip install flask ) python library. For this we can use the following template: ######## imports ##########from flask import Flask, jsonify, request, render_templateapp = Flask(__name__)############################## Additional code goes here ####################################### run app #########app.run(debug=True) Here we start by importing the required functions, the app structure and the run command to start the app. Having defined our flask app, we now need to create a template webpage. This can be done by placing the file index.html within the templates directory. <body><h1> Python Fetch Example</h1><p id='embed'>{{embed}}</p><p id='mylog'/><body> Since we are using this as a template we can use a react-style replacement syntax for certain keywords. In this instance {{embed}} is to be replaced by the embed_example string in the snippet below. @app.route('/')def home_page(): example_embed='This string is from python' return render_template('index.html', embed=example_embed) This defines the code which runs when the home page of the flask app is reached and needs to be added between the imports and the app.run() lines within app.py. Finally, we can run the app and view it using python app.py and navigating to https://127.0.0.1:5000/ in a web browser to view it. When it comes to transferring data we rely on the GET and POST functions within the fetch API. These terms are pretty self-explanatory: POST refers to the sending of information to a location, similar to sending a letter. GET refers to the retrieval of data — you know you have mail, so you go to the post office to collect (ask for) it. Within app.py we can create a URL for GET requests. The following code defines the response when the URL is called. @app.route('/test', methods=['GET', 'POST'])def testfn(): # GET request if request.method == 'GET': message = {'greeting':'Hello from Flask!'} return jsonify(message) # serialize and use JSON headers # POST request if request.method == 'POST': print(request.get_json()) # parse as JSON return 'Sucesss', 200 Following a GET request, we define a dictionary containing a greeting element and serialise it. Next, this is then posted back to the calling javascript program. After adding the following code before the app.run() command, and executing it, we can then visit https://127.0.0.1:5000/test — which should produce the following result: { "greeting": "Hello from Flask!"} Now we have set up the server-side of things, we can use fetch command to retrieve the data from it. To do this we can use the fetch promise as follows: fetch('/test') .then(function (response) { return response.json(); }).then(function (text) { console.log('GET response:'); console.log(text.greeting); }); Here we run a GET request on /test which converts the returned JSON string into an object, and then prints the greeting element to the web console. As usual, the JavaScript code should be nested between <script> tags within the HTML document. Now we have a working example we can expand it to include actual data. In reality, this could involve accessing a database, decrypting some information or filtering a table. For the purpose of this tutorial we create a data array from which we index elements: ######## Example data, in sets of 3 ############data = list(range(1,300,3))print (data) Within our Flask app, we can add optional arguments to the GET request — in this case, the array index we are interested in. This is specified through the additional page extension within the page URL /getdata/<index_no> . This argument is then passed into the page function and processed (data[int(index_no)]) within the return command. ######## Data fetch ############@app.route('/getdata/<index_no>', methods=['GET','POST'])def data_get(index_no): if request.method == 'POST': # POST request print(request.get_text()) # parse as text return 'OK', 200 else: # GET request return 't_in = %s ; result: %s ;'%(index_no, data[int(index_no)]) The fetch request remains the same with the exception of changing the GET URL to include the index of the data element we are interested in. This is done within the JS script in index.html . var index = 33;fetch(`/getdata/${index}`) .then(function (response) { return response.text(); }).then(function (text) { console.log('GET response text:'); console.log(text); }); This time, instead of returning an object, we return a string and parse it as such. This can then be used as needed within the code — be it to update a figure or display a message. We have explored a method to extract data using python and serve it to a javascript code for visualisation (alternatives include web/TCP sockets and file streaming). We are able to create a server-side python code to pre-process or decrypt data and only serve the required information to the client. This is useful if we have constantly updating data, a large (high resource) dataset, or sensitive data we can not provide to the client directly. Accompanying sample code used within this article can be found at:
[ { "code": null, "e": 612, "s": 172, "text": "Within the field of data science, it is common to be required to use a selection of tools, each specific to their job. A role requiring visualisation using a web interface, but processing of a Python script, it is often better to build a bespoke visualisation in d3 or THREE.js to display it and then fetch data as required. This article covers the creation of a simple flask app that can serve data to a web interface using the Fetch API." }, { "code": null, "e": 703, "s": 612, "text": "We start by building a repository containing an empty templates folder and an app.py file." }, { "code": null, "e": 882, "s": 703, "text": "Our app.pyfile contains the data required to create a web interface. To do this we use the flask ( pip install flask ) python library. For this we can use the following template:" }, { "code": null, "e": 1126, "s": 882, "text": "######## imports ##########from flask import Flask, jsonify, request, render_templateapp = Flask(__name__)############################## Additional code goes here ####################################### run app #########app.run(debug=True)" }, { "code": null, "e": 1233, "s": 1126, "text": "Here we start by importing the required functions, the app structure and the run command to start the app." }, { "code": null, "e": 1385, "s": 1233, "text": "Having defined our flask app, we now need to create a template webpage. This can be done by placing the file index.html within the templates directory." }, { "code": null, "e": 1470, "s": 1385, "text": "<body><h1> Python Fetch Example</h1><p id='embed'>{{embed}}</p><p id='mylog'/><body>" }, { "code": null, "e": 1669, "s": 1470, "text": "Since we are using this as a template we can use a react-style replacement syntax for certain keywords. In this instance {{embed}} is to be replaced by the embed_example string in the snippet below." }, { "code": null, "e": 1808, "s": 1669, "text": "@app.route('/')def home_page(): example_embed='This string is from python' return render_template('index.html', embed=example_embed)" }, { "code": null, "e": 1969, "s": 1808, "text": "This defines the code which runs when the home page of the flask app is reached and needs to be added between the imports and the app.run() lines within app.py." }, { "code": null, "e": 2100, "s": 1969, "text": "Finally, we can run the app and view it using python app.py and navigating to https://127.0.0.1:5000/ in a web browser to view it." }, { "code": null, "e": 2236, "s": 2100, "text": "When it comes to transferring data we rely on the GET and POST functions within the fetch API. These terms are pretty self-explanatory:" }, { "code": null, "e": 2322, "s": 2236, "text": "POST refers to the sending of information to a location, similar to sending a letter." }, { "code": null, "e": 2438, "s": 2322, "text": "GET refers to the retrieval of data — you know you have mail, so you go to the post office to collect (ask for) it." }, { "code": null, "e": 2554, "s": 2438, "text": "Within app.py we can create a URL for GET requests. The following code defines the response when the URL is called." }, { "code": null, "e": 2904, "s": 2554, "text": "@app.route('/test', methods=['GET', 'POST'])def testfn(): # GET request if request.method == 'GET': message = {'greeting':'Hello from Flask!'} return jsonify(message) # serialize and use JSON headers # POST request if request.method == 'POST': print(request.get_json()) # parse as JSON return 'Sucesss', 200" }, { "code": null, "e": 3066, "s": 2904, "text": "Following a GET request, we define a dictionary containing a greeting element and serialise it. Next, this is then posted back to the calling javascript program." }, { "code": null, "e": 3237, "s": 3066, "text": "After adding the following code before the app.run() command, and executing it, we can then visit https://127.0.0.1:5000/test — which should produce the following result:" }, { "code": null, "e": 3273, "s": 3237, "text": "{ \"greeting\": \"Hello from Flask!\"}" }, { "code": null, "e": 3426, "s": 3273, "text": "Now we have set up the server-side of things, we can use fetch command to retrieve the data from it. To do this we can use the fetch promise as follows:" }, { "code": null, "e": 3626, "s": 3426, "text": " fetch('/test') .then(function (response) { return response.json(); }).then(function (text) { console.log('GET response:'); console.log(text.greeting); });" }, { "code": null, "e": 3869, "s": 3626, "text": "Here we run a GET request on /test which converts the returned JSON string into an object, and then prints the greeting element to the web console. As usual, the JavaScript code should be nested between <script> tags within the HTML document." }, { "code": null, "e": 4043, "s": 3869, "text": "Now we have a working example we can expand it to include actual data. In reality, this could involve accessing a database, decrypting some information or filtering a table." }, { "code": null, "e": 4129, "s": 4043, "text": "For the purpose of this tutorial we create a data array from which we index elements:" }, { "code": null, "e": 4217, "s": 4129, "text": "######## Example data, in sets of 3 ############data = list(range(1,300,3))print (data)" }, { "code": null, "e": 4555, "s": 4217, "text": "Within our Flask app, we can add optional arguments to the GET request — in this case, the array index we are interested in. This is specified through the additional page extension within the page URL /getdata/<index_no> . This argument is then passed into the page function and processed (data[int(index_no)]) within the return command." }, { "code": null, "e": 4893, "s": 4555, "text": "######## Data fetch ############@app.route('/getdata/<index_no>', methods=['GET','POST'])def data_get(index_no): if request.method == 'POST': # POST request print(request.get_text()) # parse as text return 'OK', 200 else: # GET request return 't_in = %s ; result: %s ;'%(index_no, data[int(index_no)])" }, { "code": null, "e": 5084, "s": 4893, "text": "The fetch request remains the same with the exception of changing the GET URL to include the index of the data element we are interested in. This is done within the JS script in index.html ." }, { "code": null, "e": 5305, "s": 5084, "text": "var index = 33;fetch(`/getdata/${index}`) .then(function (response) { return response.text(); }).then(function (text) { console.log('GET response text:'); console.log(text); });" }, { "code": null, "e": 5486, "s": 5305, "text": "This time, instead of returning an object, we return a string and parse it as such. This can then be used as needed within the code — be it to update a figure or display a message." }, { "code": null, "e": 5786, "s": 5486, "text": "We have explored a method to extract data using python and serve it to a javascript code for visualisation (alternatives include web/TCP sockets and file streaming). We are able to create a server-side python code to pre-process or decrypt data and only serve the required information to the client." }, { "code": null, "e": 5932, "s": 5786, "text": "This is useful if we have constantly updating data, a large (high resource) dataset, or sensitive data we can not provide to the client directly." } ]
The One PyTorch Trick Which You Should Know | by Tivadar Danka | Towards Data Science
If you have ever used deep learning before, you know that debugging a model can be really hard sometimes. Tensor shape mismatches, exploding gradients, and countless other issues can surprise you. Solving these require looking at the model under the microscope. The most basic methods include littering the forward() methods with print statements or introducing breakpoints. These are of course not very scalable, because they require guessing where things went wrong, and are quite tedious to do overall. However, there is a solution: hooks. These are specific functions, able to be attached to every layer and called each time the layer is used. They basically allow you to freeze the execution of the forward or backward pass at a specific module and process its inputs and outputs. Let’s see them in action! So, a hook is just a callable object with a predefined signature, which can be registered to any nn.Module object. When the trigger method is used on the module (i.e. forward() or backward()), the module itself with its inputs and possible outputs are passed to the hook, executing before the computation proceeds to the next module. In PyTorch, you can register a hook as a forward prehook (executing before the forward pass), forward hook (executing after the forward pass), backward hook (executing after the backward pass). It might sound complicated at first, so let’s take a look at a concrete example! Suppose that we want to inspect the output of each convolutional layer in a ResNet34 architecture. This task is perfectly suitable for hooks. In the next part, I will show you how can this be performed. If you would like to follow it interactively, you can find the accompanying Jupyter notebook at https://github.com/cosmic-cortex/pytorch-hooks-tutorial. Our model is defined by the following. Creating a hook to save outputs is very simple, a basic callable object is perfectly enough for our purposes. An instance of SaveOutput will simply record the output tensor of the forward pass and stores it in a list. A forward hook can be registered with the register_forward_hook(hook) method. (For the other types of hooks, we have register_backward_hook and register_forward_pre_hook.) The return value of these methods is the hook handle, which can be used to remove the hook from the module. Now we register the hook to each convolutional layer. When this is done, the hook will be called after each forward pass of each convolutional layer. To test it out, we are going to use the following image. The forward pass: As expected, the outputs were stored properly. >>> len(save_output.outputs)36 By inspecting the tensors in this list, we can visualize what the network sees. Just for curiosity, we can check what happens later. If we go deeper in the network, the learned features become more and more high level. For instance, there is a filter which seems to be responsible for detecting the eyes. Of course, this is just the tip of the iceberg. Hooks can do much more than simply store outputs of intermediate layers. For instance, neural network pruning, which is a technique to reduce the number of parameters, can also be performed with hooks. To summarize, applying hooks is a very useful technique to learn if you want to enhance your workflow. With this under your belt, you’ll be able to do much more and do them more effectively. If you love taking machine learning concepts apart and understanding what makes them tick, we have a lot in common. Check out my blog, where I frequently publish technical posts like this!
[ { "code": null, "e": 678, "s": 172, "text": "If you have ever used deep learning before, you know that debugging a model can be really hard sometimes. Tensor shape mismatches, exploding gradients, and countless other issues can surprise you. Solving these require looking at the model under the microscope. The most basic methods include littering the forward() methods with print statements or introducing breakpoints. These are of course not very scalable, because they require guessing where things went wrong, and are quite tedious to do overall." }, { "code": null, "e": 958, "s": 678, "text": "However, there is a solution: hooks. These are specific functions, able to be attached to every layer and called each time the layer is used. They basically allow you to freeze the execution of the forward or backward pass at a specific module and process its inputs and outputs." }, { "code": null, "e": 984, "s": 958, "text": "Let’s see them in action!" }, { "code": null, "e": 1318, "s": 984, "text": "So, a hook is just a callable object with a predefined signature, which can be registered to any nn.Module object. When the trigger method is used on the module (i.e. forward() or backward()), the module itself with its inputs and possible outputs are passed to the hook, executing before the computation proceeds to the next module." }, { "code": null, "e": 1359, "s": 1318, "text": "In PyTorch, you can register a hook as a" }, { "code": null, "e": 1412, "s": 1359, "text": "forward prehook (executing before the forward pass)," }, { "code": null, "e": 1461, "s": 1412, "text": "forward hook (executing after the forward pass)," }, { "code": null, "e": 1512, "s": 1461, "text": "backward hook (executing after the backward pass)." }, { "code": null, "e": 1593, "s": 1512, "text": "It might sound complicated at first, so let’s take a look at a concrete example!" }, { "code": null, "e": 1949, "s": 1593, "text": "Suppose that we want to inspect the output of each convolutional layer in a ResNet34 architecture. This task is perfectly suitable for hooks. In the next part, I will show you how can this be performed. If you would like to follow it interactively, you can find the accompanying Jupyter notebook at https://github.com/cosmic-cortex/pytorch-hooks-tutorial." }, { "code": null, "e": 1988, "s": 1949, "text": "Our model is defined by the following." }, { "code": null, "e": 2098, "s": 1988, "text": "Creating a hook to save outputs is very simple, a basic callable object is perfectly enough for our purposes." }, { "code": null, "e": 2206, "s": 2098, "text": "An instance of SaveOutput will simply record the output tensor of the forward pass and stores it in a list." }, { "code": null, "e": 2486, "s": 2206, "text": "A forward hook can be registered with the register_forward_hook(hook) method. (For the other types of hooks, we have register_backward_hook and register_forward_pre_hook.) The return value of these methods is the hook handle, which can be used to remove the hook from the module." }, { "code": null, "e": 2540, "s": 2486, "text": "Now we register the hook to each convolutional layer." }, { "code": null, "e": 2693, "s": 2540, "text": "When this is done, the hook will be called after each forward pass of each convolutional layer. To test it out, we are going to use the following image." }, { "code": null, "e": 2711, "s": 2693, "text": "The forward pass:" }, { "code": null, "e": 2758, "s": 2711, "text": "As expected, the outputs were stored properly." }, { "code": null, "e": 2789, "s": 2758, "text": ">>> len(save_output.outputs)36" }, { "code": null, "e": 2869, "s": 2789, "text": "By inspecting the tensors in this list, we can visualize what the network sees." }, { "code": null, "e": 3094, "s": 2869, "text": "Just for curiosity, we can check what happens later. If we go deeper in the network, the learned features become more and more high level. For instance, there is a filter which seems to be responsible for detecting the eyes." }, { "code": null, "e": 3344, "s": 3094, "text": "Of course, this is just the tip of the iceberg. Hooks can do much more than simply store outputs of intermediate layers. For instance, neural network pruning, which is a technique to reduce the number of parameters, can also be performed with hooks." }, { "code": null, "e": 3535, "s": 3344, "text": "To summarize, applying hooks is a very useful technique to learn if you want to enhance your workflow. With this under your belt, you’ll be able to do much more and do them more effectively." } ]
Animate Bootstrap progress bar
Follow the below given steps to create an animated progress bar: Add a <div> with a class of .progress and .progress-striped. Also, add class .active to .progress-striped. Next, inside the above <div>, add an empty <div> with a class of .progress-bar. Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%. You can try to run the following code to create animated progress bar − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <h2>Progress Bar</h2> <h3>Normal Progress Bar</h3> <div class = "progress progress-striped"> <div class = "progress-bar progress-bar-success" role = "progressbar" aria-valuenow = "45" aria-valuemin = "0" aria-valuemax = "100" style = "width: 45%;"> <span class = "sr-only">45%Complete (success)</span> </div> </div> <h3>Animated Progress Bar</h3> <div class = "progress progress-striped active"> <div class = "progress-bar progress-bar-success" role = "progressbar" aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 40%;"> <span class = "sr-only">40% Complete</span> </div> </div> </body> </html>
[ { "code": null, "e": 1127, "s": 1062, "text": "Follow the below given steps to create an animated progress bar:" }, { "code": null, "e": 1234, "s": 1127, "text": "Add a <div> with a class of .progress and .progress-striped. Also, add class .active to .progress-striped." }, { "code": null, "e": 1314, "s": 1234, "text": "Next, inside the above <div>, add an empty <div> with a class of .progress-bar." }, { "code": null, "e": 1454, "s": 1314, "text": "Add a style attribute with the width expressed as a percentage. Say for example, style = \"60%\"; indicates that the progress bar was at 60%." }, { "code": null, "e": 1526, "s": 1454, "text": "You can try to run the following code to create animated progress bar −" }, { "code": null, "e": 1536, "s": 1526, "text": "Live Demo" }, { "code": null, "e": 2577, "s": 1536, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h2>Progress Bar</h2>\n <h3>Normal Progress Bar</h3>\n <div class = \"progress progress-striped\">\n <div class = \"progress-bar progress-bar-success\" role = \"progressbar\"\n aria-valuenow = \"45\" aria-valuemin = \"0\" aria-valuemax = \"100\" style = \"width: 45%;\">\n <span class = \"sr-only\">45%Complete (success)</span>\n </div>\n </div>\n\n <h3>Animated Progress Bar</h3>\n <div class = \"progress progress-striped active\">\n <div class = \"progress-bar progress-bar-success\" role = \"progressbar\"\n aria-valuenow = \"60\" aria-valuemin = \"0\" aria-valuemax = \"100\" style = \"width: 40%;\">\n <span class = \"sr-only\">40% Complete</span>\n </div>\n </div>\n </body>\n</html>" } ]
C-SCAN Disk Scheduling Algorithm - GeeksforGeeks
24 Dec, 2021 Prerequisite: Disk Scheduling Algorithms and SCAN Disk Scheduling Algorithm Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if a C-SCAN disk scheduling algorithm is used. The circular SCAN (C-SCAN) scheduling algorithm is a modified version of the SCAN disk scheduling algorithm that deals with the inefficiency of the SCAN algorithm by servicing the requests more uniformly. Like SCAN (Elevator Algorithm) C-SCAN moves the head from one end servicing all the requests to the other end. However, as soon as the head reaches the other end, it immediately returns to the beginning of the disk without servicing any requests on the return trip (see chart below) and starts servicing again once reaches the beginning. This is also known as the “Circular Elevator Algorithm” as it essentially treats the cylinders as a circular list that wraps around from the final cylinder to the first one. Works well with moderate to heavy loads. It provides better response time and uniform waiting time. May not be fair to service requests for tracks at the extreme end. It has more seek movements as compared to the SCAN Algorithm. Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.The head services only in the right direction from 0 to the size of the disk.While moving in the left direction do not service any of the tracks.When we reach the beginning(left end) reverse the direction.While moving in the right direction it services all tracks one by one.While moving in the right direction calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 6 until we reach the right end of the disk.If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the request array have not been serviced. Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head. The head services only in the right direction from 0 to the size of the disk. While moving in the left direction do not service any of the tracks. When we reach the beginning(left end) reverse the direction. While moving in the right direction it services all tracks one by one. While moving in the right direction calculate the absolute distance of the track from the head. Increment the total seek count with this distance. Currently serviced track position now becomes the new head position. Go to step 6 until we reach the right end of the disk. If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the request array have not been serviced. Examples: Input: Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} Initial head position = 50 Direction = right(We are moving from left to right) Output: Initial position of head: 50 Total number of seek operations = 389 Seek Sequence is 60 79 92 114 176 199 0 11 34 41 The following chart shows the sequence in which requested tracks are serviced using SCAN. Therefore, the total seek count is calculated as: = (60-50)+(79-60)+(92-79) +(114-92)+(176-114)+(199-176)+(199-0) +(11-0)+(34-11)+(41-34) = 389 The implementation of C-SCAN algorithm is given below. Note: The distance variable is used to store the absolute distance between the head and current track position. disk_size is the size of the disk. Vectors left and right store all the request tracks on the left-hand side and the right-hand side of the initial head position respectively. C++ Java Python3 C# Javascript // C++ program to demonstrate// C-SCAN Disk Scheduling algorithm#include <bits/stdc++.h>using namespace std; // Code by Vikram Chaurasia int size = 8;int disk_size = 200; void CSCAN(int arr[], int head){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // appending end values // which has to be visited // before reversing the direction left.push_back(0); right.push_back(disk_size - 1); // tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // first service the requests // on the right side of the // head. for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } // once reached the right end // jump to the beginning. head = 0; // adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.size(); i++) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } cout << "Total number of seek operations = " << seek_count << endl; cout << "Seek Sequence is" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; cout << "Initial position of head: " << head << endl; CSCAN(arr, head); return 0;} // Java program to demonstrate// C-SCAN Disk Scheduling algorithmimport java.util.*; class GFG { static int size = 8; static int disk_size = 200; public static void CSCAN(int arr[], int head) { int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(); Vector<Integer> right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // Appending end values which has // to be visited before reversing // the direction left.add(0); right.add(disk_size - 1); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // Sorting left and right vectors Collections.sort(left); Collections.sort(right); // First service the requests // on the right side of the // head. for (int i = 0; i < right.size(); i++) { cur_track = right.get(i); // Appending current track to seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to // 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.size(); i++) { cur_track = left.get(i); // Appending current track to // seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } System.out.println("Total number of seek " + "operations = " + seek_count); System.out.println("Seek Sequence is"); for (int i = 0; i < seek_sequence.size(); i++) { System.out.println(seek_sequence.get(i)); } } // Driver code public static void main(String[] args) throws Exception { // Request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; System.out.println("Initial position of head: " + head); CSCAN(arr, head); }} // This code is contributed by divyesh072019 # Python3 program to demonstrate# C-SCAN Disk Scheduling algorithmsize = 8disk_size = 200 def CSCAN(arr, head): seek_count = 0 distance = 0 cur_track = 0 left = [] right = [] seek_sequence = [] # Appending end values # which has to be visited # before reversing the direction left.append(0) right.append(disk_size - 1) # Tracks on the left of the # head will be serviced when # once the head comes back # to the beggining (left end). for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # First service the requests # on the right side of the # head. for i in range(len(right)): cur_track = right[i] # Appending current track # to seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track # Once reached the right end # jump to the beggining. head = 0 # adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1) # Now service the requests again # which are left. for i in range(len(left)): cur_track = left[i] # Appending current track # to seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track print("Total number of seek operations =", seek_count) print("Seek Sequence is") print(*seek_sequence, sep="\n") # Driver code # request arrayarr = [176, 79, 34, 60, 92, 11, 41, 114]head = 50 print("Initial position of head:", head) CSCAN(arr, head) # This code is contributed by rag2127 // C# program to demonstrate// C-SCAN Disk Scheduling algorithmusing System;using System.Collections.Generic; class GFG { static int size = 8; static int disk_size = 200; static void CSCAN(int[] arr, int head) { int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(); List<int> right = new List<int>(); List<int> seek_sequence = new List<int>(); // Appending end values which has // to be visited before reversing // the direction left.Add(0); right.Add(disk_size - 1); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // Sorting left and right vectors left.Sort(); right.Sort(); // First service the requests // on the right side of the // head. for (int i = 0; i < right.Count; i++) { cur_track = right[i]; // Appending current track to seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to // 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.Count; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } Console.WriteLine("Total number of seek " + "operations = " + seek_count); Console.WriteLine("Seek Sequence is"); for (int i = 0; i < seek_sequence.Count; i++) { Console.WriteLine(seek_sequence[i]); } } // Driver code static void Main() { // Request array int[] arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; Console.WriteLine("Initial position of head: " + head); CSCAN(arr, head); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript program to demonstrate // C-SCAN Disk Scheduling algorithm let size = 8; let disk_size = 200; function CSCAN(arr, head) { let seek_count = 0; let distance, cur_track; let left = [], right = []; let seek_sequence = []; // appending end values // which has to be visited // before reversing the direction left.push(0); right.push(disk_size - 1); // tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // first service the requests // on the right side of the // head. for (let i = 0; i < right.length; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } // once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (let i = 0; i < left.length; i++) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } document.write("Total number of seek operations = " + seek_count + "</br>"); document.write("Seek Sequence is" + "</br>"); for (let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + "</br>"); } } // request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; document.write("Initial position of head: " + head + "</br>"); CSCAN(arr, head); // This code is contributed by mukesh07.</script> Initial position of head: 50 Total number of seek operations = 389 Seek Sequence is 60 79 92 114 176 199 0 11 34 41 wilsonmun divyesh072019 divyeshrabadiya07 rag2127 SandeepShiven mukesh07 clintra gurvirlochab itskawal2000 File & Disk Management GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Layers of OSI Model ACID Properties in DBMS TCP/IP Model Normal Forms in DBMS LRU Cache Implementation LRU Cache Implementation Cache Memory in Computer Organization 'crontab' in Linux with Examples Memory Management in Operating System Mutex lock for Linux Thread Synchronization
[ { "code": null, "e": 27731, "s": 27703, "text": "\n24 Dec, 2021" }, { "code": null, "e": 27807, "s": 27731, "text": "Prerequisite: Disk Scheduling Algorithms and SCAN Disk Scheduling Algorithm" }, { "code": null, "e": 28014, "s": 27807, "text": "Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if a C-SCAN disk scheduling algorithm is used." }, { "code": null, "e": 28731, "s": 28014, "text": "The circular SCAN (C-SCAN) scheduling algorithm is a modified version of the SCAN disk scheduling algorithm that deals with the inefficiency of the SCAN algorithm by servicing the requests more uniformly. Like SCAN (Elevator Algorithm) C-SCAN moves the head from one end servicing all the requests to the other end. However, as soon as the head reaches the other end, it immediately returns to the beginning of the disk without servicing any requests on the return trip (see chart below) and starts servicing again once reaches the beginning. This is also known as the “Circular Elevator Algorithm” as it essentially treats the cylinders as a circular list that wraps around from the final cylinder to the first one." }, { "code": null, "e": 28772, "s": 28731, "text": "Works well with moderate to heavy loads." }, { "code": null, "e": 28831, "s": 28772, "text": "It provides better response time and uniform waiting time." }, { "code": null, "e": 28898, "s": 28831, "text": "May not be fair to service requests for tracks at the extreme end." }, { "code": null, "e": 28960, "s": 28898, "text": "It has more seek movements as compared to the SCAN Algorithm." }, { "code": null, "e": 29811, "s": 28960, "text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head.The head services only in the right direction from 0 to the size of the disk.While moving in the left direction do not service any of the tracks.When we reach the beginning(left end) reverse the direction.While moving in the right direction it services all tracks one by one.While moving in the right direction calculate the absolute distance of the track from the head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 6 until we reach the right end of the disk.If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the request array have not been serviced." }, { "code": null, "e": 29982, "s": 29811, "text": "Let Request array represents an array storing indexes of tracks that have been requested in ascending order of their time of arrival. ‘head’ is the position of disk head." }, { "code": null, "e": 30060, "s": 29982, "text": "The head services only in the right direction from 0 to the size of the disk." }, { "code": null, "e": 30129, "s": 30060, "text": "While moving in the left direction do not service any of the tracks." }, { "code": null, "e": 30190, "s": 30129, "text": "When we reach the beginning(left end) reverse the direction." }, { "code": null, "e": 30261, "s": 30190, "text": "While moving in the right direction it services all tracks one by one." }, { "code": null, "e": 30357, "s": 30261, "text": "While moving in the right direction calculate the absolute distance of the track from the head." }, { "code": null, "e": 30408, "s": 30357, "text": "Increment the total seek count with this distance." }, { "code": null, "e": 30477, "s": 30408, "text": "Currently serviced track position now becomes the new head position." }, { "code": null, "e": 30532, "s": 30477, "text": "Go to step 6 until we reach the right end of the disk." }, { "code": null, "e": 30671, "s": 30532, "text": "If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the request array have not been serviced." }, { "code": null, "e": 30682, "s": 30671, "text": "Examples: " }, { "code": null, "e": 30949, "s": 30682, "text": "Input: \nRequest sequence = {176, 79, 34, 60, 92, 11, 41, 114}\nInitial head position = 50\nDirection = right(We are moving from left to right)\n\nOutput:\nInitial position of head: 50\nTotal number of seek operations = 389\nSeek Sequence is\n60\n79\n92\n114\n176\n199\n0\n11\n34\n41" }, { "code": null, "e": 31040, "s": 30949, "text": "The following chart shows the sequence in which requested tracks are serviced using SCAN. " }, { "code": null, "e": 31092, "s": 31040, "text": "Therefore, the total seek count is calculated as: " }, { "code": null, "e": 31202, "s": 31092, "text": "= (60-50)+(79-60)+(92-79)\n +(114-92)+(176-114)+(199-176)+(199-0)\n +(11-0)+(34-11)+(41-34)\n= 389" }, { "code": null, "e": 31257, "s": 31202, "text": "The implementation of C-SCAN algorithm is given below." }, { "code": null, "e": 31545, "s": 31257, "text": "Note: The distance variable is used to store the absolute distance between the head and current track position. disk_size is the size of the disk. Vectors left and right store all the request tracks on the left-hand side and the right-hand side of the initial head position respectively." }, { "code": null, "e": 31549, "s": 31545, "text": "C++" }, { "code": null, "e": 31554, "s": 31549, "text": "Java" }, { "code": null, "e": 31562, "s": 31554, "text": "Python3" }, { "code": null, "e": 31565, "s": 31562, "text": "C#" }, { "code": null, "e": 31576, "s": 31565, "text": "Javascript" }, { "code": "// C++ program to demonstrate// C-SCAN Disk Scheduling algorithm#include <bits/stdc++.h>using namespace std; // Code by Vikram Chaurasia int size = 8;int disk_size = 200; void CSCAN(int arr[], int head){ int seek_count = 0; int distance, cur_track; vector<int> left, right; vector<int> seek_sequence; // appending end values // which has to be visited // before reversing the direction left.push_back(0); right.push_back(disk_size - 1); // tracks on the left of the // head will be serviced when // once the head comes back // to the beginning (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.push_back(arr[i]); if (arr[i] > head) right.push_back(arr[i]); } // sorting left and right vectors std::sort(left.begin(), left.end()); std::sort(right.begin(), right.end()); // first service the requests // on the right side of the // head. for (int i = 0; i < right.size(); i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } // once reached the right end // jump to the beginning. head = 0; // adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.size(); i++) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push_back(cur_track); // calculate absolute distance distance = abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } cout << \"Total number of seek operations = \" << seek_count << endl; cout << \"Seek Sequence is\" << endl; for (int i = 0; i < seek_sequence.size(); i++) { cout << seek_sequence[i] << endl; }} // Driver codeint main(){ // request array int arr[size] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; cout << \"Initial position of head: \" << head << endl; CSCAN(arr, head); return 0;}", "e": 33973, "s": 31576, "text": null }, { "code": "// Java program to demonstrate// C-SCAN Disk Scheduling algorithmimport java.util.*; class GFG { static int size = 8; static int disk_size = 200; public static void CSCAN(int arr[], int head) { int seek_count = 0; int distance, cur_track; Vector<Integer> left = new Vector<Integer>(); Vector<Integer> right = new Vector<Integer>(); Vector<Integer> seek_sequence = new Vector<Integer>(); // Appending end values which has // to be visited before reversing // the direction left.add(0); right.add(disk_size - 1); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.add(arr[i]); if (arr[i] > head) right.add(arr[i]); } // Sorting left and right vectors Collections.sort(left); Collections.sort(right); // First service the requests // on the right side of the // head. for (int i = 0; i < right.size(); i++) { cur_track = right.get(i); // Appending current track to seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to // 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.size(); i++) { cur_track = left.get(i); // Appending current track to // seek sequence seek_sequence.add(cur_track); // Calculate absolute distance distance = Math.abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } System.out.println(\"Total number of seek \" + \"operations = \" + seek_count); System.out.println(\"Seek Sequence is\"); for (int i = 0; i < seek_sequence.size(); i++) { System.out.println(seek_sequence.get(i)); } } // Driver code public static void main(String[] args) throws Exception { // Request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; System.out.println(\"Initial position of head: \" + head); CSCAN(arr, head); }} // This code is contributed by divyesh072019", "e": 36886, "s": 33973, "text": null }, { "code": "# Python3 program to demonstrate# C-SCAN Disk Scheduling algorithmsize = 8disk_size = 200 def CSCAN(arr, head): seek_count = 0 distance = 0 cur_track = 0 left = [] right = [] seek_sequence = [] # Appending end values # which has to be visited # before reversing the direction left.append(0) right.append(disk_size - 1) # Tracks on the left of the # head will be serviced when # once the head comes back # to the beggining (left end). for i in range(size): if (arr[i] < head): left.append(arr[i]) if (arr[i] > head): right.append(arr[i]) # Sorting left and right vectors left.sort() right.sort() # First service the requests # on the right side of the # head. for i in range(len(right)): cur_track = right[i] # Appending current track # to seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now new head head = cur_track # Once reached the right end # jump to the beggining. head = 0 # adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1) # Now service the requests again # which are left. for i in range(len(left)): cur_track = left[i] # Appending current track # to seek sequence seek_sequence.append(cur_track) # Calculate absolute distance distance = abs(cur_track - head) # Increase the total count seek_count += distance # Accessed track is now the new head head = cur_track print(\"Total number of seek operations =\", seek_count) print(\"Seek Sequence is\") print(*seek_sequence, sep=\"\\n\") # Driver code # request arrayarr = [176, 79, 34, 60, 92, 11, 41, 114]head = 50 print(\"Initial position of head:\", head) CSCAN(arr, head) # This code is contributed by rag2127", "e": 38922, "s": 36886, "text": null }, { "code": "// C# program to demonstrate// C-SCAN Disk Scheduling algorithmusing System;using System.Collections.Generic; class GFG { static int size = 8; static int disk_size = 200; static void CSCAN(int[] arr, int head) { int seek_count = 0; int distance, cur_track; List<int> left = new List<int>(); List<int> right = new List<int>(); List<int> seek_sequence = new List<int>(); // Appending end values which has // to be visited before reversing // the direction left.Add(0); right.Add(disk_size - 1); // Tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (int i = 0; i < size; i++) { if (arr[i] < head) left.Add(arr[i]); if (arr[i] > head) right.Add(arr[i]); } // Sorting left and right vectors left.Sort(); right.Sort(); // First service the requests // on the right side of the // head. for (int i = 0; i < right.Count; i++) { cur_track = right[i]; // Appending current track to seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now new head head = cur_track; } // Once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to // 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (int i = 0; i < left.Count; i++) { cur_track = left[i]; // Appending current track to // seek sequence seek_sequence.Add(cur_track); // Calculate absolute distance distance = Math.Abs(cur_track - head); // Increase the total count seek_count += distance; // Accessed track is now the new head head = cur_track; } Console.WriteLine(\"Total number of seek \" + \"operations = \" + seek_count); Console.WriteLine(\"Seek Sequence is\"); for (int i = 0; i < seek_sequence.Count; i++) { Console.WriteLine(seek_sequence[i]); } } // Driver code static void Main() { // Request array int[] arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; int head = 50; Console.WriteLine(\"Initial position of head: \" + head); CSCAN(arr, head); }} // This code is contributed by divyeshrabadiya07", "e": 41730, "s": 38922, "text": null }, { "code": "<script> // Javascript program to demonstrate // C-SCAN Disk Scheduling algorithm let size = 8; let disk_size = 200; function CSCAN(arr, head) { let seek_count = 0; let distance, cur_track; let left = [], right = []; let seek_sequence = []; // appending end values // which has to be visited // before reversing the direction left.push(0); right.push(disk_size - 1); // tracks on the left of the // head will be serviced when // once the head comes back // to the beggining (left end). for (let i = 0; i < size; i++) { if (arr[i] < head) left.push(arr[i]); if (arr[i] > head) right.push(arr[i]); } // sorting left and right vectors left.sort(function(a, b){return a - b}); right.sort(function(a, b){return a - b}); // first service the requests // on the right side of the // head. for (let i = 0; i < right.length; i++) { cur_track = right[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now new head head = cur_track; } // once reached the right end // jump to the beggining. head = 0; // adding seek count for head returning from 199 to 0 seek_count += (disk_size - 1); // Now service the requests again // which are left. for (let i = 0; i < left.length; i++) { cur_track = left[i]; // appending current track to seek sequence seek_sequence.push(cur_track); // calculate absolute distance distance = Math.abs(cur_track - head); // increase the total count seek_count += distance; // accessed track is now the new head head = cur_track; } document.write(\"Total number of seek operations = \" + seek_count + \"</br>\"); document.write(\"Seek Sequence is\" + \"</br>\"); for (let i = 0; i < seek_sequence.length; i++) { document.write(seek_sequence[i] + \"</br>\"); } } // request array let arr = [ 176, 79, 34, 60, 92, 11, 41, 114 ]; let head = 50; document.write(\"Initial position of head: \" + head + \"</br>\"); CSCAN(arr, head); // This code is contributed by mukesh07.</script>", "e": 44384, "s": 41730, "text": null }, { "code": null, "e": 44500, "s": 44384, "text": "Initial position of head: 50\nTotal number of seek operations = 389\nSeek Sequence is\n60\n79\n92\n114\n176\n199\n0\n11\n34\n41" }, { "code": null, "e": 44510, "s": 44500, "text": "wilsonmun" }, { "code": null, "e": 44524, "s": 44510, "text": "divyesh072019" }, { "code": null, "e": 44542, "s": 44524, "text": "divyeshrabadiya07" }, { "code": null, "e": 44550, "s": 44542, "text": "rag2127" }, { "code": null, "e": 44564, "s": 44550, "text": "SandeepShiven" }, { "code": null, "e": 44573, "s": 44564, "text": "mukesh07" }, { "code": null, "e": 44581, "s": 44573, "text": "clintra" }, { "code": null, "e": 44594, "s": 44581, "text": "gurvirlochab" }, { "code": null, "e": 44607, "s": 44594, "text": "itskawal2000" }, { "code": null, "e": 44630, "s": 44607, "text": "File & Disk Management" }, { "code": null, "e": 44638, "s": 44630, "text": "GATE CS" }, { "code": null, "e": 44656, "s": 44638, "text": "Operating Systems" }, { "code": null, "e": 44674, "s": 44656, "text": "Operating Systems" }, { "code": null, "e": 44772, "s": 44674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44781, "s": 44772, "text": "Comments" }, { "code": null, "e": 44794, "s": 44781, "text": "Old Comments" }, { "code": null, "e": 44814, "s": 44794, "text": "Layers of OSI Model" }, { "code": null, "e": 44838, "s": 44814, "text": "ACID Properties in DBMS" }, { "code": null, "e": 44851, "s": 44838, "text": "TCP/IP Model" }, { "code": null, "e": 44872, "s": 44851, "text": "Normal Forms in DBMS" }, { "code": null, "e": 44897, "s": 44872, "text": "LRU Cache Implementation" }, { "code": null, "e": 44922, "s": 44897, "text": "LRU Cache Implementation" }, { "code": null, "e": 44960, "s": 44922, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 44993, "s": 44960, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 45031, "s": 44993, "text": "Memory Management in Operating System" } ]
Difference between the Constructors and Methods - GeeksforGeeks
14 May, 2019 Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways. Constructors:Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class. Example: // Java Program to illustrate constructor import java.io.*; class Geek { int num; String name; // This would be invoked while an object // of that class created. Geek() { System.out.println("Constructor called"); }} class GFG { public static void main(String[] args) { // this would invoke default constructor. Geek geek1 = new Geek(); // Default constructor provides the default // values to the object like 0, null System.out.println(geek1.name); System.out.println(geek1.num); }} Constructor called null 0 Methods:A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python. Example: // Java Program to illustrate methods import java.io.*; class Addition { int sum = 0; public int addTwoInt(int a, int b) { // Adding two integer value. sum = a + b; // Returning summation of two values. return sum; }} class GFG { public static void main(String[] args) { // Creating an instance of Addition class Addition add = new Addition(); // Calling addTwoInt() method // to add two integer // using instance created // in above step. int s = add.addTwoInt(1, 2); System.out.println("Sum of two " + "integer values: " + s); }} Sum of two integer values: 3 Differences between Constructors and Methods: Akanksha_Rai Java-Constructors Java-Functions Java-Object Oriented Picked Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference between Process and Thread Stack vs Heap Memory Allocation Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 24676, "s": 24648, "text": "\n14 May, 2019" }, { "code": null, "e": 24947, "s": 24676, "text": "Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways." }, { "code": null, "e": 25333, "s": 24947, "text": "Constructors:Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class." }, { "code": null, "e": 25342, "s": 25333, "text": "Example:" }, { "code": "// Java Program to illustrate constructor import java.io.*; class Geek { int num; String name; // This would be invoked while an object // of that class created. Geek() { System.out.println(\"Constructor called\"); }} class GFG { public static void main(String[] args) { // this would invoke default constructor. Geek geek1 = new Geek(); // Default constructor provides the default // values to the object like 0, null System.out.println(geek1.name); System.out.println(geek1.num); }}", "e": 25911, "s": 25342, "text": null }, { "code": null, "e": 25938, "s": 25911, "text": "Constructor called\nnull\n0\n" }, { "code": null, "e": 26292, "s": 25938, "text": "Methods:A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python." }, { "code": null, "e": 26301, "s": 26292, "text": "Example:" }, { "code": "// Java Program to illustrate methods import java.io.*; class Addition { int sum = 0; public int addTwoInt(int a, int b) { // Adding two integer value. sum = a + b; // Returning summation of two values. return sum; }} class GFG { public static void main(String[] args) { // Creating an instance of Addition class Addition add = new Addition(); // Calling addTwoInt() method // to add two integer // using instance created // in above step. int s = add.addTwoInt(1, 2); System.out.println(\"Sum of two \" + \"integer values: \" + s); }}", "e": 27007, "s": 26301, "text": null }, { "code": null, "e": 27037, "s": 27007, "text": "Sum of two integer values: 3\n" }, { "code": null, "e": 27083, "s": 27037, "text": "Differences between Constructors and Methods:" }, { "code": null, "e": 27096, "s": 27083, "text": "Akanksha_Rai" }, { "code": null, "e": 27114, "s": 27096, "text": "Java-Constructors" }, { "code": null, "e": 27129, "s": 27114, "text": "Java-Functions" }, { "code": null, "e": 27150, "s": 27129, "text": "Java-Object Oriented" }, { "code": null, "e": 27157, "s": 27150, "text": "Picked" }, { "code": null, "e": 27176, "s": 27157, "text": "Difference Between" }, { "code": null, "e": 27181, "s": 27176, "text": "Java" }, { "code": null, "e": 27186, "s": 27181, "text": "Java" }, { "code": null, "e": 27284, "s": 27186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27293, "s": 27284, "text": "Comments" }, { "code": null, "e": 27306, "s": 27293, "text": "Old Comments" }, { "code": null, "e": 27367, "s": 27306, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27405, "s": 27367, "text": "Difference between Process and Thread" }, { "code": null, "e": 27437, "s": 27405, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 27505, "s": 27437, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27542, "s": 27505, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 27564, "s": 27542, "text": "For-each loop in Java" }, { "code": null, "e": 27589, "s": 27564, "text": "Reverse a string in Java" }, { "code": null, "e": 27625, "s": 27589, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27676, "s": 27625, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Time Intelligence calculations in R | by Hamza Rafiq | Towards Data Science
Time intelligence is simply doing calculations over periods of date or time. For example, a common request you could get is to get total sales aggregated by month for a year or to calculate total sales for products YTD and sales, same period last year to compare and calculate growth. Learning from my own practical experience, I will be sharing some of the ways you can make these calculations in R using the tidyverse and lubridate packages in R For this exercise, I created a dummy dataset in Excel. This dataset contains sales from January 2nd, 2017 till 30th September 2019 library(tidyverse) #Data manipulationlibrary(lubridate) #For working with date and timesale_data <- read_xlsx("C:\\Users\\ACER\\Desktop\\regression_test.xlsx") %>% mutate(Date = ymd(Date)) Used the read_xlsx function to read in our dataset Within the mutate function, we passed the ymd function to convert our Date column to date type This is what our dataset looks like Let's start with some basic time intelligence calculations. A common request you would get is to show total sales overtime, aggregated on a monthly level sale_data %>% group_by(Year=year(Date),Month=month(Date,label = T)) %>% summarise(total_sales=sum(Offered_Calls,na.rm = T)) After the group_by, I created the Year and Month columns and after that used the summarise function to get total_sales. There is another way to this is as well sale_data %>% group_by(Monthly=floor_date(Date,unit = "1 month")) %>% summarise(total_sales=sum(Offered_Calls,na.rm = T)) Basically, I rounded the Date column to the nearest month using the floor_date function from lubdridate and then calculated the total sales What if someone asked for total sales from January to June for 2019 and compare it with the same period for last year to see the change? sale_data %>% summarise(sales_2019 = sum(Offered_Calls[Date %within% interval("2019-01-01","2019-06-30")],na.rm = T), sales_2018 = sum(Offered_Calls[Date %within% interval("2018-01-01","2018-06-30")],na.rm = T)) So basically I used the %within% and Interval functions from the lubridate package to pass conditional parameters for the date column for which I want to calculate the sum But what if you are working with a live dataset? You wouldn't want to update your code every single time you have to run your regular report to account for the latest date parameters. I have a pretty neat solution for that as well sale_data %>% summarise(sales_current_mtd = sum(Offered_Calls[Date %within% interval(cut(Sys.Date(),"month"),Sys.Date())],na.rm = T), same_period_last_year = sum(Offered_Calls[Date %within% interval(cut(Sys.Date()-years(1),"month"),Sys.Date()-years(1))],na.rm = T)) This is the same formula as before. The only change is that I have replaced the date parameters in the interval function with functions that automatically calculate the desired date interval whenever you run your report or refresh your data. Let's break it down: cut(Sys.Date(),"month") floors the sale date to the nearest month so you will always get the first day of every month Sys.Date() basically just gets the current date. So inputting these two parameters in the interval function, you will get an interval from the start of every month till the end of every month, resulting in totals for MTD To get totals for the same period last year, you just add an additional argument. Adding the Years(-1) function for both intervals will get you the same intervals but for last year, resulting in totals for last year MTD I will show another example where you have to do calculations on a yearly granularity like YTD which will show how flexible this calculation is sale_data %>% summarise(sales_ytd = sum(Offered_Calls[Date %within% interval(cut(Sys.Date(),"year"),Sys.Date())],na.rm = T), same_period_last_year = sum(Offered_Calls[Date %within% interval(cut(Sys.Date()-years(1),"year"),Sys.Date()-years(1))],na.rm = T)) The only difference here is that I changed the parameter from “month” to “year” in the cut function. This floors the date to the start of the year. This allows us to do a YTD calculation for both the current and last year These are some of the solutions that I use at work to do “time intelligence” calculations in R. I showed both the manual process for one-time ad-hoc requests and automated solutions for regular reporting. While my examples only consisted of yearly, monthly calculations, you can do calculations on any level like weekly, daily, and quarterly by following the same principles that I showed. I found this solution really useful for calculating KPIs that have to refreshed/reported regularly in our weekly/monthly/quarterly reports. It allows me to just refresh the report without having to manually calculate them every single time.
[ { "code": null, "e": 620, "s": 172, "text": "Time intelligence is simply doing calculations over periods of date or time. For example, a common request you could get is to get total sales aggregated by month for a year or to calculate total sales for products YTD and sales, same period last year to compare and calculate growth. Learning from my own practical experience, I will be sharing some of the ways you can make these calculations in R using the tidyverse and lubridate packages in R" }, { "code": null, "e": 751, "s": 620, "text": "For this exercise, I created a dummy dataset in Excel. This dataset contains sales from January 2nd, 2017 till 30th September 2019" }, { "code": null, "e": 944, "s": 751, "text": "library(tidyverse) #Data manipulationlibrary(lubridate) #For working with date and timesale_data <- read_xlsx(\"C:\\\\Users\\\\ACER\\\\Desktop\\\\regression_test.xlsx\") %>% mutate(Date = ymd(Date))" }, { "code": null, "e": 995, "s": 944, "text": "Used the read_xlsx function to read in our dataset" }, { "code": null, "e": 1090, "s": 995, "text": "Within the mutate function, we passed the ymd function to convert our Date column to date type" }, { "code": null, "e": 1126, "s": 1090, "text": "This is what our dataset looks like" }, { "code": null, "e": 1280, "s": 1126, "text": "Let's start with some basic time intelligence calculations. A common request you would get is to show total sales overtime, aggregated on a monthly level" }, { "code": null, "e": 1412, "s": 1280, "text": "sale_data %>% group_by(Year=year(Date),Month=month(Date,label = T)) %>% summarise(total_sales=sum(Offered_Calls,na.rm = T))" }, { "code": null, "e": 1572, "s": 1412, "text": "After the group_by, I created the Year and Month columns and after that used the summarise function to get total_sales. There is another way to this is as well" }, { "code": null, "e": 1702, "s": 1572, "text": "sale_data %>% group_by(Monthly=floor_date(Date,unit = \"1 month\")) %>% summarise(total_sales=sum(Offered_Calls,na.rm = T))" }, { "code": null, "e": 1842, "s": 1702, "text": "Basically, I rounded the Date column to the nearest month using the floor_date function from lubdridate and then calculated the total sales" }, { "code": null, "e": 1979, "s": 1842, "text": "What if someone asked for total sales from January to June for 2019 and compare it with the same period for last year to see the change?" }, { "code": null, "e": 2207, "s": 1979, "text": "sale_data %>% summarise(sales_2019 = sum(Offered_Calls[Date %within% interval(\"2019-01-01\",\"2019-06-30\")],na.rm = T), sales_2018 = sum(Offered_Calls[Date %within% interval(\"2018-01-01\",\"2018-06-30\")],na.rm = T))" }, { "code": null, "e": 2379, "s": 2207, "text": "So basically I used the %within% and Interval functions from the lubridate package to pass conditional parameters for the date column for which I want to calculate the sum" }, { "code": null, "e": 2610, "s": 2379, "text": "But what if you are working with a live dataset? You wouldn't want to update your code every single time you have to run your regular report to account for the latest date parameters. I have a pretty neat solution for that as well" }, { "code": null, "e": 2892, "s": 2610, "text": "sale_data %>% summarise(sales_current_mtd = sum(Offered_Calls[Date %within% interval(cut(Sys.Date(),\"month\"),Sys.Date())],na.rm = T), same_period_last_year = sum(Offered_Calls[Date %within% interval(cut(Sys.Date()-years(1),\"month\"),Sys.Date()-years(1))],na.rm = T))" }, { "code": null, "e": 3155, "s": 2892, "text": "This is the same formula as before. The only change is that I have replaced the date parameters in the interval function with functions that automatically calculate the desired date interval whenever you run your report or refresh your data. Let's break it down:" }, { "code": null, "e": 3273, "s": 3155, "text": "cut(Sys.Date(),\"month\") floors the sale date to the nearest month so you will always get the first day of every month" }, { "code": null, "e": 3494, "s": 3273, "text": "Sys.Date() basically just gets the current date. So inputting these two parameters in the interval function, you will get an interval from the start of every month till the end of every month, resulting in totals for MTD" }, { "code": null, "e": 3714, "s": 3494, "text": "To get totals for the same period last year, you just add an additional argument. Adding the Years(-1) function for both intervals will get you the same intervals but for last year, resulting in totals for last year MTD" }, { "code": null, "e": 3858, "s": 3714, "text": "I will show another example where you have to do calculations on a yearly granularity like YTD which will show how flexible this calculation is" }, { "code": null, "e": 4130, "s": 3858, "text": "sale_data %>% summarise(sales_ytd = sum(Offered_Calls[Date %within% interval(cut(Sys.Date(),\"year\"),Sys.Date())],na.rm = T), same_period_last_year = sum(Offered_Calls[Date %within% interval(cut(Sys.Date()-years(1),\"year\"),Sys.Date()-years(1))],na.rm = T))" }, { "code": null, "e": 4352, "s": 4130, "text": "The only difference here is that I changed the parameter from “month” to “year” in the cut function. This floors the date to the start of the year. This allows us to do a YTD calculation for both the current and last year" } ]