title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Program for Hexadecimal to Decimal
14 Sep, 2021 Given a hexadecimal number as input, we need to write a program to convert the given hexadecimal number into an equivalent decimal number. Examples: Input : 67 Output: 103 Input : 512 Output: 1298 Input : 123 Output: 291 We know that hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number. For Example: If the hexadecimal number is 1A. dec_value = 1*(16^1) + 10*(16^0) = 26 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. The below diagram explains how to convert a hexadecimal number (1AB) to an equivalent decimal value: Below is the implementation of the above idea. C++ Java Python3 C# PHP Javascript // C++ program to convert hexadecimal to decimal#include <bits/stdc++.h>using namespace std; // Function to convert hexadecimal to decimal int hexadecimalToDecimal(string hexVal){ int len = hexVal.size(); // Initializing base value to 1, i.e 16^0 int base = 1; int dec_val = 0; // Extracting characters as digits from last // character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal[i] >= '0' && hexVal[i] <= '9') { dec_val += (int(hexVal[i]) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') { dec_val += (int(hexVal[i]) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val;} // driver programint main(){ string hexNum = "1A"; cout << (hexadecimalToDecimal(hexNum)); // This code is contributed by rakeshsahni return 0;} // Java program to convert hexadecimal to decimalimport java.io.*; class GFG { // Function to convert hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { int len = hexVal.length(); // Initializing base value to 1, i.e 16^0 int base = 1; int dec_val = 0; // Extracting characters as digits from last // character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val; } // driver program public static void main(String[] args) { String hexNum = "1A"; System.out.println(hexadecimalToDecimal(hexNum)); }} # Python3 program to convert# hexadecimal to decimal # Function to convert hexadecimal# to decimal def hexadecimalToDecimal(hexval): # Finding length length = len(hexval) # Initialize base value to 1, # i.e. 16*0 base = 1 dec_val = 0 # Extracting characters as digits # from last character for i in range(length - 1, -1, -1): # If character lies in '0'-'9', # converting it to integral 0-9 # by subtracting 48 from ASCII value if hexval[i] >= '0' and hexval[i] <= '9': dec_val += (ord(hexval[i]) - 48) * base # Incrementing base by power base = base * 16 # If character lies in 'A'-'F',converting # it to integral 10-15 by subtracting 55 # from ASCII value elif hexval[i] >= 'A' and hexval[i] <= 'F': dec_val += (ord(hexval[i]) - 55) * base # Incrementing base by power base = base * 16 return dec_val # Driver codeif __name__ == '__main__': hexnum = '1A' print(hexadecimalToDecimal(hexnum)) # This code is contributed by virusbuddah_ // C# program to convert// hexadecimal to decimalusing System; class GFG { // Function to convert // hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { int len = hexVal.Length; // Initializing base1 value // to 1, i.e 16^0 int base1 = 1; int dec_val = 0; // Extracting characters as // digits from last character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', // converting it to integral 0-9 // by subtracting 48 from ASCII value if (hexVal[i] >= '0' && hexVal[i] <= '9') { dec_val += (hexVal[i] - 48) * base1; // incrementing base1 by power base1 = base1 * 16; } // if character lies in 'A'-'F' , // converting it to integral // 10 - 15 by subtracting 55 // from ASCII value else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') { dec_val += (hexVal[i] - 55) * base1; // incrementing base1 by power base1 = base1 * 16; } } return dec_val; } // Driver Code static void Main() { String hexNum = "1A"; Console.WriteLine(hexadecimalToDecimal(hexNum)); }} // This code is contributed by mits <?php// PHP program to convert// hexadecimal to decimal // Function to convert// hexadecimal to decimalfunction hexadecimalToDecimal($hexVal){ $len = strlen($hexVal); // Initializing base value // to 1, i.e 16^0 $base = 1; $dec_val = 0; // Extracting characters as // digits from last character for ($i = $len - 1; $i >= 0; $i--) { // if character lies in '0'-'9', // converting it to integral 0-9 // by subtracting 48 from ASCII value. if ($hexVal[$i] >= '0' && $hexVal[$i] <= '9') { $dec_val += (ord($hexVal[$i]) - 48) * $base; // incrementing base by power $base = $base * 16; } // if character lies in 'A'-'F' , // converting it to integral // 10 - 15 by subtracting 55 // from ASCII value else if ($hexVal[$i] >= 'A' && $hexVal[$i] <= 'F') { $dec_val += (ord($hexVal[$i]) - 55) * $base; // incrementing base by power $base = $base * 16; } } return $dec_val;} // Driver Code$hexNum = "1A";echo hexadecimalToDecimal($hexNum); // This code is contributed by mits?> <script>// javascript program to convert hexadecimal to decimal // Function to convert hexadecimal to decimal function hexadecimalToDecimal(hexVal){ var len = hexVal.length; // Initializing base value to 1, i.e 16^0 var base = 1; var dec_val = 0; // Extracting characters as digits from last // character for (var i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i).charCodeAt(0) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i).charCodeAt(0) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val;} // driver programvar hexNum = "1A";document.write(hexadecimalToDecimal(hexNum)); // This code is contributed by 29AjayKumar</script> 26 Using predefined function C++ Java Python3 C# Javascript // C++ program to convert octal to decimal#include <bits/stdc++.h>using namespace std;int HexToDec(string n) { return stoi(n, 0, 16); } int main(){ string n = "1A"; cout << HexToDec(n); return 0;} // This code is contributed by rakeshsahni // Java program to convert hexadecimal to decimal import java.io.*; class GFG { public static int HexToDec(String n) { return Integer.parseInt(n, 16); } public static void main(String[] args) { String n = "1A"; System.out.println(HexToDec(n)); }} # Python program to convert hexadecimal to decimaldef HexToDec(n): return int(n, 16); if __name__ == '__main__': n = "1A"; print(HexToDec(n)); # This code is contributed by 29AjayKumar // C# program to convert hexadecimal to decimal using System; public class GFG { public static int HexToDec(String n) { return Convert.ToInt32(n, 16); } public static void Main(String[] args) { String n = "1A"; Console.WriteLine(HexToDec(n)); }} // This code is contributed by Amit Katiyar <script>// javascript program to convert octal to decimalfunction HexToDec(n) { return parseInt(n, 16); } var n = "1A";document.write(HexToDec(n));// This code is contributed by 29AjayKumar</script> 26 This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar soumya7 virusbuddha le0 29AjayKumar amit143katiyar rakeshsahni base-conversion Computer Organization & Architecture Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Sep, 2021" }, { "code": null, "e": 191, "s": 52, "text": "Given a hexadecimal number as input, we need to write a program to convert the given hexadecimal number into an equivalent decimal number." }, { "code": null, "e": 203, "s": 191, "text": "Examples: " }, { "code": null, "e": 277, "s": 203, "text": "Input : 67\nOutput: 103\n\nInput : 512\nOutput: 1298\n\nInput : 123\nOutput: 291" }, { "code": null, "e": 460, "s": 277, "text": "We know that hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). " }, { "code": null, "e": 818, "s": 460, "text": "The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number." }, { "code": null, "e": 902, "s": 818, "text": "For Example: If the hexadecimal number is 1A. dec_value = 1*(16^1) + 10*(16^0) = 26" }, { "code": null, "e": 911, "s": 902, "text": "Chapters" }, { "code": null, "e": 938, "s": 911, "text": "descriptions off, selected" }, { "code": null, "e": 988, "s": 938, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1011, "s": 988, "text": "captions off, selected" }, { "code": null, "e": 1019, "s": 1011, "text": "English" }, { "code": null, "e": 1043, "s": 1019, "text": "This is a modal window." }, { "code": null, "e": 1112, "s": 1043, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1134, "s": 1112, "text": "End of dialog window." }, { "code": null, "e": 1237, "s": 1134, "text": "The below diagram explains how to convert a hexadecimal number (1AB) to an equivalent decimal value: " }, { "code": null, "e": 1285, "s": 1237, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 1289, "s": 1285, "text": "C++" }, { "code": null, "e": 1294, "s": 1289, "text": "Java" }, { "code": null, "e": 1302, "s": 1294, "text": "Python3" }, { "code": null, "e": 1305, "s": 1302, "text": "C#" }, { "code": null, "e": 1309, "s": 1305, "text": "PHP" }, { "code": null, "e": 1320, "s": 1309, "text": "Javascript" }, { "code": "// C++ program to convert hexadecimal to decimal#include <bits/stdc++.h>using namespace std; // Function to convert hexadecimal to decimal int hexadecimalToDecimal(string hexVal){ int len = hexVal.size(); // Initializing base value to 1, i.e 16^0 int base = 1; int dec_val = 0; // Extracting characters as digits from last // character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal[i] >= '0' && hexVal[i] <= '9') { dec_val += (int(hexVal[i]) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') { dec_val += (int(hexVal[i]) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val;} // driver programint main(){ string hexNum = \"1A\"; cout << (hexadecimalToDecimal(hexNum)); // This code is contributed by rakeshsahni return 0;}", "e": 2528, "s": 1320, "text": null }, { "code": "// Java program to convert hexadecimal to decimalimport java.io.*; class GFG { // Function to convert hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { int len = hexVal.length(); // Initializing base value to 1, i.e 16^0 int base = 1; int dec_val = 0; // Extracting characters as digits from last // character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val; } // driver program public static void main(String[] args) { String hexNum = \"1A\"; System.out.println(hexadecimalToDecimal(hexNum)); }}", "e": 3914, "s": 2528, "text": null }, { "code": "# Python3 program to convert# hexadecimal to decimal # Function to convert hexadecimal# to decimal def hexadecimalToDecimal(hexval): # Finding length length = len(hexval) # Initialize base value to 1, # i.e. 16*0 base = 1 dec_val = 0 # Extracting characters as digits # from last character for i in range(length - 1, -1, -1): # If character lies in '0'-'9', # converting it to integral 0-9 # by subtracting 48 from ASCII value if hexval[i] >= '0' and hexval[i] <= '9': dec_val += (ord(hexval[i]) - 48) * base # Incrementing base by power base = base * 16 # If character lies in 'A'-'F',converting # it to integral 10-15 by subtracting 55 # from ASCII value elif hexval[i] >= 'A' and hexval[i] <= 'F': dec_val += (ord(hexval[i]) - 55) * base # Incrementing base by power base = base * 16 return dec_val # Driver codeif __name__ == '__main__': hexnum = '1A' print(hexadecimalToDecimal(hexnum)) # This code is contributed by virusbuddah_", "e": 5019, "s": 3914, "text": null }, { "code": "// C# program to convert// hexadecimal to decimalusing System; class GFG { // Function to convert // hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { int len = hexVal.Length; // Initializing base1 value // to 1, i.e 16^0 int base1 = 1; int dec_val = 0; // Extracting characters as // digits from last character for (int i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', // converting it to integral 0-9 // by subtracting 48 from ASCII value if (hexVal[i] >= '0' && hexVal[i] <= '9') { dec_val += (hexVal[i] - 48) * base1; // incrementing base1 by power base1 = base1 * 16; } // if character lies in 'A'-'F' , // converting it to integral // 10 - 15 by subtracting 55 // from ASCII value else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') { dec_val += (hexVal[i] - 55) * base1; // incrementing base1 by power base1 = base1 * 16; } } return dec_val; } // Driver Code static void Main() { String hexNum = \"1A\"; Console.WriteLine(hexadecimalToDecimal(hexNum)); }} // This code is contributed by mits", "e": 6374, "s": 5019, "text": null }, { "code": "<?php// PHP program to convert// hexadecimal to decimal // Function to convert// hexadecimal to decimalfunction hexadecimalToDecimal($hexVal){ $len = strlen($hexVal); // Initializing base value // to 1, i.e 16^0 $base = 1; $dec_val = 0; // Extracting characters as // digits from last character for ($i = $len - 1; $i >= 0; $i--) { // if character lies in '0'-'9', // converting it to integral 0-9 // by subtracting 48 from ASCII value. if ($hexVal[$i] >= '0' && $hexVal[$i] <= '9') { $dec_val += (ord($hexVal[$i]) - 48) * $base; // incrementing base by power $base = $base * 16; } // if character lies in 'A'-'F' , // converting it to integral // 10 - 15 by subtracting 55 // from ASCII value else if ($hexVal[$i] >= 'A' && $hexVal[$i] <= 'F') { $dec_val += (ord($hexVal[$i]) - 55) * $base; // incrementing base by power $base = $base * 16; } } return $dec_val;} // Driver Code$hexNum = \"1A\";echo hexadecimalToDecimal($hexNum); // This code is contributed by mits?>", "e": 7686, "s": 6374, "text": null }, { "code": "<script>// javascript program to convert hexadecimal to decimal // Function to convert hexadecimal to decimal function hexadecimalToDecimal(hexVal){ var len = hexVal.length; // Initializing base value to 1, i.e 16^0 var base = 1; var dec_val = 0; // Extracting characters as digits from last // character for (var i = len - 1; i >= 0; i--) { // if character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i).charCodeAt(0) - 48) * base; // incrementing base by power base = base * 16; } // if character lies in 'A'-'F' , converting // it to integral 10 - 15 by subtracting 55 // from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i).charCodeAt(0) - 55) * base; // incrementing base by power base = base * 16; } } return dec_val;} // driver programvar hexNum = \"1A\";document.write(hexadecimalToDecimal(hexNum)); // This code is contributed by 29AjayKumar</script>", "e": 8926, "s": 7686, "text": null }, { "code": null, "e": 8929, "s": 8926, "text": "26" }, { "code": null, "e": 8955, "s": 8929, "text": "Using predefined function" }, { "code": null, "e": 8959, "s": 8955, "text": "C++" }, { "code": null, "e": 8964, "s": 8959, "text": "Java" }, { "code": null, "e": 8972, "s": 8964, "text": "Python3" }, { "code": null, "e": 8975, "s": 8972, "text": "C#" }, { "code": null, "e": 8986, "s": 8975, "text": "Javascript" }, { "code": "// C++ program to convert octal to decimal#include <bits/stdc++.h>using namespace std;int HexToDec(string n) { return stoi(n, 0, 16); } int main(){ string n = \"1A\"; cout << HexToDec(n); return 0;} // This code is contributed by rakeshsahni", "e": 9240, "s": 8986, "text": null }, { "code": "// Java program to convert hexadecimal to decimal import java.io.*; class GFG { public static int HexToDec(String n) { return Integer.parseInt(n, 16); } public static void main(String[] args) { String n = \"1A\"; System.out.println(HexToDec(n)); }}", "e": 9526, "s": 9240, "text": null }, { "code": "# Python program to convert hexadecimal to decimaldef HexToDec(n): return int(n, 16); if __name__ == '__main__': n = \"1A\"; print(HexToDec(n)); # This code is contributed by 29AjayKumar", "e": 9724, "s": 9526, "text": null }, { "code": "// C# program to convert hexadecimal to decimal using System; public class GFG { public static int HexToDec(String n) { return Convert.ToInt32(n, 16); } public static void Main(String[] args) { String n = \"1A\"; Console.WriteLine(HexToDec(n)); }} // This code is contributed by Amit Katiyar", "e": 10053, "s": 9724, "text": null }, { "code": "<script>// javascript program to convert octal to decimalfunction HexToDec(n) { return parseInt(n, 16); } var n = \"1A\";document.write(HexToDec(n));// This code is contributed by 29AjayKumar</script>", "e": 10269, "s": 10053, "text": null }, { "code": null, "e": 10272, "s": 10269, "text": "26" }, { "code": null, "e": 10569, "s": 10272, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 10695, "s": 10569, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10708, "s": 10695, "text": "Mithun Kumar" }, { "code": null, "e": 10716, "s": 10708, "text": "soumya7" }, { "code": null, "e": 10728, "s": 10716, "text": "virusbuddha" }, { "code": null, "e": 10732, "s": 10728, "text": "le0" }, { "code": null, "e": 10744, "s": 10732, "text": "29AjayKumar" }, { "code": null, "e": 10759, "s": 10744, "text": "amit143katiyar" }, { "code": null, "e": 10771, "s": 10759, "text": "rakeshsahni" }, { "code": null, "e": 10787, "s": 10771, "text": "base-conversion" }, { "code": null, "e": 10824, "s": 10787, "text": "Computer Organization & Architecture" }, { "code": null, "e": 10859, "s": 10824, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 10867, "s": 10859, "text": "GATE CS" } ]
GraphQL - Authenticating Client
Authentication is the process or action of verifying the identity of a user or a process. It is important that an application authenticates a user to ensure that the data is not available to an anonymous user. In this section, we will learn how to authenticate a GraphQL client. In this example, we will use jQuery to create a client application. To authenticate requests, we will use express-jwt module on the server-side. The express-jwt module is a middleware that lets you authenticate HTTP requests using JWT tokens. JSON Web Token (JWT) is a long string that identifies the logged in user. Once the user logs in successfully, the server generates a JWT token. This token distinctly identifies a log. In other words, the token is a representation of user's identity. So next time, when the client comes to the server, it has to present this token to get the required resources. The client can be either a mobile application or a web application. We will follow a step-wise procedure to understand this illustration. Following are the steps for setting up the server − Create a folder auth-server-app. Change your directory to auth-server-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter. type Query { greetingWithAuth:String } Create a file resolvers.js in the project folder and add the following code − The resolver will verify if an authenticated user object is available in the context object of GraphQL. It will raise an exception if an authenticated user is not available. const db = require('./db') const Query = { greetingWithAuth:(root,args,context,info) => { //check if the context.user is null if (!context.user) { throw new Error('Unauthorized'); } return "Hello from TutorialsPoint, welcome back : "+context.user.firstName; } } module.exports = {Query} The authentication middleware authenticates callers using a JSON Web Token. The URL for authentication is http://localhost:9000/login. This is a post operation. The user has to submit his email and password which will be validated from the backend. If a valid token is generated using jwt.sign method, the client will have to send this in header for subsequent requests. If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control. The following code uses two modules − jsonwebtoken and express-jwt to authenticate requests − When the user clicks on the greet button, a request for the /graphql route is issued. If the user is not authenticated, he will be prompted to authenticate himself. When the user clicks on the greet button, a request for the /graphql route is issued. If the user is not authenticated, he will be prompted to authenticate himself. The user is presented with a form that accepts email id and password. In our example, the /login route is responsible for authenticating the user. The user is presented with a form that accepts email id and password. In our example, the /login route is responsible for authenticating the user. The /login route verifies if a match is found in the database for credentials provided by the user. The /login route verifies if a match is found in the database for credentials provided by the user. If the credentials are invalid, a HTTP 401 exception is returned to the user. If the credentials are invalid, a HTTP 401 exception is returned to the user. If the credentials are valid, a token is generated by the server. This token is sent as a part of response to the user. This is done by the jwt.sign function. If the credentials are valid, a token is generated by the server. This token is sent as a part of response to the user. This is done by the jwt.sign function. const expressJwt = require('express-jwt'); const jwt = require('jsonwebtoken'); //private key const jwtSecret = Buffer.from('Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt', 'base64'); app.post('/login', (req, res) => { const {email, password} = req.body; //check database const user = db.students.list().find((user) => user.email === email); if (!(user && user.password === password)) { res.sendStatus(401); return; } //generate a token based on private key, token doesn't have an expiry const token = jwt.sign({sub: user.id}, jwtSecret); res.send({token}); }); For every request, the app.use() function will be called. This in turn will invoke the expressJWT middleware. This middleware will decode the JSON Web Token. The user id stored in the token will be retrieved and stored as a property user in the request object. //decodes the JWT and stores in request object app.use(expressJwt({ secret: jwtSecret, credentialsRequired: false })); To make available the user property within GraphQL context, this property is assigned to the context object as shown below − //Make req.user available to GraphQL context app.use('/graphql', graphqlExpress((req) => ({ schema, context: {user: req.user &&apm; db.students.get(req.user.sub)} }))); Create server.js in current folder path. The complete server.js file is as follows − const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const expressJwt = require('express-jwt'); //auth const jwt = require('jsonwebtoken'); //auth const db = require('./db'); var port = process.env.PORT || 9000 const jwtSecret = Buffer.from('Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt', 'base64'); const app = express(); const fs = require('fs') const typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'}) const resolvers = require('./resolvers') const {makeExecutableSchema} = require('graphql-tools') const schema = makeExecutableSchema({typeDefs, resolvers}) app.use(cors(), bodyParser.json(), expressJwt({ secret: jwtSecret, credentialsRequired: false })); const {graphiqlExpress,graphqlExpress} = require('apollo-server-express') app.use('/graphql', graphqlExpress((req) => ({ schema, context: {user: req.user && db.students.get(req.user.sub)} }))); app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'})) //authenticate students app.post('/login', (req, res) => { const email = req.body.email; const password = req.body.password; const user = db.students.list().find((user) => user.email === email); if (!(user && user.password === password)) { res.sendStatus(401); return; } const token = jwt.sign({sub: user.id}, jwtSecret); res.send({token}); }); app.listen(port, () => console.info(`Server started on port ${port}`)); Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor − { greetingWithAuth } In the below response, we got an error as we are not authenticated user. { "data": { "greetingWithAuth": null }, "errors": [ { "message": "Unauthorized", "locations": [ { "line": 2, "column": 3 } ], "path": [ "greetingWithAuth" ] } ] } In the next section, let us create a client application to authenticate. In the client application, a greet button is provided which will invoke the schema greetingWithAuth. If you click the button without login, it will give you the error message as below − Once you log in with a user available in database, the following screen will appear − To access greeting, we need to first access the URL http://localhost:9000/login route as below. The response will contain the token generated from the server. $.ajax({ url:"http://localhost:9000/login", contentType:"application/json", type:"POST", data:JSON.stringify({email,password}), success:function(response) { loginToken = response.token; $('#authStatus') .html("authenticated successfully") .css({"color":"green",'font-weight':'bold'}); $("#greetingDiv").html('').css({'color':''}); }, error:(xhr,err) => alert('error') }) After a successful login, we can access greetingWithAuth schema as given below. There should be an Authorizationheader for all the subsequent requests with bearer token. { url: "http://localhost:9000/graphql", contentType: "application/json", headers: {"Authorization": 'bearer '+loginToken}, type:'POST', data: JSON.stringify({ query:`{greetingWithAuth}` } The following is the code for index.html − <!DOCTYPE html> <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { let loginToken = ""; $("#btnGreet").click(function() { $.ajax({url: "http://localhost:9000/graphql", contentType: "application/json", headers: {"Authorization": 'bearer '+loginToken}, type:'POST', data: JSON.stringify({ query:`{greetingWithAuth}` }), success: function(result) { $("#greetingDiv").html("<h1>"+result.data.greetingWithAuth+"</h1>") }, error:function(jQxhr,error) { if(jQxhr.status == 401) { $("#greetingDiv").html('please authenticate first!!') .css({"color":"red",'font-weight':'bold'}) return; } $("#greetingDiv").html('error').css("color","red"); } }); }); $('#btnAuthenticate').click(function() { var email = $("#txtEmail").val(); var password = $("#txtPwd").val(); if(email && password) { $.ajax({ url:"http://localhost:9000/login", contentType:"application/json", type:"POST", data:JSON.stringify({email,password}), success:function(response) { loginToken = response.token; $('#authStatus') .html("authenticated successfully") .css({"color":"green",'font-weight':'bold'}); $("#greetingDiv").html('').css({'color':''}); }, error:(xhr,err) => alert('error') }) }else alert("email and pwd empty") }) }); </script> </head> <body> <h1> GraphQL Authentication </h1> <hr/> <section> <button id = "btnGreet">Greet</button> <br/> <br/> <div id = "greetingDiv"></div> </section> <br/> <br/> <br/> <hr/> <section id = "LoginSection"> <header> <h2>*Login first to access greeting </h2> </header> <input type = "text" value = "[email protected]" placeholder = "enter email" id = "txtEmail"/> <br/> <input type = "password" value = "pass123" placeholder = "enter password" id = "txtPwd"/> <br/> <input type = "button" id = "btnAuthenticate" value = "Login"/> <p id = "authStatus"></p>
[ { "code": null, "e": 2364, "s": 2085, "text": "Authentication is the process or action of verifying the identity of a user or a process. It is important that an application authenticates a user to ensure that the data is not available to an anonymous user. In this section, we will learn how to authenticate a GraphQL client." }, { "code": null, "e": 2509, "s": 2364, "text": "In this example, we will use jQuery to create a client application. To authenticate requests, we will use express-jwt module on the server-side." }, { "code": null, "e": 2681, "s": 2509, "text": "The express-jwt module is a middleware that lets you authenticate HTTP requests using JWT tokens. JSON Web Token (JWT) is a long string that identifies the logged in user." }, { "code": null, "e": 3036, "s": 2681, "text": "Once the user logs in successfully, the server generates a JWT token. This token distinctly identifies a log. In other words, the token is a representation of user's identity. So next time, when the client comes to the server, it has to present this token to get the required resources. The client can be either a mobile application or a web application." }, { "code": null, "e": 3106, "s": 3036, "text": "We will follow a step-wise procedure to understand this illustration." }, { "code": null, "e": 3158, "s": 3106, "text": "Following are the steps for setting up the server −" }, { "code": null, "e": 3315, "s": 3158, "text": "Create a folder auth-server-app. Change your directory to auth-server-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter." }, { "code": null, "e": 3357, "s": 3315, "text": "type Query\n{\n greetingWithAuth:String\n}" }, { "code": null, "e": 3435, "s": 3357, "text": "Create a file resolvers.js in the project folder and add the following code −" }, { "code": null, "e": 3609, "s": 3435, "text": "The resolver will verify if an authenticated user object is available in the context object of GraphQL. It will raise an exception if an authenticated user is not available." }, { "code": null, "e": 3938, "s": 3609, "text": "const db = require('./db')\n\nconst Query = {\n greetingWithAuth:(root,args,context,info) => {\n\n //check if the context.user is null\n if (!context.user) {\n throw new Error('Unauthorized');\n }\n return \"Hello from TutorialsPoint, welcome back : \"+context.user.firstName;\n }\n}\n\nmodule.exports = {Query}" }, { "code": null, "e": 4073, "s": 3938, "text": "The authentication middleware authenticates callers using a JSON Web Token. The URL for authentication is http://localhost:9000/login." }, { "code": null, "e": 4309, "s": 4073, "text": "This is a post operation. The user has to submit his email and password which will be validated from the backend. If a valid token is generated using jwt.sign method, the client will have to send this in header for subsequent requests." }, { "code": null, "e": 4451, "s": 4309, "text": "If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control." }, { "code": null, "e": 4545, "s": 4451, "text": "The following code uses two modules − jsonwebtoken and express-jwt to authenticate requests −" }, { "code": null, "e": 4710, "s": 4545, "text": "When the user clicks on the greet button, a request for the /graphql route is issued. If the user is not authenticated, he will be prompted to authenticate himself." }, { "code": null, "e": 4875, "s": 4710, "text": "When the user clicks on the greet button, a request for the /graphql route is issued. If the user is not authenticated, he will be prompted to authenticate himself." }, { "code": null, "e": 5022, "s": 4875, "text": "The user is presented with a form that accepts email id and password. In our example, the /login route is responsible for authenticating the user." }, { "code": null, "e": 5169, "s": 5022, "text": "The user is presented with a form that accepts email id and password. In our example, the /login route is responsible for authenticating the user." }, { "code": null, "e": 5269, "s": 5169, "text": "The /login route verifies if a match is found in the database for credentials provided by the user." }, { "code": null, "e": 5369, "s": 5269, "text": "The /login route verifies if a match is found in the database for credentials provided by the user." }, { "code": null, "e": 5447, "s": 5369, "text": "If the credentials are invalid, a HTTP 401 exception is returned to the user." }, { "code": null, "e": 5525, "s": 5447, "text": "If the credentials are invalid, a HTTP 401 exception is returned to the user." }, { "code": null, "e": 5684, "s": 5525, "text": "If the credentials are valid, a token is generated by the server. This token is sent as a part of response to the user. This is done by the jwt.sign function." }, { "code": null, "e": 5843, "s": 5684, "text": "If the credentials are valid, a token is generated by the server. This token is sent as a part of response to the user. This is done by the jwt.sign function." }, { "code": null, "e": 6439, "s": 5843, "text": "const expressJwt = require('express-jwt');\nconst jwt = require('jsonwebtoken');\n\n//private key\nconst jwtSecret = Buffer.from('Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt', 'base64');\n\napp.post('/login', (req, res) => {\n const {email, password} = req.body;\n \n //check database\n const user = db.students.list().find((user) => user.email === email);\n if (!(user && user.password === password)) {\n res.sendStatus(401);\n return;\n }\n \n //generate a token based on private key, token doesn't have an expiry\n const token = jwt.sign({sub: user.id}, jwtSecret);\n res.send({token});\n});" }, { "code": null, "e": 6700, "s": 6439, "text": "For every request, the app.use() function will be called. This in turn will invoke the expressJWT middleware. This middleware will decode the JSON Web Token. The user id stored in the token will be retrieved and stored as a property user in the request object." }, { "code": null, "e": 6825, "s": 6700, "text": "//decodes the JWT and stores in request object\napp.use(expressJwt({\n secret: jwtSecret,\n credentialsRequired: false\n}));" }, { "code": null, "e": 6950, "s": 6825, "text": "To make available the user property within GraphQL context, this property is assigned to the context object as shown below −" }, { "code": null, "e": 7125, "s": 6950, "text": "//Make req.user available to GraphQL context\napp.use('/graphql', graphqlExpress((req) => ({\n schema,\n context: {user: req.user &&apm; db.students.get(req.user.sub)}\n})));" }, { "code": null, "e": 7210, "s": 7125, "text": "Create server.js in current folder path. The complete server.js file is as follows −" }, { "code": null, "e": 8659, "s": 7210, "text": "const bodyParser = require('body-parser');\nconst cors = require('cors');\nconst express = require('express');\nconst expressJwt = require('express-jwt'); //auth\nconst jwt = require('jsonwebtoken'); //auth\nconst db = require('./db');\n\nvar port = process.env.PORT || 9000\nconst jwtSecret = Buffer.from('Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt', 'base64');\nconst app = express();\n\nconst fs = require('fs')\nconst typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'})\nconst resolvers = require('./resolvers')\nconst {makeExecutableSchema} = require('graphql-tools')\n\nconst schema = makeExecutableSchema({typeDefs, resolvers})\n\napp.use(cors(), bodyParser.json(), expressJwt({\n secret: jwtSecret,\n credentialsRequired: false\n}));\n\nconst {graphiqlExpress,graphqlExpress} = require('apollo-server-express')\n\napp.use('/graphql', graphqlExpress((req) => ({\n schema,\n context: {user: req.user && db.students.get(req.user.sub)}\n})));\napp.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))\n\n//authenticate students\napp.post('/login', (req, res) => {\n const email = req.body.email;\n const password = req.body.password;\n\n const user = db.students.list().find((user) => user.email === email);\n if (!(user && user.password === password)) {\n res.sendStatus(401);\n return;\n }\n const token = jwt.sign({sub: user.id}, jwtSecret);\n res.send({token});\n});\n\napp.listen(port, () => console.info(`Server started on port ${port}`));" }, { "code": null, "e": 8813, "s": 8659, "text": "Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application." }, { "code": null, "e": 8916, "s": 8813, "text": "Open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor −" }, { "code": null, "e": 8940, "s": 8916, "text": "{\n greetingWithAuth\n}" }, { "code": null, "e": 9013, "s": 8940, "text": "In the below response, we got an error as we are not authenticated user." }, { "code": null, "e": 9317, "s": 9013, "text": "{\n \"data\": {\n \"greetingWithAuth\": null\n },\n \"errors\": [\n {\n \"message\": \"Unauthorized\",\n \"locations\": [\n {\n \"line\": 2,\n \"column\": 3\n }\n ],\n \"path\": [\n \"greetingWithAuth\"\n ]\n }\n ]\n}" }, { "code": null, "e": 9390, "s": 9317, "text": "In the next section, let us create a client application to authenticate." }, { "code": null, "e": 9576, "s": 9390, "text": "In the client application, a greet button is provided which will invoke the schema greetingWithAuth. If you click the button without login, it will give you the error message as below −" }, { "code": null, "e": 9662, "s": 9576, "text": "Once you log in with a user available in database, the following screen will appear −" }, { "code": null, "e": 9758, "s": 9662, "text": "To access greeting, we need to first access the URL http://localhost:9000/login route as below." }, { "code": null, "e": 9821, "s": 9758, "text": "The response will contain the token generated from the server." }, { "code": null, "e": 10244, "s": 9821, "text": "$.ajax({\n url:\"http://localhost:9000/login\",\n contentType:\"application/json\",\n type:\"POST\",\n data:JSON.stringify({email,password}),\n success:function(response) {\n loginToken = response.token;\n $('#authStatus')\n .html(\"authenticated successfully\")\n .css({\"color\":\"green\",'font-weight':'bold'});\n $(\"#greetingDiv\").html('').css({'color':''});\n },\n error:(xhr,err) => alert('error')\n})" }, { "code": null, "e": 10414, "s": 10244, "text": "After a successful login, we can access greetingWithAuth schema as given below. There should be an Authorizationheader for all the subsequent requests with bearer token." }, { "code": null, "e": 10619, "s": 10414, "text": "{ \n url: \"http://localhost:9000/graphql\",\n contentType: \"application/json\",\n headers: {\"Authorization\": 'bearer '+loginToken}, type:'POST',\n data: JSON.stringify({\n query:`{greetingWithAuth}`\n}" }, { "code": null, "e": 10662, "s": 10619, "text": "The following is the code for index.html −" } ]
Python | Print the initials of a name with last name in full
21 Nov, 2018 Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space except the last space. At last space we have to take all the characters after the last space in a simple approach. Using Python in inbuilt functions we can split the words into a list, then traverse till the second last word and print the first character in capitals using upper() function in python and then add the last word using title() function in Python which automatically converts the first alphabet to capital. # python program to print initials of a name def name(s): # split the string into a list l = s.split() new = "" # traverse in the list for i in range(len(l)-1): s = l[i] # adds the capital first character new += (s[0].upper()+'.') # l[-1] gives last item of list l. We # use title to print first character in # capital. new += l[-1].title() return new # Driver code s ="mohandas karamchand gandhi" print(name(s)) Output: M.K.Gandhi Python list-programs Python string-programs python-list python-string Python Strings python-list Strings 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() Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Nov, 2018" }, { "code": null, "e": 192, "s": 54, "text": "Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots." }, { "code": null, "e": 202, "s": 192, "text": "Examples:" }, { "code": null, "e": 303, "s": 202, "text": "Input : geeks for geeks\nOutput : G.F.Geeks\n\nInput : mohandas karamchand gandhi\nOutput : M.K.Gandhi \n" }, { "code": null, "e": 517, "s": 303, "text": "A naive approach of this will be to iterate for spaces and print the next letter after every space except the last space. At last space we have to take all the characters after the last space in a simple approach." }, { "code": null, "e": 822, "s": 517, "text": "Using Python in inbuilt functions we can split the words into a list, then traverse till the second last word and print the first character in capitals using upper() function in python and then add the last word using title() function in Python which automatically converts the first alphabet to capital." }, { "code": "# python program to print initials of a name def name(s): # split the string into a list l = s.split() new = \"\" # traverse in the list for i in range(len(l)-1): s = l[i] # adds the capital first character new += (s[0].upper()+'.') # l[-1] gives last item of list l. We # use title to print first character in # capital. new += l[-1].title() return new # Driver code s =\"mohandas karamchand gandhi\" print(name(s)) ", "e": 1344, "s": 822, "text": null }, { "code": null, "e": 1352, "s": 1344, "text": "Output:" }, { "code": null, "e": 1364, "s": 1352, "text": "M.K.Gandhi\n" }, { "code": null, "e": 1385, "s": 1364, "text": "Python list-programs" }, { "code": null, "e": 1408, "s": 1385, "text": "Python string-programs" }, { "code": null, "e": 1420, "s": 1408, "text": "python-list" }, { "code": null, "e": 1434, "s": 1420, "text": "python-string" }, { "code": null, "e": 1441, "s": 1434, "text": "Python" }, { "code": null, "e": 1449, "s": 1441, "text": "Strings" }, { "code": null, "e": 1461, "s": 1449, "text": "python-list" }, { "code": null, "e": 1469, "s": 1461, "text": "Strings" }, { "code": null, "e": 1567, "s": 1469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1585, "s": 1567, "text": "Python Dictionary" }, { "code": null, "e": 1627, "s": 1585, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1649, "s": 1627, "text": "Enumerate() in Python" }, { "code": null, "e": 1684, "s": 1649, "text": "Read a file line by line in Python" }, { "code": null, "e": 1710, "s": 1684, "text": "Python String | replace()" }, { "code": null, "e": 1756, "s": 1710, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 1781, "s": 1756, "text": "Reverse a string in Java" }, { "code": null, "e": 1796, "s": 1781, "text": "C++ Data Types" }, { "code": null, "e": 1856, "s": 1796, "text": "Write a program to print all permutations of a given string" } ]
Thread States in Operating Systems
25 Nov, 2019 When a thread moves through the system, it is always in one of the five states: (1) Ready (2) Running (3) Waiting (4) Delayed (5) Blocked Excluding CREATION and FINISHED state. When an application is to be processed, then it creates a thread.It is then allocated the required resources(such as a network) and it comes in the READY queue.When the thread scheduler (like a process scheduler) assign the thread with processor, it comes in RUNNING queue.When the process needs some other event to be triggered, which is outsides it’s control (like another process to be completed), it transitions from RUNNING to WAITING queue.When the application has the capability to delay the processing of the thread, it when needed can delay the thread and put it to sleep for a specific amount of time. The thread then transitions from RUNNING to DELAYED queue.An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep.When thread generates an I/O request and cannot move further till it’s done, it transitions from RUNNING to BLOCKED queue.After the process is completed, the thread transitions from RUNNING to FINISHED. When an application is to be processed, then it creates a thread. It is then allocated the required resources(such as a network) and it comes in the READY queue. When the thread scheduler (like a process scheduler) assign the thread with processor, it comes in RUNNING queue. When the process needs some other event to be triggered, which is outsides it’s control (like another process to be completed), it transitions from RUNNING to WAITING queue. When the application has the capability to delay the processing of the thread, it when needed can delay the thread and put it to sleep for a specific amount of time. The thread then transitions from RUNNING to DELAYED queue.An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep. An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep. When thread generates an I/O request and cannot move further till it’s done, it transitions from RUNNING to BLOCKED queue. After the process is completed, the thread transitions from RUNNING to FINISHED. The difference between the WAITING and BLOCKED transition is that in WAITING the thread waits for the signal from another thread or waits for another process to be completed, meaning the burst time is specific. While, in BLOCKED state, there is no specified time (it depends on the user when to give an input). In order to execute all the processes successfully, the processor needs to maintain the information about each thread through Thread Control Blocks (TCB). mutli-threading Processes & Threads GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Three address code in Compiler Introduction of Process Synchronization Differences between IPv4 and IPv6 Phases of a Compiler Banker's Algorithm in Operating System Disk Scheduling Algorithms Introduction of Deadlock in Operating System Paging in Operating System File Allocation Methods
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2019" }, { "code": null, "e": 108, "s": 28, "text": "When a thread moves through the system, it is always in one of the five states:" }, { "code": null, "e": 167, "s": 108, "text": "(1) Ready\n(2) Running\n(3) Waiting\n(4) Delayed\n(5) Blocked " }, { "code": null, "e": 206, "s": 167, "text": "Excluding CREATION and FINISHED state." }, { "code": null, "e": 1301, "s": 206, "text": "When an application is to be processed, then it creates a thread.It is then allocated the required resources(such as a network) and it comes in the READY queue.When the thread scheduler (like a process scheduler) assign the thread with processor, it comes in RUNNING queue.When the process needs some other event to be triggered, which is outsides it’s control (like another process to be completed), it transitions from RUNNING to WAITING queue.When the application has the capability to delay the processing of the thread, it when needed can delay the thread and put it to sleep for a specific amount of time. The thread then transitions from RUNNING to DELAYED queue.An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep.When thread generates an I/O request and cannot move further till it’s done, it transitions from RUNNING to BLOCKED queue.After the process is completed, the thread transitions from RUNNING to FINISHED." }, { "code": null, "e": 1367, "s": 1301, "text": "When an application is to be processed, then it creates a thread." }, { "code": null, "e": 1463, "s": 1367, "text": "It is then allocated the required resources(such as a network) and it comes in the READY queue." }, { "code": null, "e": 1577, "s": 1463, "text": "When the thread scheduler (like a process scheduler) assign the thread with processor, it comes in RUNNING queue." }, { "code": null, "e": 1751, "s": 1577, "text": "When the process needs some other event to be triggered, which is outsides it’s control (like another process to be completed), it transitions from RUNNING to WAITING queue." }, { "code": null, "e": 2198, "s": 1751, "text": "When the application has the capability to delay the processing of the thread, it when needed can delay the thread and put it to sleep for a specific amount of time. The thread then transitions from RUNNING to DELAYED queue.An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep." }, { "code": null, "e": 2421, "s": 2198, "text": "An example of delaying of thread is snoozing of an alarm. After it rings for the first time and is not switched off by the user, it rings again after a specific amount of time. During that time, the thread is put to sleep." }, { "code": null, "e": 2544, "s": 2421, "text": "When thread generates an I/O request and cannot move further till it’s done, it transitions from RUNNING to BLOCKED queue." }, { "code": null, "e": 2625, "s": 2544, "text": "After the process is completed, the thread transitions from RUNNING to FINISHED." }, { "code": null, "e": 2936, "s": 2625, "text": "The difference between the WAITING and BLOCKED transition is that in WAITING the thread waits for the signal from another thread or waits for another process to be completed, meaning the burst time is specific. While, in BLOCKED state, there is no specified time (it depends on the user when to give an input)." }, { "code": null, "e": 3091, "s": 2936, "text": "In order to execute all the processes successfully, the processor needs to maintain the information about each thread through Thread Control Blocks (TCB)." }, { "code": null, "e": 3107, "s": 3091, "text": "mutli-threading" }, { "code": null, "e": 3127, "s": 3107, "text": "Processes & Threads" }, { "code": null, "e": 3135, "s": 3127, "text": "GATE CS" }, { "code": null, "e": 3153, "s": 3135, "text": "Operating Systems" }, { "code": null, "e": 3171, "s": 3153, "text": "Operating Systems" }, { "code": null, "e": 3269, "s": 3171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3322, "s": 3269, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3353, "s": 3322, "text": "Three address code in Compiler" }, { "code": null, "e": 3393, "s": 3353, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 3427, "s": 3393, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 3448, "s": 3427, "text": "Phases of a Compiler" }, { "code": null, "e": 3487, "s": 3448, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 3514, "s": 3487, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 3559, "s": 3514, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 3586, "s": 3559, "text": "Paging in Operating System" } ]
Length of the longest subarray whose Bitwise XOR is K
17 May, 2021 Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray having Bitwise XOR of all its elements equal to K. Examples: Input: arr[] = { 1, 2, 4, 7, 2 }, K = 1Output: 3Explanation: Subarray having Bitwise XOR equal to K(= 1) are { { 1 }, { 2, 4, 7 }, { 1 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 1) is 3 Input: arr[] = { 2, 5, 6, 1, 0, 3, 5, 6 }, K = 4Output: 6Explanation:Subarray having Bitwise XOR equal to K(= 4) are { { 6, 1, 0, 3 }, { 5, 6, 1, 0, 3, 5 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 4) is 6. Approach: The problem can be solved using Hashing and Prefix Sum technique. Following are the observation: a1 ^ a2 ^ a3 ^ ..... ^ an = K => a2 ^ a3 ^ ..... ^ an ^ K = a1 Follow the steps below to solve the problem: Initialize a variable, say prefixXOR, to store the Bitwise XOR of all elements up to the ith index of the given array. Initialize a Map, say mp, to store the indices of the computed prefix XORs of the array. Initialize a variable, say maxLen, to store the length of the longest subarray whose Bitwise XOR is equal to K. Traverse the array arr[] using variable i. For every ith index, update prefixXOR = prefixXOR ^ arr[i] and check if (prefixXOR ^ K) is present in the Map or not. If found to be true, then update maxLen = max(maxLen, i – mp[prefixXOR ^ K]). If prefixXOR is not present in the Map, then insert prefixXOR into the Map. Finally, print the value of maxLen. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kint LongestLenXORK(int arr[], int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array map<int, int> mp; // Insert 0 into the map mp[0] = -1; // Traverse the array for (int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.count(prefixXOR ^ K)) { // Update maxLen maxLen = max(maxLen, (i - mp[prefixXOR ^ K])); } // If prefixXOR not present // in the Map if (!mp.count(prefixXOR)) { // Insert prefixXOR // into the map mp[prefixXOR] = i; } } return maxLen;} // Driver Codeint main(){ int arr[] = { 1, 2, 4, 7, 2 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; cout<< LongestLenXORK(arr, N, K); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int LongestLenXORK(int arr[], int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Insert 0 into the map mp.put(0, -1); // Traverse the array for(int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.containsKey(prefixXOR ^ K)) { // Update maxLen maxLen = Math.max(maxLen, (i - mp.get(prefixXOR ^ K))); } // If prefixXOR not present // in the Map if (!mp.containsKey(prefixXOR)) { // Insert prefixXOR // into the map mp.put(prefixXOR, i); } } return maxLen;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 4, 7, 2 }; int N = arr.length; int K = 1; System.out.print(LongestLenXORK(arr, N, K));}} // This code is contributed by Amit Katiyar # Python3 program to implement# the above approach # Function to find the length of the longest# subarray whose bitwise XOR is equal to Kdef LongestLenXORK(arr, N, K): # Stores prefix XOR # of the array prefixXOR = 0 # Stores length of longest subarray # having bitwise XOR equal to K maxLen = 0 # Stores index of prefix # XOR of the array mp = {} # Insert 0 into the map mp[0] = -1 # Traverse the array for i in range(N): # Update prefixXOR prefixXOR ^= arr[i] # If (prefixXOR ^ K) present # in the map if (prefixXOR ^ K) in mp: # Update maxLen maxLen = max(maxLen, (i - mp[prefixXOR ^ K])) # If prefixXOR not present # in the Map else: # Insert prefixXOR # into the map mp[prefixXOR] = i return maxLen # Driver Codeif __name__ == "__main__" : arr = [ 1, 2, 4, 7, 2 ] N = len(arr) K = 1 print(LongestLenXORK(arr, N, K)) # This code is contributed by AnkThon // C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int longestLenXORK(int []arr, int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array Dictionary<int, int> mp = new Dictionary<int, int>(); // Insert 0 into the map mp.Add(0, -1); // Traverse the array for(int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.ContainsKey(prefixXOR ^ K)) { // Update maxLen maxLen = Math.Max(maxLen, (i - mp[prefixXOR ^ K])); } // If prefixXOR not present // in the Map if (!mp.ContainsKey(prefixXOR)) { // Insert prefixXOR // into the map mp.Add(prefixXOR, i); } } return maxLen;} // Driver Codepublic static void Main(String[] args){ int []arr = {1, 2, 4, 7, 2}; int N = arr.Length; int K = 1; Console.Write(longestLenXORK(arr, N, K));}} // This code is contributed by shikhasingrajput <script> // JavaScript program to implement// the above approach // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kfunction LongestLenXORK(arr, N, K){ // Stores prefix XOR // of the array var prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K var maxLen = 0; // Stores index of prefix // XOR of the array var mp = new Map(); // Insert 0 into the map mp.set(0, -1); // Traverse the array for (var i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.has(prefixXOR ^ K)) { // Update maxLen maxLen = Math.max(maxLen, (i - mp.get(prefixXOR ^ K))); } // If prefixXOR not present // in the Map if (!mp.has(prefixXOR)) { // Insert prefixXOR // into the map mp.set(prefixXOR, i); } } return maxLen;} // Driver Codevar arr = [1, 2, 4, 7, 2];var N = arr.length;var K = 1;document.write( LongestLenXORK(arr, N, K)); </script> Output: 3 Time Complexity: O(N)Auxiliary Space: O(N) amit143katiyar ankthon shikhasingrajput rrrtnx Bitwise-XOR cpp-map Hash prefix subarray Arrays Bit Magic Hash Mathematical Arrays Hash Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2021" }, { "code": null, "e": 207, "s": 52, "text": "Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray having Bitwise XOR of all its elements equal to K." }, { "code": null, "e": 217, "s": 207, "text": "Examples:" }, { "code": null, "e": 438, "s": 217, "text": "Input: arr[] = { 1, 2, 4, 7, 2 }, K = 1Output: 3Explanation: Subarray having Bitwise XOR equal to K(= 1) are { { 1 }, { 2, 4, 7 }, { 1 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 1) is 3" }, { "code": null, "e": 679, "s": 438, "text": "Input: arr[] = { 2, 5, 6, 1, 0, 3, 5, 6 }, K = 4Output: 6Explanation:Subarray having Bitwise XOR equal to K(= 4) are { { 6, 1, 0, 3 }, { 5, 6, 1, 0, 3, 5 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 4) is 6." }, { "code": null, "e": 786, "s": 679, "text": "Approach: The problem can be solved using Hashing and Prefix Sum technique. Following are the observation:" }, { "code": null, "e": 816, "s": 786, "text": "a1 ^ a2 ^ a3 ^ ..... ^ an = K" }, { "code": null, "e": 849, "s": 816, "text": "=> a2 ^ a3 ^ ..... ^ an ^ K = a1" }, { "code": null, "e": 894, "s": 849, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 1013, "s": 894, "text": "Initialize a variable, say prefixXOR, to store the Bitwise XOR of all elements up to the ith index of the given array." }, { "code": null, "e": 1102, "s": 1013, "text": "Initialize a Map, say mp, to store the indices of the computed prefix XORs of the array." }, { "code": null, "e": 1214, "s": 1102, "text": "Initialize a variable, say maxLen, to store the length of the longest subarray whose Bitwise XOR is equal to K." }, { "code": null, "e": 1453, "s": 1214, "text": "Traverse the array arr[] using variable i. For every ith index, update prefixXOR = prefixXOR ^ arr[i] and check if (prefixXOR ^ K) is present in the Map or not. If found to be true, then update maxLen = max(maxLen, i – mp[prefixXOR ^ K])." }, { "code": null, "e": 1529, "s": 1453, "text": "If prefixXOR is not present in the Map, then insert prefixXOR into the Map." }, { "code": null, "e": 1565, "s": 1529, "text": "Finally, print the value of maxLen." }, { "code": null, "e": 1616, "s": 1565, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1620, "s": 1616, "text": "C++" }, { "code": null, "e": 1625, "s": 1620, "text": "Java" }, { "code": null, "e": 1633, "s": 1625, "text": "Python3" }, { "code": null, "e": 1636, "s": 1633, "text": "C#" }, { "code": null, "e": 1647, "s": 1636, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kint LongestLenXORK(int arr[], int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array map<int, int> mp; // Insert 0 into the map mp[0] = -1; // Traverse the array for (int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.count(prefixXOR ^ K)) { // Update maxLen maxLen = max(maxLen, (i - mp[prefixXOR ^ K])); } // If prefixXOR not present // in the Map if (!mp.count(prefixXOR)) { // Insert prefixXOR // into the map mp[prefixXOR] = i; } } return maxLen;} // Driver Codeint main(){ int arr[] = { 1, 2, 4, 7, 2 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; cout<< LongestLenXORK(arr, N, K); return 0;}", "e": 2883, "s": 1647, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int LongestLenXORK(int arr[], int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Insert 0 into the map mp.put(0, -1); // Traverse the array for(int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.containsKey(prefixXOR ^ K)) { // Update maxLen maxLen = Math.max(maxLen, (i - mp.get(prefixXOR ^ K))); } // If prefixXOR not present // in the Map if (!mp.containsKey(prefixXOR)) { // Insert prefixXOR // into the map mp.put(prefixXOR, i); } } return maxLen;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 4, 7, 2 }; int N = arr.length; int K = 1; System.out.print(LongestLenXORK(arr, N, K));}} // This code is contributed by Amit Katiyar", "e": 4387, "s": 2883, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the length of the longest# subarray whose bitwise XOR is equal to Kdef LongestLenXORK(arr, N, K): # Stores prefix XOR # of the array prefixXOR = 0 # Stores length of longest subarray # having bitwise XOR equal to K maxLen = 0 # Stores index of prefix # XOR of the array mp = {} # Insert 0 into the map mp[0] = -1 # Traverse the array for i in range(N): # Update prefixXOR prefixXOR ^= arr[i] # If (prefixXOR ^ K) present # in the map if (prefixXOR ^ K) in mp: # Update maxLen maxLen = max(maxLen, (i - mp[prefixXOR ^ K])) # If prefixXOR not present # in the Map else: # Insert prefixXOR # into the map mp[prefixXOR] = i return maxLen # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 2, 4, 7, 2 ] N = len(arr) K = 1 print(LongestLenXORK(arr, N, K)) # This code is contributed by AnkThon", "e": 5493, "s": 4387, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int longestLenXORK(int []arr, int N, int K){ // Stores prefix XOR // of the array int prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K int maxLen = 0; // Stores index of prefix // XOR of the array Dictionary<int, int> mp = new Dictionary<int, int>(); // Insert 0 into the map mp.Add(0, -1); // Traverse the array for(int i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.ContainsKey(prefixXOR ^ K)) { // Update maxLen maxLen = Math.Max(maxLen, (i - mp[prefixXOR ^ K])); } // If prefixXOR not present // in the Map if (!mp.ContainsKey(prefixXOR)) { // Insert prefixXOR // into the map mp.Add(prefixXOR, i); } } return maxLen;} // Driver Codepublic static void Main(String[] args){ int []arr = {1, 2, 4, 7, 2}; int N = arr.Length; int K = 1; Console.Write(longestLenXORK(arr, N, K));}} // This code is contributed by shikhasingrajput", "e": 7006, "s": 5493, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kfunction LongestLenXORK(arr, N, K){ // Stores prefix XOR // of the array var prefixXOR = 0; // Stores length of longest subarray // having bitwise XOR equal to K var maxLen = 0; // Stores index of prefix // XOR of the array var mp = new Map(); // Insert 0 into the map mp.set(0, -1); // Traverse the array for (var i = 0; i < N; i++) { // Update prefixXOR prefixXOR ^= arr[i]; // If (prefixXOR ^ K) present // in the map if (mp.has(prefixXOR ^ K)) { // Update maxLen maxLen = Math.max(maxLen, (i - mp.get(prefixXOR ^ K))); } // If prefixXOR not present // in the Map if (!mp.has(prefixXOR)) { // Insert prefixXOR // into the map mp.set(prefixXOR, i); } } return maxLen;} // Driver Codevar arr = [1, 2, 4, 7, 2];var N = arr.length;var K = 1;document.write( LongestLenXORK(arr, N, K)); </script>", "e": 8174, "s": 7006, "text": null }, { "code": null, "e": 8182, "s": 8174, "text": "Output:" }, { "code": null, "e": 8184, "s": 8182, "text": "3" }, { "code": null, "e": 8227, "s": 8184, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 8242, "s": 8227, "text": "amit143katiyar" }, { "code": null, "e": 8250, "s": 8242, "text": "ankthon" }, { "code": null, "e": 8267, "s": 8250, "text": "shikhasingrajput" }, { "code": null, "e": 8274, "s": 8267, "text": "rrrtnx" }, { "code": null, "e": 8286, "s": 8274, "text": "Bitwise-XOR" }, { "code": null, "e": 8294, "s": 8286, "text": "cpp-map" }, { "code": null, "e": 8299, "s": 8294, "text": "Hash" }, { "code": null, "e": 8306, "s": 8299, "text": "prefix" }, { "code": null, "e": 8315, "s": 8306, "text": "subarray" }, { "code": null, "e": 8322, "s": 8315, "text": "Arrays" }, { "code": null, "e": 8332, "s": 8322, "text": "Bit Magic" }, { "code": null, "e": 8337, "s": 8332, "text": "Hash" }, { "code": null, "e": 8350, "s": 8337, "text": "Mathematical" }, { "code": null, "e": 8357, "s": 8350, "text": "Arrays" }, { "code": null, "e": 8362, "s": 8357, "text": "Hash" }, { "code": null, "e": 8375, "s": 8362, "text": "Mathematical" }, { "code": null, "e": 8385, "s": 8375, "text": "Bit Magic" }, { "code": null, "e": 8483, "s": 8385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8551, "s": 8483, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8595, "s": 8551, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 8627, "s": 8595, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8675, "s": 8627, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 8689, "s": 8675, "text": "Linear Search" }, { "code": null, "e": 8716, "s": 8689, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 8762, "s": 8716, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 8830, "s": 8762, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 8859, "s": 8830, "text": "Count set bits in an integer" } ]
Java Program to Create a Thread
06 Jun, 2021 Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is created as a result of the main thread. This is the last thread to complete execution. A thread can programmatically be created by: Implementing the java.lang.Runnable interface.Extending the java.lang.Thread class. Implementing the java.lang.Runnable interface. Extending the java.lang.Thread class. You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a thread object and call the start() method. Thread Class: The Thread class provides constructors and methods for creating and operating on threads. The thread extends the Object and implements the Runnable interface. 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. // start a newly created thread. // Thread moves from new state to runnable state // When it gets a chance, executes the target run() method public void start() Runnable interface: Any class with instances that are intended to be executed by a thread should implement the Runnable interface. The Runnable interface has only one method, which is called run(). // Thread action is performed public void run() Benefits of creating threads : When compared to processes, Java Threads are more lightweight; it takes less time and resources to create a thread. Threads share the data and code of their parent process. Thread communication is simpler than process communication. Context switching between threads is usually cheaper than switching between processes. Calling run() instead of start() The common mistake is starting a thread using run() instead of start() method. Thread myThread = new Thread(MyRunnable()); myThread.run(); //should be start(); The run() method is not called by the thread you created. Instead, it is called by the thread that created the myThread. Example 1: By using Thread Class Java import java.io.*;class GFG extends Thread { public void run() { System.out.print("Welcome to GeeksforGeeks."); } public static void main(String[] args) { GFG g = new GFG(); // creating thread g.start(); // starting thread }} Welcome to GeeksforGeeks. Example 2: By implementing Runnable interface Java import java.io.*;class GFG implements Runnable { public static void main(String args[]) { // create an object of Runnable target GFG gfg = new GFG(); // pass the runnable reference to Thread Thread t = new Thread(gfg, "gfg"); // start the thread t.start(); // get the name of the thread System.out.println(t.getName()); } @Override public void run() { System.out.println("Inside run method"); }} gfg Inside run method Java-Multithreading Picked Java Java Programs 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2021" }, { "code": null, "e": 387, "s": 52, "text": "Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. The slave thread is created as a result of the main thread. This is the last thread to complete execution." }, { "code": null, "e": 433, "s": 387, "text": " A thread can programmatically be created by:" }, { "code": null, "e": 517, "s": 433, "text": "Implementing the java.lang.Runnable interface.Extending the java.lang.Thread class." }, { "code": null, "e": 564, "s": 517, "text": "Implementing the java.lang.Runnable interface." }, { "code": null, "e": 602, "s": 564, "text": "Extending the java.lang.Thread class." }, { "code": null, "e": 763, "s": 602, "text": "You can create threads by implementing the runnable interface and overriding the run() method. Then, you can create a thread object and call the start() method." }, { "code": null, "e": 777, "s": 763, "text": "Thread Class:" }, { "code": null, "e": 936, "s": 777, "text": "The Thread class provides constructors and methods for creating and operating on threads. The thread extends the Object and implements the Runnable interface." }, { "code": null, "e": 945, "s": 936, "text": "Chapters" }, { "code": null, "e": 972, "s": 945, "text": "descriptions off, selected" }, { "code": null, "e": 1022, "s": 972, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1045, "s": 1022, "text": "captions off, selected" }, { "code": null, "e": 1053, "s": 1045, "text": "English" }, { "code": null, "e": 1077, "s": 1053, "text": "This is a modal window." }, { "code": null, "e": 1146, "s": 1077, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1168, "s": 1146, "text": "End of dialog window." }, { "code": null, "e": 1331, "s": 1168, "text": "// start a newly created thread.\n// Thread moves from new state to runnable state\n// When it gets a chance, executes the target run() method\npublic void start() " }, { "code": null, "e": 1351, "s": 1331, "text": "Runnable interface:" }, { "code": null, "e": 1529, "s": 1351, "text": "Any class with instances that are intended to be executed by a thread should implement the Runnable interface. The Runnable interface has only one method, which is called run()." }, { "code": null, "e": 1578, "s": 1529, "text": "// Thread action is performed\npublic void run() " }, { "code": null, "e": 1609, "s": 1578, "text": "Benefits of creating threads :" }, { "code": null, "e": 1725, "s": 1609, "text": "When compared to processes, Java Threads are more lightweight; it takes less time and resources to create a thread." }, { "code": null, "e": 1782, "s": 1725, "text": "Threads share the data and code of their parent process." }, { "code": null, "e": 1842, "s": 1782, "text": "Thread communication is simpler than process communication." }, { "code": null, "e": 1929, "s": 1842, "text": "Context switching between threads is usually cheaper than switching between processes." }, { "code": null, "e": 1962, "s": 1929, "text": "Calling run() instead of start()" }, { "code": null, "e": 2042, "s": 1962, "text": "The common mistake is starting a thread using run() instead of start() method. " }, { "code": null, "e": 2128, "s": 2042, "text": " Thread myThread = new Thread(MyRunnable());\n myThread.run(); //should be start();" }, { "code": null, "e": 2250, "s": 2128, "text": "The run() method is not called by the thread you created. Instead, it is called by the thread that created the myThread. " }, { "code": null, "e": 2283, "s": 2250, "text": "Example 1: By using Thread Class" }, { "code": null, "e": 2288, "s": 2283, "text": "Java" }, { "code": "import java.io.*;class GFG extends Thread { public void run() { System.out.print(\"Welcome to GeeksforGeeks.\"); } public static void main(String[] args) { GFG g = new GFG(); // creating thread g.start(); // starting thread }}", "e": 2552, "s": 2288, "text": null }, { "code": null, "e": 2578, "s": 2552, "text": "Welcome to GeeksforGeeks." }, { "code": null, "e": 2624, "s": 2578, "text": "Example 2: By implementing Runnable interface" }, { "code": null, "e": 2629, "s": 2624, "text": "Java" }, { "code": "import java.io.*;class GFG implements Runnable { public static void main(String args[]) { // create an object of Runnable target GFG gfg = new GFG(); // pass the runnable reference to Thread Thread t = new Thread(gfg, \"gfg\"); // start the thread t.start(); // get the name of the thread System.out.println(t.getName()); } @Override public void run() { System.out.println(\"Inside run method\"); }}", "e": 3112, "s": 2629, "text": null }, { "code": null, "e": 3134, "s": 3112, "text": "gfg\nInside run method" }, { "code": null, "e": 3154, "s": 3134, "text": "Java-Multithreading" }, { "code": null, "e": 3161, "s": 3154, "text": "Picked" }, { "code": null, "e": 3166, "s": 3161, "text": "Java" }, { "code": null, "e": 3180, "s": 3166, "text": "Java Programs" }, { "code": null, "e": 3185, "s": 3180, "text": "Java" }, { "code": null, "e": 3283, "s": 3185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3298, "s": 3283, "text": "Stream In Java" }, { "code": null, "e": 3319, "s": 3298, "text": "Introduction to Java" }, { "code": null, "e": 3340, "s": 3319, "text": "Constructors in Java" }, { "code": null, "e": 3359, "s": 3340, "text": "Exceptions in Java" }, { "code": null, "e": 3376, "s": 3359, "text": "Generics in Java" }, { "code": null, "e": 3402, "s": 3376, "text": "Java Programming Examples" }, { "code": null, "e": 3436, "s": 3402, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3483, "s": 3436, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3521, "s": 3483, "text": "Factory method design pattern in Java" } ]
How do I generate random floats in C++?
In C or C++, we cannot create random float directly. We can create random floats using some trick. We will create two random integer values, then divide them to get random float value. Sometimes it may generate an integer quotient, so to reduce the probability of that, we are multiplying the result with some floating point constant like 0.5. #include <iostream> #include <cstdlib> #include <ctime> using namespace std; main() { srand((unsigned int)time(NULL)); float a = 5.0; for (int i=0;i<20;i++) cout << (float(rand())/float((RAND_MAX)) * a) << endl; } 2.07648 4.3115 1.31092 2.22465 2.17292 1.48381 1.91137 0.56505 2.24326 4.44517 3.1695 2.39067 1.89062 4.35881 4.17524 0.189673 1.87521 1.76916 2.3217 2.20481
[ { "code": null, "e": 1372, "s": 1187, "text": "In C or C++, we cannot create random float directly. We can create random floats using some trick. We will create two random integer values, then divide them to get random float value." }, { "code": null, "e": 1531, "s": 1372, "text": "Sometimes it may generate an integer quotient, so to reduce the probability of that, we are multiplying the result with some floating point constant like 0.5." }, { "code": null, "e": 1760, "s": 1531, "text": "#include <iostream>\n#include <cstdlib>\n#include <ctime>\nusing namespace std;\nmain() {\n srand((unsigned int)time(NULL));\n float a = 5.0;\n for (int i=0;i<20;i++)\n cout << (float(rand())/float((RAND_MAX)) * a) << endl;\n}" }, { "code": null, "e": 1918, "s": 1760, "text": "2.07648\n4.3115\n1.31092\n2.22465\n2.17292\n1.48381\n1.91137\n0.56505\n2.24326\n4.44517\n3.1695\n2.39067\n1.89062\n4.35881\n4.17524\n0.189673\n1.87521\n1.76916\n2.3217\n2.20481" } ]
Data Classes in Python | An Introduction
23 Apr, 2021 dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced in Python3.7, one can also use it in Python3.6 by installing dataclasses library. pip install dataclasses The DataClasses are implemented by using decorators with classes. Attributes are declared using Type Hints in Python which is essentially, specifying data type for variables in python. Python3 # A basic Data Class # Importing dataclass modulefrom dataclasses import dataclass @dataclassclass GfgArticle(): """A class for holding an article content""" # Attributes Declaration # using Type Hints title: str author: str language: str upvotes: int # A DataClass objectarticle = GfgArticle("DataClasses", "vibhu4agarwal", "Python", 0)print(article) Output: GfgArticle(title=’DataClasses’, author=’vibhu4agarwal’, language=’Python’, upvotes=0) The two noticeable points in above code. Without a __init__() constructor, the class accepted values and assigned it to appropriate variables. The output of printing object is a neat representation of the data present in it, without any explicit function coded to do this. That means it has a modified __repr__() function. The dataclass provides an in built __init__() constructor to classes which handle the data and object creation for them. Python3 article = GfgArticle() TypeError: __init__() missing 4 required positional arguments: ‘title’, ‘author’, ‘language’, and ‘upvotes’ We can also modify the functioning of in-built constructor by passing certain arguments or using special functions which will be discussed in further articles.Equality of DataClasses Since the classes store data, checking two objects if they have the same data is a very common task that’s needed with dataclasses. This is accomplished by using the == operator. Below is the code for an equivalent class for storing an article without a dataclass decorator. Python3 class NormalArticle(): """A class for holding an article content""" # Equivalent Constructor def __init__(self, title, author, language, upvotes): self.title = title self.author = author self.language = language self.upvotes = upvotes # Two DataClass objectsdClassArticle1 = GfgArticle("DataClasses", "vibhu4agarwal", "Python", 0)dClassArticle2 = GfgArticle("DataClasses", "vibhu4agarwal", "Python", 0) # Two objects of a normal classarticle1 = NormalArticle("DataClasses", "vibhu4agarwal", "Python", 0)article2 = NormalArticle("DataClasses", "vibhu4agarwal", "Python", 0) Python3 print("DataClass Equal:", dClassArticle1 == dClassArticle2)print("Normal Class Equal:", article1 == article2) Output: DataClass Equal: True Normal Class Equal: False Equality between two objects using == operator in python checks for the same memory location. Since two objects take different memory locations on creation, the output for equality is False. Equality between DataClass objects checks for the equality of data present in it. This accounts for True as output for equality check between two DataClass objects which contain same data. simmytarika5 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 412, "s": 28, "text": "dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced in Python3.7, one can also use it in Python3.6 by installing dataclasses library. " }, { "code": null, "e": 436, "s": 412, "text": "pip install dataclasses" }, { "code": null, "e": 622, "s": 436, "text": "The DataClasses are implemented by using decorators with classes. Attributes are declared using Type Hints in Python which is essentially, specifying data type for variables in python. " }, { "code": null, "e": 630, "s": 622, "text": "Python3" }, { "code": "# A basic Data Class # Importing dataclass modulefrom dataclasses import dataclass @dataclassclass GfgArticle(): \"\"\"A class for holding an article content\"\"\" # Attributes Declaration # using Type Hints title: str author: str language: str upvotes: int # A DataClass objectarticle = GfgArticle(\"DataClasses\", \"vibhu4agarwal\", \"Python\", 0)print(article)", "e": 1045, "s": 630, "text": null }, { "code": null, "e": 1055, "s": 1045, "text": "Output: " }, { "code": null, "e": 1143, "s": 1055, "text": "GfgArticle(title=’DataClasses’, author=’vibhu4agarwal’, language=’Python’, upvotes=0) " }, { "code": null, "e": 1186, "s": 1143, "text": "The two noticeable points in above code. " }, { "code": null, "e": 1288, "s": 1186, "text": "Without a __init__() constructor, the class accepted values and assigned it to appropriate variables." }, { "code": null, "e": 1468, "s": 1288, "text": "The output of printing object is a neat representation of the data present in it, without any explicit function coded to do this. That means it has a modified __repr__() function." }, { "code": null, "e": 1591, "s": 1468, "text": "The dataclass provides an in built __init__() constructor to classes which handle the data and object creation for them. " }, { "code": null, "e": 1599, "s": 1591, "text": "Python3" }, { "code": "article = GfgArticle()", "e": 1622, "s": 1599, "text": null }, { "code": null, "e": 1732, "s": 1622, "text": "TypeError: __init__() missing 4 required positional arguments: ‘title’, ‘author’, ‘language’, and ‘upvotes’ " }, { "code": null, "e": 2192, "s": 1732, "text": "We can also modify the functioning of in-built constructor by passing certain arguments or using special functions which will be discussed in further articles.Equality of DataClasses Since the classes store data, checking two objects if they have the same data is a very common task that’s needed with dataclasses. This is accomplished by using the == operator. Below is the code for an equivalent class for storing an article without a dataclass decorator. " }, { "code": null, "e": 2200, "s": 2192, "text": "Python3" }, { "code": "class NormalArticle(): \"\"\"A class for holding an article content\"\"\" # Equivalent Constructor def __init__(self, title, author, language, upvotes): self.title = title self.author = author self.language = language self.upvotes = upvotes # Two DataClass objectsdClassArticle1 = GfgArticle(\"DataClasses\", \"vibhu4agarwal\", \"Python\", 0)dClassArticle2 = GfgArticle(\"DataClasses\", \"vibhu4agarwal\", \"Python\", 0) # Two objects of a normal classarticle1 = NormalArticle(\"DataClasses\", \"vibhu4agarwal\", \"Python\", 0)article2 = NormalArticle(\"DataClasses\", \"vibhu4agarwal\", \"Python\", 0)", "e": 3015, "s": 2200, "text": null }, { "code": null, "e": 3023, "s": 3015, "text": "Python3" }, { "code": "print(\"DataClass Equal:\", dClassArticle1 == dClassArticle2)print(\"Normal Class Equal:\", article1 == article2)", "e": 3133, "s": 3023, "text": null }, { "code": null, "e": 3143, "s": 3133, "text": "Output: " }, { "code": null, "e": 3191, "s": 3143, "text": "DataClass Equal: True\nNormal Class Equal: False" }, { "code": null, "e": 3572, "s": 3191, "text": "Equality between two objects using == operator in python checks for the same memory location. Since two objects take different memory locations on creation, the output for equality is False. Equality between DataClass objects checks for the equality of data present in it. This accounts for True as output for equality check between two DataClass objects which contain same data. " }, { "code": null, "e": 3585, "s": 3572, "text": "simmytarika5" }, { "code": null, "e": 3600, "s": 3585, "text": "python-modules" }, { "code": null, "e": 3607, "s": 3600, "text": "Python" } ]
Node2Vec Algorithm
13 Dec, 2021 Prerequisite: Word2Vec Word Embedding: It is a language modeling technique used for mapping words to vectors of real numbers. It represents words or phrases in vector space with several dimensions. Word embeddings can be generated using various methods like neural networks, co-occurrence matrix, probabilistic models, etc. Word2Vec: It consists of models for generating word embedding. Node2Vec: A node embedding algorithm that computes a vector representation of a node based on random walks in the graph. The neighborhood nodes of the graph is also sampled through deep random walks. This algorithm performs a biased random walk procedure in order to efficiently explore diverse neighborhoods. It is based on a similar principle as Word2Vec but instead of word embeddings, we create node embeddings here. Intuition: Node2Vec framework is based on the principle of learning continuous feature representation for nodes in the graph and preserving the knowledge gained from the neighboring 100 nodes. Lets us understand how the algorithm works. Say we have a graph having a few interconnected nodes creating a network. So, Node2Vec algorithm learns a dense representation (say 100 dimensions/features) of every node in the network. The algorithm suggests that if we plot these 100 dimensions of each node in a 2 dimensional graph by applying PCA, the distance of the two nodes in that low-dimensional graph would be same as their actual distance in the given network. In this way, the framework maximizes the likelihood of preserving neighboring nodes even if you represent them in a low-dimensional space. (As shown in Fig 1) Fig1 : Intuition Real-Life Example: Let us take an example of textual data given to us to understand its working in detail. The Node2Vec framework suggests that random walks through the series of nodes in the graph can be treated as sentences. Each node in this graph is treated like a unique, individual word and each random walk through the network is treated as a sentence. By creating and using a “continuous bag of words model” on which the Node2Vec framework learns, it can predict the next possible set of words by searching the neighbours of the given word. This is the power of Node2Vec algorithm. Node2Vec Algorithm: node2vecWalk (Graph G' = (V, E, π), Start node u, Length l): Initialize walk to [u] for (walk_iter = 1 to l): curr = walk[−1] Vcurr = GetNeighbors(curr, G') s = AliasSample(Vcurr, π) Append s to walk return walk Learn_Features (Graph G = (V, E, W)): Dimensions -> d Walks per node -> r Walk length -> l Context size -> k Return -> p In-out -> q π = PreprocessModifiedWeights (G, p, q) G' = (V, E, π) Initialize walks = 0 for (iter = 1 to r): for (all nodes u ∈ V): walk = node2vecWalk(G', u, l) Append walk to walks f = StochasticGradientDescent(k, d, walks) return f Applications: Social Media Network: Let’s consider each node in the network as a ‘USER’ and the neighboring nodes as the ‘FRIENDS’ of the that user. Each node has a set of features that involves their likes and dislikes. So, by using Node2Vec framework, we can identify which is the closest friend of the user easily.Recommendation System Network: The recommendation system gives two ‘USERS’ (nodes) the same recommendation of a product based on the similarity of their feature set. It this way, these recommendation systems give similar recommendations to a group of such similar nodes hence making it efficient. Social Media Network: Let’s consider each node in the network as a ‘USER’ and the neighboring nodes as the ‘FRIENDS’ of the that user. Each node has a set of features that involves their likes and dislikes. So, by using Node2Vec framework, we can identify which is the closest friend of the user easily. Recommendation System Network: The recommendation system gives two ‘USERS’ (nodes) the same recommendation of a product based on the similarity of their feature set. It this way, these recommendation systems give similar recommendations to a group of such similar nodes hence making it efficient. sooda367 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI An introduction to Machine Learning
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Dec, 2021" }, { "code": null, "e": 51, "s": 28, "text": "Prerequisite: Word2Vec" }, { "code": null, "e": 352, "s": 51, "text": "Word Embedding: It is a language modeling technique used for mapping words to vectors of real numbers. It represents words or phrases in vector space with several dimensions. Word embeddings can be generated using various methods like neural networks, co-occurrence matrix, probabilistic models, etc." }, { "code": null, "e": 416, "s": 352, "text": "Word2Vec: It consists of models for generating word embedding. " }, { "code": null, "e": 727, "s": 416, "text": "Node2Vec: A node embedding algorithm that computes a vector representation of a node based on random walks in the graph. The neighborhood nodes of the graph is also sampled through deep random walks. This algorithm performs a biased random walk procedure in order to efficiently explore diverse neighborhoods. " }, { "code": null, "e": 839, "s": 727, "text": "It is based on a similar principle as Word2Vec but instead of word embeddings, we create node embeddings here. " }, { "code": null, "e": 851, "s": 839, "text": "Intuition: " }, { "code": null, "e": 1267, "s": 851, "text": "Node2Vec framework is based on the principle of learning continuous feature representation for nodes in the graph and preserving the knowledge gained from the neighboring 100 nodes. Lets us understand how the algorithm works. Say we have a graph having a few interconnected nodes creating a network. So, Node2Vec algorithm learns a dense representation (say 100 dimensions/features) of every node in the network. " }, { "code": null, "e": 1504, "s": 1267, "text": "The algorithm suggests that if we plot these 100 dimensions of each node in a 2 dimensional graph by applying PCA, the distance of the two nodes in that low-dimensional graph would be same as their actual distance in the given network. " }, { "code": null, "e": 1663, "s": 1504, "text": "In this way, the framework maximizes the likelihood of preserving neighboring nodes even if you represent them in a low-dimensional space. (As shown in Fig 1)" }, { "code": null, "e": 1680, "s": 1663, "text": "Fig1 : Intuition" }, { "code": null, "e": 1699, "s": 1680, "text": "Real-Life Example:" }, { "code": null, "e": 2041, "s": 1699, "text": "Let us take an example of textual data given to us to understand its working in detail. The Node2Vec framework suggests that random walks through the series of nodes in the graph can be treated as sentences. Each node in this graph is treated like a unique, individual word and each random walk through the network is treated as a sentence. " }, { "code": null, "e": 2273, "s": 2041, "text": "By creating and using a “continuous bag of words model” on which the Node2Vec framework learns, it can predict the next possible set of words by searching the neighbours of the given word. This is the power of Node2Vec algorithm. " }, { "code": null, "e": 2294, "s": 2273, "text": "Node2Vec Algorithm: " }, { "code": null, "e": 2551, "s": 2294, "text": "node2vecWalk (Graph G' = (V, E, π), Start node u, Length l):\n\n Initialize walk to [u]\n for (walk_iter = 1 to l):\n curr = walk[−1]\n Vcurr = GetNeighbors(curr, G')\n s = AliasSample(Vcurr, π)\n Append s to walk\n return walk" }, { "code": null, "e": 3011, "s": 2551, "text": "Learn_Features (Graph G = (V, E, W)):\n\n Dimensions -> d \n Walks per node -> r\n Walk length -> l \n Context size -> k \n Return -> p\n In-out -> q\n \n π = PreprocessModifiedWeights (G, p, q)\n G' = (V, E, π)\n \n Initialize walks = 0\n \n for (iter = 1 to r):\n for (all nodes u ∈ V):\n walk = node2vecWalk(G', u, l)\n Append walk to walks\n\n f = StochasticGradientDescent(k, d, walks)\n return f" }, { "code": null, "e": 3026, "s": 3011, "text": "Applications: " }, { "code": null, "e": 3626, "s": 3026, "text": "Social Media Network: Let’s consider each node in the network as a ‘USER’ and the neighboring nodes as the ‘FRIENDS’ of the that user. Each node has a set of features that involves their likes and dislikes. So, by using Node2Vec framework, we can identify which is the closest friend of the user easily.Recommendation System Network: The recommendation system gives two ‘USERS’ (nodes) the same recommendation of a product based on the similarity of their feature set. It this way, these recommendation systems give similar recommendations to a group of such similar nodes hence making it efficient." }, { "code": null, "e": 3930, "s": 3626, "text": "Social Media Network: Let’s consider each node in the network as a ‘USER’ and the neighboring nodes as the ‘FRIENDS’ of the that user. Each node has a set of features that involves their likes and dislikes. So, by using Node2Vec framework, we can identify which is the closest friend of the user easily." }, { "code": null, "e": 4227, "s": 3930, "text": "Recommendation System Network: The recommendation system gives two ‘USERS’ (nodes) the same recommendation of a product based on the similarity of their feature set. It this way, these recommendation systems give similar recommendations to a group of such similar nodes hence making it efficient." }, { "code": null, "e": 4236, "s": 4227, "text": "sooda367" }, { "code": null, "e": 4253, "s": 4236, "text": "Machine Learning" }, { "code": null, "e": 4270, "s": 4253, "text": "Machine Learning" }, { "code": null, "e": 4368, "s": 4270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4409, "s": 4368, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4442, "s": 4409, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4478, "s": 4442, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4502, "s": 4478, "text": "Markov Decision Process" }, { "code": null, "e": 4553, "s": 4502, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 4586, "s": 4553, "text": "Normalization vs Standardization" }, { "code": null, "e": 4626, "s": 4586, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 4667, "s": 4626, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 4695, "s": 4667, "text": "Types of Environments in AI" } ]
Select from table where value does not exist with MySQL?
For this, you can use NOT IN() − mysql> create table DemoTable1991 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) ); Query OK, 0 rows affected (0.61 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1991(StudentName) values('Chris'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable1991(StudentName) values('Bob'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1991(StudentName) values('David'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1991(StudentName) values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1991(StudentName) values('Mike'); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement − mysql> select * from DemoTable1991; This will produce the following output − +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | Bob | | 3 | David | | 4 | Sam | | 5 | Mike | +-----------+-------------+ 5 rows in set (0.03 sec) Here is the query to select * from table where value does not exist: mysql> select * from DemoTable1991 where StudentName NOT IN('Bob','Sam','Mike'); This will produce the following output − +-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 3 | David | +-----------+-------------+ 2 rows in set (0.04 sec)
[ { "code": null, "e": 1095, "s": 1062, "text": "For this, you can use NOT IN() −" }, { "code": null, "e": 1252, "s": 1095, "text": "mysql> create table DemoTable1991\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(20)\n);\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1308, "s": 1252, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1798, "s": 1308, "text": "mysql> insert into DemoTable1991(StudentName) values('Chris');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable1991(StudentName) values('Bob');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable1991(StudentName) values('David');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable1991(StudentName) values('Sam');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1991(StudentName) values('Mike');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1858, "s": 1798, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1894, "s": 1858, "text": "mysql> select * from DemoTable1991;" }, { "code": null, "e": 1935, "s": 1894, "text": "This will produce the following output −" }, { "code": null, "e": 2212, "s": 1935, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Chris |\n| 2 | Bob |\n| 3 | David |\n| 4 | Sam |\n| 5 | Mike |\n+-----------+-------------+\n5 rows in set (0.03 sec)" }, { "code": null, "e": 2281, "s": 2212, "text": "Here is the query to select * from table where value does not exist:" }, { "code": null, "e": 2365, "s": 2281, "text": "mysql> select * from DemoTable1991\n where StudentName NOT IN('Bob','Sam','Mike');" }, { "code": null, "e": 2406, "s": 2365, "text": "This will produce the following output −" }, { "code": null, "e": 2599, "s": 2406, "text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Chris |\n| 3 | David |\n+-----------+-------------+\n2 rows in set (0.04 sec)" } ]
Python Program to Swap Two Variables - GeeksforGeeks
08 Jul, 2021 Given two variables x and y, write a Python program to swap their values. Let’s see different methods in Python to do this task. Method 1: Using Naive approachThe most naive approach is to store the value of one variable(say x) in a temporary variable, then assigning the variable x with the value of variable y. Finally, assign the variable y with the value of the temporary variable. Python3 # Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# Using third variabletemp = xx = yy = temp print("Value of x:", x)print("Value of y:", y) Value of x: 50 Value of y: 10 Method 2: Using comma operatorUsing the comma operator the value of variables can be swapped without using a third variable. Python3 # Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# without using third variablex, y = y, x print("Value of x:", x)print("Value of y:", y) Value of x: 50 Value of y: 10 Method 3: Using XORThe bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010). Python3 # Python program to demonstrate# Swapping of two variables x = 10y = 50 # Swapping using xorx = x ^ yy = x ^ yx = x ^ y print("Value of x:", x)print("Value of y:", y) Value of x: 50 Value of y: 10 Method 4: Using arithmetic operators we can perform swapping in two ways. Using addition and subtraction operator : The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum. Python3 # Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# using arithmetic operationsx = x + y y = x - y x = x - y print("Value of x:", x)print("Value of y:", y) Value of x: 50 Value of y: 10 Using multiplication and division operator : The idea is to get multiplication of the two given numbers. The numbers can then be calculated by using the division. Python3 # Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two numbers# Using multiplication operator x = x * yy = x / yx = x / y print("Value of x : ", x)print("Value of y : ", y) Value of x : 50.0 Value of y : 10.0 Method 5: using Bitwise addition and subtraction for swapping. Python3 #Python program to demonstrate#swapping of two numbersa = 5b = 1a = (a & b) + (a | b)b = a + (~b) + 1a = a + (~b) + 1print("a after swapping: ", a)print("b after swapping: ", b) a after swapping: 1 b after swapping: 5 ASNR1010 singhbishalkumarsingh python-basics Swap-Program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24236, "s": 24208, "text": "\n08 Jul, 2021" }, { "code": null, "e": 24367, "s": 24236, "text": "Given two variables x and y, write a Python program to swap their values. Let’s see different methods in Python to do this task. " }, { "code": null, "e": 24625, "s": 24367, "text": "Method 1: Using Naive approachThe most naive approach is to store the value of one variable(say x) in a temporary variable, then assigning the variable x with the value of variable y. Finally, assign the variable y with the value of the temporary variable. " }, { "code": null, "e": 24633, "s": 24625, "text": "Python3" }, { "code": "# Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# Using third variabletemp = xx = yy = temp print(\"Value of x:\", x)print(\"Value of y:\", y)", "e": 24823, "s": 24633, "text": null }, { "code": null, "e": 24853, "s": 24823, "text": "Value of x: 50\nValue of y: 10" }, { "code": null, "e": 24979, "s": 24853, "text": "Method 2: Using comma operatorUsing the comma operator the value of variables can be swapped without using a third variable. " }, { "code": null, "e": 24987, "s": 24979, "text": "Python3" }, { "code": "# Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# without using third variablex, y = y, x print(\"Value of x:\", x)print(\"Value of y:\", y)", "e": 25176, "s": 24987, "text": null }, { "code": null, "e": 25206, "s": 25176, "text": "Value of x: 50\nValue of y: 10" }, { "code": null, "e": 25509, "s": 25206, "text": "Method 3: Using XORThe bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010). " }, { "code": null, "e": 25517, "s": 25509, "text": "Python3" }, { "code": "# Python program to demonstrate# Swapping of two variables x = 10y = 50 # Swapping using xorx = x ^ yy = x ^ yx = x ^ y print(\"Value of x:\", x)print(\"Value of y:\", y)", "e": 25684, "s": 25517, "text": null }, { "code": null, "e": 25714, "s": 25684, "text": "Value of x: 50\nValue of y: 10" }, { "code": null, "e": 25788, "s": 25714, "text": "Method 4: Using arithmetic operators we can perform swapping in two ways." }, { "code": null, "e": 25830, "s": 25788, "text": "Using addition and subtraction operator :" }, { "code": null, "e": 25959, "s": 25830, "text": "The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum. " }, { "code": null, "e": 25967, "s": 25959, "text": "Python3" }, { "code": "# Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two variables# using arithmetic operationsx = x + y y = x - y x = x - y print(\"Value of x:\", x)print(\"Value of y:\", y)", "e": 26173, "s": 25967, "text": null }, { "code": null, "e": 26203, "s": 26173, "text": "Value of x: 50\nValue of y: 10" }, { "code": null, "e": 26248, "s": 26203, "text": "Using multiplication and division operator :" }, { "code": null, "e": 26366, "s": 26248, "text": "The idea is to get multiplication of the two given numbers. The numbers can then be calculated by using the division." }, { "code": null, "e": 26374, "s": 26366, "text": "Python3" }, { "code": "# Python program to demonstrate# swapping of two variables x = 10y = 50 # Swapping of two numbers# Using multiplication operator x = x * yy = x / yx = x / y print(\"Value of x : \", x)print(\"Value of y : \", y)", "e": 26582, "s": 26374, "text": null }, { "code": null, "e": 26620, "s": 26582, "text": "Value of x : 50.0\nValue of y : 10.0" }, { "code": null, "e": 26683, "s": 26620, "text": "Method 5: using Bitwise addition and subtraction for swapping." }, { "code": null, "e": 26691, "s": 26683, "text": "Python3" }, { "code": "#Python program to demonstrate#swapping of two numbersa = 5b = 1a = (a & b) + (a | b)b = a + (~b) + 1a = a + (~b) + 1print(\"a after swapping: \", a)print(\"b after swapping: \", b)", "e": 26869, "s": 26691, "text": null }, { "code": null, "e": 26911, "s": 26869, "text": "a after swapping: 1\nb after swapping: 5" }, { "code": null, "e": 26920, "s": 26911, "text": "ASNR1010" }, { "code": null, "e": 26942, "s": 26920, "text": "singhbishalkumarsingh" }, { "code": null, "e": 26956, "s": 26942, "text": "python-basics" }, { "code": null, "e": 26969, "s": 26956, "text": "Swap-Program" }, { "code": null, "e": 26976, "s": 26969, "text": "Python" }, { "code": null, "e": 26992, "s": 26976, "text": "Python Programs" }, { "code": null, "e": 27090, "s": 26992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27099, "s": 27090, "text": "Comments" }, { "code": null, "e": 27112, "s": 27099, "text": "Old Comments" }, { "code": null, "e": 27133, "s": 27112, "text": "Python OOPs Concepts" }, { "code": null, "e": 27165, "s": 27133, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27188, "s": 27165, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27210, "s": 27188, "text": "Defaultdict in Python" }, { "code": null, "e": 27237, "s": 27210, "text": "Python Classes and Objects" }, { "code": null, "e": 27259, "s": 27237, "text": "Defaultdict in Python" }, { "code": null, "e": 27298, "s": 27259, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27344, "s": 27298, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27382, "s": 27344, "text": "Python | Convert a list to dictionary" } ]
Apex - Collections
Collections is a type of variable that can store multiple number of records. For example, List can store multiple number of Account object's records. Let us now have a detailed overview of all collection types. List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically to use with List. List index always starts with 0. This is synonymous to the array in Java. A list should be declared with the keyword 'List'. Example Below is the list which contains the List of a primitive data type (string), that is the list of cities. List<string> ListOfCities = new List<string>(); System.debug('Value Of ListOfCities'+ListOfCities); Declaring the initial values of list is optional. However, we will declare the initial values here. Following is an example which shows the same. List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'}; System.debug('Value ListOfStates'+ListOfStates); List<account> AccountToDelete = new List<account> (); //This will be null System.debug('Value AccountToDelete'+AccountToDelete); We can declare the nested List as well. It can go up to five levels. This is called the Multidimensional list. This is the list of set of integers. List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>(); System.debug('value myNestedList'+myNestedList); List can contain any number of records, but there is a limitation on heap size to prevent the performance issue and monopolizing the resources. There are methods available for Lists which we can be utilized while programming to achieve some functionalities like calculating the size of List, adding an element, etc. Following are some most frequently used methods − size() add() get() clear() set() The following example demonstrates the use of all these methods // Initialize the List List<string> ListOfStatesMethod = new List<string>(); // This statement would give null as output in Debug logs System.debug('Value of List'+ ListOfStatesMethod); // Add element to the list using add method ListOfStatesMethod.add('New York'); ListOfStatesMethod.add('Ohio'); // This statement would give New York and Ohio as output in Debug logs System.debug('Value of List with new States'+ ListOfStatesMethod); // Get the element at the index 0 String StateAtFirstPosition = ListOfStatesMethod.get(0); // This statement would give New York as output in Debug log System.debug('Value of List at First Position'+ StateAtFirstPosition); // set the element at 1 position ListOfStatesMethod.set(0, 'LA'); // This statement would give output in Debug log System.debug('Value of List with element set at First Position' + ListOfStatesMethod[0]); // Remove all the elements in List ListOfStatesMethod.clear(); // This statement would give output in Debug log System.debug('Value of List'+ ListOfStatesMethod); You can use the array notation as well to declare the List, as given below, but this is not general practice in Apex programming − String [] ListOfStates = new List<string>(); A Set is a collection type which contains multiple number of unordered unique records. A Set cannot have duplicate records. Like Lists, Sets can be nested. Example We will be defining the set of products which company is selling. Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'}; System.debug('Value of ProductSet'+ProductSet); Set does support methods which we can utilize while programming as shown below (we are extending the above example) − // Adds an element to the set // Define set if not defined previously Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'}; ProductSet.add('HCL'); System.debug('Set with New Value '+ProductSet); // Removes an element from set ProductSet.remove('HCL'); System.debug('Set with removed value '+ProductSet); // Check whether set contains the particular element or not and returns true or false ProductSet.contains('HCL'); System.debug('Value of Set with all values '+ProductSet); It is a key value pair which contains the unique key for each value. Both key and value can be of any data type. Example The following example represents the map of the Product Name with the Product code. // Initialize the Map Map<string, string> ProductCodeToProductName = new Map<string, string> {'1000'=>'HCL', '1001'=>'H2SO4'}; // This statement would give as output as key value pair in Debug log System.debug('value of ProductCodeToProductName'+ProductCodeToProductName); Following are a few examples which demonstrate the methods that can be used with Map − // Define a new map Map<string, string> ProductCodeToProductName = new Map<string, string>(); // Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value ProductCodeToProductName.put('1002', 'Acetone'); // Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value ProductCodeToProductName.put('1003', 'Ketone'); // Assert that the map contains a specified key and respective value System.assert(ProductCodeToProductName.containsKey('1002')); System.debug('If output is true then Map contains the key and output is:' + ProductCodeToProductName.containsKey('1002')); // Retrieves a value, given a particular key String value = ProductCodeToProductName.get('1002'); System.debug('Value at the Specified key using get function: '+value); // Return a set that contains all of the keys in the map Set SetOfKeys = ProductCodeToProductName.keySet(); System.debug('Value of Set with Keys '+SetOfKeys); Map values may be unordered and hence we should not rely on the order in which the values are stored and try to access the map always using keys. Map value can be null. Map keys when declared String are case-sensitive; for example, ABC and abc will be considered as different keys and treated as unique. 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2263, "s": 2052, "text": "Collections is a type of variable that can store multiple number of records. For example, List can store multiple number of Account object's records. Let us now have a detailed overview of all collection types." }, { "code": null, "e": 2647, "s": 2263, "text": "List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically to use with List. List index always starts with 0. This is synonymous to the array in Java. A list should be declared with the keyword 'List'." }, { "code": null, "e": 2655, "s": 2647, "text": "Example" }, { "code": null, "e": 2760, "s": 2655, "text": "Below is the list which contains the List of a primitive data type (string), that is the list of cities." }, { "code": null, "e": 2860, "s": 2760, "text": "List<string> ListOfCities = new List<string>();\nSystem.debug('Value Of ListOfCities'+ListOfCities);" }, { "code": null, "e": 3006, "s": 2860, "text": "Declaring the initial values of list is optional. However, we will declare the initial values here. Following is an example which shows the same." }, { "code": null, "e": 3120, "s": 3006, "text": "List<string> ListOfStates = new List<string> {'NY', 'LA', 'LV'};\nSystem.debug('Value ListOfStates'+ListOfStates);" }, { "code": null, "e": 3249, "s": 3120, "text": "List<account> AccountToDelete = new List<account> (); //This will be null\nSystem.debug('Value AccountToDelete'+AccountToDelete);" }, { "code": null, "e": 3360, "s": 3249, "text": "We can declare the nested List as well. It can go up to five levels. This is called the\nMultidimensional list." }, { "code": null, "e": 3397, "s": 3360, "text": "This is the list of set of integers." }, { "code": null, "e": 3518, "s": 3397, "text": "List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>();\nSystem.debug('value myNestedList'+myNestedList);" }, { "code": null, "e": 3662, "s": 3518, "text": "List can contain any number of records, but there is a limitation on heap size to prevent the performance issue and monopolizing the resources." }, { "code": null, "e": 3834, "s": 3662, "text": "There are methods available for Lists which we can be utilized while programming to achieve some functionalities like calculating the size of List, adding an element, etc." }, { "code": null, "e": 3884, "s": 3834, "text": "Following are some most frequently used methods −" }, { "code": null, "e": 3891, "s": 3884, "text": "size()" }, { "code": null, "e": 3897, "s": 3891, "text": "add()" }, { "code": null, "e": 3903, "s": 3897, "text": "get()" }, { "code": null, "e": 3911, "s": 3903, "text": "clear()" }, { "code": null, "e": 3917, "s": 3911, "text": "set()" }, { "code": null, "e": 3981, "s": 3917, "text": "The following example demonstrates the use of all these methods" }, { "code": null, "e": 5017, "s": 3981, "text": "// Initialize the List\nList<string> ListOfStatesMethod = new List<string>();\n\n// This statement would give null as output in Debug logs\nSystem.debug('Value of List'+ ListOfStatesMethod);\n\n// Add element to the list using add method\nListOfStatesMethod.add('New York');\nListOfStatesMethod.add('Ohio');\n\n// This statement would give New York and Ohio as output in Debug logs\nSystem.debug('Value of List with new States'+ ListOfStatesMethod);\n\n// Get the element at the index 0\nString StateAtFirstPosition = ListOfStatesMethod.get(0);\n\n// This statement would give New York as output in Debug log\nSystem.debug('Value of List at First Position'+ StateAtFirstPosition);\n\n// set the element at 1 position\nListOfStatesMethod.set(0, 'LA');\n\n// This statement would give output in Debug log\nSystem.debug('Value of List with element set at First Position' + ListOfStatesMethod[0]);\n\n// Remove all the elements in List\nListOfStatesMethod.clear();\n\n// This statement would give output in Debug log\nSystem.debug('Value of List'+ ListOfStatesMethod);" }, { "code": null, "e": 5148, "s": 5017, "text": "You can use the array notation as well to declare the List, as given below, but this is not general practice in Apex programming −" }, { "code": null, "e": 5194, "s": 5148, "text": "String [] ListOfStates = new List<string>();\n" }, { "code": null, "e": 5350, "s": 5194, "text": "A Set is a collection type which contains multiple number of unordered unique records. A Set cannot have duplicate records. Like Lists, Sets can be nested." }, { "code": null, "e": 5358, "s": 5350, "text": "Example" }, { "code": null, "e": 5424, "s": 5358, "text": "We will be defining the set of products which company is selling." }, { "code": null, "e": 5545, "s": 5424, "text": "Set<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};\nSystem.debug('Value of ProductSet'+ProductSet);\n" }, { "code": null, "e": 5663, "s": 5545, "text": "Set does support methods which we can utilize while programming as shown below (we are extending the above example) −" }, { "code": null, "e": 6159, "s": 5663, "text": "// Adds an element to the set\n// Define set if not defined previously\nSet<string> ProductSet = new Set<string>{'Phenol', 'Benzene', 'H2SO4'};\nProductSet.add('HCL');\nSystem.debug('Set with New Value '+ProductSet);\n\n// Removes an element from set\nProductSet.remove('HCL');\nSystem.debug('Set with removed value '+ProductSet);\n\n// Check whether set contains the particular element or not and returns true or false\nProductSet.contains('HCL');\nSystem.debug('Value of Set with all values '+ProductSet);" }, { "code": null, "e": 6272, "s": 6159, "text": "It is a key value pair which contains the unique key for each value. Both key and value can be of any data type." }, { "code": null, "e": 6280, "s": 6272, "text": "Example" }, { "code": null, "e": 6364, "s": 6280, "text": "The following example represents the map of the Product Name with the Product code." }, { "code": null, "e": 6638, "s": 6364, "text": "// Initialize the Map\nMap<string, string> ProductCodeToProductName = new Map<string, string>\n{'1000'=>'HCL', '1001'=>'H2SO4'};\n\n// This statement would give as output as key value pair in Debug log\nSystem.debug('value of ProductCodeToProductName'+ProductCodeToProductName);" }, { "code": null, "e": 6725, "s": 6638, "text": "Following are a few examples which demonstrate the methods that can be used with Map −" }, { "code": null, "e": 7674, "s": 6725, "text": "// Define a new map\nMap<string, string> ProductCodeToProductName = new Map<string, string>();\n\n// Insert a new key-value pair in the map where '1002' is key and 'Acetone' is value\nProductCodeToProductName.put('1002', 'Acetone');\n\n// Insert a new key-value pair in the map where '1003' is key and 'Ketone' is value\nProductCodeToProductName.put('1003', 'Ketone');\n\n// Assert that the map contains a specified key and respective value\nSystem.assert(ProductCodeToProductName.containsKey('1002'));\nSystem.debug('If output is true then Map contains the key and output is:'\n + ProductCodeToProductName.containsKey('1002'));\n\n// Retrieves a value, given a particular key\nString value = ProductCodeToProductName.get('1002');\nSystem.debug('Value at the Specified key using get function: '+value);\n\n// Return a set that contains all of the keys in the map\nSet SetOfKeys = ProductCodeToProductName.keySet();\nSystem.debug('Value of Set with Keys '+SetOfKeys);" }, { "code": null, "e": 7978, "s": 7674, "text": "Map values may be unordered and hence we should not rely on the order in which the values are stored and try to access the map always using keys. Map value can be null. Map keys when declared String are case-sensitive; for example, ABC and abc will be considered as different keys and treated as unique." }, { "code": null, "e": 8011, "s": 7978, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 8024, "s": 8011, "text": " Vijay Thapa" }, { "code": null, "e": 8056, "s": 8024, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 8064, "s": 8056, "text": " Uplatz" }, { "code": null, "e": 8097, "s": 8064, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 8122, "s": 8097, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 8155, "s": 8122, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 8170, "s": 8155, "text": " Ali Saleh Ali" }, { "code": null, "e": 8203, "s": 8170, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 8216, "s": 8203, "text": " Soham Ghosh" }, { "code": null, "e": 8251, "s": 8216, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8263, "s": 8251, "text": " GUHARAJANM" }, { "code": null, "e": 8270, "s": 8263, "text": " Print" }, { "code": null, "e": 8281, "s": 8270, "text": " Add Notes" } ]
Java String isEmpty() Method
❮ String Methods Find out if a string is empty or not: String myStr1 = "Hello"; String myStr2 = ""; System.out.println(myStr1.isEmpty()); System.out.println(myStr2.isEmpty()); Try it Yourself » The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not. public boolean isEmpty() None. true - The string is empty (length() is 0) false - The string is not empty We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 57, "s": 19, "text": "Find out if a string is empty or not:" }, { "code": null, "e": 178, "s": 57, "text": "String myStr1 = \"Hello\";\nString myStr2 = \"\";\nSystem.out.println(myStr1.isEmpty());\nSystem.out.println(myStr2.isEmpty());" }, { "code": null, "e": 198, "s": 178, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 261, "s": 198, "text": "The isEmpty() method checks whether a string \nis empty or not." }, { "code": null, "e": 344, "s": 261, "text": "This method returns true if the string is empty (length() is 0), and false if not." }, { "code": null, "e": 370, "s": 344, "text": "public boolean isEmpty()\n" }, { "code": null, "e": 376, "s": 370, "text": "None." }, { "code": null, "e": 419, "s": 376, "text": "true - The string is empty (length() is 0)" }, { "code": null, "e": 452, "s": 419, "text": "false - The string is not empty " }, { "code": null, "e": 485, "s": 452, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 527, "s": 485, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 634, "s": 527, "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": 653, "s": 634, "text": "[email protected]" } ]
Streaming Twitter Data into a MySQL Database | by Daniel Foley | Towards Data Science
Given the frequency that I have seen database languages listed as a requirement for data science jobs, I thought it would be a good idea to do a post on MySQL today. In particular, I wanted to look at how we can use python and an API to stream data directly into a MySQL database. I did this recently for a personal project and thought I would share my code and provide an introductory tutorial for those who may not be familiar with these tools. We are going to be using the Twitter API to search for tweets containing specific keywords and stream this directly into our database. Once we have done this, the data will be available for further analysis at any time. This task requires a few things: A Twitter account and API credentialsA MySQL databaseThe Tweepy and mysql-connector Python Libraries A Twitter account and API credentials A MySQL database The Tweepy and mysql-connector Python Libraries Before we access the API you need to set up a twitter app. I won’t do an in-depth tutorial on this but briefly, you need to do the following: go to the following website https://developer.twitter.com/ and create an account. (This step is a bit more involved then it used to be and involves providing a brief summary of what you intend to do with the tweets and what they will be used for. I believe it has something to do with new EU privacy laws.) Once you have verified your email you can log into your account. You should be able to create a new app on the following webpage: https://developer.twitter.com/en/apps Fill in all the details about your app and then create your access token. Make a note of your consumer key, consumer secret, OAuth access token and OAuth access token secret. These are needed to connect to the API. For a more complete tutorial on this, I suggest this blog post. After these steps, our app is now able to connect to the Twitter streaming API provided we write the correct code. Next up, I will go through setting up the MySQL database so we have somewhere to store all of our data. There are many different types of databases we could use for this particular task including NoSQL databases such as MongoDB or Redis. I have, however, chosen to use MySQL as I am more familiar with it and it is still one of the most popular databases out there. Before we begin, we will need to install MySQL Workbench and MySQL server. Here is a video tutorial explaining how to install both and set everything up to start collecting the data. Once you have finished the tutorial above, you should have a connection and a schema/database set up (My database is imaginatively called twitterdb). After we have set up MySQL workbench and are somewhat familiar with the interface, we can finally create a table to store our twitter data. Creating a table is very straightforward and we can use the UI or even use queries. Using the UI we just right click on our database and click create a table. We can then input our column names and data types directly. At this point, it is worth thinking about the data we want to store and what kind of data types they will be. To get a better understanding of the data types we need we should take a peek at the TwitterAPI documentation. Essentially I want the username of the person who wrote the tweet, the time it was created, the tweet, the retweet count, the place the tweet originated and the location (more on these below). This corresponds to 6 columns plus the primary key and we can define the datatypes as follows: primary key: INT(11) username: VARCHAR(255) created_at: VARCHAR(45) tweet: TEXT retweet_count: INT(11) location: VARCHAR(100) place: VARCHAR(100) OK now that we have our database set up, its’ time to jump into the Python code. There are a few things we want our code to do: We want to create a class that allows us to connect to the Twitter API.We also need to create some code that connects to our database and reads the data into the correct columns. We want to create a class that allows us to connect to the Twitter API. We also need to create some code that connects to our database and reads the data into the correct columns. We are going to be using the Tweepy library which will make it very easy for us to connect to the API and start streaming the data. Before we start, we are again going to look at some delicious documentation. In the Tweepy documentation, we can find some really useful examples of the classes and methods we need to use to interact with the API. The code below is a simple example that allows us to connect to the API and print tweets from our timeline: import tweepyauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)public_tweets = api.home_timeline()for tweet in public_tweets: print(tweet.text) Alright, so hopefully this is pretty straightforward. It looks like we just need to set our credentials, access the timeline and loop through it to print it out. What we want to do is a bit different. We want to stream live tweets into our database and according to the documentation, need to do the following three things: Create a class inheriting from StreamListener.Instantiate an object from this class.Use this object to connect to the API. Create a class inheriting from StreamListener. Instantiate an object from this class. Use this object to connect to the API. This seems straightforward enough. Lets see how we do this in Python (Full code at end of post). We need to import some libraries and also to set our tokens and secret keys and our password for the database. I have saved all of these in the setting.sh file which gets called using the code below and sets the tokens and keys as environment variables. subprocess.call(“./settings.sh”, shell=True) Note that in our imports, we need mysql-connector. Again, here is some useful examples of how the library works. We can install any libraries that we don’t have using the pip command in the terminal (I am on Mac) like below. We should then be able to import these libraries from our script. pip install mysql-connectorpip install tweepy Next up, we need to set up our class inheriting from StreamListener. We are going to give the class three methods. These are methods that the class already implements which we are going to override. The code below implements this. Let’s go through this step by step to make sure everything is clear. The first method, on_connect() simply notifies us when we are connected to the stream. The on_error() method prints an error whenever our HTTP status code is not 200 (200 means everything worked). List of codes for those interested: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes OK, the next method, on_data() is a little more complex. To understand this we will need to know a little bit more about the structure of the tweets. When we access the API we are getting a JSON response (very similar structure to a python dictionary). More info here. Essentially our tweet object that is returned looks something like this: { “created_at”:”Thu Apr 06 15:24:15 +0000 2017", “id”: 850006245121695744, “id_str”: “850006245121695744”, “text”: “1/ Today we’re sharing our vision for the future of the Twitter API platform!nhttps://t.co/XweGngmxlP", “user”: {}, “entities”: {} } So we have a JSON object which contains key, value pairs (note there are a few attributes not listed here that we will use). So what data do we actually want from this? There is actually quite a lot of information available from the tweet object and I recommend going through the documentation to see what attributes might interest you. For this analysis I chose to collect data on the username, the time the tweet was created (this is more useful if we collect tweets over time), the actual tweet, the country of the tweet, the location (which is more local) and finally the retweet count and this is reflected in the code above. The final few lines call the connect() method which takes our variables as parameters. This code is all wrapped in a try, except statement to catch any errors, we may run into. Alright, you may have noticed that we haven’t created the connect() method yet so let’s create it. This method is not surprisingly, going to connect to our database and feed in all the data. As I said before, the method takes in our variables created in the on_data() method of the StreamListener class as arguments and inserts them into the columns of the same name in our database. To connect to our database we simply use the connector.connect method and pass in our database info which we can find from MySQL workbench. If our connection was successful, a cursor object is created allowing us to execute SQL statements. Now we can write our query and insert the data into the correct table in our twitterdb database using the execute command. While is_connected() is true our database connection stays open and continually feeds the data into the database until we kill it in the terminal (using Ctrl+C). We can create a list of words that we want to filter the stream for. I am a bit of a golf fan so I decided to search for words relating to golf. In practice, you can put whatever you want in this list. Now we just need to set up our script to call these functions when we execute the file from the terminal. To access the API we need to pass our credentials as arguments to the OAuthHandler method and the set_access_token method. Next, we create the stream by passing in our verified api object and our listener. We can also create our list of words to filter for here. To start the stream we simply call the filter method on our stream object and pass in our list of words as an argument. I saved this script as StreamSQL.py. If we want to run this code and start collecting tweets we can use the terminal. One important thing to note here is that we need to make sure our SQL server is up and running for the script to work so it is worth double checking this before we run the script. We can open a terminal directly from the folder where we stored the script and simply type: python StreamSQL.py Hopefully, this has shown that it is not that complicated to set up a data pipeline with MySQL especially when taking advantage of the powerful libraries Python has to offer. SQL is a really important aspect of doing data science and this is pretty obvious if you have ever looked at the requirements of a data scientist in job advertisements. Although this didn’t really involve any deep understanding of SQL or writing complex queries I think it is still a really useful to be able to understand do this kind of task. For those interested in learning more about SQL, I took the following free course which I found excellent for practicing some of the key concepts and understanding some of the more advanced functionality. I recommend this to anyone interested in improving their SQL skills. In a future post, I will focus on extracting the raw data we collected, clean it and perform some simple analysis which will illustrate some of the interesting things we can do with this type of data. Until next time!! Link to Part 2: https://towardsdatascience.com/building-an-etl-pipeline-in-python-f96845089635
[ { "code": null, "e": 618, "s": 171, "text": "Given the frequency that I have seen database languages listed as a requirement for data science jobs, I thought it would be a good idea to do a post on MySQL today. In particular, I wanted to look at how we can use python and an API to stream data directly into a MySQL database. I did this recently for a personal project and thought I would share my code and provide an introductory tutorial for those who may not be familiar with these tools." }, { "code": null, "e": 871, "s": 618, "text": "We are going to be using the Twitter API to search for tweets containing specific keywords and stream this directly into our database. Once we have done this, the data will be available for further analysis at any time. This task requires a few things:" }, { "code": null, "e": 972, "s": 871, "text": "A Twitter account and API credentialsA MySQL databaseThe Tweepy and mysql-connector Python Libraries" }, { "code": null, "e": 1010, "s": 972, "text": "A Twitter account and API credentials" }, { "code": null, "e": 1027, "s": 1010, "text": "A MySQL database" }, { "code": null, "e": 1075, "s": 1027, "text": "The Tweepy and mysql-connector Python Libraries" }, { "code": null, "e": 1217, "s": 1075, "text": "Before we access the API you need to set up a twitter app. I won’t do an in-depth tutorial on this but briefly, you need to do the following:" }, { "code": null, "e": 1524, "s": 1217, "text": "go to the following website https://developer.twitter.com/ and create an account. (This step is a bit more involved then it used to be and involves providing a brief summary of what you intend to do with the tweets and what they will be used for. I believe it has something to do with new EU privacy laws.)" }, { "code": null, "e": 1692, "s": 1524, "text": "Once you have verified your email you can log into your account. You should be able to create a new app on the following webpage: https://developer.twitter.com/en/apps" }, { "code": null, "e": 1766, "s": 1692, "text": "Fill in all the details about your app and then create your access token." }, { "code": null, "e": 1907, "s": 1766, "text": "Make a note of your consumer key, consumer secret, OAuth access token and OAuth access token secret. These are needed to connect to the API." }, { "code": null, "e": 2190, "s": 1907, "text": "For a more complete tutorial on this, I suggest this blog post. After these steps, our app is now able to connect to the Twitter streaming API provided we write the correct code. Next up, I will go through setting up the MySQL database so we have somewhere to store all of our data." }, { "code": null, "e": 2635, "s": 2190, "text": "There are many different types of databases we could use for this particular task including NoSQL databases such as MongoDB or Redis. I have, however, chosen to use MySQL as I am more familiar with it and it is still one of the most popular databases out there. Before we begin, we will need to install MySQL Workbench and MySQL server. Here is a video tutorial explaining how to install both and set everything up to start collecting the data." }, { "code": null, "e": 3653, "s": 2635, "text": "Once you have finished the tutorial above, you should have a connection and a schema/database set up (My database is imaginatively called twitterdb). After we have set up MySQL workbench and are somewhat familiar with the interface, we can finally create a table to store our twitter data. Creating a table is very straightforward and we can use the UI or even use queries. Using the UI we just right click on our database and click create a table. We can then input our column names and data types directly. At this point, it is worth thinking about the data we want to store and what kind of data types they will be. To get a better understanding of the data types we need we should take a peek at the TwitterAPI documentation. Essentially I want the username of the person who wrote the tweet, the time it was created, the tweet, the retweet count, the place the tweet originated and the location (more on these below). This corresponds to 6 columns plus the primary key and we can define the datatypes as follows:" }, { "code": null, "e": 3674, "s": 3653, "text": "primary key: INT(11)" }, { "code": null, "e": 3697, "s": 3674, "text": "username: VARCHAR(255)" }, { "code": null, "e": 3721, "s": 3697, "text": "created_at: VARCHAR(45)" }, { "code": null, "e": 3733, "s": 3721, "text": "tweet: TEXT" }, { "code": null, "e": 3756, "s": 3733, "text": "retweet_count: INT(11)" }, { "code": null, "e": 3779, "s": 3756, "text": "location: VARCHAR(100)" }, { "code": null, "e": 3799, "s": 3779, "text": "place: VARCHAR(100)" }, { "code": null, "e": 3927, "s": 3799, "text": "OK now that we have our database set up, its’ time to jump into the Python code. There are a few things we want our code to do:" }, { "code": null, "e": 4106, "s": 3927, "text": "We want to create a class that allows us to connect to the Twitter API.We also need to create some code that connects to our database and reads the data into the correct columns." }, { "code": null, "e": 4178, "s": 4106, "text": "We want to create a class that allows us to connect to the Twitter API." }, { "code": null, "e": 4286, "s": 4178, "text": "We also need to create some code that connects to our database and reads the data into the correct columns." }, { "code": null, "e": 4740, "s": 4286, "text": "We are going to be using the Tweepy library which will make it very easy for us to connect to the API and start streaming the data. Before we start, we are again going to look at some delicious documentation. In the Tweepy documentation, we can find some really useful examples of the classes and methods we need to use to interact with the API. The code below is a simple example that allows us to connect to the API and print tweets from our timeline:" }, { "code": null, "e": 4972, "s": 4740, "text": "import tweepyauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)public_tweets = api.home_timeline()for tweet in public_tweets: print(tweet.text)" }, { "code": null, "e": 5296, "s": 4972, "text": "Alright, so hopefully this is pretty straightforward. It looks like we just need to set our credentials, access the timeline and loop through it to print it out. What we want to do is a bit different. We want to stream live tweets into our database and according to the documentation, need to do the following three things:" }, { "code": null, "e": 5419, "s": 5296, "text": "Create a class inheriting from StreamListener.Instantiate an object from this class.Use this object to connect to the API." }, { "code": null, "e": 5466, "s": 5419, "text": "Create a class inheriting from StreamListener." }, { "code": null, "e": 5505, "s": 5466, "text": "Instantiate an object from this class." }, { "code": null, "e": 5544, "s": 5505, "text": "Use this object to connect to the API." }, { "code": null, "e": 5895, "s": 5544, "text": "This seems straightforward enough. Lets see how we do this in Python (Full code at end of post). We need to import some libraries and also to set our tokens and secret keys and our password for the database. I have saved all of these in the setting.sh file which gets called using the code below and sets the tokens and keys as environment variables." }, { "code": null, "e": 5940, "s": 5895, "text": "subprocess.call(“./settings.sh”, shell=True)" }, { "code": null, "e": 6231, "s": 5940, "text": "Note that in our imports, we need mysql-connector. Again, here is some useful examples of how the library works. We can install any libraries that we don’t have using the pip command in the terminal (I am on Mac) like below. We should then be able to import these libraries from our script." }, { "code": null, "e": 6277, "s": 6231, "text": "pip install mysql-connectorpip install tweepy" }, { "code": null, "e": 6508, "s": 6277, "text": "Next up, we need to set up our class inheriting from StreamListener. We are going to give the class three methods. These are methods that the class already implements which we are going to override. The code below implements this." }, { "code": null, "e": 6866, "s": 6508, "text": "Let’s go through this step by step to make sure everything is clear. The first method, on_connect() simply notifies us when we are connected to the stream. The on_error() method prints an error whenever our HTTP status code is not 200 (200 means everything worked). List of codes for those interested: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" }, { "code": null, "e": 7135, "s": 6866, "text": "OK, the next method, on_data() is a little more complex. To understand this we will need to know a little bit more about the structure of the tweets. When we access the API we are getting a JSON response (very similar structure to a python dictionary). More info here." }, { "code": null, "e": 7208, "s": 7135, "text": "Essentially our tweet object that is returned looks something like this:" }, { "code": null, "e": 7470, "s": 7208, "text": "{ “created_at”:”Thu Apr 06 15:24:15 +0000 2017\", “id”: 850006245121695744, “id_str”: “850006245121695744”, “text”: “1/ Today we’re sharing our vision for the future of the Twitter API platform!nhttps://t.co/XweGngmxlP\", “user”: {}, “entities”: {} }" }, { "code": null, "e": 8101, "s": 7470, "text": "So we have a JSON object which contains key, value pairs (note there are a few attributes not listed here that we will use). So what data do we actually want from this? There is actually quite a lot of information available from the tweet object and I recommend going through the documentation to see what attributes might interest you. For this analysis I chose to collect data on the username, the time the tweet was created (this is more useful if we collect tweets over time), the actual tweet, the country of the tweet, the location (which is more local) and finally the retweet count and this is reflected in the code above." }, { "code": null, "e": 8278, "s": 8101, "text": "The final few lines call the connect() method which takes our variables as parameters. This code is all wrapped in a try, except statement to catch any errors, we may run into." }, { "code": null, "e": 9187, "s": 8278, "text": "Alright, you may have noticed that we haven’t created the connect() method yet so let’s create it. This method is not surprisingly, going to connect to our database and feed in all the data. As I said before, the method takes in our variables created in the on_data() method of the StreamListener class as arguments and inserts them into the columns of the same name in our database. To connect to our database we simply use the connector.connect method and pass in our database info which we can find from MySQL workbench. If our connection was successful, a cursor object is created allowing us to execute SQL statements. Now we can write our query and insert the data into the correct table in our twitterdb database using the execute command. While is_connected() is true our database connection stays open and continually feeds the data into the database until we kill it in the terminal (using Ctrl+C)." }, { "code": null, "e": 9389, "s": 9187, "text": "We can create a list of words that we want to filter the stream for. I am a bit of a golf fan so I decided to search for words relating to golf. In practice, you can put whatever you want in this list." }, { "code": null, "e": 9915, "s": 9389, "text": "Now we just need to set up our script to call these functions when we execute the file from the terminal. To access the API we need to pass our credentials as arguments to the OAuthHandler method and the set_access_token method. Next, we create the stream by passing in our verified api object and our listener. We can also create our list of words to filter for here. To start the stream we simply call the filter method on our stream object and pass in our list of words as an argument. I saved this script as StreamSQL.py." }, { "code": null, "e": 10176, "s": 9915, "text": "If we want to run this code and start collecting tweets we can use the terminal. One important thing to note here is that we need to make sure our SQL server is up and running for the script to work so it is worth double checking this before we run the script." }, { "code": null, "e": 10268, "s": 10176, "text": "We can open a terminal directly from the folder where we stored the script and simply type:" }, { "code": null, "e": 10288, "s": 10268, "text": "python StreamSQL.py" }, { "code": null, "e": 10808, "s": 10288, "text": "Hopefully, this has shown that it is not that complicated to set up a data pipeline with MySQL especially when taking advantage of the powerful libraries Python has to offer. SQL is a really important aspect of doing data science and this is pretty obvious if you have ever looked at the requirements of a data scientist in job advertisements. Although this didn’t really involve any deep understanding of SQL or writing complex queries I think it is still a really useful to be able to understand do this kind of task." }, { "code": null, "e": 11283, "s": 10808, "text": "For those interested in learning more about SQL, I took the following free course which I found excellent for practicing some of the key concepts and understanding some of the more advanced functionality. I recommend this to anyone interested in improving their SQL skills. In a future post, I will focus on extracting the raw data we collected, clean it and perform some simple analysis which will illustrate some of the interesting things we can do with this type of data." }, { "code": null, "e": 11301, "s": 11283, "text": "Until next time!!" } ]
FuzzyWuzzy: Find Similar Strings within one column in Python | Towards Data Science
There are different ways to make data dirty, and inconsistent data entry is one of them. Inconsistent values are even worse than duplicates, and sometimes difficult to detect. This article presents how I apply FuzzyWuzzy package to find similar ramen brand names in a ramen review dataset (full Jupyter Notebook can be found on my GitHub). You may also find functions to shorten your codes here. import pandas as pdimport numpy as npfrom fuzzywuzzy import process, fuzzramen = pd.read_excel('The-Ramen-Rater-The-Big-List-1-3400-Current- As-Of-Jan-25-2020.xlsx')ramen.head() ramen.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3400 entries, 0 to 3399Data columns (total 6 columns):Review # 3400 non-null int64Brand 3400 non-null objectVariety 3400 non-null objectStyle 3400 non-null objectCountry 3400 non-null objectStars 3400 non-null objectdtypes: int64(1), object(5)memory usage: 159.5+ KB This dataset is very simple and easy to understand. Before moving to FuzzyWuzzy, I would like to check some more information. First of all, I remove leading and trailing spaces (if available) in every column, and then print out their number of unique values. for col in ramen[['Brand','Variety','Style','Country']]: ramen[col] = ramen[col].str.strip() print('Number of unique values in ' + str(col) +': ' + str(ramen[col].nunique()))Number of unique values in Brand: 499Number of unique values in Variety: 3170Number of unique values in Style: 8Number of unique values in Country: 48 By sorting unique brand names, we can see if there are similar ones. The result only shows the first 20 brands. unique_brand = ramen['Brand'].unique().tolist()sorted(unique_brand)[:20]['1 To 3 Noodles', '7 Select', '7 Select/Nissin', '7-Eleven / Nissin', 'A-One', 'A-Sha', 'A-Sha Dry Noodle', 'A1', 'ABC', 'Acecook', 'Adabi', 'Ah Lai', 'Aji-no-men', 'Ajinatori', 'Ajinomoto', 'Alhami', 'Amianda', 'Amino', "Annie Chun's", 'Aroi'] We can see some suspicious names right at the beginning. Next, let’s have some tests with FuzzyWuzzy. FuzzyWuzzy has four scorer options to find the Levenshtein distance between two strings. In this example, I would check on the token sort ratio and the token set ratio since I believe they are more suitable for this dataset which might have mixed words order and duplicated words. I pick four brand names and find their similar names in the Brand column. Since we’re matching the Brand column with itself, the result will always include the selected name with a score of 100. The token sort ratio scorer tokenizes the strings and cleans them by returning these strings to lower cases, removing punctuations, and then sorting them alphabetically. After that, it finds the Levenshtein distance and returns the similarity percentage. process.extract('7 Select', unique_brand, scorer=fuzz.token_sort_ratio)[('7 Select', 100), ('7 Select/Nissin', 70), ('Jinbo Selection', 61), ('Seven & I', 53), ('Lele', 50)] This result means that 7 Select/Nissin has 70% similarity when referring to 7 Select. Not bad if I set the threshold at 70% to get the pair of 7 Select — 7 Select/Nissin. process.extract('A-Sha', unique_brand, scorer=fuzz.token_sort_ratio)[('A-Sha', 100), ('Shan', 67), ('Nasoya', 55), ('Alhami', 55), ('Ah Lai', 55)] Below 70%, there’s no match for A-sha. process.extract('Acecook', unique_brand, scorer=fuzz.token_sort_ratio)[('Acecook', 100), ('Vina Acecook', 74), ('Yatekomo', 53), ('Sahmyook', 53), ('Panco', 50)] Still good at 70% threshold. process.extract("Chef Nic's Noodles", unique_brand, scorer=fuzz.token_sort_ratio)[("Chef Nic's Noodles", 100), ("Mr. Lee's Noodles", 71), ('Fantastic Noodles', 69), ('1 To 3 Noodles', 62), ("Mom's Dry Noodle", 59)] Now, we have a problem here. Token sort ratio scorer will get the wrong pair of Chef Nic’s Noodles — Mr. Lee’s Noodles if I set 70% threshold. process.extract('Chorip Dong', unique_brand, scorer=fuzz.token_sort_ratio)[('Chorip Dong', 100), ('ChoripDong', 95), ('Hi-Myon', 56), ('Mr. Udon', 56), ('Maison de Coree', 54)] This one looks good enough. The token set ratio scorer also tokenizes the strings and follows processing steps just like the token sort ratio. Then it collects common tokens between two strings and performs pairwise comparisons to find the similarity percentage. process.extract('7 Select', unique_brand, scorer=fuzz.token_set_ratio)[('7 Select', 100), ('7 Select/Nissin', 100), ('The Ramen Rater Select', 86), ('Jinbo Selection', 61), ('Seven & I', 53)] Since the token set ratio is more flexible, the score has increased from 70% to 100% for 7 Select — 7 Select/Nissin. process.extract('A-Sha', unique_brand, scorer=fuzz.token_set_ratio)[('A-Sha', 100), ('A-Sha Dry Noodle', 100), ('Shan', 67), ('Nasoya', 55), ('Alhami', 55)] Now we see A-Sha has another name as A-Sha Dry Noodle. And we can see this only by using token set ratio. process.extract('Acecook', unique_brand, scorer=fuzz.token_set_ratio)[('Acecook', 100), ('Vina Acecook', 100), ('Yatekomo', 53), ('Sahmyook', 53), ('Panco', 50)] This one got 100% just like the 7 Select case. process.extract("Chef Nic's Noodles", unique_brand, scorer=fuzz.token_set_ratio)[("Chef Nic's Noodles", 100), ('S&S', 100), ('Mr. Noodles', 82), ("Mr. Lee's Noodles", 72), ('Tseng Noodles', 70)] This one gets much worse when token set ratio returns 100% for the pair of Chef Nic’s Noodles — S&S. process.extract('Chorip Dong', unique_brand, scorer=fuzz.token_set_ratio)[('Chorip Dong', 100), ('ChoripDong', 95), ('Hi-Myon', 56), ('Mr. Udon', 56), ('Maison de Coree', 54)] We have the same result for this one. Although the token set ratio is more flexible and can detect more similar strings than the token sort ratio, it might also bring in more wrong matches. In this part, I employ token sort ratio first and create a table showing brand names, their similarities, and their scores. #Create tuples of brand names, matched brand names, and the scorescore_sort = [(x,) + i for x in unique_brand for i in process.extract(x, unique_brand, scorer=fuzz.token_sort_ratio)]#Create a dataframe from the tuplessimilarity_sort = pd.DataFrame(score_sort, columns=['brand_sort','match_sort','score_sort'])similarity_sort.head() Since we’re looking for matched values from the same column, one value pair would have another same pair in a reversed order. For example, we will find one pair of EDO Pack — Gau Do, and another pair of Gau Do — EDO Pack. To eliminate one of them later, we need to find “representative” values for the same pairs. similarity_sort['sorted_brand_sort'] = np.minimum(similarity_sort['brand_sort'], similarity_sort['match_sort'])similarity_sort.head() Based on the tests above, I only care of those pairs which have at least 80% similarity. I also exclude those which match to themselves (brand value and match value are exactly the same) and those which are duplicated pairs. high_score_sort = similarity_sort[(similarity_sort['score_sort'] >= 80) & (similarity_sort['brand_sort'] != similarity_sort['match_sort']) & (similarity_sort['sorted_brand_sort'] != similarity_sort['match_sort'])]high_score_sort = high_score_sort.drop('sorted_brand_sort',axis=1).copy() Now, let’s see the result. high_score_sort.groupby(['brand_sort','score_sort']).agg( {'match_sort': ', '.join}).sort_values( ['score_sort'], ascending=False) From the score of 95 and above, everything looks good. In each pair, the two values might have typos, one missing character, or inconsistent format, but overall they obviously refer to each other. Below 95, it would be harder to tell. We can look at some examples by listing out data from each pair. #Souper - Super - 91%ramen[(ramen['Brand'] == 'Souper') | (ramen['Brand'] == 'Super')].sort_values(['Brand']) For this pair, we see that these two brands come from different manufacturers/countries, and there’s also no similarity in their ramen types or styles. I would say that these brands are not the same. #Ped Chef - Red Chef - 88%ramen[(ramen['Brand'] == 'Ped Chef') | (ramen['Brand'] == 'Red Chef')].sort_values(['Brand']) Here, we only have one record of the Ped Chef brand, and we also see the same pattern in its variety name in comparison with the Red Chef brand. I’m pretty sure these two brands are the same. For a small dataset like this one, we can continue to check other pairs by the same method. From the threshold of 84% and below, we can ignore some pairs which are obviously different or we can make a quick check as above. To apply the token set ratio, I can just go over the same steps; this part can be found on my Github. The comparison result include names, their matches using token sort ratio and token set ratio, and the scores respectively. Now we can see how different it is between two scorers. As expected, the token set ratio matches wrong names with high scores (e.g. S&S, Mr.Noodles). However, it does bring in more matches compared to the token sort ratio (e.g. 7 Select/Nissin, Sugakiya Foods, Vina Acecook). This means to get the most matches, one should use both of the scorers. With your ramen knowledge and FuzzyWuzzy, can you pick out any correct match?
[ { "code": null, "e": 568, "s": 172, "text": "There are different ways to make data dirty, and inconsistent data entry is one of them. Inconsistent values are even worse than duplicates, and sometimes difficult to detect. This article presents how I apply FuzzyWuzzy package to find similar ramen brand names in a ramen review dataset (full Jupyter Notebook can be found on my GitHub). You may also find functions to shorten your codes here." }, { "code": null, "e": 765, "s": 568, "text": "import pandas as pdimport numpy as npfrom fuzzywuzzy import process, fuzzramen = pd.read_excel('The-Ramen-Rater-The-Big-List-1-3400-Current- As-Of-Jan-25-2020.xlsx')ramen.head()" }, { "code": null, "e": 1122, "s": 765, "text": "ramen.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3400 entries, 0 to 3399Data columns (total 6 columns):Review # 3400 non-null int64Brand 3400 non-null objectVariety 3400 non-null objectStyle 3400 non-null objectCountry 3400 non-null objectStars 3400 non-null objectdtypes: int64(1), object(5)memory usage: 159.5+ KB" }, { "code": null, "e": 1381, "s": 1122, "text": "This dataset is very simple and easy to understand. Before moving to FuzzyWuzzy, I would like to check some more information. First of all, I remove leading and trailing spaces (if available) in every column, and then print out their number of unique values." }, { "code": null, "e": 1712, "s": 1381, "text": "for col in ramen[['Brand','Variety','Style','Country']]: ramen[col] = ramen[col].str.strip() print('Number of unique values in ' + str(col) +': ' + str(ramen[col].nunique()))Number of unique values in Brand: 499Number of unique values in Variety: 3170Number of unique values in Style: 8Number of unique values in Country: 48" }, { "code": null, "e": 1824, "s": 1712, "text": "By sorting unique brand names, we can see if there are similar ones. The result only shows the first 20 brands." }, { "code": null, "e": 2142, "s": 1824, "text": "unique_brand = ramen['Brand'].unique().tolist()sorted(unique_brand)[:20]['1 To 3 Noodles', '7 Select', '7 Select/Nissin', '7-Eleven / Nissin', 'A-One', 'A-Sha', 'A-Sha Dry Noodle', 'A1', 'ABC', 'Acecook', 'Adabi', 'Ah Lai', 'Aji-no-men', 'Ajinatori', 'Ajinomoto', 'Alhami', 'Amianda', 'Amino', \"Annie Chun's\", 'Aroi']" }, { "code": null, "e": 2244, "s": 2142, "text": "We can see some suspicious names right at the beginning. Next, let’s have some tests with FuzzyWuzzy." }, { "code": null, "e": 2525, "s": 2244, "text": "FuzzyWuzzy has four scorer options to find the Levenshtein distance between two strings. In this example, I would check on the token sort ratio and the token set ratio since I believe they are more suitable for this dataset which might have mixed words order and duplicated words." }, { "code": null, "e": 2720, "s": 2525, "text": "I pick four brand names and find their similar names in the Brand column. Since we’re matching the Brand column with itself, the result will always include the selected name with a score of 100." }, { "code": null, "e": 2975, "s": 2720, "text": "The token sort ratio scorer tokenizes the strings and cleans them by returning these strings to lower cases, removing punctuations, and then sorting them alphabetically. After that, it finds the Levenshtein distance and returns the similarity percentage." }, { "code": null, "e": 3149, "s": 2975, "text": "process.extract('7 Select', unique_brand, scorer=fuzz.token_sort_ratio)[('7 Select', 100), ('7 Select/Nissin', 70), ('Jinbo Selection', 61), ('Seven & I', 53), ('Lele', 50)]" }, { "code": null, "e": 3320, "s": 3149, "text": "This result means that 7 Select/Nissin has 70% similarity when referring to 7 Select. Not bad if I set the threshold at 70% to get the pair of 7 Select — 7 Select/Nissin." }, { "code": null, "e": 3467, "s": 3320, "text": "process.extract('A-Sha', unique_brand, scorer=fuzz.token_sort_ratio)[('A-Sha', 100), ('Shan', 67), ('Nasoya', 55), ('Alhami', 55), ('Ah Lai', 55)]" }, { "code": null, "e": 3506, "s": 3467, "text": "Below 70%, there’s no match for A-sha." }, { "code": null, "e": 3668, "s": 3506, "text": "process.extract('Acecook', unique_brand, scorer=fuzz.token_sort_ratio)[('Acecook', 100), ('Vina Acecook', 74), ('Yatekomo', 53), ('Sahmyook', 53), ('Panco', 50)]" }, { "code": null, "e": 3697, "s": 3668, "text": "Still good at 70% threshold." }, { "code": null, "e": 3912, "s": 3697, "text": "process.extract(\"Chef Nic's Noodles\", unique_brand, scorer=fuzz.token_sort_ratio)[(\"Chef Nic's Noodles\", 100), (\"Mr. Lee's Noodles\", 71), ('Fantastic Noodles', 69), ('1 To 3 Noodles', 62), (\"Mom's Dry Noodle\", 59)]" }, { "code": null, "e": 4055, "s": 3912, "text": "Now, we have a problem here. Token sort ratio scorer will get the wrong pair of Chef Nic’s Noodles — Mr. Lee’s Noodles if I set 70% threshold." }, { "code": null, "e": 4232, "s": 4055, "text": "process.extract('Chorip Dong', unique_brand, scorer=fuzz.token_sort_ratio)[('Chorip Dong', 100), ('ChoripDong', 95), ('Hi-Myon', 56), ('Mr. Udon', 56), ('Maison de Coree', 54)]" }, { "code": null, "e": 4260, "s": 4232, "text": "This one looks good enough." }, { "code": null, "e": 4495, "s": 4260, "text": "The token set ratio scorer also tokenizes the strings and follows processing steps just like the token sort ratio. Then it collects common tokens between two strings and performs pairwise comparisons to find the similarity percentage." }, { "code": null, "e": 4687, "s": 4495, "text": "process.extract('7 Select', unique_brand, scorer=fuzz.token_set_ratio)[('7 Select', 100), ('7 Select/Nissin', 100), ('The Ramen Rater Select', 86), ('Jinbo Selection', 61), ('Seven & I', 53)]" }, { "code": null, "e": 4804, "s": 4687, "text": "Since the token set ratio is more flexible, the score has increased from 70% to 100% for 7 Select — 7 Select/Nissin." }, { "code": null, "e": 4961, "s": 4804, "text": "process.extract('A-Sha', unique_brand, scorer=fuzz.token_set_ratio)[('A-Sha', 100), ('A-Sha Dry Noodle', 100), ('Shan', 67), ('Nasoya', 55), ('Alhami', 55)]" }, { "code": null, "e": 5067, "s": 4961, "text": "Now we see A-Sha has another name as A-Sha Dry Noodle. And we can see this only by using token set ratio." }, { "code": null, "e": 5229, "s": 5067, "text": "process.extract('Acecook', unique_brand, scorer=fuzz.token_set_ratio)[('Acecook', 100), ('Vina Acecook', 100), ('Yatekomo', 53), ('Sahmyook', 53), ('Panco', 50)]" }, { "code": null, "e": 5276, "s": 5229, "text": "This one got 100% just like the 7 Select case." }, { "code": null, "e": 5471, "s": 5276, "text": "process.extract(\"Chef Nic's Noodles\", unique_brand, scorer=fuzz.token_set_ratio)[(\"Chef Nic's Noodles\", 100), ('S&S', 100), ('Mr. Noodles', 82), (\"Mr. Lee's Noodles\", 72), ('Tseng Noodles', 70)]" }, { "code": null, "e": 5572, "s": 5471, "text": "This one gets much worse when token set ratio returns 100% for the pair of Chef Nic’s Noodles — S&S." }, { "code": null, "e": 5748, "s": 5572, "text": "process.extract('Chorip Dong', unique_brand, scorer=fuzz.token_set_ratio)[('Chorip Dong', 100), ('ChoripDong', 95), ('Hi-Myon', 56), ('Mr. Udon', 56), ('Maison de Coree', 54)]" }, { "code": null, "e": 5786, "s": 5748, "text": "We have the same result for this one." }, { "code": null, "e": 5938, "s": 5786, "text": "Although the token set ratio is more flexible and can detect more similar strings than the token sort ratio, it might also bring in more wrong matches." }, { "code": null, "e": 6062, "s": 5938, "text": "In this part, I employ token sort ratio first and create a table showing brand names, their similarities, and their scores." }, { "code": null, "e": 6423, "s": 6062, "text": "#Create tuples of brand names, matched brand names, and the scorescore_sort = [(x,) + i for x in unique_brand for i in process.extract(x, unique_brand, scorer=fuzz.token_sort_ratio)]#Create a dataframe from the tuplessimilarity_sort = pd.DataFrame(score_sort, columns=['brand_sort','match_sort','score_sort'])similarity_sort.head()" }, { "code": null, "e": 6737, "s": 6423, "text": "Since we’re looking for matched values from the same column, one value pair would have another same pair in a reversed order. For example, we will find one pair of EDO Pack — Gau Do, and another pair of Gau Do — EDO Pack. To eliminate one of them later, we need to find “representative” values for the same pairs." }, { "code": null, "e": 6871, "s": 6737, "text": "similarity_sort['sorted_brand_sort'] = np.minimum(similarity_sort['brand_sort'], similarity_sort['match_sort'])similarity_sort.head()" }, { "code": null, "e": 7096, "s": 6871, "text": "Based on the tests above, I only care of those pairs which have at least 80% similarity. I also exclude those which match to themselves (brand value and match value are exactly the same) and those which are duplicated pairs." }, { "code": null, "e": 7414, "s": 7096, "text": "high_score_sort = similarity_sort[(similarity_sort['score_sort'] >= 80) & (similarity_sort['brand_sort'] != similarity_sort['match_sort']) & (similarity_sort['sorted_brand_sort'] != similarity_sort['match_sort'])]high_score_sort = high_score_sort.drop('sorted_brand_sort',axis=1).copy()" }, { "code": null, "e": 7441, "s": 7414, "text": "Now, let’s see the result." }, { "code": null, "e": 7618, "s": 7441, "text": "high_score_sort.groupby(['brand_sort','score_sort']).agg( {'match_sort': ', '.join}).sort_values( ['score_sort'], ascending=False)" }, { "code": null, "e": 7918, "s": 7618, "text": "From the score of 95 and above, everything looks good. In each pair, the two values might have typos, one missing character, or inconsistent format, but overall they obviously refer to each other. Below 95, it would be harder to tell. We can look at some examples by listing out data from each pair." }, { "code": null, "e": 8028, "s": 7918, "text": "#Souper - Super - 91%ramen[(ramen['Brand'] == 'Souper') | (ramen['Brand'] == 'Super')].sort_values(['Brand'])" }, { "code": null, "e": 8228, "s": 8028, "text": "For this pair, we see that these two brands come from different manufacturers/countries, and there’s also no similarity in their ramen types or styles. I would say that these brands are not the same." }, { "code": null, "e": 8348, "s": 8228, "text": "#Ped Chef - Red Chef - 88%ramen[(ramen['Brand'] == 'Ped Chef') | (ramen['Brand'] == 'Red Chef')].sort_values(['Brand'])" }, { "code": null, "e": 8540, "s": 8348, "text": "Here, we only have one record of the Ped Chef brand, and we also see the same pattern in its variety name in comparison with the Red Chef brand. I’m pretty sure these two brands are the same." }, { "code": null, "e": 8763, "s": 8540, "text": "For a small dataset like this one, we can continue to check other pairs by the same method. From the threshold of 84% and below, we can ignore some pairs which are obviously different or we can make a quick check as above." }, { "code": null, "e": 8865, "s": 8763, "text": "To apply the token set ratio, I can just go over the same steps; this part can be found on my Github." }, { "code": null, "e": 8989, "s": 8865, "text": "The comparison result include names, their matches using token sort ratio and token set ratio, and the scores respectively." }, { "code": null, "e": 9337, "s": 8989, "text": "Now we can see how different it is between two scorers. As expected, the token set ratio matches wrong names with high scores (e.g. S&S, Mr.Noodles). However, it does bring in more matches compared to the token sort ratio (e.g. 7 Select/Nissin, Sugakiya Foods, Vina Acecook). This means to get the most matches, one should use both of the scorers." } ]
How to get an Entry box within a Messagebox in Tkinter?
There are various methods and built-in functions available with the messagebox library in tkinter. Let's assume you want to display a messagebox and take some input from the user in an Entry widget. In this case, you can use the askstring library from simpledialog. The askstring library creates a window that takes two arguments, the title of the window, and the input title before the Entry widget. Let's take an example to understand how it works. # Import the required library from tkinter import * from tkinter.simpledialog import askstring from tkinter.messagebox import showinfo # Create an instance of tkinter frame and window win=Tk() win.geometry("700x300") name = askstring('Name', 'What is your name?') showinfo('Hello!', 'Hi, {}'.format(name)) win.mainloop() Running the above code will display a popup message box asking the user to enter the name in the given Entry widget. Enter the name and click "OK". It will display the following message −
[ { "code": null, "e": 1513, "s": 1062, "text": "There are various methods and built-in functions available with the messagebox library in tkinter. Let's assume you want to display a messagebox and take some input from the user in an Entry widget. In this case, you can use the askstring library from simpledialog. The askstring library creates a window that takes two arguments, the title of the window, and the input title before the Entry widget. Let's take an example to understand how it works." }, { "code": null, "e": 1837, "s": 1513, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter.simpledialog import askstring\nfrom tkinter.messagebox import showinfo\n\n# Create an instance of tkinter frame and window\nwin=Tk()\nwin.geometry(\"700x300\")\n\nname = askstring('Name', 'What is your name?')\nshowinfo('Hello!', 'Hi, {}'.format(name))\n\nwin.mainloop()" }, { "code": null, "e": 1954, "s": 1837, "text": "Running the above code will display a popup message box asking the user to enter the name in the given Entry widget." }, { "code": null, "e": 2025, "s": 1954, "text": "Enter the name and click \"OK\". It will display the following message −" } ]
How to convert Byte Array to Image in java?
Java provides ImageIO class for reading and writing an image. To convert a byte array to an image. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class. Finally, Write the image to using the write() method of the ImageIo class. import java.io.ByteArrayOutputStream; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ByteArrayToImage { public static void main(String args[]) throws Exception { BufferedImage bImage = ImageIO.read(new File("sample.jpg")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", bos ); byte [] data = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(data); BufferedImage bImage2 = ImageIO.read(bis); ImageIO.write(bImage2, "jpg", new File("output.jpg") ); System.out.println("image created"); } } image created
[ { "code": null, "e": 1161, "s": 1062, "text": "Java provides ImageIO class for reading and writing an image. To convert a byte array to an image." }, { "code": null, "e": 1270, "s": 1161, "text": "Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor." }, { "code": null, "e": 1379, "s": 1270, "text": "Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor." }, { "code": null, "e": 1507, "s": 1379, "text": "Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter)." }, { "code": null, "e": 1635, "s": 1507, "text": "Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter)." }, { "code": null, "e": 1710, "s": 1635, "text": "Finally, Write the image to using the write() method of the ImageIo class." }, { "code": null, "e": 1785, "s": 1710, "text": "Finally, Write the image to using the write() method of the ImageIo class." }, { "code": null, "e": 2442, "s": 1785, "text": "import java.io.ByteArrayOutputStream;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport javax.imageio.ImageIO;\npublic class ByteArrayToImage {\n public static void main(String args[]) throws Exception {\n BufferedImage bImage = ImageIO.read(new File(\"sample.jpg\"));\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n ImageIO.write(bImage, \"jpg\", bos );\n byte [] data = bos.toByteArray();\n ByteArrayInputStream bis = new ByteArrayInputStream(data);\n BufferedImage bImage2 = ImageIO.read(bis);\n ImageIO.write(bImage2, \"jpg\", new File(\"output.jpg\") );\n System.out.println(\"image created\");\n }\n}" }, { "code": null, "e": 2456, "s": 2442, "text": "image created" } ]
Intersection of two subgroups of a group is again a subgroup - GeeksforGeeks
05 Mar, 2021 Group : It is a set equipped with a binary operation that combines any two elements to form a third element in such a way that three conditions called group axioms are satisfied, namely associativity, identity, and invertibility. Subgroup : If a non-void subset H of a group G is itself a group under the operation of G, we say H is a subgroup of G. To Prove : Prove that the intersection of two subgroups of a group G is again a subgroup of G. Proof : Let H1 and H2 be any two subgroups of G.Then, H1 ∩ H2 ≠ ∅ Since at least the identity element ‘e’ is common to both H1 and H2 .In order to prove that H1 ∩ H2 is a subgroup, it is sufficient to prove that a ∈ H1 ∩ H2 , b ∈ H1 ∩ H2 ⇢ a b-1 ∈ H1 ∩ H2 Now, a ∈ H1 ∩ H2 ⇢ a ∈ H1 and a ∈ H2 b ∈ H1 ∩ H2 ⇢ b ∈ H1 and b ∈ H2 Since H1 and H2 are subgroups.Therefore, a ∈ H1 , b ∈ H1 ⇢ ab-1 ∈ H1 and a ∈ H2 , b ∈ H2 ⇢ ab-1 ∈ H2 Thus, ab-1 ∈ H1 and ab-1 ∈ H2 ⇢ ab-1 ∈ H1 ∩ H2 Hence, H1 ∩ H2 is a subgroup of G and that is our theorem i.e. The intersection of two subgroups of a group is again a subgroup. Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Activation Functions Difference between Propositional Logic and Predicate Logic Proof that vertex cover is NP complete Mathematics | Matrix Introduction Logic Notations in LaTeX Univariate, Bivariate and Multivariate data and its analysis Brackets in Latex Secant Method of Numerical analysis Betweenness Centrality (Centrality Measure)
[ { "code": null, "e": 24501, "s": 24473, "text": "\n05 Mar, 2021" }, { "code": null, "e": 24731, "s": 24501, "text": "Group : It is a set equipped with a binary operation that combines any two elements to form a third element in such a way that three conditions called group axioms are satisfied, namely associativity, identity, and invertibility." }, { "code": null, "e": 24851, "s": 24731, "text": "Subgroup : If a non-void subset H of a group G is itself a group under the operation of G, we say H is a subgroup of G." }, { "code": null, "e": 24947, "s": 24851, "text": "To Prove : Prove that the intersection of two subgroups of a group G is again a subgroup of G." }, { "code": null, "e": 25019, "s": 24947, "text": "Proof : Let H1 and H2 be any two subgroups of G.Then, " }, { "code": null, "e": 25035, "s": 25019, "text": "H1 ∩ H2 ≠ ∅" }, { "code": null, "e": 25183, "s": 25035, "text": "Since at least the identity element ‘e’ is common to both H1 and H2 .In order to prove that H1 ∩ H2 is a subgroup, it is sufficient to prove that" }, { "code": null, "e": 25231, "s": 25183, "text": " a ∈ H1 ∩ H2 , b ∈ H1 ∩ H2\n⇢ a b-1 ∈ H1 ∩ H2" }, { "code": null, "e": 25236, "s": 25231, "text": "Now," }, { "code": null, "e": 25314, "s": 25236, "text": " a ∈ H1 ∩ H2 \n⇢ a ∈ H1 and a ∈ H2\n b ∈ H1 ∩ H2\n⇢ b ∈ H1 and b ∈ H2" }, { "code": null, "e": 25355, "s": 25314, "text": "Since H1 and H2 are subgroups.Therefore," }, { "code": null, "e": 25391, "s": 25355, "text": " a ∈ H1 , b ∈ H1\n⇢ ab-1 ∈ H1 " }, { "code": null, "e": 25416, "s": 25391, "text": "and " }, { "code": null, "e": 25448, "s": 25416, "text": " a ∈ H2 , b ∈ H2\n⇢ ab-1 ∈ H2" }, { "code": null, "e": 25461, "s": 25448, "text": "Thus, " }, { "code": null, "e": 25512, "s": 25461, "text": " ab-1 ∈ H1 and ab-1 ∈ H2\n⇢ ab-1 ∈ H1 ∩ H2" }, { "code": null, "e": 25642, "s": 25512, "text": "Hence, H1 ∩ H2 is a subgroup of G and that is our theorem i.e. The intersection of two subgroups of a group is again a subgroup." }, { "code": null, "e": 25666, "s": 25642, "text": "Engineering Mathematics" }, { "code": null, "e": 25764, "s": 25666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25773, "s": 25764, "text": "Comments" }, { "code": null, "e": 25786, "s": 25773, "text": "Old Comments" }, { "code": null, "e": 25807, "s": 25786, "text": "Activation Functions" }, { "code": null, "e": 25866, "s": 25807, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 25905, "s": 25866, "text": "Proof that vertex cover is NP complete" }, { "code": null, "e": 25939, "s": 25905, "text": "Mathematics | Matrix Introduction" }, { "code": null, "e": 25964, "s": 25939, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 26025, "s": 25964, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 26043, "s": 26025, "text": "Brackets in Latex" }, { "code": null, "e": 26079, "s": 26043, "text": "Secant Method of Numerical analysis" } ]
4 Pandas GroupBy Tricks You Should Know | by Christopher Tao | Medium | Towards Data Science
As one of the most popular libraries in Python, Pandas has been utilised very commonly especially in data EDA (Exploratory Data Analysis) jobs. Very typically, it can be used for filtering and transforming dataset just like what we usually do using SQL queries. They share a lot of similar concepts such as joining tables. However, some features from them have the same names but different concepts. “Group By” is one of them. In this article, I’ll introduce some tricks for the Pandas group by function, which could improve our productivity in EDA jobs. Hopefully at least one is something you never familiar with so that it could help you. I’m sure that you know how to import Pandas in Python, but still, let me put it here. All the rest of the code in this article assume Pandas has been imported as follows. import pandas as pd Let’s do not waste too much time on getting a sample dataset. The iris dataset is quite commonly used in Data Science as the “hello world” dataset. We can easily get it from the Sci-kit Learn library. Let’s import it and load the iris dataset. from sklearn.datasets import load_irisiris = load_iris() The iris dataset is a dictionary after loaded. The value of the key “data” is a 2-D array containing all the features of 3 types of iris. The “feature_names” contains the column names in order. The “target” contains encoded classes of iris, which as 0, 1 or 2. Finally, the “targe_names” contains the actual names of the three types of iris, which is corresponding to the encoding number 0, 1 and 2. You’ll understand how it looks like if you print it out. The following code is for loading the iris dataset into a Pandas data frame we expected. df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])df['class'] = iris['target']df['class'] = df['class'].apply(lambda i: iris['target_names'][i]) The first line of the code creates the data frame from the 2-D array with the column names. The second line added the encoded iris class, and the third line translated the numbers into iris class names. Now, we are on the same page. Let’s use this sample data frame for the rest of this article. The basic idea of the Pandas group by function is not for the sake of grouping categorical values together, but to calculate some aggregated values afterwards. So, the aggregation is performed for each group. For example, we can group the data frame based on the iris classification, and calculate the average value for each feature (column). df.groupby('class').mean() Other than mean() there are lots of aggregation functions such as min(), max() and count(). OK, this section is only for review purpose. Now we should begin. It is quite common to use the count() function to aggregate the groups to get the number of rows for each group. However, this is sometimes not what you want. That is, when there are NULL or NaN values in the data frame, they will NOT be counted by the count() function. Let’s manually assign a NaN value to the data frame. df.iloc[0,0] = None The above code will create a NaN value for the first row of the sepal length column. Then, let’s use the count() function over it. df.groupby('class')['sepal length (cm)'].count() The setosa iris is counted as 49, but there is actually 50 rows. This is because the count() function doesn’t actually count NaN values. There is another aggregation function that is rarely used — size(). This function will pick up all the values even though it is NaN. df.groupby('class')['sepal length (cm)'].size() Sometimes, we may want to rename the aggregated column rather than just having a “max” or “mean” as the name which doesn’t indicate which column it aggregated from. We can actually specify the names as the arguments in the agg() function. df.groupby('class')['sepal length (cm)'].agg( sepal_average_length='mean', sepal_standard_deviation='std') Pandas provides many aggregation functions such as mean() and count(). However, it is still quite limited if we can only use these functions. In fact, we can define our own aggregation functions and pass it into the agg() function. For example, if we want to get the mean of each column, as well as convert them into millimeters, we can define the customised function as follows. def transformed_mean(value): value *= 100 value_mean = value.mean() return round(value_mean, 2) Then, simply pass this function name into the agg() function as argument. df_mm = df.groupby('class').agg(transformed_mean)df_mm.columns = ['sepal length (mm)', 'sepal width (mm)', 'petal length (mm)', 'petal width (mm)'] Don’t forget to rename the column names by changing the unit to make sure they are consistent :) Of course, for such as relatively simple function, we can also define an anonymous function using lambda as follows. df_mm = df.groupby('class').agg(lambda x: round((x * 100).mean(), 2)) So, we don’t have to define a separated function. However, it is recommended to define a proper function if the logic is relatively complex for better readability. Do we have to use Group By on categorical variables? The answer is NO. If a variable is continuous, what we need to do is just creating bins to make sure they are converted into categorical values. In Pandas, we can easily create bins with equal ranges using the pd.cut() function. sepal_len_groups = pd.cut(df['sepal length (cm)'], bins=3) The code above created 3 bins with equal spans. Equal means that the distances between the 3 bins are exactly the same. Then, we can directly use these three bins in group by. df.groupby(sepal_len_groups)['sepal length (cm)'].agg(count='count') In this article, I’ve introduced some tricks when using the group by function along with the aggregation function in Pandas. Using the correct methods can improve our productivity to a large extent sometimes. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 599, "s": 172, "text": "As one of the most popular libraries in Python, Pandas has been utilised very commonly especially in data EDA (Exploratory Data Analysis) jobs. Very typically, it can be used for filtering and transforming dataset just like what we usually do using SQL queries. They share a lot of similar concepts such as joining tables. However, some features from them have the same names but different concepts. “Group By” is one of them." }, { "code": null, "e": 814, "s": 599, "text": "In this article, I’ll introduce some tricks for the Pandas group by function, which could improve our productivity in EDA jobs. Hopefully at least one is something you never familiar with so that it could help you." }, { "code": null, "e": 985, "s": 814, "text": "I’m sure that you know how to import Pandas in Python, but still, let me put it here. All the rest of the code in this article assume Pandas has been imported as follows." }, { "code": null, "e": 1005, "s": 985, "text": "import pandas as pd" }, { "code": null, "e": 1249, "s": 1005, "text": "Let’s do not waste too much time on getting a sample dataset. The iris dataset is quite commonly used in Data Science as the “hello world” dataset. We can easily get it from the Sci-kit Learn library. Let’s import it and load the iris dataset." }, { "code": null, "e": 1306, "s": 1249, "text": "from sklearn.datasets import load_irisiris = load_iris()" }, { "code": null, "e": 1706, "s": 1306, "text": "The iris dataset is a dictionary after loaded. The value of the key “data” is a 2-D array containing all the features of 3 types of iris. The “feature_names” contains the column names in order. The “target” contains encoded classes of iris, which as 0, 1 or 2. Finally, the “targe_names” contains the actual names of the three types of iris, which is corresponding to the encoding number 0, 1 and 2." }, { "code": null, "e": 1852, "s": 1706, "text": "You’ll understand how it looks like if you print it out. The following code is for loading the iris dataset into a Pandas data frame we expected." }, { "code": null, "e": 2014, "s": 1852, "text": "df = pd.DataFrame(data=iris['data'], columns=iris['feature_names'])df['class'] = iris['target']df['class'] = df['class'].apply(lambda i: iris['target_names'][i])" }, { "code": null, "e": 2217, "s": 2014, "text": "The first line of the code creates the data frame from the 2-D array with the column names. The second line added the encoded iris class, and the third line translated the numbers into iris class names." }, { "code": null, "e": 2310, "s": 2217, "text": "Now, we are on the same page. Let’s use this sample data frame for the rest of this article." }, { "code": null, "e": 2519, "s": 2310, "text": "The basic idea of the Pandas group by function is not for the sake of grouping categorical values together, but to calculate some aggregated values afterwards. So, the aggregation is performed for each group." }, { "code": null, "e": 2653, "s": 2519, "text": "For example, we can group the data frame based on the iris classification, and calculate the average value for each feature (column)." }, { "code": null, "e": 2680, "s": 2653, "text": "df.groupby('class').mean()" }, { "code": null, "e": 2772, "s": 2680, "text": "Other than mean() there are lots of aggregation functions such as min(), max() and count()." }, { "code": null, "e": 2838, "s": 2772, "text": "OK, this section is only for review purpose. Now we should begin." }, { "code": null, "e": 3109, "s": 2838, "text": "It is quite common to use the count() function to aggregate the groups to get the number of rows for each group. However, this is sometimes not what you want. That is, when there are NULL or NaN values in the data frame, they will NOT be counted by the count() function." }, { "code": null, "e": 3162, "s": 3109, "text": "Let’s manually assign a NaN value to the data frame." }, { "code": null, "e": 3182, "s": 3162, "text": "df.iloc[0,0] = None" }, { "code": null, "e": 3267, "s": 3182, "text": "The above code will create a NaN value for the first row of the sepal length column." }, { "code": null, "e": 3313, "s": 3267, "text": "Then, let’s use the count() function over it." }, { "code": null, "e": 3362, "s": 3313, "text": "df.groupby('class')['sepal length (cm)'].count()" }, { "code": null, "e": 3499, "s": 3362, "text": "The setosa iris is counted as 49, but there is actually 50 rows. This is because the count() function doesn’t actually count NaN values." }, { "code": null, "e": 3632, "s": 3499, "text": "There is another aggregation function that is rarely used — size(). This function will pick up all the values even though it is NaN." }, { "code": null, "e": 3680, "s": 3632, "text": "df.groupby('class')['sepal length (cm)'].size()" }, { "code": null, "e": 3845, "s": 3680, "text": "Sometimes, we may want to rename the aggregated column rather than just having a “max” or “mean” as the name which doesn’t indicate which column it aggregated from." }, { "code": null, "e": 3919, "s": 3845, "text": "We can actually specify the names as the arguments in the agg() function." }, { "code": null, "e": 4032, "s": 3919, "text": "df.groupby('class')['sepal length (cm)'].agg( sepal_average_length='mean', sepal_standard_deviation='std')" }, { "code": null, "e": 4174, "s": 4032, "text": "Pandas provides many aggregation functions such as mean() and count(). However, it is still quite limited if we can only use these functions." }, { "code": null, "e": 4412, "s": 4174, "text": "In fact, we can define our own aggregation functions and pass it into the agg() function. For example, if we want to get the mean of each column, as well as convert them into millimeters, we can define the customised function as follows." }, { "code": null, "e": 4517, "s": 4412, "text": "def transformed_mean(value): value *= 100 value_mean = value.mean() return round(value_mean, 2)" }, { "code": null, "e": 4591, "s": 4517, "text": "Then, simply pass this function name into the agg() function as argument." }, { "code": null, "e": 4739, "s": 4591, "text": "df_mm = df.groupby('class').agg(transformed_mean)df_mm.columns = ['sepal length (mm)', 'sepal width (mm)', 'petal length (mm)', 'petal width (mm)']" }, { "code": null, "e": 4836, "s": 4739, "text": "Don’t forget to rename the column names by changing the unit to make sure they are consistent :)" }, { "code": null, "e": 4953, "s": 4836, "text": "Of course, for such as relatively simple function, we can also define an anonymous function using lambda as follows." }, { "code": null, "e": 5023, "s": 4953, "text": "df_mm = df.groupby('class').agg(lambda x: round((x * 100).mean(), 2))" }, { "code": null, "e": 5187, "s": 5023, "text": "So, we don’t have to define a separated function. However, it is recommended to define a proper function if the logic is relatively complex for better readability." }, { "code": null, "e": 5258, "s": 5187, "text": "Do we have to use Group By on categorical variables? The answer is NO." }, { "code": null, "e": 5469, "s": 5258, "text": "If a variable is continuous, what we need to do is just creating bins to make sure they are converted into categorical values. In Pandas, we can easily create bins with equal ranges using the pd.cut() function." }, { "code": null, "e": 5528, "s": 5469, "text": "sepal_len_groups = pd.cut(df['sepal length (cm)'], bins=3)" }, { "code": null, "e": 5648, "s": 5528, "text": "The code above created 3 bins with equal spans. Equal means that the distances between the 3 bins are exactly the same." }, { "code": null, "e": 5704, "s": 5648, "text": "Then, we can directly use these three bins in group by." }, { "code": null, "e": 5773, "s": 5704, "text": "df.groupby(sepal_len_groups)['sepal length (cm)'].agg(count='count')" }, { "code": null, "e": 5982, "s": 5773, "text": "In this article, I’ve introduced some tricks when using the group by function along with the aggregation function in Pandas. Using the correct methods can improve our productivity to a large extent sometimes." }, { "code": null, "e": 5993, "s": 5982, "text": "medium.com" } ]
Substring with Concatenation of All Words in C++
Suppose we have a string, s, and we also have a list of words, words present in the array are all of the same length. We have to find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. So if the input is like “barfoothefoobarman” and words are [“foo”, “bar”], then the output will be [0,9]. This is because the substring starting at index 0 and 9 are “barfoo” and “foobar”. To solve this, we will follow these steps − Define a method called ok(), this will take string s, map wordCnt, and n − Define a method called ok(), this will take string s, map wordCnt, and n − make a copy of s into temp make a copy of s into temp for i in range n to size of s – 1if size of temp is multiple of 0, thenif when temp is not present in wordCnt, then return falseotherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string.increase temp by s[i] for i in range n to size of s – 1 if size of temp is multiple of 0, thenif when temp is not present in wordCnt, then return falseotherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. if size of temp is multiple of 0, then if when temp is not present in wordCnt, then return false if when temp is not present in wordCnt, then return false otherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. otherwise if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. increase temp by s[i] increase temp by s[i] if temp is not in wordCnt, then return false if temp is not in wordCnt, then return false otherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. otherwise if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string. return true when size of wordCnt is 0 return true when size of wordCnt is 0 From the main method, do this From the main method, do this if size of a is 0, or size of b is 0, then return empty array if size of a is 0, or size of b is 0, then return empty array make a map wordCnt, store the frequency of strings present in b into wordCnt make a map wordCnt, store the frequency of strings present in b into wordCnt make an array called ans make an array called ans window := number of words x number of characters in each word window := number of words x number of characters in each word make one copy of string a into temp make one copy of string a into temp for i in range window to size of a – 1if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert i – window into ansinsert a[i] into tempif size of temp > window, then delete substring from 0, 1 for i in range window to size of a – 1 if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert i – window into ans if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), then insert i – window into ans insert i – window into ans insert a[i] into temp insert a[i] into temp if size of temp > window, then delete substring from 0, 1 if size of temp > window, then delete substring from 0, 1 if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert size of a – window into ans if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), then insert size of a – window into ans insert size of a – window into ans return ans return ans Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: bool ok(string s, unordered_map <string, int> wordCnt, int n){ string temp = ""; for(int i = 0; i < n; i++){ temp += s[i]; } for(int i = n; i < s.size(); i++){ if(temp.size() % n == 0){ if(wordCnt.find(temp) == wordCnt.end())return false; else{ if(wordCnt[temp] == 1){ wordCnt.erase(temp); temp = ""; } else{ wordCnt[temp]--; temp = ""; } } } temp += s[i]; } if(wordCnt.find(temp) == wordCnt.end())return false; else{ if(wordCnt[temp] == 1){ wordCnt.erase(temp); temp = ""; } else{ wordCnt[temp]--; temp = ""; } } return wordCnt.size() == 0; } vector<int> findSubstring(string a, vector<string> &b) { if(a.size() == 0 || b.size() == 0)return {}; unordered_map <string, int> wordCnt; for(int i = 0; i < b.size(); i++)wordCnt[b[i]]++; vector <int> ans; int window = b.size() * b[0].size(); string temp =""; for(int i = 0; i < window; i++)temp += a[i]; for(int i = window; i < a.size(); i++){ if(temp.size() % window == 0 && ok(temp, wordCnt, b[0].size())){ ans.push_back(i - window); } temp += a[i]; if(temp.size() > window)temp.erase(0, 1); } if(temp .size() % window ==0 && ok(temp, wordCnt, b[0].size()))ans.push_back(a.size() - window); return ans; } }; main(){ vector<string> v = {"foo", "bar"}; Solution ob; print_vector(ob.findSubstring("barfoothefoobarman", v)); } 1,2,3,4,5,6,7 3 [0, 9, ]
[ { "code": null, "e": 1337, "s": 1062, "text": "Suppose we have a string, s, and we also have a list of words, words present in the array are all of the same length. We have to find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters." }, { "code": null, "e": 1526, "s": 1337, "text": "So if the input is like “barfoothefoobarman” and words are [“foo”, “bar”], then the output will be [0,9]. This is because the substring starting at index 0 and 9 are “barfoo” and “foobar”." }, { "code": null, "e": 1570, "s": 1526, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1645, "s": 1570, "text": "Define a method called ok(), this will take string s, map wordCnt, and n −" }, { "code": null, "e": 1720, "s": 1645, "text": "Define a method called ok(), this will take string s, map wordCnt, and n −" }, { "code": null, "e": 1747, "s": 1720, "text": "make a copy of s into temp" }, { "code": null, "e": 1774, "s": 1747, "text": "make a copy of s into temp" }, { "code": null, "e": 2091, "s": 1774, "text": "for i in range n to size of s – 1if size of temp is multiple of 0, thenif when temp is not present in wordCnt, then return falseotherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string.increase temp by s[i]" }, { "code": null, "e": 2125, "s": 2091, "text": "for i in range n to size of s – 1" }, { "code": null, "e": 2388, "s": 2125, "text": "if size of temp is multiple of 0, thenif when temp is not present in wordCnt, then return falseotherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 2427, "s": 2388, "text": "if size of temp is multiple of 0, then" }, { "code": null, "e": 2485, "s": 2427, "text": "if when temp is not present in wordCnt, then return false" }, { "code": null, "e": 2543, "s": 2485, "text": "if when temp is not present in wordCnt, then return false" }, { "code": null, "e": 2711, "s": 2543, "text": "otherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 2721, "s": 2711, "text": "otherwise" }, { "code": null, "e": 2803, "s": 2721, "text": "if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string" }, { "code": null, "e": 2885, "s": 2803, "text": "if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string" }, { "code": null, "e": 2963, "s": 2885, "text": "otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 3041, "s": 2963, "text": "otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 3063, "s": 3041, "text": "increase temp by s[i]" }, { "code": null, "e": 3085, "s": 3063, "text": "increase temp by s[i]" }, { "code": null, "e": 3130, "s": 3085, "text": "if temp is not in wordCnt, then return false" }, { "code": null, "e": 3175, "s": 3130, "text": "if temp is not in wordCnt, then return false" }, { "code": null, "e": 3343, "s": 3175, "text": "otherwiseif wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty stringotherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 3353, "s": 3343, "text": "otherwise" }, { "code": null, "e": 3435, "s": 3353, "text": "if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string" }, { "code": null, "e": 3517, "s": 3435, "text": "if wordCnt[temp] is 1, then delete temp from wordCnt, set temp as an empty string" }, { "code": null, "e": 3595, "s": 3517, "text": "otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 3673, "s": 3595, "text": "otherwise decrease the value of wordCnt[temp] by 1, set temp as empty string." }, { "code": null, "e": 3711, "s": 3673, "text": "return true when size of wordCnt is 0" }, { "code": null, "e": 3749, "s": 3711, "text": "return true when size of wordCnt is 0" }, { "code": null, "e": 3779, "s": 3749, "text": "From the main method, do this" }, { "code": null, "e": 3809, "s": 3779, "text": "From the main method, do this" }, { "code": null, "e": 3871, "s": 3809, "text": "if size of a is 0, or size of b is 0, then return empty array" }, { "code": null, "e": 3933, "s": 3871, "text": "if size of a is 0, or size of b is 0, then return empty array" }, { "code": null, "e": 4010, "s": 3933, "text": "make a map wordCnt, store the frequency of strings present in b into wordCnt" }, { "code": null, "e": 4087, "s": 4010, "text": "make a map wordCnt, store the frequency of strings present in b into wordCnt" }, { "code": null, "e": 4112, "s": 4087, "text": "make an array called ans" }, { "code": null, "e": 4137, "s": 4112, "text": "make an array called ans" }, { "code": null, "e": 4199, "s": 4137, "text": "window := number of words x number of characters in each word" }, { "code": null, "e": 4261, "s": 4199, "text": "window := number of words x number of characters in each word" }, { "code": null, "e": 4297, "s": 4261, "text": "make one copy of string a into temp" }, { "code": null, "e": 4333, "s": 4297, "text": "make one copy of string a into temp" }, { "code": null, "e": 4558, "s": 4333, "text": "for i in range window to size of a – 1if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert i – window into ansinsert a[i] into tempif size of temp > window, then delete substring from 0, 1" }, { "code": null, "e": 4597, "s": 4558, "text": "for i in range window to size of a – 1" }, { "code": null, "e": 4706, "s": 4597, "text": "if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert i – window into ans" }, { "code": null, "e": 4789, "s": 4706, "text": "if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), then" }, { "code": null, "e": 4816, "s": 4789, "text": "insert i – window into ans" }, { "code": null, "e": 4843, "s": 4816, "text": "insert i – window into ans" }, { "code": null, "e": 4865, "s": 4843, "text": "insert a[i] into temp" }, { "code": null, "e": 4887, "s": 4865, "text": "insert a[i] into temp" }, { "code": null, "e": 4945, "s": 4887, "text": "if size of temp > window, then delete substring from 0, 1" }, { "code": null, "e": 5003, "s": 4945, "text": "if size of temp > window, then delete substring from 0, 1" }, { "code": null, "e": 5120, "s": 5003, "text": "if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), theninsert size of a – window into ans" }, { "code": null, "e": 5203, "s": 5120, "text": "if temp size is divisible by window and call ok(temp, wordCnt, size of b[0]), then" }, { "code": null, "e": 5238, "s": 5203, "text": "insert size of a – window into ans" }, { "code": null, "e": 5273, "s": 5238, "text": "insert size of a – window into ans" }, { "code": null, "e": 5284, "s": 5273, "text": "return ans" }, { "code": null, "e": 5295, "s": 5284, "text": "return ans" }, { "code": null, "e": 5367, "s": 5295, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 5378, "s": 5367, "text": " Live Demo" }, { "code": null, "e": 7341, "s": 5378, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n bool ok(string s, unordered_map <string, int> wordCnt, int n){\n string temp = \"\";\n for(int i = 0; i < n; i++){\n temp += s[i];\n }\n for(int i = n; i < s.size(); i++){\n if(temp.size() % n == 0){\n if(wordCnt.find(temp) == wordCnt.end())return false;\n else{\n if(wordCnt[temp] == 1){\n wordCnt.erase(temp);\n temp = \"\";\n }\n else{\n wordCnt[temp]--;\n temp = \"\";\n }\n }\n }\n temp += s[i];\n }\n if(wordCnt.find(temp) == wordCnt.end())return false;\n else{\n if(wordCnt[temp] == 1){\n wordCnt.erase(temp);\n temp = \"\";\n }\n else{\n wordCnt[temp]--;\n temp = \"\";\n }\n }\n return wordCnt.size() == 0;\n }\n vector<int> findSubstring(string a, vector<string> &b) {\n if(a.size() == 0 || b.size() == 0)return {};\n unordered_map <string, int> wordCnt;\n for(int i = 0; i < b.size(); i++)wordCnt[b[i]]++;\n vector <int> ans;\n int window = b.size() * b[0].size();\n string temp =\"\";\n for(int i = 0; i < window; i++)temp += a[i];\n for(int i = window; i < a.size(); i++){\n if(temp.size() % window == 0 && ok(temp, wordCnt, b[0].size())){\n ans.push_back(i - window);\n }\n temp += a[i];\n if(temp.size() > window)temp.erase(0, 1);\n }\n if(temp .size() % window ==0 && ok(temp, wordCnt, b[0].size()))ans.push_back(a.size() - window);\n return ans;\n }\n};\nmain(){\n vector<string> v = {\"foo\", \"bar\"};\n Solution ob;\n print_vector(ob.findSubstring(\"barfoothefoobarman\", v));\n}" }, { "code": null, "e": 7357, "s": 7341, "text": "1,2,3,4,5,6,7\n3" }, { "code": null, "e": 7366, "s": 7357, "text": "[0, 9, ]" } ]
Calculate age from date of birth in MySQL?
To calculate age from date of birth, you can use the below syntax − select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName; Let us first create a table − mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentDOB datetime ); Query OK, 0 rows affected (0.61 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(StudentDOB) values('1996-01-12'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentDOB) values('1990-12-31'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentDOB) values('1989-04-01'); Query OK, 1 row affected (0.45 sec) mysql> insert into DemoTable(StudentDOB) values('2000-06-17'); Query OK, 1 row affected (0.16 sec) Following is the query to display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+---------------------+ | StudentId | StudentDOB | +-----------+---------------------+ | 1 | 1996-01-12 00:00:00 | | 2 | 1990-12-31 00:00:00 | | 3 | 1989-04-01 00:00:00 | | 4 | 2000-06-17 00:00:00 | +-----------+---------------------+ 4 rows in set (0.00 sec) Here is the query to calculate age from date of birth − mysql> select timestampdiff(YEAR,StudentDOB,now()) AS AGE from DemoTable; This will produce the following output − +------+ | AGE | +------+ | 23 | | 28 | | 30 | | 18 | +------+ 4 rows in set (0.03 sec)
[ { "code": null, "e": 1130, "s": 1062, "text": "To calculate age from date of birth, you can use the below syntax −" }, { "code": null, "e": 1214, "s": 1130, "text": "select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName;" }, { "code": null, "e": 1244, "s": 1214, "text": "Let us first create a table −" }, { "code": null, "e": 1393, "s": 1244, "text": "mysql> create table DemoTable\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentDOB datetime\n);\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1449, "s": 1393, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1845, "s": 1449, "text": "mysql> insert into DemoTable(StudentDOB) values('1996-01-12');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentDOB) values('1990-12-31');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentDOB) values('1989-04-01');\nQuery OK, 1 row affected (0.45 sec)\nmysql> insert into DemoTable(StudentDOB) values('2000-06-17');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1931, "s": 1845, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1962, "s": 1931, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2003, "s": 1962, "text": "This will produce the following output −" }, { "code": null, "e": 2316, "s": 2003, "text": "+-----------+---------------------+\n| StudentId | StudentDOB |\n+-----------+---------------------+\n| 1 | 1996-01-12 00:00:00 |\n| 2 | 1990-12-31 00:00:00 |\n| 3 | 1989-04-01 00:00:00 |\n| 4 | 2000-06-17 00:00:00 |\n+-----------+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2372, "s": 2316, "text": "Here is the query to calculate age from date of birth −" }, { "code": null, "e": 2446, "s": 2372, "text": "mysql> select timestampdiff(YEAR,StudentDOB,now()) AS AGE from DemoTable;" }, { "code": null, "e": 2487, "s": 2446, "text": "This will produce the following output −" }, { "code": null, "e": 2584, "s": 2487, "text": "+------+\n| AGE |\n+------+\n| 23 |\n| 28 |\n| 30 |\n| 18 |\n+------+\n4 rows in set (0.03 sec)" } ]
What are the differences between an Integer and an int in Java?
The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two’s complement integer whereas an Integer is a class that wraps a primitive type int in an object. An Integer can be used as an argument to a method that requires an object, whereas int can be used as an argument to a method that requires an integer value, that can be used for arithmetic expression. An int datatype helps to store integer values in memory whereas Integer helps to convert int into an object and to convert an object into an int. The variable of int type is mutable unless it is marked as final and the Integer class contains one int value and is immutable. Live Demo public class PrimitiveDataTypeTest { public static void main(String []args) { // Declaration of int int a = 20; int b = 40; int result = a+b; System.out.println("Result is: " + result); } } Result is: 60 Live Demo public class WrapperClassTest { public static void main(String []args) { int a = 20; Integer b = Integer.valueOf(a); System.out.println("Converted Value of b is: " + b); Integer c = new Integer(30); int d = c.intValue(); System.out.println("Converted Value of d is: " + d); } } Converted Value of b is: 20 Converted Value of d is: 30
[ { "code": null, "e": 1186, "s": 1062, "text": "The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type." }, { "code": null, "e": 1335, "s": 1186, "text": "An int is a data type that stores 32-bit signed two’s complement integer whereas an Integer is a class that wraps a primitive type int in an object." }, { "code": null, "e": 1537, "s": 1335, "text": "An Integer can be used as an argument to a method that requires an object, whereas int can be used as an argument to a method that requires an integer value, that can be used for arithmetic expression." }, { "code": null, "e": 1683, "s": 1537, "text": "An int datatype helps to store integer values in memory whereas Integer helps to convert int into an object and to convert an object into an int." }, { "code": null, "e": 1811, "s": 1683, "text": "The variable of int type is mutable unless it is marked as final and the Integer class contains one int value and is immutable." }, { "code": null, "e": 1821, "s": 1811, "text": "Live Demo" }, { "code": null, "e": 2047, "s": 1821, "text": "public class PrimitiveDataTypeTest {\n public static void main(String []args) {\n // Declaration of int\n int a = 20;\n int b = 40;\n int result = a+b;\n System.out.println(\"Result is: \" + result);\n }\n}" }, { "code": null, "e": 2061, "s": 2047, "text": "Result is: 60" }, { "code": null, "e": 2071, "s": 2061, "text": "Live Demo" }, { "code": null, "e": 2391, "s": 2071, "text": "public class WrapperClassTest {\n public static void main(String []args) {\n int a = 20;\n Integer b = Integer.valueOf(a);\n System.out.println(\"Converted Value of b is: \" + b);\n Integer c = new Integer(30);\n int d = c.intValue();\n System.out.println(\"Converted Value of d is: \" + d);\n }\n}" }, { "code": null, "e": 2447, "s": 2391, "text": "Converted Value of b is: 20\nConverted Value of d is: 30" } ]
Lexicographically smallest string formed repeatedly deleting character from substring 10 - GeeksforGeeks
22 Jul, 2021 Given a binary string S of length N, the task is to find lexicographically the smallest string formed after modifying the string by selecting any substring “10” and removing any one of the characters from that substring, any number of times. Examples: Input: S = “0101”Output: 001Explanation:Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S to “001”, which is the smallest. Input: S =”11001101′′Output: 0001Explanation:One possible way to obtain Lexicographically the smallest string is: Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S as S = “1001101”.Removing the S[0](=1) from the substring, “10” over the range [0, 1] modifies the string S as S = “001101”.Removing the S[3](=1) from the substring, “10” over the range [3, 4] modifies the string S as S = “00101”.Removing the S[2](=1) from the substring, “10” over the range [2, 3] modifies the string S as S = “0001”.Now any character can not be removed. Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S as S = “1001101”. Removing the S[0](=1) from the substring, “10” over the range [0, 1] modifies the string S as S = “001101”. Removing the S[3](=1) from the substring, “10” over the range [3, 4] modifies the string S as S = “00101”. Removing the S[2](=1) from the substring, “10” over the range [2, 3] modifies the string S as S = “0001”. Now any character can not be removed. Therefore, the lexicographically smallest obtained string is “0001”. Approach: The given problem can be solved based on the following observations: It can be observed that the character ‘1‘ after the last zero can not be removed as one will not be able to find any “10” substring. Lexicographically, the smallest string will contain as much as zero as it can before the first one. It can be observed that every ‘1‘ can be deleted if there is at least one ‘0‘ after it. Therefore, the idea is to remove all the ones before the last occurring ‘0‘ from the string. Follow the steps below to solve the problem: Initialize two variables, say ans and LastZe, to store the resulting string and the index of last occurring ‘0‘. Iterate over the characters of string S using the variable i and then if S[i] is ‘0‘ then assign i to LastZe. Iterate over the characters of string S using the variable i and perform the following operations:If S[i] = ‘0’ and i ≤ LastZe, then append S[i] to ans.Otherwise, if i > LastZe, then append S[i] to ans. If S[i] = ‘0’ and i ≤ LastZe, then append S[i] to ans. Otherwise, if i > LastZe, then append S[i] to ans. Finally, after completing the above steps, print the result as ans. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find smallest lexicogra-// phically smallest stringstring lexicographicallySmallestString(string S, int N){ // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string string ans; // Traverse the string S for (int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S[i] == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for (int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S[i] == '0') ans += S[i]; // If i is greater than lastZe else if (i > LastZe) ans += S[i]; } // Return ans return ans;} // Driver Codeint main(){ // Input string S = "11001101"; int N = S.size(); // Function Call cout << lexicographicallySmallestString(S, N); return 0;} // Java program for the above approachimport java.lang.*;import java.util.*; class GFG{ // Function to find smallest lexicogra-// phically smallest stringstatic String lexicographicallySmallestString(String S, int N){ // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string String ans = ""; // Traverse the string S for(int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S.charAt(i) == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for(int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S.charAt(i) == '0') ans += S.charAt(i); // If i is greater than lastZe else if (i > LastZe) ans += S.charAt(i); } // Return ans return ans;} // Driver codepublic static void main(String[] args){ // Input String S = "11001101"; int N = S.length(); // Function Call System.out.println( lexicographicallySmallestString(S, N));}} // This code is contributed by avijitmondal1998 # Python program for the above approach # Function to find smallest lexicogra-# phically smallest stringdef lexicographicallySmallestString(S, N): # Stores the index of last # occuring 0 LastZe = -1 # Stores the lexicographically # smallest string ans = "" # Traverse the S for i in range(N - 1, -1, -1): # If str[i] is 0 if (S[i] == '0'): # Assign i to lastZe LastZe = i break # Traverse the str for i in range(N): # If i is less than or equal # to lastZe and str[i] is 0 if (i <= LastZe and S[i] == '0'): ans += S[i] # If i is greater than lastZe elif (i > LastZe): ans += S[i] # Return ans return ans # Driver Codeif __name__ == '__main__': # Input S = "11001101" N = len(S) # Function Call print (lexicographicallySmallestString(S, N)) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;class GFG { // Function to find smallest lexicogra- // phically smallest string static string lexicographicallySmallestString(string S, int N) { // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string string ans = ""; // Traverse the string S for (int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S[i] == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for (int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S[i] == '0') ans += S[i]; // If i is greater than lastZe else if (i > LastZe) ans += S[i]; } // Return ans return ans; } // Driver Code public static void Main() { // Input string S = "11001101"; int N = S.Length; // Function Call Console.Write( lexicographicallySmallestString(S, N)); }} // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to find smallest lexicogra-// phically smallest stringfunction lexicographicallySmallestString(S, N){ // Stores the index of last // occuring 0 var LastZe = -1; // Stores the lexicographically // smallest string var ans = ""; // Traverse the string S for(var i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S.charAt(i) == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for(var i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S.charAt(i) == '0') ans += S.charAt(i); // If i is greater than lastZe else if (i > LastZe) ans += S.charAt(i); } // Return ans return ans;} // Driver code // Inputvar S = "11001101";var N = S.length; // Function Calldocument.write(lexicographicallySmallestString(S, N)); // This code is contributed by shivanisinghss2110 </script> 0001 Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 ukasp avijitmondal1998 shivanisinghss2110 lexicographic-ordering substring Game Theory Searching Strings Searching Strings Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Classification of Algorithms with Examples Moving on grid A modified game of Nim The prisoner's dilemma in Game theory A Binary String Game Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25260, "s": 25232, "text": "\n22 Jul, 2021" }, { "code": null, "e": 25502, "s": 25260, "text": "Given a binary string S of length N, the task is to find lexicographically the smallest string formed after modifying the string by selecting any substring “10” and removing any one of the characters from that substring, any number of times." }, { "code": null, "e": 25512, "s": 25502, "text": "Examples:" }, { "code": null, "e": 25676, "s": 25512, "text": "Input: S = “0101”Output: 001Explanation:Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S to “001”, which is the smallest." }, { "code": null, "e": 25790, "s": 25676, "text": "Input: S =”11001101′′Output: 0001Explanation:One possible way to obtain Lexicographically the smallest string is:" }, { "code": null, "e": 26262, "s": 25790, "text": "Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S as S = “1001101”.Removing the S[0](=1) from the substring, “10” over the range [0, 1] modifies the string S as S = “001101”.Removing the S[3](=1) from the substring, “10” over the range [3, 4] modifies the string S as S = “00101”.Removing the S[2](=1) from the substring, “10” over the range [2, 3] modifies the string S as S = “0001”.Now any character can not be removed." }, { "code": null, "e": 26373, "s": 26262, "text": "Removing the S[1](=1) from the substring, “10” over the range [1, 2] modifies the string S as S = “1001101”." }, { "code": null, "e": 26483, "s": 26373, "text": "Removing the S[0](=1) from the substring, “10” over the range [0, 1] modifies the string S as S = “001101”." }, { "code": null, "e": 26592, "s": 26483, "text": "Removing the S[3](=1) from the substring, “10” over the range [3, 4] modifies the string S as S = “00101”." }, { "code": null, "e": 26700, "s": 26592, "text": "Removing the S[2](=1) from the substring, “10” over the range [2, 3] modifies the string S as S = “0001”." }, { "code": null, "e": 26738, "s": 26700, "text": "Now any character can not be removed." }, { "code": null, "e": 26807, "s": 26738, "text": "Therefore, the lexicographically smallest obtained string is “0001”." }, { "code": null, "e": 26888, "s": 26807, "text": " Approach: The given problem can be solved based on the following observations: " }, { "code": null, "e": 27021, "s": 26888, "text": "It can be observed that the character ‘1‘ after the last zero can not be removed as one will not be able to find any “10” substring." }, { "code": null, "e": 27121, "s": 27021, "text": "Lexicographically, the smallest string will contain as much as zero as it can before the first one." }, { "code": null, "e": 27209, "s": 27121, "text": "It can be observed that every ‘1‘ can be deleted if there is at least one ‘0‘ after it." }, { "code": null, "e": 27302, "s": 27209, "text": "Therefore, the idea is to remove all the ones before the last occurring ‘0‘ from the string." }, { "code": null, "e": 27347, "s": 27302, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27460, "s": 27347, "text": "Initialize two variables, say ans and LastZe, to store the resulting string and the index of last occurring ‘0‘." }, { "code": null, "e": 27570, "s": 27460, "text": "Iterate over the characters of string S using the variable i and then if S[i] is ‘0‘ then assign i to LastZe." }, { "code": null, "e": 27773, "s": 27570, "text": "Iterate over the characters of string S using the variable i and perform the following operations:If S[i] = ‘0’ and i ≤ LastZe, then append S[i] to ans.Otherwise, if i > LastZe, then append S[i] to ans." }, { "code": null, "e": 27828, "s": 27773, "text": "If S[i] = ‘0’ and i ≤ LastZe, then append S[i] to ans." }, { "code": null, "e": 27879, "s": 27828, "text": "Otherwise, if i > LastZe, then append S[i] to ans." }, { "code": null, "e": 27947, "s": 27879, "text": "Finally, after completing the above steps, print the result as ans." }, { "code": null, "e": 27998, "s": 27947, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28002, "s": 27998, "text": "C++" }, { "code": null, "e": 28007, "s": 28002, "text": "Java" }, { "code": null, "e": 28015, "s": 28007, "text": "Python3" }, { "code": null, "e": 28018, "s": 28015, "text": "C#" }, { "code": null, "e": 28029, "s": 28018, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find smallest lexicogra-// phically smallest stringstring lexicographicallySmallestString(string S, int N){ // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string string ans; // Traverse the string S for (int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S[i] == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for (int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S[i] == '0') ans += S[i]; // If i is greater than lastZe else if (i > LastZe) ans += S[i]; } // Return ans return ans;} // Driver Codeint main(){ // Input string S = \"11001101\"; int N = S.size(); // Function Call cout << lexicographicallySmallestString(S, N); return 0;}", "e": 29085, "s": 28029, "text": null }, { "code": "// Java program for the above approachimport java.lang.*;import java.util.*; class GFG{ // Function to find smallest lexicogra-// phically smallest stringstatic String lexicographicallySmallestString(String S, int N){ // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string String ans = \"\"; // Traverse the string S for(int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S.charAt(i) == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for(int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S.charAt(i) == '0') ans += S.charAt(i); // If i is greater than lastZe else if (i > LastZe) ans += S.charAt(i); } // Return ans return ans;} // Driver codepublic static void main(String[] args){ // Input String S = \"11001101\"; int N = S.length(); // Function Call System.out.println( lexicographicallySmallestString(S, N));}} // This code is contributed by avijitmondal1998", "e": 30370, "s": 29085, "text": null }, { "code": "# Python program for the above approach # Function to find smallest lexicogra-# phically smallest stringdef lexicographicallySmallestString(S, N): # Stores the index of last # occuring 0 LastZe = -1 # Stores the lexicographically # smallest string ans = \"\" # Traverse the S for i in range(N - 1, -1, -1): # If str[i] is 0 if (S[i] == '0'): # Assign i to lastZe LastZe = i break # Traverse the str for i in range(N): # If i is less than or equal # to lastZe and str[i] is 0 if (i <= LastZe and S[i] == '0'): ans += S[i] # If i is greater than lastZe elif (i > LastZe): ans += S[i] # Return ans return ans # Driver Codeif __name__ == '__main__': # Input S = \"11001101\" N = len(S) # Function Call print (lexicographicallySmallestString(S, N)) # This code is contributed by mohit kumar 29.", "e": 31329, "s": 30370, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { // Function to find smallest lexicogra- // phically smallest string static string lexicographicallySmallestString(string S, int N) { // Stores the index of last // occuring 0 int LastZe = -1; // Stores the lexicographically // smallest string string ans = \"\"; // Traverse the string S for (int i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S[i] == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for (int i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S[i] == '0') ans += S[i]; // If i is greater than lastZe else if (i > LastZe) ans += S[i]; } // Return ans return ans; } // Driver Code public static void Main() { // Input string S = \"11001101\"; int N = S.Length; // Function Call Console.Write( lexicographicallySmallestString(S, N)); }} // This code is contributed by ukasp.", "e": 32647, "s": 31329, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find smallest lexicogra-// phically smallest stringfunction lexicographicallySmallestString(S, N){ // Stores the index of last // occuring 0 var LastZe = -1; // Stores the lexicographically // smallest string var ans = \"\"; // Traverse the string S for(var i = N - 1; i >= 0; i--) { // If str[i] is 0 if (S.charAt(i) == '0') { // Assign i to lastZe LastZe = i; break; } } // Traverse the string str for(var i = 0; i < N; i++) { // If i is less than or equal // to lastZe and str[i] is 0 if (i <= LastZe && S.charAt(i) == '0') ans += S.charAt(i); // If i is greater than lastZe else if (i > LastZe) ans += S.charAt(i); } // Return ans return ans;} // Driver code // Inputvar S = \"11001101\";var N = S.length; // Function Calldocument.write(lexicographicallySmallestString(S, N)); // This code is contributed by shivanisinghss2110 </script>", "e": 33764, "s": 32647, "text": null }, { "code": null, "e": 33769, "s": 33764, "text": "0001" }, { "code": null, "e": 33812, "s": 33769, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 33827, "s": 33812, "text": "mohit kumar 29" }, { "code": null, "e": 33833, "s": 33827, "text": "ukasp" }, { "code": null, "e": 33850, "s": 33833, "text": "avijitmondal1998" }, { "code": null, "e": 33869, "s": 33850, "text": "shivanisinghss2110" }, { "code": null, "e": 33892, "s": 33869, "text": "lexicographic-ordering" }, { "code": null, "e": 33902, "s": 33892, "text": "substring" }, { "code": null, "e": 33914, "s": 33902, "text": "Game Theory" }, { "code": null, "e": 33924, "s": 33914, "text": "Searching" }, { "code": null, "e": 33932, "s": 33924, "text": "Strings" }, { "code": null, "e": 33942, "s": 33932, "text": "Searching" }, { "code": null, "e": 33950, "s": 33942, "text": "Strings" }, { "code": null, "e": 33962, "s": 33950, "text": "Game Theory" }, { "code": null, "e": 34060, "s": 33962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34103, "s": 34060, "text": "Classification of Algorithms with Examples" }, { "code": null, "e": 34118, "s": 34103, "text": "Moving on grid" }, { "code": null, "e": 34141, "s": 34118, "text": "A modified game of Nim" }, { "code": null, "e": 34179, "s": 34141, "text": "The prisoner's dilemma in Game theory" }, { "code": null, "e": 34200, "s": 34179, "text": "A Binary String Game" }, { "code": null, "e": 34214, "s": 34200, "text": "Binary Search" }, { "code": null, "e": 34282, "s": 34214, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34296, "s": 34282, "text": "Linear Search" }, { "code": null, "e": 34320, "s": 34296, "text": "Find the Missing Number" } ]
RESTful Web Services - Quick Guide
REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000. In REST architecture, a REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML. JSON is the most popular one. Following four HTTP methods are commonly used in REST based architecture. GET − Provides a read only access to a resource. GET − Provides a read only access to a resource. POST − Used to create a new resource. POST − Used to create a new resource. DELETE − Used to remove a resource. DELETE − Used to remove a resource. PUT − Used to update a existing resource or create a new resource. PUT − Used to update a existing resource or create a new resource. A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards. Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods. In next chapters, we'll create a webservice say user management with following functionalities − This tutorial will guide you on how to prepare a development environment to start your work with Jersey Framework to create RESTful Web Services. Jersey framework implements JAX-RS 2.0 API, which is a standard specification to create RESTful Web Services. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you the Jersey Framework is setup. You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find the instructions for installing JDK in the downloaded files. Follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains Java and Javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:\jdk1.7.0_75, you would have to put the following line in your C:\autoexec.bat file. set PATH = C:\jdk1.7.0_75\bin;%PATH% set JAVA_HOME = C:\jdk1.7.0_75 Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer → select Properties → then Advanced → then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C Shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.7.0_75 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE. All the examples in this tutorial have been written using the Eclipse IDE. So, I would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution to a convenient location. For example, in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set the PATH variable appropriately. Eclipse can be started by executing the following commands on a windows machine, or you can simply double click on eclipse.exe. %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine, then your screen should display the following result − Now, if everything is fine, then you can proceed to setup the Jersey framework. Following are a few simple steps to download and install the framework on your machine. Make a choice whether you want to install Jersey on Windows, or Unix and then proceed to the next step to download the .zip file for windows and then the .tz file for Unix. Make a choice whether you want to install Jersey on Windows, or Unix and then proceed to the next step to download the .zip file for windows and then the .tz file for Unix. Download the latest version of Jersey framework binaries from the following link – https://jersey.java.net/download.html. Download the latest version of Jersey framework binaries from the following link – https://jersey.java.net/download.html. At the time of writing this tutorial, I downloaded jaxrs-ri-2.17.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside E:\jaxrs-ri-2.17\jaxrs-ri as shown in the following screenshot. At the time of writing this tutorial, I downloaded jaxrs-ri-2.17.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside E:\jaxrs-ri-2.17\jaxrs-ri as shown in the following screenshot. You will find all the Jersey libraries in the directories C:\jaxrs-ri-2.17\jaxrs-ri\lib and dependencies in C:\jaxrs-ri-2.17\jaxrs-ri\ext. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face problem while running your application. If you are using Eclipse, then it is not required to set the CLASSPATH because all the settings will be done through Eclipse. You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-7.0.59 on windows, or /usr/local/apache-tomcat-7.0.59 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations. Tomcat can be started by executing the following commands on a windows machine, or you can simply double click on startup.bat. %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-7.0.59\bin\startup.bat Tomcat can be started by executing the following commands on a Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-7.0.59/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display the following result − Further information about configuring and running Tomcat can be found in the documentation included on this page. This information can also be found on the Tomcat website − https://tomcat.apache.org. Tomcat can be stopped by executing the following commands on a windows machine − %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-7.0.59\bin\shutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-7.0.59/bin/shutdown.sh Once you are done with this last step, you are ready to proceed for your first Jersey example which you will see in the next chapter. Let us start writing the actual RESTful web services with Jersey Framework. Before you start writing your first example using the Jersey Framework, you have to make sure that you have setup your Jersey environment properly as explained in the RESTful Web Services - Environment Setup chapter. Here, I am also assuming that you have a little working knowledge of Eclipse IDE. So, let us proceed to write a simple Jersey Application which will expose a web service method to display the list of users. The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File → New → Project and finally select the Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as shown in the following screenshot − Once your project is created successfully, you will have the following content in your Project Explorer − As a second step let us add Jersey Framework and its dependencies (libraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/lib directory of the project. \jaxrs-ri-2.17\jaxrs-ri\api \jaxrs-ri-2.17\jaxrs-ri\ext \jaxrs-ri-2.17\jaxrs-ri\lib Now, right click on your project name UserManagement and then follow the option available in context menu − Build Path → Configure Build Path to display the Java Build Path window. Now use Add JARs button available under Libraries tab to add the JARs present in WEBINF/lib directory. Now let us create the actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package. Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package. User.java package com.tutorialspoint; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; private String profession; public User(){} public User(int id, String name, String profession){ this.id = id; this.name = name; this.profession = profession; } public int getId() { return id; } @XmlElement public void setId(int id) { this.id = id; } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public String getProfession() { return profession; } @XmlElement public void setProfession(String profession) { this.profession = profession; } } UserDao.java package com.tutorialspoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class UserDao { public List<User> getAllUsers(){ List<User> userList = null; try { File file = new File("Users.dat"); if (!file.exists()) { User user = new User(1, "Mahesh", "Teacher"); userList = new ArrayList<User>(); userList.add(user); saveUserList(userList); } else{ FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); userList = (List<User>) ois.readObject(); ois.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return userList; } private void saveUserList(List<User> userList){ try { File file = new File("Users.dat"); FileOutputStream fos; fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(userList); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } UserService.java package com.tutorialspoint; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/UserService") public class UserService { UserDao userDao = new UserDao(); @GET @Path("/users") @Produces(MediaType.APPLICATION_XML) public List<User> getUsers(){ return userDao.getAllUsers(); } } There are two important points to be noted about the main program, The first step is to specify a path for the web service using @Path annotation to the UserService. The first step is to specify a path for the web service using @Path annotation to the UserService. The second step is to specify a path for the particular web service method using @Path annotation to method of UserService. The second step is to specify a path for the particular web service method using @Path annotation to method of UserService. You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our application. web.xml <?xml version = "1.0" encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name>User Management</display-name> <servlet> <servlet-name>Jersey RESTful Application</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.tutorialspoint</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Jersey RESTful Application</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> Once you are done with creating source and web configuration files, you are ready for this step which is compiling and running your program. To do this, using Eclipse, export your application as a war file and deploy the same in tomcat. To create a WAR file using eclipse, follow the option File → export → Web → War File and finally select project UserManagement and destination folder. To deploy a war file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and start the Tomcat. We are using Postman, a Chrome extension, to test our webservices. Make a request to UserManagement to get list of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the following result. Congratulations, you have created your first RESTful Application successfully. REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON. A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format. For example, in RESTful Web Services - First Application chapter, a user is a resource which is represented using the following XML format − <user> <id>1</id> <name>Mahesh</name> <profession>Teacher</profession> </user> The same resource can be represented in JSON format as follows − { "id":1, "name":"Mahesh", "profession":"Teacher" } REST does not impose any restriction on the format of a resource representation. A client can ask for JSON representation whereas another client may ask for XML representation of the same resource to the server and so on. It is the responsibility of the REST server to pass the client the resource in the format that the client understands. Following are some important points to be considered while designing a representation format of a resource in RESTful Web Services. Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource. Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource. Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources. Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources. Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations. Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations. However, at present most of the web services are representing resources using either XML or JSON format. There are plenty of libraries and tools available to understand, parse, and modify XML and JSON data. RESTful Web Services make use of HTTP protocols as a medium of communication between client and server. A client sends a message in form of a HTTP Request and the server responds in the form of an HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself. Let us have a look on the HTTP Request and HTTP Response messages for HTTP 1.1. An HTTP Request has five major parts − Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc. Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc. URI − Uniform Resource Identifier (URI) to identify the resource on the server. URI − Uniform Resource Identifier (URI) to identify the resource on the server. HTTP Version − Indicates the HTTP version. For example, HTTP v1.1. HTTP Version − Indicates the HTTP version. For example, HTTP v1.1. Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc. Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc. Request Body − Message content or Resource representation. Request Body − Message content or Resource representation. An HTTP Response has four major parts − Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok. Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok. HTTP Version − Indicates the HTTP version. For example HTTP v1.1. HTTP Version − Indicates the HTTP version. For example HTTP v1.1. Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc. Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc. Response Body − Response message content or Resource representation. Response Body − Response message content or Resource representation. As we have explained in the RESTful Web Services - First Application chapter, let us put http://localhost:8080/UserManagement/rest/UserService/users in the POSTMAN with a GET request. If you click on the Preview button which is near the send button of Postman and then click on the Send button, you may see the following output. Here you can see, the browser sent a GET request and received a response body as XML. Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person. Each resource in REST architecture is identified by its URI (Uniform Resource Identifier). A URI is of the following format − <protocol>://<service-name>/<ResourceType>/<ResourceID> Purpose of an URI is to locate a resource(s) on the server hosting the web service. Another important attribute of a request is VERB which identifies the operation to be performed on the resource. For example, in RESTful Web Services - First Application chapter, the URI is http://localhost:8080/UserManagement/rest/UserService/users and the VERB is GET. The following are important points to be considered while designing a URI − Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource. Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource. Avoid using spaces − Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users. Avoid using spaces − Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users. Use lowercase letters − Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only. Use lowercase letters − Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only. Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300. Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300. Use HTTP Verb − Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI. Use HTTP Verb − Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI. Following is an example of a poor URI to fetch a user. http://localhost:8080/UserManagement/rest/UserService/getUser/1 Following is an example of a good URI to fetch a user. http://localhost:8080/UserManagement/rest/UserService/users/1 As we have discussed in the earlier chapters that RESTful Web Service uses a lot of HTTP verbs to determine the operation to be carried out on the specified resource(s). The following table states the examples of the most commonly used HTTP Verbs. GET http://localhost:8080/UserManagement/rest/UserService/users Gets the list of users. (Read Only) 2 GET http://localhost:8080/UserManagement/rest/UserService/users/1 Gets the User of Id 1 (Read Only) 3 PUT http://localhost:8080/UserManagement/rest/UserService/users/2 Inserts User with Id 2 (Idempotent) 4 POST http://localhost:8080/UserManagement/rest/UserService/users/2 Updates the User with Id 2 (N/A) 5 DELETE http://localhost:8080/UserManagement/rest/UserService/users/1 Deletes the User with Id 1 (Idempotent) 6 OPTIONS http://localhost:8080/UserManagement/rest/UserService/users Lists out the supported operations in a web service. (Read Only) 7 HEAD http://localhost:8080/UserManagement/rest/UserService/users Returns the HTTP Header only, no Body. (Read Only) The following points are to be considered. GET operations are read only and are safe. GET operations are read only and are safe. PUT and DELETE operations are idempotent, which means their result will always be the same, no matter how many times these operations are invoked. PUT and DELETE operations are idempotent, which means their result will always be the same, no matter how many times these operations are invoked. PUT and POST operation are nearly the same with the difference lying only in the result where the PUT operation is idempotent and POST operation can cause a different result. PUT and POST operation are nearly the same with the difference lying only in the result where the PUT operation is idempotent and POST operation can cause a different result. Let us update an Example created in the RESTful Web Services - First Application chapter to create a Web service which can perform CRUD (Create, Read, Update, Delete) operations. For simplicity, we have used a file I/O to replace Database operations. Let us update the User.java, UserDao.java and UserService.java files under the com.tutorialspoint package. package com.tutorialspoint; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; private String profession; public User(){} public User(int id, String name, String profession){ this.id = id; this.name = name; this.profession = profession; } public int getId() { return id; } @XmlElement public void setId(int id) { this.id = id; } public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public String getProfession() { return profession; } @XmlElement public void setProfession(String profession) { this.profession = profession; } @Override public boolean equals(Object object){ if(object == null){ return false; }else if(!(object instanceof User)){ return false; }else { User user = (User)object; if(id == user.getId() && name.equals(user.getName()) && profession.equals(user.getProfession())){ return true; } } return false; } } package com.tutorialspoint; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class UserDao { public List<User> getAllUsers(){ List<User> userList = null; try { File file = new File("Users.dat"); if (!file.exists()) { User user = new User(1, "Mahesh", "Teacher"); userList = new ArrayList<User>(); userList.add(user); saveUserList(userList); } else{ FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); userList = (List<User>) ois.readObject(); ois.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return userList; } public User getUser(int id){ List<User> users = getAllUsers(); for(User user: users){ if(user.getId() == id){ return user; } } return null; } public int addUser(User pUser){ List<User> userList = getAllUsers(); boolean userExists = false; for(User user: userList){ if(user.getId() == pUser.getId()){ userExists = true; break; } } if(!userExists){ userList.add(pUser); saveUserList(userList); return 1; } return 0; } public int updateUser(User pUser){ List<User> userList = getAllUsers(); for(User user: userList){ if(user.getId() == pUser.getId()){ int index = userList.indexOf(user); userList.set(index, pUser); saveUserList(userList); return 1; } } return 0; } public int deleteUser(int id){ List<User> userList = getAllUsers(); for(User user: userList){ if(user.getId() == id){ int index = userList.indexOf(user); userList.remove(index); saveUserList(userList); return 1; } } return 0; } private void saveUserList(List<User> userList){ try { File file = new File("Users.dat"); FileOutputStream fos; fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(userList); oos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } package com.tutorialspoint; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; @Path("/UserService") public class UserService { UserDao userDao = new UserDao(); private static final String SUCCESS_RESULT = "<result>success</result>"; private static final String FAILURE_RESULT = "<result>failure</result>"; @GET @Path("/users") @Produces(MediaType.APPLICATION_XML) public List<User> getUsers(){ return userDao.getAllUsers(); } @GET @Path("/users/{userid}") @Produces(MediaType.APPLICATION_XML) public User getUser(@PathParam("userid") int userid){ return userDao.getUser(userid); } @PUT @Path("/users") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String createUser(@FormParam("id") int id, @FormParam("name") String name, @FormParam("profession") String profession, @Context HttpServletResponse servletResponse) throws IOException{ User user = new User(id, name, profession); int result = userDao.addUser(user); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @POST @Path("/users") @Produces(MediaType.APPLICATION_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String updateUser(@FormParam("id") int id, @FormParam("name") String name, @FormParam("profession") String profession, @Context HttpServletResponse servletResponse) throws IOException{ User user = new User(id, name, profession); int result = userDao.updateUser(user); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @DELETE @Path("/users/{userid}") @Produces(MediaType.APPLICATION_XML) public String deleteUser(@PathParam("userid") int userid){ int result = userDao.deleteUser(userid); if(result == 1){ return SUCCESS_RESULT; } return FAILURE_RESULT; } @OPTIONS @Path("/users") @Produces(MediaType.APPLICATION_XML) public String getSupportedOperations(){ return "<operations>GET, PUT, POST, DELETE</operations>"; } } Now using Eclipse, export your application as a WAR File and deploy the same in Tomcat. To create a WAR file using eclipse, follow this path – File → export → Web → War File and finally select project UserManagement and the destination folder. To deploy a WAR file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and the start Tomcat. Jersey provides APIs to create a Web Service Client to test web services. We have created a sample test class WebServiceTester.java under the com.tutorialspoint package in the same project. package com.tutorialspoint; import java.util.List; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; public class WebServiceTester { private Client client; private String REST_SERVICE_URL = " http://localhost:8080/UserManagement/rest/UserService/users"; private static final String SUCCESS_RESULT = "<result>success</result>"; private static final String PASS = "pass"; private static final String FAIL = "fail"; private void init(){ this.client = ClientBuilder.newClient(); } public static void main(String[] args){ WebServiceTester tester = new WebServiceTester(); //initialize the tester tester.init(); //test get all users Web Service Method tester.testGetAllUsers(); //test get user Web Service Method tester.testGetUser(); //test update user Web Service Method tester.testUpdateUser(); //test add user Web Service Method tester.testAddUser(); //test delete user Web Service Method tester.testDeleteUser(); } //Test: Get list of all users //Test: Check if list is not empty private void testGetAllUsers(){ GenericType<List<User>> list = new GenericType<List<User>>() {}; List<User> users = client .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .get(list); String result = PASS; if(users.isEmpty()){ result = FAIL; } System.out.println("Test case name: testGetAllUsers, Result: " + result ); } //Test: Get User of id 1 //Test: Check if user is same as sample user private void testGetUser(){ User sampleUser = new User(); sampleUser.setId(1); User user = client .target(REST_SERVICE_URL) .path("/{userid}") .resolveTemplate("userid", 1) .request(MediaType.APPLICATION_XML) .get(User.class); String result = FAIL; if(sampleUser != null && sampleUser.getId() == user.getId()){ result = PASS; } System.out.println("Test case name: testGetUser, Result: " + result ); } //Test: Update User of id 1 //Test: Check if result is success XML. private void testUpdateUser(){ Form form = new Form(); form.param("id", "1"); form.param("name", "suresh"); form.param("profession", "clerk"); String callResult = client .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testUpdateUser, Result: " + result); } //Test: Add User of id 2 //Test: Check if result is success XML. private void testAddUser(){ Form form = new Form(); form.param("id", "2"); form.param("name", "naresh"); form.param("profession", "clerk"); String callResult = client .target(REST_SERVICE_URL) .request(MediaType.APPLICATION_XML) .put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testAddUser, Result: " + result ); } //Test: Delete User of id 2 //Test: Check if result is success XML. private void testDeleteUser(){ String callResult = client .target(REST_SERVICE_URL) .path("/{userid}") .resolveTemplate("userid", 2) .request(MediaType.APPLICATION_XML) .delete(String.class); String result = PASS; if(!SUCCESS_RESULT.equals(callResult)){ result = FAIL; } System.out.println("Test case name: testDeleteUser, Result: " + result); } } Now run the tester using Eclipse. Right click on the file and follow the option Run as → Java Application. You will see the following result in the Eclipse console − Test case name: testGetAllUsers, Result: pass Test case name: testGetUser, Result: pass Test case name: testUpdateUser, Result: pass Test case name: testAddUser, Result: pass Test case name: testDeleteUser, Result: pass As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client. RESTful Web Services should adhere to this restriction. We have seen this in the RESTful Web Services - Methods chapter, that the web service methods are not storing any information from the client they are invoked from. Consider the following URL − https://localhost:8080/UserManagement/rest/UserService/users/1 If you hit the above url using your browser or using a java based client or using Postman, result will always be the User XML whose Id is 1 because the server does not store any information about the client. <user> <id>1</id> <name>mahesh</name> <profession>1</profession> </user> Following are the benefits of statelessness in RESTful Web Services − Web services can treat each method request independently. Web services can treat each method request independently. Web services need not maintain the client's previous interactions. It simplifies the application design. Web services need not maintain the client's previous interactions. It simplifies the application design. As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols. As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols. Following are the disadvantages of statelessness in RESTful Web Services − Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of. Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of. Caching refers to storing the server response in the client itself, so that a client need not make a server request for the same resource again and again. A server response should have information about how caching is to be done, so that a client caches the response for a time-period or never caches the server response. Following are the headers which a server response can have in order to configure a client's caching − 1 Date Date and Time of the resource when it was created. 2 Last Modified Date and Time of the resource when it was last modified. 3 Cache-Control Primary header to control caching. 4 Expires Expiration date and time of caching. 5 Age Duration in seconds from when resource was fetched from the server. Following are the details of a Cache-Control header − 1 Public Indicates that resource is cacheable by any component. 2 Private Indicates that resource is cacheable only by the client and the server, no intermediary can cache the resource. 3 no-cache/no-store Indicates that a resource is not cacheable. 4 max-age Indicates the caching is valid up to max-age in seconds. After this, client has to make another request. 5 must-revalidate Indication to server to revalidate resource if max-age has passed. Always keep static contents like images, CSS, JavaScript cacheable, with expiration date of 2 to 3 days. Always keep static contents like images, CSS, JavaScript cacheable, with expiration date of 2 to 3 days. Never keep expiry date too high. Never keep expiry date too high. Dynamic content should be cached for a few hours only. Dynamic content should be cached for a few hours only. As RESTful Web Services work with HTTP URL Paths, it is very important to safeguard a RESTful Web Service in the same manner as a website is secured. Following are the best practices to be adhered to while designing a RESTful Web Service − Validation − Validate all inputs on the server. Protect your server against SQL or NoSQL injection attacks. Validation − Validate all inputs on the server. Protect your server against SQL or NoSQL injection attacks. Session Based Authentication − Use session based authentication to authenticate a user whenever a request is made to a Web Service method. Session Based Authentication − Use session based authentication to authenticate a user whenever a request is made to a Web Service method. No Sensitive Data in the URL − Never use username, password or session token in a URL, these values should be passed to Web Service via the POST method. No Sensitive Data in the URL − Never use username, password or session token in a URL, these values should be passed to Web Service via the POST method. Restriction on Method Execution − Allow restricted use of methods like GET, POST and DELETE methods. The GET method should not be able to delete data. Restriction on Method Execution − Allow restricted use of methods like GET, POST and DELETE methods. The GET method should not be able to delete data. Validate Malformed XML/JSON − Check for well-formed input passed to a web service method. Validate Malformed XML/JSON − Check for well-formed input passed to a web service method. Throw generic Error Messages − A web service method should use HTTP error messages like 403 to show access forbidden, etc. Throw generic Error Messages − A web service method should use HTTP error messages like 403 to show access forbidden, etc. 1 200 OK − shows success. 2 201 CREATED − when a resource is successfully created using POST or PUT request. Returns link to the newly created resource using the location header. 3 204 NO CONTENT − when response body is empty. For example, a DELETE request. 4 304 NOT MODIFIED − used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location, etc. 5 400 BAD REQUEST − states that an invalid input is provided. For example, validation error, missing data. 6 401 UNAUTHORIZED − states that user is using invalid or wrong authentication token. 7 403 FORBIDDEN − states that the user is not having access to the method being used. For example, Delete access without admin rights. 8 404 NOT FOUND − states that the method is not available. 9 409 CONFLICT − states conflict situation while executing the method. For example, adding duplicate entry. 10 500 INTERNAL SERVER ERROR − states that the server has thrown some exception while executing the method. JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful Web Services. Following are the most commonly used annotations to map a resource as a web service resource. 1 @Path Relative path of the resource class/method. 2 @GET HTTP Get request, used to fetch resource. 3 @PUT HTTP PUT request, used to update resource. 4 @POST HTTP POST request, used to create a new resource. 5 @DELETE HTTP DELETE request, used to delete resource. 6 @HEAD HTTP HEAD request, used to get status of method availability. 7 @Produces States the HTTP Response generated by web service. For example, APPLICATION/XML, TEXT/HTML, APPLICATION/JSON etc. 8 @Consumes States the HTTP Request type. For example, application/x-www-formurlencoded to accept form data in HTTP body during POST request. 9 @PathParam Binds the parameter passed to the method to a value in path. 10 @QueryParam Binds the parameter passed to method to a query parameter in the path. 11 @MatrixParam Binds the parameter passed to the method to a HTTP matrix parameter in path. 12 @HeaderParam Binds the parameter passed to the method to a HTTP header. 13 @CookieParam Binds the parameter passed to the method to a Cookie. 14 @FormParam Binds the parameter passed to the method to a form value. 15 @DefaultValue Assigns a default value to a parameter passed to the method. 16 @Context Context of the resource. For example, HTTPRequest as a context. Note − We have used Jersey, a reference implementation of JAX-RS 2.0 by Oracle, in the RESTful Web Services - First Application and RESTful Web Services - Methods chapters. 71 Lectures 10 hours Chaand Sheikh 27 Lectures 2 hours Vinod Kumar Kayartaya 517 Lectures 57 hours Chaand Sheikh 35 Lectures 3.5 hours Antonio Papa Print Add Notes Bookmark this page
[ { "code": null, "e": 2162, "s": 1855, "text": "REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000." }, { "code": null, "e": 2450, "s": 2162, "text": "In REST architecture, a REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML. JSON is the most popular one." }, { "code": null, "e": 2524, "s": 2450, "text": "Following four HTTP methods are commonly used in REST based architecture." }, { "code": null, "e": 2573, "s": 2524, "text": "GET − Provides a read only access to a resource." }, { "code": null, "e": 2622, "s": 2573, "text": "GET − Provides a read only access to a resource." }, { "code": null, "e": 2660, "s": 2622, "text": "POST − Used to create a new resource." }, { "code": null, "e": 2698, "s": 2660, "text": "POST − Used to create a new resource." }, { "code": null, "e": 2734, "s": 2698, "text": "DELETE − Used to remove a resource." }, { "code": null, "e": 2770, "s": 2734, "text": "DELETE − Used to remove a resource." }, { "code": null, "e": 2837, "s": 2770, "text": "PUT − Used to update a existing resource or create a new resource." }, { "code": null, "e": 2904, "s": 2837, "text": "PUT − Used to update a existing resource or create a new resource." }, { "code": null, "e": 3398, "s": 2904, "text": "A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards." }, { "code": null, "e": 3711, "s": 3398, "text": "Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods." }, { "code": null, "e": 3808, "s": 3711, "text": "In next chapters, we'll create a webservice say user management with following functionalities −" }, { "code": null, "e": 4193, "s": 3808, "text": "This tutorial will guide you on how to prepare a development environment to start your work with Jersey Framework to create RESTful Web Services. Jersey framework implements JAX-RS 2.0 API, which is a standard specification to create RESTful Web Services. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you the Jersey Framework is setup." }, { "code": null, "e": 4601, "s": 4193, "text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find the instructions for installing JDK in the downloaded files. Follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains Java and Javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 4740, "s": 4601, "text": "If you are running Windows and installed the JDK in C:\\jdk1.7.0_75, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 4810, "s": 4740, "text": "set PATH = C:\\jdk1.7.0_75\\bin;%PATH% \nset JAVA_HOME = C:\\jdk1.7.0_75\n" }, { "code": null, "e": 5019, "s": 4810, "text": "Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer → select Properties → then Advanced → then Environment Variables. Then, you would update the PATH value and press the OK button." }, { "code": null, "e": 5177, "s": 5019, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.7.0_75 and you use the C Shell, you would put the following into your .cshrc file." }, { "code": null, "e": 5264, "s": 5177, "text": "setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk1.7.0_75\n" }, { "code": null, "e": 5545, "s": 5264, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE." }, { "code": null, "e": 5713, "s": 5545, "text": "All the examples in this tutorial have been written using the Eclipse IDE. So, I would suggest you should have the latest version of Eclipse installed on your machine." }, { "code": null, "e": 6034, "s": 5713, "text": "To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution to a convenient location. For example, in C:\\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set the PATH variable appropriately." }, { "code": null, "e": 6162, "s": 6034, "text": "Eclipse can be started by executing the following commands on a windows machine, or you can simply double click on eclipse.exe." }, { "code": null, "e": 6187, "s": 6162, "text": "%C:\\eclipse\\eclipse.exe\n" }, { "code": null, "e": 6287, "s": 6187, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 6317, "s": 6287, "text": "$/usr/local/eclipse/eclipse \n" }, { "code": null, "e": 6423, "s": 6317, "text": "After a successful startup, if everything is fine, then your screen should display the following result −" }, { "code": null, "e": 6591, "s": 6423, "text": "Now, if everything is fine, then you can proceed to setup the Jersey framework. Following are a few simple steps to download and install the framework on your machine." }, { "code": null, "e": 6764, "s": 6591, "text": "Make a choice whether you want to install Jersey on Windows, or Unix and then proceed to the next step to download the .zip file for windows and then the .tz file for Unix." }, { "code": null, "e": 6937, "s": 6764, "text": "Make a choice whether you want to install Jersey on Windows, or Unix and then proceed to the next step to download the .zip file for windows and then the .tz file for Unix." }, { "code": null, "e": 7059, "s": 6937, "text": "Download the latest version of Jersey framework binaries from the following link – https://jersey.java.net/download.html." }, { "code": null, "e": 7181, "s": 7059, "text": "Download the latest version of Jersey framework binaries from the following link – https://jersey.java.net/download.html." }, { "code": null, "e": 7423, "s": 7181, "text": "At the time of writing this tutorial, I downloaded jaxrs-ri-2.17.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside E:\\jaxrs-ri-2.17\\jaxrs-ri as shown in the following screenshot." }, { "code": null, "e": 7665, "s": 7423, "text": "At the time of writing this tutorial, I downloaded jaxrs-ri-2.17.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside E:\\jaxrs-ri-2.17\\jaxrs-ri as shown in the following screenshot." }, { "code": null, "e": 8063, "s": 7665, "text": "You will find all the Jersey libraries in the directories C:\\jaxrs-ri-2.17\\jaxrs-ri\\lib and dependencies in C:\\jaxrs-ri-2.17\\jaxrs-ri\\ext. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face problem while running your application. If you are using Eclipse, then it is not required to set the CLASSPATH because all the settings will be done through Eclipse." }, { "code": null, "e": 8422, "s": 8063, "text": "You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\\apache-tomcat-7.0.59 on windows, or /usr/local/apache-tomcat-7.0.59 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations." }, { "code": null, "e": 8549, "s": 8422, "text": "Tomcat can be started by executing the following commands on a windows machine, or you can simply double click on startup.bat." }, { "code": null, "e": 8582, "s": 8549, "text": "%CATALINA_HOME%\\bin\\startup.bat\n" }, { "code": null, "e": 8585, "s": 8582, "text": "or" }, { "code": null, "e": 8627, "s": 8585, "text": "C:\\apache-tomcat-7.0.59\\bin\\startup.bat \n" }, { "code": null, "e": 8728, "s": 8627, "text": "Tomcat can be started by executing the following commands on a Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 8759, "s": 8728, "text": "$CATALINA_HOME/bin/startup.sh\n" }, { "code": null, "e": 8762, "s": 8759, "text": "or" }, { "code": null, "e": 8810, "s": 8762, "text": "/usr/local/apache-tomcat-7.0.59/bin/startup.sh\n" }, { "code": null, "e": 9010, "s": 8810, "text": "After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display the following result −" }, { "code": null, "e": 9210, "s": 9010, "text": "Further information about configuring and running Tomcat can be found in the documentation included on this page. This information can also be found on the Tomcat website − https://tomcat.apache.org." }, { "code": null, "e": 9291, "s": 9210, "text": "Tomcat can be stopped by executing the following commands on a windows machine −" }, { "code": null, "e": 9322, "s": 9291, "text": "%CATALINA_HOME%\\bin\\shutdown \n" }, { "code": null, "e": 9325, "s": 9322, "text": "or" }, { "code": null, "e": 9364, "s": 9325, "text": "C:\\apache-tomcat-7.0.59\\bin\\shutdown \n" }, { "code": null, "e": 9463, "s": 9364, "text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 9496, "s": 9463, "text": "$CATALINA_HOME/bin/shutdown.sh \n" }, { "code": null, "e": 9499, "s": 9496, "text": "or" }, { "code": null, "e": 9548, "s": 9499, "text": "/usr/local/apache-tomcat-7.0.59/bin/shutdown.sh\n" }, { "code": null, "e": 9682, "s": 9548, "text": "Once you are done with this last step, you are ready to proceed for your first Jersey example which you will see in the next chapter." }, { "code": null, "e": 10057, "s": 9682, "text": "Let us start writing the actual RESTful web services with Jersey Framework. Before you start writing your first example using the Jersey Framework, you have to make sure that you have setup your Jersey environment properly as explained in the RESTful Web Services - Environment Setup chapter. Here, I am also assuming that you have a little working knowledge of Eclipse IDE." }, { "code": null, "e": 10182, "s": 10057, "text": "So, let us proceed to write a simple Jersey Application which will expose a web service method to display the list of users." }, { "code": null, "e": 10465, "s": 10182, "text": "The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File → New → Project and finally select the Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as shown in the following screenshot −" }, { "code": null, "e": 10571, "s": 10465, "text": "Once your project is created successfully, you will have the following content in your Project Explorer −" }, { "code": null, "e": 10777, "s": 10571, "text": "As a second step let us add Jersey Framework and its dependencies (libraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/lib directory of the project." }, { "code": null, "e": 10805, "s": 10777, "text": "\\jaxrs-ri-2.17\\jaxrs-ri\\api" }, { "code": null, "e": 10833, "s": 10805, "text": "\\jaxrs-ri-2.17\\jaxrs-ri\\ext" }, { "code": null, "e": 10861, "s": 10833, "text": "\\jaxrs-ri-2.17\\jaxrs-ri\\lib" }, { "code": null, "e": 11042, "s": 10861, "text": "Now, right click on your project name UserManagement and then follow the option available in context menu − Build Path → Configure Build Path to display the Java Build Path window." }, { "code": null, "e": 11145, "s": 11042, "text": "Now use Add JARs button available under Libraries tab to add the JARs present in WEBINF/lib directory." }, { "code": null, "e": 11380, "s": 11145, "text": "Now let us create the actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package." }, { "code": null, "e": 11485, "s": 11380, "text": "Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package." }, { "code": null, "e": 11495, "s": 11485, "text": "User.java" }, { "code": null, "e": 12484, "s": 11495, "text": "package com.tutorialspoint; \n\nimport java.io.Serializable; \nimport javax.xml.bind.annotation.XmlElement; \nimport javax.xml.bind.annotation.XmlRootElement; \n@XmlRootElement(name = \"user\") \n\npublic class User implements Serializable { \n private static final long serialVersionUID = 1L; \n private int id; \n private String name; \n private String profession; \n public User(){} \n \n public User(int id, String name, String profession){ \n this.id = id; \n this.name = name; \n this.profession = profession; \n } \n public int getId() { \n return id; \n } \n @XmlElement \n public void setId(int id) { \n this.id = id; \n } \n public String getName() { \n return name; \n } \n @XmlElement\n public void setName(String name) { \n this.name = name; \n } \n public String getProfession() { \n return profession; \n } \n @XmlElement \n public void setProfession(String profession) { \n this.profession = profession; \n } \n} " }, { "code": null, "e": 12497, "s": 12484, "text": "UserDao.java" }, { "code": null, "e": 14078, "s": 12497, "text": "package com.tutorialspoint; \n\nimport java.io.File; \nimport java.io.FileInputStream; \nimport java.io.FileNotFoundException; \nimport java.io.FileOutputStream; \nimport java.io.IOException; \nimport java.io.ObjectInputStream; \nimport java.io.ObjectOutputStream; \nimport java.util.ArrayList; \nimport java.util.List; \n\npublic class UserDao { \n public List<User> getAllUsers(){ \n \n List<User> userList = null; \n try { \n File file = new File(\"Users.dat\"); \n if (!file.exists()) { \n User user = new User(1, \"Mahesh\", \"Teacher\"); \n userList = new ArrayList<User>(); \n userList.add(user); \n saveUserList(userList); \n } \n else{ \n FileInputStream fis = new FileInputStream(file); \n ObjectInputStream ois = new ObjectInputStream(fis); \n userList = (List<User>) ois.readObject(); \n ois.close(); \n } \n } catch (IOException e) { \n e.printStackTrace(); \n } catch (ClassNotFoundException e) { \n e.printStackTrace(); \n } \n return userList; \n } \n private void saveUserList(List<User> userList){ \n try { \n File file = new File(\"Users.dat\"); \n FileOutputStream fos; \n fos = new FileOutputStream(file); \n ObjectOutputStream oos = new ObjectOutputStream(fos); \n oos.writeObject(userList); \n oos.close(); \n } catch (FileNotFoundException e) { \n e.printStackTrace(); \n } catch (IOException e) { \n e.printStackTrace(); \n } \n } \n}" }, { "code": null, "e": 14095, "s": 14078, "text": "UserService.java" }, { "code": null, "e": 14509, "s": 14095, "text": "package com.tutorialspoint; \n\nimport java.util.List; \nimport javax.ws.rs.GET; \nimport javax.ws.rs.Path; \nimport javax.ws.rs.Produces; \nimport javax.ws.rs.core.MediaType; \n@Path(\"/UserService\") \n\npublic class UserService { \n UserDao userDao = new UserDao(); \n @GET \n @Path(\"/users\") \n @Produces(MediaType.APPLICATION_XML) \n public List<User> getUsers(){ \n return userDao.getAllUsers(); \n } \n}" }, { "code": null, "e": 14576, "s": 14509, "text": "There are two important points to be noted about the main program," }, { "code": null, "e": 14675, "s": 14576, "text": "The first step is to specify a path for the web service using @Path annotation to the UserService." }, { "code": null, "e": 14774, "s": 14675, "text": "The first step is to specify a path for the web service using @Path annotation to the UserService." }, { "code": null, "e": 14898, "s": 14774, "text": "The second step is to specify a path for the particular web service method using @Path annotation to method of UserService." }, { "code": null, "e": 15022, "s": 14898, "text": "The second step is to specify a path for the particular web service method using @Path annotation to method of UserService." }, { "code": null, "e": 15160, "s": 15022, "text": "You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our application." }, { "code": null, "e": 15168, "s": 15160, "text": "web.xml" }, { "code": null, "e": 16040, "s": 15168, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\" \n id = \"WebApp_ID\" version = \"3.0\"> \n <display-name>User Management</display-name> \n <servlet> \n <servlet-name>Jersey RESTful Application</servlet-name> \n <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> \n <init-param> \n <param-name>jersey.config.server.provider.packages</param-name> \n <param-value>com.tutorialspoint</param-value> \n </init-param> \n </servlet> \n <servlet-mapping> \n <servlet-name>Jersey RESTful Application</servlet-name> \n <url-pattern>/rest/*</url-pattern> \n </servlet-mapping> \n</web-app>" }, { "code": null, "e": 16277, "s": 16040, "text": "Once you are done with creating source and web configuration files, you are ready for this step which is compiling and running your program. To do this, using Eclipse, export your application as a war file and deploy the same in tomcat." }, { "code": null, "e": 16568, "s": 16277, "text": "To create a WAR file using eclipse, follow the option File → export → Web → War File and finally select project UserManagement and destination folder. To deploy a war file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and start the Tomcat." }, { "code": null, "e": 16635, "s": 16568, "text": "We are using Postman, a Chrome extension, to test our webservices." }, { "code": null, "e": 16820, "s": 16635, "text": "Make a request to UserManagement to get list of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the following result." }, { "code": null, "e": 16899, "s": 16820, "text": "Congratulations, you have created your first RESTful Application successfully." }, { "code": null, "e": 17341, "s": 16899, "text": "REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON." }, { "code": null, "e": 17651, "s": 17341, "text": "A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format." }, { "code": null, "e": 17792, "s": 17651, "text": "For example, in RESTful Web Services - First Application chapter, a user is a resource which is represented using the following XML format −" }, { "code": null, "e": 17884, "s": 17792, "text": "<user> \n <id>1</id> \n <name>Mahesh</name>\n <profession>Teacher</profession> \n</user> " }, { "code": null, "e": 17949, "s": 17884, "text": "The same resource can be represented in JSON format as follows −" }, { "code": null, "e": 18014, "s": 17949, "text": "{ \n \"id\":1, \n \"name\":\"Mahesh\", \n \"profession\":\"Teacher\" \n}" }, { "code": null, "e": 18355, "s": 18014, "text": "REST does not impose any restriction on the format of a resource representation. A client can ask for JSON representation whereas another client may ask for XML representation of the same resource to the server and so on. It is the responsibility of the REST server to pass the client the resource in the format that the client understands." }, { "code": null, "e": 18487, "s": 18355, "text": "Following are some important points to be considered while designing a representation format of a resource in RESTful Web Services." }, { "code": null, "e": 18622, "s": 18487, "text": "Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource." }, { "code": null, "e": 18757, "s": 18622, "text": "Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource." }, { "code": null, "e": 18970, "s": 18757, "text": "Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources." }, { "code": null, "e": 19183, "s": 18970, "text": "Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources." }, { "code": null, "e": 19298, "s": 19183, "text": "Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations." }, { "code": null, "e": 19413, "s": 19298, "text": "Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations." }, { "code": null, "e": 19620, "s": 19413, "text": "However, at present most of the web services are representing resources using either XML or JSON format. There are plenty of libraries and tools available to understand, parse, and modify XML and JSON data." }, { "code": null, "e": 20039, "s": 19620, "text": "RESTful Web Services make use of HTTP protocols as a medium of communication between client and server. A client sends a message in form of a HTTP Request and the server responds in the form of an HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself. Let us have a look on the HTTP Request and HTTP Response messages for HTTP 1.1." }, { "code": null, "e": 20078, "s": 20039, "text": "An HTTP Request has five major parts −" }, { "code": null, "e": 20149, "s": 20078, "text": "Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc." }, { "code": null, "e": 20220, "s": 20149, "text": "Verb − Indicates the HTTP methods such as GET, POST, DELETE, PUT, etc." }, { "code": null, "e": 20300, "s": 20220, "text": "URI − Uniform Resource Identifier (URI) to identify the resource on the server." }, { "code": null, "e": 20380, "s": 20300, "text": "URI − Uniform Resource Identifier (URI) to identify the resource on the server." }, { "code": null, "e": 20447, "s": 20380, "text": "HTTP Version − Indicates the HTTP version. For example, HTTP v1.1." }, { "code": null, "e": 20514, "s": 20447, "text": "HTTP Version − Indicates the HTTP version. For example, HTTP v1.1." }, { "code": null, "e": 20718, "s": 20514, "text": "Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc." }, { "code": null, "e": 20922, "s": 20718, "text": "Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client (or browser) type, format supported by the client, format of the message body, cache settings, etc." }, { "code": null, "e": 20981, "s": 20922, "text": "Request Body − Message content or Resource representation." }, { "code": null, "e": 21040, "s": 20981, "text": "Request Body − Message content or Resource representation." }, { "code": null, "e": 21080, "s": 21040, "text": "An HTTP Response has four major parts −" }, { "code": null, "e": 21231, "s": 21080, "text": "Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok." }, { "code": null, "e": 21382, "s": 21231, "text": "Status/Response Code − Indicates the Server status for the requested resource. For example, 404 means resource not found and 200 means response is ok." }, { "code": null, "e": 21448, "s": 21382, "text": "HTTP Version − Indicates the HTTP version. For example HTTP v1.1." }, { "code": null, "e": 21514, "s": 21448, "text": "HTTP Version − Indicates the HTTP version. For example HTTP v1.1." }, { "code": null, "e": 21675, "s": 21514, "text": "Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc." }, { "code": null, "e": 21836, "s": 21675, "text": "Response Header − Contains metadata for the HTTP Response message as keyvalue pairs. For example, content length, content type, response date, server type, etc." }, { "code": null, "e": 21905, "s": 21836, "text": "Response Body − Response message content or Resource representation." }, { "code": null, "e": 21974, "s": 21905, "text": "Response Body − Response message content or Resource representation." }, { "code": null, "e": 22303, "s": 21974, "text": "As we have explained in the RESTful Web Services - First Application chapter, let us put http://localhost:8080/UserManagement/rest/UserService/users in the POSTMAN with a GET request. If you click on the Preview button which is near the send button of Postman and then click on the Send button, you may see the following output." }, { "code": null, "e": 22389, "s": 22303, "text": "Here you can see, the browser sent a GET request and received a response body as XML." }, { "code": null, "e": 22529, "s": 22389, "text": "Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person." }, { "code": null, "e": 22655, "s": 22529, "text": "Each resource in REST architecture is identified by its URI (Uniform Resource Identifier). A URI is of the following format −" }, { "code": null, "e": 22712, "s": 22655, "text": "<protocol>://<service-name>/<ResourceType>/<ResourceID>\n" }, { "code": null, "e": 23067, "s": 22712, "text": "Purpose of an URI is to locate a resource(s) on the server hosting the web service. Another important attribute of a request is VERB which identifies the operation to be performed on the resource. For example, in RESTful Web Services - First Application chapter, the URI is http://localhost:8080/UserManagement/rest/UserService/users and the VERB is GET." }, { "code": null, "e": 23143, "s": 23067, "text": "The following are important points to be considered while designing a URI −" }, { "code": null, "e": 23261, "s": 23143, "text": "Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource." }, { "code": null, "e": 23379, "s": 23261, "text": "Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource." }, { "code": null, "e": 23531, "s": 23379, "text": "Avoid using spaces − Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users." }, { "code": null, "e": 23683, "s": 23531, "text": "Avoid using spaces − Use underscore (_) or hyphen (-) when using a long resource name. For example, use authorized_users instead of authorized%20users." }, { "code": null, "e": 23807, "s": 23683, "text": "Use lowercase letters − Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only." }, { "code": null, "e": 23931, "s": 23807, "text": "Use lowercase letters − Although URI is case-insensitive, it is a good practice to keep the url in lower case letters only." }, { "code": null, "e": 24148, "s": 23931, "text": "Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300." }, { "code": null, "e": 24365, "s": 24148, "text": "Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to a new URI using the HTTP Status code, 300." }, { "code": null, "e": 24515, "s": 24365, "text": "Use HTTP Verb − Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI." }, { "code": null, "e": 24665, "s": 24515, "text": "Use HTTP Verb − Always use HTTP Verb like GET, PUT and DELETE to do the operations on the resource. It is not good to use operations name in the URI." }, { "code": null, "e": 24720, "s": 24665, "text": "Following is an example of a poor URI to fetch a user." }, { "code": null, "e": 24786, "s": 24720, "text": "http://localhost:8080/UserManagement/rest/UserService/getUser/1 \n" }, { "code": null, "e": 24841, "s": 24786, "text": "Following is an example of a good URI to fetch a user." }, { "code": null, "e": 24904, "s": 24841, "text": "http://localhost:8080/UserManagement/rest/UserService/users/1\n" }, { "code": null, "e": 25152, "s": 24904, "text": "As we have discussed in the earlier chapters that RESTful Web Service uses a lot of HTTP verbs to determine the operation to be carried out on the specified resource(s). The following table states the examples of the most commonly used HTTP Verbs." }, { "code": null, "e": 25156, "s": 25152, "text": "GET" }, { "code": null, "e": 25216, "s": 25156, "text": "http://localhost:8080/UserManagement/rest/UserService/users" }, { "code": null, "e": 25240, "s": 25216, "text": "Gets the list of users." }, { "code": null, "e": 25252, "s": 25240, "text": "(Read Only)" }, { "code": null, "e": 25254, "s": 25252, "text": "2" }, { "code": null, "e": 25258, "s": 25254, "text": "GET" }, { "code": null, "e": 25320, "s": 25258, "text": "http://localhost:8080/UserManagement/rest/UserService/users/1" }, { "code": null, "e": 25342, "s": 25320, "text": "Gets the User of Id 1" }, { "code": null, "e": 25354, "s": 25342, "text": "(Read Only)" }, { "code": null, "e": 25356, "s": 25354, "text": "3" }, { "code": null, "e": 25360, "s": 25356, "text": "PUT" }, { "code": null, "e": 25422, "s": 25360, "text": "http://localhost:8080/UserManagement/rest/UserService/users/2" }, { "code": null, "e": 25445, "s": 25422, "text": "Inserts User with Id 2" }, { "code": null, "e": 25458, "s": 25445, "text": "(Idempotent)" }, { "code": null, "e": 25460, "s": 25458, "text": "4" }, { "code": null, "e": 25465, "s": 25460, "text": "POST" }, { "code": null, "e": 25527, "s": 25465, "text": "http://localhost:8080/UserManagement/rest/UserService/users/2" }, { "code": null, "e": 25554, "s": 25527, "text": "Updates the User with Id 2" }, { "code": null, "e": 25560, "s": 25554, "text": "(N/A)" }, { "code": null, "e": 25562, "s": 25560, "text": "5" }, { "code": null, "e": 25569, "s": 25562, "text": "DELETE" }, { "code": null, "e": 25631, "s": 25569, "text": "http://localhost:8080/UserManagement/rest/UserService/users/1" }, { "code": null, "e": 25658, "s": 25631, "text": "Deletes the User with Id 1" }, { "code": null, "e": 25671, "s": 25658, "text": "(Idempotent)" }, { "code": null, "e": 25673, "s": 25671, "text": "6" }, { "code": null, "e": 25681, "s": 25673, "text": "OPTIONS" }, { "code": null, "e": 25741, "s": 25681, "text": "http://localhost:8080/UserManagement/rest/UserService/users" }, { "code": null, "e": 25794, "s": 25741, "text": "Lists out the supported operations in a web service." }, { "code": null, "e": 25806, "s": 25794, "text": "(Read Only)" }, { "code": null, "e": 25808, "s": 25806, "text": "7" }, { "code": null, "e": 25813, "s": 25808, "text": "HEAD" }, { "code": null, "e": 25873, "s": 25813, "text": "http://localhost:8080/UserManagement/rest/UserService/users" }, { "code": null, "e": 25912, "s": 25873, "text": "Returns the HTTP Header only, no Body." }, { "code": null, "e": 25924, "s": 25912, "text": "(Read Only)" }, { "code": null, "e": 25967, "s": 25924, "text": "The following points are to be considered." }, { "code": null, "e": 26010, "s": 25967, "text": "GET operations are read only and are safe." }, { "code": null, "e": 26053, "s": 26010, "text": "GET operations are read only and are safe." }, { "code": null, "e": 26200, "s": 26053, "text": "PUT and DELETE operations are idempotent, which means their result will always be the same, no matter how many times these operations are invoked." }, { "code": null, "e": 26347, "s": 26200, "text": "PUT and DELETE operations are idempotent, which means their result will always be the same, no matter how many times these operations are invoked." }, { "code": null, "e": 26522, "s": 26347, "text": "PUT and POST operation are nearly the same with the difference lying only in the result where the PUT operation is idempotent and POST operation can cause a different result." }, { "code": null, "e": 26697, "s": 26522, "text": "PUT and POST operation are nearly the same with the difference lying only in the result where the PUT operation is idempotent and POST operation can cause a different result." }, { "code": null, "e": 26948, "s": 26697, "text": "Let us update an Example created in the RESTful Web Services - First Application chapter to create a Web service which can perform CRUD (Create, Read, Update, Delete) operations. For simplicity, we have used a file I/O to replace Database operations." }, { "code": null, "e": 27055, "s": 26948, "text": "Let us update the User.java, UserDao.java and UserService.java files under the com.tutorialspoint package." }, { "code": null, "e": 28486, "s": 27055, "text": "package com.tutorialspoint; \n\nimport java.io.Serializable; \nimport javax.xml.bind.annotation.XmlElement; \nimport javax.xml.bind.annotation.XmlRootElement; \n@XmlRootElement(name = \"user\") \n\npublic class User implements Serializable { \n private static final long serialVersionUID = 1L; \n private int id; \n private String name; \n private String profession; \n public User(){} \n \n public User(int id, String name, String profession){ \n this.id = id; \n this.name = name; \n this.profession = profession; \n } \n \n public int getId() {\n return id; \n } \n @XmlElement \n public void setId(int id) { \n this.id = id; \n } \n public String getName() { \n return name; \n } \n @XmlElement \n public void setName(String name) { \n this.name = name; \n } \n public String getProfession() { \n return profession; \n } \n @XmlElement \n public void setProfession(String profession) { \n this.profession = profession; \n } \n @Override \n public boolean equals(Object object){ \n if(object == null){ \n return false; \n }else if(!(object instanceof User)){ \n return false; \n }else { \n User user = (User)object; \n if(id == user.getId() \n && name.equals(user.getName()) \n && profession.equals(user.getProfession())){ \n return true; \n }\n } \n return false; \n } \n} " }, { "code": null, "e": 31388, "s": 28486, "text": "package com.tutorialspoint; \n\nimport java.io.File; \nimport java.io.FileInputStream; \nimport java.io.FileNotFoundException; \nimport java.io.FileOutputStream; \nimport java.io.IOException; \nimport java.io.ObjectInputStream; \nimport java.io.ObjectOutputStream; \nimport java.util.ArrayList; \nimport java.util.List; \n\npublic class UserDao { \n public List<User> getAllUsers(){ \n List<User> userList = null; \n try { \n File file = new File(\"Users.dat\"); \n if (!file.exists()) { \n User user = new User(1, \"Mahesh\", \"Teacher\"); \n userList = new ArrayList<User>(); \n userList.add(user); \n saveUserList(userList); \n } \n else{ \n FileInputStream fis = new FileInputStream(file); \n ObjectInputStream ois = new ObjectInputStream(fis); \n userList = (List<User>) ois.readObject(); \n ois.close(); \n }\n } catch (IOException e) { \n e.printStackTrace(); \n } catch (ClassNotFoundException e) { \n e.printStackTrace(); \n } \n return userList; \n } \n public User getUser(int id){ \n List<User> users = getAllUsers(); \n for(User user: users){ \n if(user.getId() == id){ \n return user; \n } \n } \n return null; \n } \n public int addUser(User pUser){ \n List<User> userList = getAllUsers(); \n boolean userExists = false; \n for(User user: userList){ \n if(user.getId() == pUser.getId()){ \n userExists = true; \n break; \n } \n } \n if(!userExists){ \n userList.add(pUser); \n saveUserList(userList); \n return 1; \n } \n return 0; \n }\n public int updateUser(User pUser){ \n List<User> userList = getAllUsers(); \n for(User user: userList){ \n if(user.getId() == pUser.getId()){ \n int index = userList.indexOf(user); \n userList.set(index, pUser); \n saveUserList(userList); \n return 1; \n } \n } \n return 0; \n } \n public int deleteUser(int id){ \n List<User> userList = getAllUsers(); \n for(User user: userList){ \n if(user.getId() == id){ \n int index = userList.indexOf(user); \n userList.remove(index); \n saveUserList(userList); \n return 1; \n } \n } \n return 0; \n } \n private void saveUserList(List<User> userList){ \n try { \n File file = new File(\"Users.dat\"); \n FileOutputStream fos; \n fos = new FileOutputStream(file);\n ObjectOutputStream oos = new ObjectOutputStream(fos); \n oos.writeObject(userList); \n oos.close(); \n } catch (FileNotFoundException e) { \n e.printStackTrace(); \n } catch (IOException e) { \n e.printStackTrace(); \n } \n } \n}" }, { "code": null, "e": 34016, "s": 31388, "text": "package com.tutorialspoint; \n\nimport java.io.IOException; \nimport java.util.List; \nimport javax.servlet.http.HttpServletResponse; \nimport javax.ws.rs.Consumes; \nimport javax.ws.rs.DELETE; \nimport javax.ws.rs.FormParam; \nimport javax.ws.rs.GET; \nimport javax.ws.rs.OPTIONS; \nimport javax.ws.rs.POST; \nimport javax.ws.rs.PUT; \nimport javax.ws.rs.Path; \nimport javax.ws.rs.PathParam; \nimport javax.ws.rs.Produces; \nimport javax.ws.rs.core.Context; \nimport javax.ws.rs.core.MediaType; \n@Path(\"/UserService\") \n\npublic class UserService { \n \n UserDao userDao = new UserDao(); \n private static final String SUCCESS_RESULT = \"<result>success</result>\"; \n private static final String FAILURE_RESULT = \"<result>failure</result>\"; \n @GET \n @Path(\"/users\") \n @Produces(MediaType.APPLICATION_XML) \n public List<User> getUsers(){ \n return userDao.getAllUsers(); \n } \n @GET \n @Path(\"/users/{userid}\") \n @Produces(MediaType.APPLICATION_XML) \n public User getUser(@PathParam(\"userid\") int userid){ \n return userDao.getUser(userid); \n } \n @PUT \n @Path(\"/users\") \n @Produces(MediaType.APPLICATION_XML) \n @Consumes(MediaType.APPLICATION_FORM_URLENCODED) \n public String createUser(@FormParam(\"id\") int id, \n @FormParam(\"name\") String name, \n @FormParam(\"profession\") String profession, \n @Context HttpServletResponse servletResponse) throws IOException{ \n User user = new User(id, name, profession); \n int result = userDao.addUser(user); \n if(result == 1){ \n return SUCCESS_RESULT; \n } \n return FAILURE_RESULT; \n } \n @POST \n @Path(\"/users\") \n @Produces(MediaType.APPLICATION_XML)\n @Consumes(MediaType.APPLICATION_FORM_URLENCODED) \n public String updateUser(@FormParam(\"id\") int id, \n @FormParam(\"name\") String name, \n @FormParam(\"profession\") String profession, \n @Context HttpServletResponse servletResponse) throws IOException{ \n User user = new User(id, name, profession); \n int result = userDao.updateUser(user); \n if(result == 1){ \n return SUCCESS_RESULT; \n } \n return FAILURE_RESULT; \n } \n @DELETE \n @Path(\"/users/{userid}\") \n @Produces(MediaType.APPLICATION_XML) \n public String deleteUser(@PathParam(\"userid\") int userid){ \n int result = userDao.deleteUser(userid); \n if(result == 1){ \n return SUCCESS_RESULT; \n } \n return FAILURE_RESULT; \n } \n @OPTIONS \n @Path(\"/users\") \n @Produces(MediaType.APPLICATION_XML) \n public String getSupportedOperations(){ \n return \"<operations>GET, PUT, POST, DELETE</operations>\"; \n } \n}" }, { "code": null, "e": 34400, "s": 34016, "text": "Now using Eclipse, export your application as a WAR File and deploy the same in Tomcat. To create a WAR file using eclipse, follow this path – File → export → Web → War File and finally select project UserManagement and the destination folder. To deploy a WAR file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and the start Tomcat." }, { "code": null, "e": 34590, "s": 34400, "text": "Jersey provides APIs to create a Web Service Client to test web services. We have created a sample test class WebServiceTester.java under the com.tutorialspoint package in the same project." }, { "code": null, "e": 38798, "s": 34590, "text": "package com.tutorialspoint; \n\nimport java.util.List; \nimport javax.ws.rs.client.Client; \nimport javax.ws.rs.client.ClientBuilder; \nimport javax.ws.rs.client.Entity; \nimport javax.ws.rs.core.Form; \nimport javax.ws.rs.core.GenericType; \nimport javax.ws.rs.core.MediaType; \n\npublic class WebServiceTester { \n private Client client; \n private String REST_SERVICE_URL = \"\n http://localhost:8080/UserManagement/rest/UserService/users\"; \n private static final String SUCCESS_RESULT = \"<result>success</result>\"; \n private static final String PASS = \"pass\"; \n private static final String FAIL = \"fail\"; \n private void init(){ \n this.client = ClientBuilder.newClient(); \n } \n public static void main(String[] args){ \n WebServiceTester tester = new WebServiceTester(); \n //initialize the tester \n tester.init(); \n //test get all users Web Service Method \n tester.testGetAllUsers(); \n //test get user Web Service Method \n tester.testGetUser();\n //test update user Web Service Method \n tester.testUpdateUser(); \n //test add user Web Service Method \n tester.testAddUser(); \n //test delete user Web Service Method \n tester.testDeleteUser(); \n } \n //Test: Get list of all users \n //Test: Check if list is not empty \n private void testGetAllUsers(){ \n GenericType<List<User>> list = new GenericType<List<User>>() {}; \n List<User> users = client \n .target(REST_SERVICE_URL) \n .request(MediaType.APPLICATION_XML) \n .get(list); \n String result = PASS; \n if(users.isEmpty()){ \n result = FAIL; \n } \n System.out.println(\"Test case name: testGetAllUsers, Result: \" + result ); \n } \n //Test: Get User of id 1 \n //Test: Check if user is same as sample user \n private void testGetUser(){ \n User sampleUser = new User(); \n sampleUser.setId(1); \n User user = client \n .target(REST_SERVICE_URL) \n .path(\"/{userid}\") \n .resolveTemplate(\"userid\", 1) \n .request(MediaType.APPLICATION_XML) \n .get(User.class); \n String result = FAIL; \n if(sampleUser != null && sampleUser.getId() == user.getId()){\n result = PASS; \n } \n System.out.println(\"Test case name: testGetUser, Result: \" + result ); \n } \n //Test: Update User of id 1 \n //Test: Check if result is success XML. \n private void testUpdateUser(){ \n Form form = new Form(); \n form.param(\"id\", \"1\"); \n form.param(\"name\", \"suresh\"); \n form.param(\"profession\", \"clerk\"); \n String callResult = client \n .target(REST_SERVICE_URL) \n .request(MediaType.APPLICATION_XML) \n .post(Entity.entity(form, \n MediaType.APPLICATION_FORM_URLENCODED_TYPE), \n String.class); \n String result = PASS; \n if(!SUCCESS_RESULT.equals(callResult)){ \n result = FAIL; \n } \n System.out.println(\"Test case name: testUpdateUser, Result: \" + result); \n } \n //Test: Add User of id 2 \n //Test: Check if result is success XML. \n private void testAddUser(){ \n Form form = new Form(); \n form.param(\"id\", \"2\"); \n form.param(\"name\", \"naresh\"); \n form.param(\"profession\", \"clerk\"); \n String callResult = client \n .target(REST_SERVICE_URL) \n .request(MediaType.APPLICATION_XML) \n .put(Entity.entity(form, \n MediaType.APPLICATION_FORM_URLENCODED_TYPE), \n String.class); \n \n String result = PASS; \n if(!SUCCESS_RESULT.equals(callResult)){ \n result = FAIL; \n } \n System.out.println(\"Test case name: testAddUser, Result: \" + result ); \n } \n //Test: Delete User of id 2 \n //Test: Check if result is success XML. \n private void testDeleteUser(){ \n String callResult = client \n .target(REST_SERVICE_URL) \n .path(\"/{userid}\") \n .resolveTemplate(\"userid\", 2) \n .request(MediaType.APPLICATION_XML) \n .delete(String.class); \n String result = PASS; \n if(!SUCCESS_RESULT.equals(callResult)){ \n result = FAIL; \n } \n System.out.println(\"Test case name: testDeleteUser, Result: \" + result); \n } \n}" }, { "code": null, "e": 38964, "s": 38798, "text": "Now run the tester using Eclipse. Right click on the file and follow the option Run as → Java Application. You will see the following result in the Eclipse console −" }, { "code": null, "e": 39190, "s": 38964, "text": "Test case name: testGetAllUsers, Result: pass \nTest case name: testGetUser, Result: pass \nTest case name: testUpdateUser, Result: pass \nTest case name: testAddUser, Result: pass \nTest case name: testDeleteUser, Result: pass \n" }, { "code": null, "e": 39587, "s": 39190, "text": "As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client." }, { "code": null, "e": 39808, "s": 39587, "text": "RESTful Web Services should adhere to this restriction. We have seen this in the RESTful Web Services - Methods chapter, that the web service methods are not storing any information from the client they are invoked from." }, { "code": null, "e": 39837, "s": 39808, "text": "Consider the following URL −" }, { "code": null, "e": 39900, "s": 39837, "text": "https://localhost:8080/UserManagement/rest/UserService/users/1" }, { "code": null, "e": 40108, "s": 39900, "text": "If you hit the above url using your browser or using a java based client or using Postman, result will always be the User XML whose Id is 1 because the server does not store any information about the client." }, { "code": null, "e": 40194, "s": 40108, "text": "<user> \n <id>1</id> \n <name>mahesh</name> \n <profession>1</profession> \n</user>" }, { "code": null, "e": 40264, "s": 40194, "text": "Following are the benefits of statelessness in RESTful Web Services −" }, { "code": null, "e": 40322, "s": 40264, "text": "Web services can treat each method request independently." }, { "code": null, "e": 40380, "s": 40322, "text": "Web services can treat each method request independently." }, { "code": null, "e": 40485, "s": 40380, "text": "Web services need not maintain the client's previous interactions. It simplifies the application design." }, { "code": null, "e": 40590, "s": 40485, "text": "Web services need not maintain the client's previous interactions. It simplifies the application design." }, { "code": null, "e": 40696, "s": 40590, "text": "As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols." }, { "code": null, "e": 40802, "s": 40696, "text": "As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols." }, { "code": null, "e": 40877, "s": 40802, "text": "Following are the disadvantages of statelessness in RESTful Web Services −" }, { "code": null, "e": 41038, "s": 40877, "text": "Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of." }, { "code": null, "e": 41199, "s": 41038, "text": "Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of." }, { "code": null, "e": 41521, "s": 41199, "text": "Caching refers to storing the server response in the client itself, so that a client need not make a server request for the same resource again and again. A server response should have information about how caching is to be done, so that a client caches the response for a time-period or never caches the server response." }, { "code": null, "e": 41623, "s": 41521, "text": "Following are the headers which a server response can have in order to configure a client's caching −" }, { "code": null, "e": 41625, "s": 41623, "text": "1" }, { "code": null, "e": 41630, "s": 41625, "text": "Date" }, { "code": null, "e": 41681, "s": 41630, "text": "Date and Time of the resource when it was created." }, { "code": null, "e": 41683, "s": 41681, "text": "2" }, { "code": null, "e": 41697, "s": 41683, "text": "Last Modified" }, { "code": null, "e": 41754, "s": 41697, "text": "Date and Time of the resource when it was last modified." }, { "code": null, "e": 41756, "s": 41754, "text": "3" }, { "code": null, "e": 41770, "s": 41756, "text": "Cache-Control" }, { "code": null, "e": 41805, "s": 41770, "text": "Primary header to control caching." }, { "code": null, "e": 41807, "s": 41805, "text": "4" }, { "code": null, "e": 41815, "s": 41807, "text": "Expires" }, { "code": null, "e": 41852, "s": 41815, "text": "Expiration date and time of caching." }, { "code": null, "e": 41854, "s": 41852, "text": "5" }, { "code": null, "e": 41858, "s": 41854, "text": "Age" }, { "code": null, "e": 41926, "s": 41858, "text": "Duration in seconds from when resource was fetched from the server." }, { "code": null, "e": 41980, "s": 41926, "text": "Following are the details of a Cache-Control header −" }, { "code": null, "e": 41982, "s": 41980, "text": "1" }, { "code": null, "e": 41989, "s": 41982, "text": "Public" }, { "code": null, "e": 42044, "s": 41989, "text": "Indicates that resource is cacheable by any component." }, { "code": null, "e": 42046, "s": 42044, "text": "2" }, { "code": null, "e": 42054, "s": 42046, "text": "Private" }, { "code": null, "e": 42166, "s": 42054, "text": "Indicates that resource is cacheable only by the client and the server, no intermediary can cache the resource." }, { "code": null, "e": 42168, "s": 42166, "text": "3" }, { "code": null, "e": 42186, "s": 42168, "text": "no-cache/no-store" }, { "code": null, "e": 42230, "s": 42186, "text": "Indicates that a resource is not cacheable." }, { "code": null, "e": 42232, "s": 42230, "text": "4" }, { "code": null, "e": 42240, "s": 42232, "text": "max-age" }, { "code": null, "e": 42345, "s": 42240, "text": "Indicates the caching is valid up to max-age in seconds. After this, client has to make another request." }, { "code": null, "e": 42347, "s": 42345, "text": "5" }, { "code": null, "e": 42363, "s": 42347, "text": "must-revalidate" }, { "code": null, "e": 42430, "s": 42363, "text": "Indication to server to revalidate resource if max-age has passed." }, { "code": null, "e": 42535, "s": 42430, "text": "Always keep static contents like images, CSS, JavaScript cacheable, with expiration date of 2 to 3 days." }, { "code": null, "e": 42640, "s": 42535, "text": "Always keep static contents like images, CSS, JavaScript cacheable, with expiration date of 2 to 3 days." }, { "code": null, "e": 42673, "s": 42640, "text": "Never keep expiry date too high." }, { "code": null, "e": 42706, "s": 42673, "text": "Never keep expiry date too high." }, { "code": null, "e": 42761, "s": 42706, "text": "Dynamic content should be cached for a few hours only." }, { "code": null, "e": 42816, "s": 42761, "text": "Dynamic content should be cached for a few hours only." }, { "code": null, "e": 42966, "s": 42816, "text": "As RESTful Web Services work with HTTP URL Paths, it is very important to safeguard a RESTful Web Service in the same manner as a website is secured." }, { "code": null, "e": 43056, "s": 42966, "text": "Following are the best practices to be adhered to while designing a RESTful Web Service −" }, { "code": null, "e": 43164, "s": 43056, "text": "Validation − Validate all inputs on the server. Protect your server against SQL or NoSQL injection attacks." }, { "code": null, "e": 43272, "s": 43164, "text": "Validation − Validate all inputs on the server. Protect your server against SQL or NoSQL injection attacks." }, { "code": null, "e": 43411, "s": 43272, "text": "Session Based Authentication − Use session based authentication to authenticate a user whenever a request is made to a Web Service method." }, { "code": null, "e": 43550, "s": 43411, "text": "Session Based Authentication − Use session based authentication to authenticate a user whenever a request is made to a Web Service method." }, { "code": null, "e": 43703, "s": 43550, "text": "No Sensitive Data in the URL − Never use username, password or session token in a URL, these values should be passed to Web Service via the POST method." }, { "code": null, "e": 43856, "s": 43703, "text": "No Sensitive Data in the URL − Never use username, password or session token in a URL, these values should be passed to Web Service via the POST method." }, { "code": null, "e": 44007, "s": 43856, "text": "Restriction on Method Execution − Allow restricted use of methods like GET, POST and DELETE methods. The GET method should not be able to delete data." }, { "code": null, "e": 44158, "s": 44007, "text": "Restriction on Method Execution − Allow restricted use of methods like GET, POST and DELETE methods. The GET method should not be able to delete data." }, { "code": null, "e": 44248, "s": 44158, "text": "Validate Malformed XML/JSON − Check for well-formed input passed to a web service method." }, { "code": null, "e": 44338, "s": 44248, "text": "Validate Malformed XML/JSON − Check for well-formed input passed to a web service method." }, { "code": null, "e": 44461, "s": 44338, "text": "Throw generic Error Messages − A web service method should use HTTP error messages like 403 to show access forbidden, etc." }, { "code": null, "e": 44584, "s": 44461, "text": "Throw generic Error Messages − A web service method should use HTTP error messages like 403 to show access forbidden, etc." }, { "code": null, "e": 44586, "s": 44584, "text": "1" }, { "code": null, "e": 44590, "s": 44586, "text": "200" }, { "code": null, "e": 44610, "s": 44590, "text": "OK − shows success." }, { "code": null, "e": 44612, "s": 44610, "text": "2" }, { "code": null, "e": 44616, "s": 44612, "text": "201" }, { "code": null, "e": 44763, "s": 44616, "text": "CREATED − when a resource is successfully created using POST or PUT request. Returns link to the newly created resource using the location header." }, { "code": null, "e": 44765, "s": 44763, "text": "3" }, { "code": null, "e": 44769, "s": 44765, "text": "204" }, { "code": null, "e": 44842, "s": 44769, "text": "NO CONTENT − when response body is empty. For example, a DELETE request." }, { "code": null, "e": 44844, "s": 44842, "text": "4" }, { "code": null, "e": 44848, "s": 44844, "text": "304" }, { "code": null, "e": 45011, "s": 44848, "text": "NOT MODIFIED − used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location, etc." }, { "code": null, "e": 45013, "s": 45011, "text": "5" }, { "code": null, "e": 45017, "s": 45013, "text": "400" }, { "code": null, "e": 45118, "s": 45017, "text": "BAD REQUEST − states that an invalid input is provided. For example, validation error, missing data." }, { "code": null, "e": 45120, "s": 45118, "text": "6" }, { "code": null, "e": 45124, "s": 45120, "text": "401" }, { "code": null, "e": 45205, "s": 45124, "text": "UNAUTHORIZED − states that user is using invalid or wrong authentication token. " }, { "code": null, "e": 45207, "s": 45205, "text": "7" }, { "code": null, "e": 45211, "s": 45207, "text": "403" }, { "code": null, "e": 45340, "s": 45211, "text": "FORBIDDEN − states that the user is not having access to the method being used. For example, Delete access without admin rights." }, { "code": null, "e": 45342, "s": 45340, "text": "8" }, { "code": null, "e": 45346, "s": 45342, "text": "404" }, { "code": null, "e": 45399, "s": 45346, "text": "NOT FOUND − states that the method is not available." }, { "code": null, "e": 45401, "s": 45399, "text": "9" }, { "code": null, "e": 45405, "s": 45401, "text": "409" }, { "code": null, "e": 45507, "s": 45405, "text": "CONFLICT − states conflict situation while executing the method. For example, adding duplicate entry." }, { "code": null, "e": 45510, "s": 45507, "text": "10" }, { "code": null, "e": 45514, "s": 45510, "text": "500" }, { "code": null, "e": 45615, "s": 45514, "text": "INTERNAL SERVER ERROR − states that the server has thrown some exception while executing the method." }, { "code": null, "e": 46040, "s": 45615, "text": "JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful Web Services." }, { "code": null, "e": 46134, "s": 46040, "text": "Following are the most commonly used annotations to map a resource as a web service resource." }, { "code": null, "e": 46136, "s": 46134, "text": "1" }, { "code": null, "e": 46142, "s": 46136, "text": "@Path" }, { "code": null, "e": 46186, "s": 46142, "text": "Relative path of the resource class/method." }, { "code": null, "e": 46188, "s": 46186, "text": "2" }, { "code": null, "e": 46193, "s": 46188, "text": "@GET" }, { "code": null, "e": 46235, "s": 46193, "text": "HTTP Get request, used to fetch resource." }, { "code": null, "e": 46237, "s": 46235, "text": "3" }, { "code": null, "e": 46242, "s": 46237, "text": "@PUT" }, { "code": null, "e": 46285, "s": 46242, "text": "HTTP PUT request, used to update resource." }, { "code": null, "e": 46287, "s": 46285, "text": "4" }, { "code": null, "e": 46293, "s": 46287, "text": "@POST" }, { "code": null, "e": 46343, "s": 46293, "text": "HTTP POST request, used to create a new resource." }, { "code": null, "e": 46345, "s": 46343, "text": "5" }, { "code": null, "e": 46353, "s": 46345, "text": "@DELETE" }, { "code": null, "e": 46399, "s": 46353, "text": "HTTP DELETE request, used to delete resource." }, { "code": null, "e": 46401, "s": 46399, "text": "6" }, { "code": null, "e": 46407, "s": 46401, "text": "@HEAD" }, { "code": null, "e": 46469, "s": 46407, "text": "HTTP HEAD request, used to get status of method availability." }, { "code": null, "e": 46471, "s": 46469, "text": "7" }, { "code": null, "e": 46481, "s": 46471, "text": "@Produces" }, { "code": null, "e": 46595, "s": 46481, "text": "States the HTTP Response generated by web service. For example, APPLICATION/XML, TEXT/HTML, APPLICATION/JSON etc." }, { "code": null, "e": 46597, "s": 46595, "text": "8" }, { "code": null, "e": 46607, "s": 46597, "text": "@Consumes" }, { "code": null, "e": 46737, "s": 46607, "text": "States the HTTP Request type. For example, application/x-www-formurlencoded to accept form data in HTTP body during POST request." }, { "code": null, "e": 46739, "s": 46737, "text": "9" }, { "code": null, "e": 46750, "s": 46739, "text": "@PathParam" }, { "code": null, "e": 46811, "s": 46750, "text": "Binds the parameter passed to the method to a value in path." }, { "code": null, "e": 46814, "s": 46811, "text": "10" }, { "code": null, "e": 46826, "s": 46814, "text": "@QueryParam" }, { "code": null, "e": 46897, "s": 46826, "text": "Binds the parameter passed to method to a query parameter in the path." }, { "code": null, "e": 46900, "s": 46897, "text": "11" }, { "code": null, "e": 46913, "s": 46900, "text": "@MatrixParam" }, { "code": null, "e": 46990, "s": 46913, "text": "Binds the parameter passed to the method to a HTTP matrix parameter in path." }, { "code": null, "e": 46993, "s": 46990, "text": "12" }, { "code": null, "e": 47006, "s": 46993, "text": "@HeaderParam" }, { "code": null, "e": 47065, "s": 47006, "text": "Binds the parameter passed to the method to a HTTP header." }, { "code": null, "e": 47068, "s": 47065, "text": "13" }, { "code": null, "e": 47082, "s": 47068, "text": "@CookieParam " }, { "code": null, "e": 47136, "s": 47082, "text": "Binds the parameter passed to the method to a Cookie." }, { "code": null, "e": 47139, "s": 47136, "text": "14" }, { "code": null, "e": 47150, "s": 47139, "text": "@FormParam" }, { "code": null, "e": 47208, "s": 47150, "text": "Binds the parameter passed to the method to a form value." }, { "code": null, "e": 47211, "s": 47208, "text": "15" }, { "code": null, "e": 47225, "s": 47211, "text": "@DefaultValue" }, { "code": null, "e": 47286, "s": 47225, "text": "Assigns a default value to a parameter passed to the method." }, { "code": null, "e": 47289, "s": 47286, "text": "16" }, { "code": null, "e": 47298, "s": 47289, "text": "@Context" }, { "code": null, "e": 47362, "s": 47298, "text": "Context of the resource. For example, HTTPRequest as a context." }, { "code": null, "e": 47535, "s": 47362, "text": "Note − We have used Jersey, a reference implementation of JAX-RS 2.0 by Oracle, in the RESTful Web Services - First Application and RESTful Web Services - Methods chapters." }, { "code": null, "e": 47569, "s": 47535, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 47584, "s": 47569, "text": " Chaand Sheikh" }, { "code": null, "e": 47617, "s": 47584, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 47640, "s": 47617, "text": " Vinod Kumar Kayartaya" }, { "code": null, "e": 47675, "s": 47640, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 47690, "s": 47675, "text": " Chaand Sheikh" }, { "code": null, "e": 47725, "s": 47690, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 47739, "s": 47725, "text": " Antonio Papa" }, { "code": null, "e": 47746, "s": 47739, "text": " Print" }, { "code": null, "e": 47757, "s": 47746, "text": " Add Notes" } ]
How to add delay in a loop in JavaScript?
To add delay in a loop, use the setTimeout() metod in JavaScript. Following is the code for adding delay in a loop − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Adding delay in a loop in JavaScript</h1> <div class="result"></div> <button class="Btn">Start</button> <h3>Click on the above button to start the loop</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); BtnEle.addEventListener("click", () => { for (let i = 0; i < 10; i++) { setTimeout(function () { resEle.innerHTML += "i = " + i + "<br>"; }, 2000 * i); } }); </script> </body> </html> On clicking the ‘START’ button, 3 there will be delay after each iteration −
[ { "code": null, "e": 1179, "s": 1062, "text": "To add delay in a loop, use the setTimeout() metod in JavaScript. Following is the code for\nadding delay in a loop −" }, { "code": null, "e": 1190, "s": 1179, "text": " Live Demo" }, { "code": null, "e": 2058, "s": 1190, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Adding delay in a loop in JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">Start</button>\n<h3>Click on the above button to start the loop</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n BtnEle.addEventListener(\"click\", () => {\n for (let i = 0; i < 10; i++) {\n setTimeout(function () {\n resEle.innerHTML += \"i = \" + i + \"<br>\";\n }, 2000 * i);\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2135, "s": 2058, "text": "On clicking the ‘START’ button, 3\nthere will be delay after each iteration −" } ]
Numba: “weapon of mass optimization” | by Alex Diaz | Towards Data Science
Numba is a Python compiler, specifically for numerical functions and allows you to accelerate your applications with high performance functions written directly in Python. Numba generates machine code optimized from pure Python code using LLVM. With a couple of simple changes, our Python code (function-oriented) can be optimized “just-in-time” to obtain a performance similar to that of C, C++, without having to change the language. You can find the entire code in my GitHub! :) What is Numba?First steps: Compile for the CPUNumba for GPUConclusion What is Numba? First steps: Compile for the CPU Numba for GPU Conclusion Numba is a compiler that allows you to accelerate Python code (numerical functions) for both CPU and GPU: Function Compiler: Numba compiles Python functions, not whole applications or parts of it. Basically, Numba is another Python module to improve the performance of our functions.Just-in-time: (Dynamic translation) Numba translates the bytecode (intermediate code more abstract than the machine code) to machine code immediately before its execution to improve the execution speed.Numerically-focused: Numba is focused on numerical data, such as int, float, complex. For now, there are limitations to use it with string data. Function Compiler: Numba compiles Python functions, not whole applications or parts of it. Basically, Numba is another Python module to improve the performance of our functions. Just-in-time: (Dynamic translation) Numba translates the bytecode (intermediate code more abstract than the machine code) to machine code immediately before its execution to improve the execution speed. Numerically-focused: Numba is focused on numerical data, such as int, float, complex. For now, there are limitations to use it with string data. Numba is not the only way to program in CUDA, it is usually programmed in C/C ++ directly for it. But Numba allows you to program directly in Python and optimize it for both CPU and GPU with few changes in our code. In relation to Python, there are other alternatives such as pyCUDA, here is a comparison between them: CUDA C/C++: It is the most common and flexible way to program in CUDAAccelerate applications in C, C ++. It is the most common and flexible way to program in CUDA Accelerate applications in C, C ++. pyCUDA It is the most efficient CUDA form for PythonIt requires programming C in our Python code and, in general, many code modifications. It is the most efficient CUDA form for Python It requires programming C in our Python code and, in general, many code modifications. Numba Less efficient than pyCUDAIt allows you to write your code in Python and optimize it with few modificationsIt also optimizes the Python code for CPU Less efficient than pyCUDA It allows you to write your code in Python and optimize it with few modifications It also optimizes the Python code for CPU The objectives of this talk are the following: Use Numba to compile functions on the CPU Understand how Numba works Accelerate Numpy ufuncs in GPU Write Kernels using Numba (Next tutorial) Numba, apart from being able to speed up the functions in the GPU, can be used to optimize functions in the CPU. To do this, Python decorators (function modifiers) are used. First of all, we are going to start to evaluate the function hypot to try how Numba works. We need to use the decorator @jit in our function. >>> # Numba function>>> hypot(3.0, 4.0)5.0>>> # Python function>>> hypot.py_func(3.0, 4.0)5.0 The result is the same in Numba as in the Python function, since Numba saves the original implementation of the function in .py_func. Naturally, it is important to measure the performance of our code, check if Numba really works well and observe the difference between Python implementation and Numba implementation. Furthermore, the library math already includes the hypot function, we can evaluate it also. >>> # Python function>>> %timeit hypot.py_func(3.0, 4.0)The slowest run took 17.62 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 260 ns per loop>>> # Numba function>>> %timeit hypot(3.0, 4.0)The slowest run took 33.89 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 216 ns per loop>>> # math function>>> %timeit math.hypot(3.0, 4.0)The slowest run took 105.55 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 133 ns per loop The math.hypot function is even faster than Numba!! This is because Numba introduces a certain overhead to each function call, which is larger than the Python function call overhead, very fast functions (like the previous one) will be affected by this. (However, if you call a Numba function from another, there is very little overhead, sometimes even zero if the compiler integrates the function into the other. In short, check if the functions are really accelerating with Numba). numba.pydata.org When we initialize the hypot function: IR Intermediate Representations Bytecode Analysis Intermediate code more abstract than machine code LLVM Low Level Virtual Machine, infrastructure to develop compilers NVVM It is an IR compiler based on LLVM, it is designed to represent GPU kernels Each line of python is preceded by several lines of Numba IR code. The most useful is to see the type annotations that show us how Numba treats the variables, for example, in “pyobject” it is indicating that Numba does not know the np.sin function and that he should call it from Python. We can inspect the process for the hypot using .inspect_types(). >>> @jit>>> def foo_np(x):>>> return np.sin(x)>>> foo_np(2)>>> foo_np.inspect_types()foo_np (int64,)----------------------------# File: <ipython-input-18-02574ac7ba04> # --- LINE 1 --- # label 0 @jit # --- LINE 2 --- def foo_np(x): # --- LINE 3 --- # x = arg(0, name=x) :: int64 # $0.1 = global(np: <module 'numpy' from '/usr/local/lib/python3.6/dist-packages/numpy/__init__.py'>) :: Module(<module 'numpy' from '/usr/local/lib/python3.6/dist-packages/numpy/__init__.py'>) # $0.2 = getattr(value=$0.1, attr=sin) :: Function(<ufunc 'sin'>) # del $0.1 # $0.4 = call $0.2(x, func=$0.2, args=[Var(x, <ipython-input-18-02574ac7ba04> (3))], kws=(), vararg=None) :: (int64,) -> float64 # del x # del $0.2 # $0.5 = cast(value=$0.4) :: float64 # del $0.4 # return $0.5 return np.sin(x) ============================================== We are going to measure the performance of creating fractals using the Mandelbrot Set, and we will see how Numba helps us to improve our performance. 1 loop, best of 3: 4.62 s per loop<matplotlib.image.AxesImage at 0x7f986ce23780> It takes about 4.62 seconds to generate a fractal using Mandelbrot set, now we are going to improve the performance using Numba, we just have to add the @jit decorator. The slowest run took 4.17 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 52.4 ms per loop We can observe how we have achieved to reduce the time to build fractals from 4.62 seconds to 52.4 ms... and this has been done only adding a decorator!! We have said that Numba only works for numeric functions, although Numba compiles and runs any Python code, there are some types of data that it cannot compile yet (such as dictionaries) and it also makes no sense to compile them. >>> @jit>>> def dictionary(dict_test):>>> return dict_test['house']dictionary({'house': 2, 'car': 35})2 But it has not failed !! We have said that Numba does not compile dictionaries... The point here is that Numba creates 2 functions, one of them in Python and another in Numba. So here we are seeing the python solution, we can verify this by doing nopython = True. jit(nopython = True) is equivalent to njit >>> @jit(nopython = True)>>> def dictionary(dict_test):>>> return dict_test['house']dictionary({'house': 2, 'car': 35})-----------------------------------------TypingError Traceback (most recent call last)<ipython-input-31-14d1c8683c01> in <module>() 3 return dict_test['house'] 4 ----> 5 dictionary({'house': 245, 'car': 350})2 frames/usr/local/lib/python3.6/dist-packages/numba/six.py in reraise(tp, value, tb) 656 value = tp() 657 if value.__traceback__ is not tb:--> 658 raise value.with_traceback(tb) 659 raise value 660TypingError: Failed in nopython mode pipeline (step: nopython frontend)Internal error at <numba.typeinfer.ArgConstraint object at 0x7f986c1bed68>:--%<----------------------------------------- There are two ways to program in GPU using Numba: 1. ufuncs/gufuncs__ 2. CUDA Python Kernels (Next tutorial) One of the main design features of the GPU is the ability to handle data in parallel, so the universal functions of numpy (ufunc) are an ideal candidate to implement them in GPU programming. Note: ufunc are functions that perform the same operation on each element of a numpy array. For instance: As we have said before, the ufunc functions are an ideal candidate to use them with GPU because of their parallelism. Therefore, Numba has the ability to create compiled ufunc functions without using C. To do this, we must use the decorator @vectorize. Let’s start with an example using @vectorize to compile and optimize a CPU ufunc. array([ 24, 343, 15, 9]) Instead of using the CPU to compile and execute the previous function, we are going to use CUDA in the GPU and for this we must use a “target attribute”. We will indicate what type each variable is (arguments and return value). return_value_type(argument1_value_type, argument2_value_type, ...) To do this, we will use the previous function that expects 2 int64 values and returns another int64 value. We will designate target = 'cuda' to be able to execute it in the GPU. array([ 24, 343, 15, 9]) We can check the speed of running it on CPU or GPU: >>> %timeit np.add(a, b) # Numpy en CPUThe slowest run took 38.66 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 511 ns per loop>>> %timeit add_ufunc_gpu(a, b) # Numpy en GPUThe slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 755 μs per loop GPU is slower than the CPU!!! Quiet, this has an explanation ... But first let’s see what happens when we call that function... When we execute this function, Numba produces: Compile a CUDA kernel to execute the ufunc function in parallel over all the elements of the input arrayAssign the inputs and outputs to the GPU memoryCopy the input to the GPURun the CUDA KernelCopy the results back from the GPU to the CPUReturn the results as a numpy array Compile a CUDA kernel to execute the ufunc function in parallel over all the elements of the input array Assign the inputs and outputs to the GPU memory Copy the input to the GPU Run the CUDA Kernel Copy the results back from the GPU to the CPU Return the results as a numpy array As compared to the implementation in C, Numba allows you to perform these types of tasks in a more concise way. Why is the GPU slower than the CPU? Our inputs are too small: The GPU achieves better performance using parallelism operating on thousands of values ​​at once. Our inputs are 4 or 64 dimensions, we need larger arrays to keep the GPU occupied. Very simple calculation: Sending the calculation to the GPU requires a lot of “effort” compared to calling the CPU function. If our function does not require excessive mathematical computation (this is usually called * arithmetic intensity *), then the GPU could take longer than in the CPU. Numba copies the data to the GPU. The variable types of our inputs are larger than necessary: ​​Our example uses int64 and we probably do not need them. Practically, in CPU, 32 and 64-bits have the same computing speed, but in GPU, 64-bits have a slight increase in computational speed (it can reach up to 24x slower respectively to 32-bits). So it is important to keep this in mind when executing our function in the GPU. With this in mind, we will try to apply what has been learned in the previous points to see if it is really faster to operate on the GPU than the CPU. We are going to calculate a density function, which is a slightly more complex operation with larger arrays. Let’s calculate the value of a Gaussian density function in x given the mean and sigma: >>> %timeit norm_pdf.pdf(x, loc=mean, scale=sigma) # CPU function10 loops, best of 3: 60.8 ms per loop>>> %timeit gaussian_dens_gpu(x, mean, sigma) # GPU function100 loops, best of 3: 6.88 ms per loop We can even define our function to be executed in the CPU using Numba. >>> %timeit gaussian_dens_cpu(x, mean, sigma) # CPU10 loops, best of 3: 23.6 ms per loop It is even faster than the function written in Python, but slower than the one executed in the GPU. Unfortunately, there are several functions that do not fall within the scope of the definition of ufunc, therefore, to execute functions in the GPU that do not meet that requirement we use cuda.jit. We can use "device functions" that run on our GPU. Note: “devices functions” are functions that can only be called from a kernel or from another “device” function. >>> %timeit polar_distance(rho1, theta1, rho2, theta2)The slowest run took 23.16 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 10.2 ms per loop To sum up, Numba is a Python compiler, specifically for numerical functions and allows you to accelerate your applications with high performance functions written directly in Python. It is a stable tool, which allows you to optimize code oriented to operate with arrays. Thanks to its ease of use (just a decorator!!) provides us with a very powerful tool to improve the performance of our code. Suggestions and reviews are welcome. Follow me and thank you for reading! :)
[ { "code": null, "e": 343, "s": 171, "text": "Numba is a Python compiler, specifically for numerical functions and allows you to accelerate your applications with high performance functions written directly in Python." }, { "code": null, "e": 607, "s": 343, "text": "Numba generates machine code optimized from pure Python code using LLVM. With a couple of simple changes, our Python code (function-oriented) can be optimized “just-in-time” to obtain a performance similar to that of C, C++, without having to change the language." }, { "code": null, "e": 653, "s": 607, "text": "You can find the entire code in my GitHub! :)" }, { "code": null, "e": 723, "s": 653, "text": "What is Numba?First steps: Compile for the CPUNumba for GPUConclusion" }, { "code": null, "e": 738, "s": 723, "text": "What is Numba?" }, { "code": null, "e": 771, "s": 738, "text": "First steps: Compile for the CPU" }, { "code": null, "e": 785, "s": 771, "text": "Numba for GPU" }, { "code": null, "e": 796, "s": 785, "text": "Conclusion" }, { "code": null, "e": 902, "s": 796, "text": "Numba is a compiler that allows you to accelerate Python code (numerical functions) for both CPU and GPU:" }, { "code": null, "e": 1426, "s": 902, "text": "Function Compiler: Numba compiles Python functions, not whole applications or parts of it. Basically, Numba is another Python module to improve the performance of our functions.Just-in-time: (Dynamic translation) Numba translates the bytecode (intermediate code more abstract than the machine code) to machine code immediately before its execution to improve the execution speed.Numerically-focused: Numba is focused on numerical data, such as int, float, complex. For now, there are limitations to use it with string data." }, { "code": null, "e": 1604, "s": 1426, "text": "Function Compiler: Numba compiles Python functions, not whole applications or parts of it. Basically, Numba is another Python module to improve the performance of our functions." }, { "code": null, "e": 1807, "s": 1604, "text": "Just-in-time: (Dynamic translation) Numba translates the bytecode (intermediate code more abstract than the machine code) to machine code immediately before its execution to improve the execution speed." }, { "code": null, "e": 1952, "s": 1807, "text": "Numerically-focused: Numba is focused on numerical data, such as int, float, complex. For now, there are limitations to use it with string data." }, { "code": null, "e": 2271, "s": 1952, "text": "Numba is not the only way to program in CUDA, it is usually programmed in C/C ++ directly for it. But Numba allows you to program directly in Python and optimize it for both CPU and GPU with few changes in our code. In relation to Python, there are other alternatives such as pyCUDA, here is a comparison between them:" }, { "code": null, "e": 2283, "s": 2271, "text": "CUDA C/C++:" }, { "code": null, "e": 2376, "s": 2283, "text": "It is the most common and flexible way to program in CUDAAccelerate applications in C, C ++." }, { "code": null, "e": 2434, "s": 2376, "text": "It is the most common and flexible way to program in CUDA" }, { "code": null, "e": 2470, "s": 2434, "text": "Accelerate applications in C, C ++." }, { "code": null, "e": 2477, "s": 2470, "text": "pyCUDA" }, { "code": null, "e": 2609, "s": 2477, "text": "It is the most efficient CUDA form for PythonIt requires programming C in our Python code and, in general, many code modifications." }, { "code": null, "e": 2655, "s": 2609, "text": "It is the most efficient CUDA form for Python" }, { "code": null, "e": 2742, "s": 2655, "text": "It requires programming C in our Python code and, in general, many code modifications." }, { "code": null, "e": 2748, "s": 2742, "text": "Numba" }, { "code": null, "e": 2897, "s": 2748, "text": "Less efficient than pyCUDAIt allows you to write your code in Python and optimize it with few modificationsIt also optimizes the Python code for CPU" }, { "code": null, "e": 2924, "s": 2897, "text": "Less efficient than pyCUDA" }, { "code": null, "e": 3006, "s": 2924, "text": "It allows you to write your code in Python and optimize it with few modifications" }, { "code": null, "e": 3048, "s": 3006, "text": "It also optimizes the Python code for CPU" }, { "code": null, "e": 3095, "s": 3048, "text": "The objectives of this talk are the following:" }, { "code": null, "e": 3137, "s": 3095, "text": "Use Numba to compile functions on the CPU" }, { "code": null, "e": 3164, "s": 3137, "text": "Understand how Numba works" }, { "code": null, "e": 3195, "s": 3164, "text": "Accelerate Numpy ufuncs in GPU" }, { "code": null, "e": 3237, "s": 3195, "text": "Write Kernels using Numba (Next tutorial)" }, { "code": null, "e": 3411, "s": 3237, "text": "Numba, apart from being able to speed up the functions in the GPU, can be used to optimize functions in the CPU. To do this, Python decorators (function modifiers) are used." }, { "code": null, "e": 3553, "s": 3411, "text": "First of all, we are going to start to evaluate the function hypot to try how Numba works. We need to use the decorator @jit in our function." }, { "code": null, "e": 3647, "s": 3553, "text": ">>> # Numba function>>> hypot(3.0, 4.0)5.0>>> # Python function>>> hypot.py_func(3.0, 4.0)5.0" }, { "code": null, "e": 3781, "s": 3647, "text": "The result is the same in Numba as in the Python function, since Numba saves the original implementation of the function in .py_func." }, { "code": null, "e": 4056, "s": 3781, "text": "Naturally, it is important to measure the performance of our code, check if Numba really works well and observe the difference between Python implementation and Numba implementation. Furthermore, the library math already includes the hypot function, we can evaluate it also." }, { "code": null, "e": 4693, "s": 4056, "text": ">>> # Python function>>> %timeit hypot.py_func(3.0, 4.0)The slowest run took 17.62 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 260 ns per loop>>> # Numba function>>> %timeit hypot(3.0, 4.0)The slowest run took 33.89 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 216 ns per loop>>> # math function>>> %timeit math.hypot(3.0, 4.0)The slowest run took 105.55 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 133 ns per loop" }, { "code": null, "e": 4946, "s": 4693, "text": "The math.hypot function is even faster than Numba!! This is because Numba introduces a certain overhead to each function call, which is larger than the Python function call overhead, very fast functions (like the previous one) will be affected by this." }, { "code": null, "e": 5176, "s": 4946, "text": "(However, if you call a Numba function from another, there is very little overhead, sometimes even zero if the compiler integrates the function into the other. In short, check if the functions are really accelerating with Numba)." }, { "code": null, "e": 5193, "s": 5176, "text": "numba.pydata.org" }, { "code": null, "e": 5232, "s": 5193, "text": "When we initialize the hypot function:" }, { "code": null, "e": 5264, "s": 5232, "text": "IR Intermediate Representations" }, { "code": null, "e": 5332, "s": 5264, "text": "Bytecode Analysis Intermediate code more abstract than machine code" }, { "code": null, "e": 5400, "s": 5332, "text": "LLVM Low Level Virtual Machine, infrastructure to develop compilers" }, { "code": null, "e": 5481, "s": 5400, "text": "NVVM It is an IR compiler based on LLVM, it is designed to represent GPU kernels" }, { "code": null, "e": 5834, "s": 5481, "text": "Each line of python is preceded by several lines of Numba IR code. The most useful is to see the type annotations that show us how Numba treats the variables, for example, in “pyobject” it is indicating that Numba does not know the np.sin function and that he should call it from Python. We can inspect the process for the hypot using .inspect_types()." }, { "code": null, "e": 6721, "s": 5834, "text": ">>> @jit>>> def foo_np(x):>>> return np.sin(x)>>> foo_np(2)>>> foo_np.inspect_types()foo_np (int64,)----------------------------# File: <ipython-input-18-02574ac7ba04> # --- LINE 1 --- # label 0 @jit # --- LINE 2 --- def foo_np(x): # --- LINE 3 --- # x = arg(0, name=x) :: int64 # $0.1 = global(np: <module 'numpy' from '/usr/local/lib/python3.6/dist-packages/numpy/__init__.py'>) :: Module(<module 'numpy' from '/usr/local/lib/python3.6/dist-packages/numpy/__init__.py'>) # $0.2 = getattr(value=$0.1, attr=sin) :: Function(<ufunc 'sin'>) # del $0.1 # $0.4 = call $0.2(x, func=$0.2, args=[Var(x, <ipython-input-18-02574ac7ba04> (3))], kws=(), vararg=None) :: (int64,) -> float64 # del x # del $0.2 # $0.5 = cast(value=$0.4) :: float64 # del $0.4 # return $0.5 return np.sin(x) ==============================================" }, { "code": null, "e": 6871, "s": 6721, "text": "We are going to measure the performance of creating fractals using the Mandelbrot Set, and we will see how Numba helps us to improve our performance." }, { "code": null, "e": 6952, "s": 6871, "text": "1 loop, best of 3: 4.62 s per loop<matplotlib.image.AxesImage at 0x7f986ce23780>" }, { "code": null, "e": 7121, "s": 6952, "text": "It takes about 4.62 seconds to generate a fractal using Mandelbrot set, now we are going to improve the performance using Numba, we just have to add the @jit decorator." }, { "code": null, "e": 7275, "s": 7121, "text": "The slowest run took 4.17 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 52.4 ms per loop" }, { "code": null, "e": 7429, "s": 7275, "text": "We can observe how we have achieved to reduce the time to build fractals from 4.62 seconds to 52.4 ms... and this has been done only adding a decorator!!" }, { "code": null, "e": 7660, "s": 7429, "text": "We have said that Numba only works for numeric functions, although Numba compiles and runs any Python code, there are some types of data that it cannot compile yet (such as dictionaries) and it also makes no sense to compile them." }, { "code": null, "e": 7767, "s": 7660, "text": ">>> @jit>>> def dictionary(dict_test):>>> return dict_test['house']dictionary({'house': 2, 'car': 35})2" }, { "code": null, "e": 8031, "s": 7767, "text": "But it has not failed !! We have said that Numba does not compile dictionaries... The point here is that Numba creates 2 functions, one of them in Python and another in Numba. So here we are seeing the python solution, we can verify this by doing nopython = True." }, { "code": null, "e": 8074, "s": 8031, "text": "jit(nopython = True) is equivalent to njit" }, { "code": null, "e": 8873, "s": 8074, "text": ">>> @jit(nopython = True)>>> def dictionary(dict_test):>>> return dict_test['house']dictionary({'house': 2, 'car': 35})-----------------------------------------TypingError Traceback (most recent call last)<ipython-input-31-14d1c8683c01> in <module>() 3 return dict_test['house'] 4 ----> 5 dictionary({'house': 245, 'car': 350})2 frames/usr/local/lib/python3.6/dist-packages/numba/six.py in reraise(tp, value, tb) 656 value = tp() 657 if value.__traceback__ is not tb:--> 658 raise value.with_traceback(tb) 659 raise value 660TypingError: Failed in nopython mode pipeline (step: nopython frontend)Internal error at <numba.typeinfer.ArgConstraint object at 0x7f986c1bed68>:--%<-----------------------------------------" }, { "code": null, "e": 8923, "s": 8873, "text": "There are two ways to program in GPU using Numba:" }, { "code": null, "e": 8943, "s": 8923, "text": "1. ufuncs/gufuncs__" }, { "code": null, "e": 8982, "s": 8943, "text": "2. CUDA Python Kernels (Next tutorial)" }, { "code": null, "e": 9173, "s": 8982, "text": "One of the main design features of the GPU is the ability to handle data in parallel, so the universal functions of numpy (ufunc) are an ideal candidate to implement them in GPU programming." }, { "code": null, "e": 9279, "s": 9173, "text": "Note: ufunc are functions that perform the same operation on each element of a numpy array. For instance:" }, { "code": null, "e": 9532, "s": 9279, "text": "As we have said before, the ufunc functions are an ideal candidate to use them with GPU because of their parallelism. Therefore, Numba has the ability to create compiled ufunc functions without using C. To do this, we must use the decorator @vectorize." }, { "code": null, "e": 9614, "s": 9532, "text": "Let’s start with an example using @vectorize to compile and optimize a CPU ufunc." }, { "code": null, "e": 9642, "s": 9614, "text": "array([ 24, 343, 15, 9])" }, { "code": null, "e": 9870, "s": 9642, "text": "Instead of using the CPU to compile and execute the previous function, we are going to use CUDA in the GPU and for this we must use a “target attribute”. We will indicate what type each variable is (arguments and return value)." }, { "code": null, "e": 9937, "s": 9870, "text": "return_value_type(argument1_value_type, argument2_value_type, ...)" }, { "code": null, "e": 10115, "s": 9937, "text": "To do this, we will use the previous function that expects 2 int64 values and returns another int64 value. We will designate target = 'cuda' to be able to execute it in the GPU." }, { "code": null, "e": 10143, "s": 10115, "text": "array([ 24, 343, 15, 9])" }, { "code": null, "e": 10195, "s": 10143, "text": "We can check the speed of running it on CPU or GPU:" }, { "code": null, "e": 10601, "s": 10195, "text": ">>> %timeit np.add(a, b) # Numpy en CPUThe slowest run took 38.66 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 511 ns per loop>>> %timeit add_ufunc_gpu(a, b) # Numpy en GPUThe slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 755 μs per loop" }, { "code": null, "e": 10729, "s": 10601, "text": "GPU is slower than the CPU!!! Quiet, this has an explanation ... But first let’s see what happens when we call that function..." }, { "code": null, "e": 10776, "s": 10729, "text": "When we execute this function, Numba produces:" }, { "code": null, "e": 11052, "s": 10776, "text": "Compile a CUDA kernel to execute the ufunc function in parallel over all the elements of the input arrayAssign the inputs and outputs to the GPU memoryCopy the input to the GPURun the CUDA KernelCopy the results back from the GPU to the CPUReturn the results as a numpy array" }, { "code": null, "e": 11157, "s": 11052, "text": "Compile a CUDA kernel to execute the ufunc function in parallel over all the elements of the input array" }, { "code": null, "e": 11205, "s": 11157, "text": "Assign the inputs and outputs to the GPU memory" }, { "code": null, "e": 11231, "s": 11205, "text": "Copy the input to the GPU" }, { "code": null, "e": 11251, "s": 11231, "text": "Run the CUDA Kernel" }, { "code": null, "e": 11297, "s": 11251, "text": "Copy the results back from the GPU to the CPU" }, { "code": null, "e": 11333, "s": 11297, "text": "Return the results as a numpy array" }, { "code": null, "e": 11445, "s": 11333, "text": "As compared to the implementation in C, Numba allows you to perform these types of tasks in a more concise way." }, { "code": null, "e": 11481, "s": 11445, "text": "Why is the GPU slower than the CPU?" }, { "code": null, "e": 11688, "s": 11481, "text": "Our inputs are too small: The GPU achieves better performance using parallelism operating on thousands of values ​​at once. Our inputs are 4 or 64 dimensions, we need larger arrays to keep the GPU occupied." }, { "code": null, "e": 11980, "s": 11688, "text": "Very simple calculation: Sending the calculation to the GPU requires a lot of “effort” compared to calling the CPU function. If our function does not require excessive mathematical computation (this is usually called * arithmetic intensity *), then the GPU could take longer than in the CPU." }, { "code": null, "e": 12014, "s": 11980, "text": "Numba copies the data to the GPU." }, { "code": null, "e": 12403, "s": 12014, "text": "The variable types of our inputs are larger than necessary: ​​Our example uses int64 and we probably do not need them. Practically, in CPU, 32 and 64-bits have the same computing speed, but in GPU, 64-bits have a slight increase in computational speed (it can reach up to 24x slower respectively to 32-bits). So it is important to keep this in mind when executing our function in the GPU." }, { "code": null, "e": 12663, "s": 12403, "text": "With this in mind, we will try to apply what has been learned in the previous points to see if it is really faster to operate on the GPU than the CPU. We are going to calculate a density function, which is a slightly more complex operation with larger arrays." }, { "code": null, "e": 12751, "s": 12663, "text": "Let’s calculate the value of a Gaussian density function in x given the mean and sigma:" }, { "code": null, "e": 12953, "s": 12751, "text": ">>> %timeit norm_pdf.pdf(x, loc=mean, scale=sigma) # CPU function10 loops, best of 3: 60.8 ms per loop>>> %timeit gaussian_dens_gpu(x, mean, sigma) # GPU function100 loops, best of 3: 6.88 ms per loop" }, { "code": null, "e": 13024, "s": 12953, "text": "We can even define our function to be executed in the CPU using Numba." }, { "code": null, "e": 13113, "s": 13024, "text": ">>> %timeit gaussian_dens_cpu(x, mean, sigma) # CPU10 loops, best of 3: 23.6 ms per loop" }, { "code": null, "e": 13213, "s": 13113, "text": "It is even faster than the function written in Python, but slower than the one executed in the GPU." }, { "code": null, "e": 13463, "s": 13213, "text": "Unfortunately, there are several functions that do not fall within the scope of the definition of ufunc, therefore, to execute functions in the GPU that do not meet that requirement we use cuda.jit. We can use \"device functions\" that run on our GPU." }, { "code": null, "e": 13576, "s": 13463, "text": "Note: “devices functions” are functions that can only be called from a kernel or from another “device” function." }, { "code": null, "e": 13785, "s": 13576, "text": ">>> %timeit polar_distance(rho1, theta1, rho2, theta2)The slowest run took 23.16 times longer than the fastest. This could mean that an intermediate result is being cached. 1 loop, best of 3: 10.2 ms per loop" }, { "code": null, "e": 13968, "s": 13785, "text": "To sum up, Numba is a Python compiler, specifically for numerical functions and allows you to accelerate your applications with high performance functions written directly in Python." }, { "code": null, "e": 14181, "s": 13968, "text": "It is a stable tool, which allows you to optimize code oriented to operate with arrays. Thanks to its ease of use (just a decorator!!) provides us with a very powerful tool to improve the performance of our code." } ]
Aggregating and grouping data in SQL with Group by and Partition by | by Lan Chu | Towards Data Science
Aggregate functions are a very powerful tool to analyze the data and gain useful business insights. The most commonly used SQL aggregate functions include SUM, MAX, MIN, COUNT and AVERAGE. Aggregators are very often used in conjunction with Grouping functions in order to summarize the data. In this story, I will show you how to use a combination of aggregate function and grouping functions. Let’s parepare some sample data for this lesson using these scripts below. You can use different platforms of your choice, for instances SQL FIDDLE, KHAN ACADEMY etc. CREATE TABLE Customer (id INTEGER , name TEXT, product TEXT, OwnershipPercentage numeric(4,3) , Effective_date numeric);INSERT INTO Customer VALUES (1, “BankA”, “A01”, 0.028, 20180223) ;INSERT INTO Customer VALUES (1, “BankA”,”A02", 0.018, 20181224) ;INSERT INTO Customer VALUES (2, “BankB”,”B01", 0.025, 20190101) ;INSERT INTO Customer VALUES (2, “BankB”,”B02", 0.045, 20200101) ;select * from Customer; Now you see that for each customer, there are multiple (in this case, 2) records for OwnershipPercentage and effective dates with regard to different Products. Let’s say, I need to produce a report for my boss and want to do some data analytics to back my report up. Depending on what I want to see, I will use different aggregate functions. In this lesson, I will give examples using SUM() and MAX() functions. You can come up with different scenarios to play around with other functions. I would, for instance, like to see how the portfolio has changed over time for each customer compared to the previous report. To do so, I want to see the total ownership percentage for each customer regardless of Product. There are two ways I can do this: using GROUP BY AND PARTITION BY Using GROUPBY Very simple, what I can do is using aggregate SUM() function following by a ‘GROUP BY’ Clause. In the query, SUM() function will adds up all the values in a numeric column (OwnershipPercentage). GROUP BY clause groups all identical values in columns which are the attributes we choose, in this case Customer ID and Name. SELECT ID,Name,sum(p.ownershippercentage) AS onwership_percentageFROM Customer GROUP BY ID, Name Using OVER and PARTITION(BY) Another way to get somehow a similar result is using OVER and PARTITION(BY) function. To use the OVER and PARTITION BY clauses, you simply need to specify the column that you want your aggregated results to be partitioned by. The Over(partition by) clause will ask SQL to only add up the values inside each partition (Customer ID in this case). SELECT ID, Name,ProductID,OwnershipPercentage,sum(OwnershipPercentage) over(partition by ID) as total_ownership_percentageFROM Customer c With the above query, I will get a column called total_ownership_percentage which is the total of owership percentage values for each customer. Now you may have realized the differences between the output of GROUP BY and OVER(PARTITION BY). GROUP BY essentially reduces the number of returned records by rolling the data up using the attribute we specify. OVER(PARTITION BY) meanwhile provides rolled-up data without rolling up all the records. In this case, by using PARTITION BY, I will be able to return the OwnershipPercentage per given Product per Customer; and the total percentage per Customer in a same row. This would mean that I will have repeating data for the total OwnershipPercentage per Customer but the good thing is, no data has been lost during the aggregation — as opposed to the case with GROUP BY. SELECT ID,Name, p.OwnershipPercentage,max(c.OwnershipPercentage) as ownership_percentage FROM Customer c GROUP BY ID,Name Using the above code, I will receive this message: Column ‘Customer.OwnershipPercentage’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. This is because GROUP BY will only return unique results per group and the SELECT list can only consist aggregate functions or columns that are part of the GROUP BY clause. So depending on what you want to get, you can use different functions to get the optimal output. Go for GROUP BY when you need one unique record per group, and PARTITION BY would be the best opion when you do not want to lose any data but still want to do the aggregation. Using aggregate MAX() and GROUP BY Here is another scenario using MAX(). Let’s assume I now want to know the most recently added product and its OwnershipPercentage per Customer. One solution for this is applying aggregate Max() function and GROUP BY in a sub-query. A sub-query is a SELECT Statement within another SQL Statement. select c.Name, c.ownershippercentage,c.Effective_date as effective_datefrom Customer cinner join (select Name, max(Effective_date) as max_datefrom Customer group by Name) don c.Name = d.Nameand c.Effective_date = d.max_date The sub-query will return a table which I called “d”. With this sub-query, I get the latest Effective Date for each Customer in Table “d”. From that, I perform a JOIN between Table “Customer” and Table “d” to derive the OwnershipPercentage for that latest effective date. The above query will give you the desired output but is not the optimal solution. We had to use a JOIN statement and a combination of aggregate MAX() and GROUP BY in a sub-query which increases the complexity. Find below a more efficient code: SELECT c.ID, c.Name, c.ProductID, c.OwnershipPercentage, c.Effective_DateFROM Customer cWHERE c.Effective_Date = (SELECT MAX(p.Effective_Date) FROM Customer p WHERE p.ID = C.ID) Either way will give you the same result as below: Thank you for reading. I hope this helps with learning.
[ { "code": null, "e": 566, "s": 172, "text": "Aggregate functions are a very powerful tool to analyze the data and gain useful business insights. The most commonly used SQL aggregate functions include SUM, MAX, MIN, COUNT and AVERAGE. Aggregators are very often used in conjunction with Grouping functions in order to summarize the data. In this story, I will show you how to use a combination of aggregate function and grouping functions." }, { "code": null, "e": 733, "s": 566, "text": "Let’s parepare some sample data for this lesson using these scripts below. You can use different platforms of your choice, for instances SQL FIDDLE, KHAN ACADEMY etc." }, { "code": null, "e": 1138, "s": 733, "text": "CREATE TABLE Customer (id INTEGER , name TEXT, product TEXT, OwnershipPercentage numeric(4,3) , Effective_date numeric);INSERT INTO Customer VALUES (1, “BankA”, “A01”, 0.028, 20180223) ;INSERT INTO Customer VALUES (1, “BankA”,”A02\", 0.018, 20181224) ;INSERT INTO Customer VALUES (2, “BankB”,”B01\", 0.025, 20190101) ;INSERT INTO Customer VALUES (2, “BankB”,”B02\", 0.045, 20200101) ;select * from Customer;" }, { "code": null, "e": 1628, "s": 1138, "text": "Now you see that for each customer, there are multiple (in this case, 2) records for OwnershipPercentage and effective dates with regard to different Products. Let’s say, I need to produce a report for my boss and want to do some data analytics to back my report up. Depending on what I want to see, I will use different aggregate functions. In this lesson, I will give examples using SUM() and MAX() functions. You can come up with different scenarios to play around with other functions." }, { "code": null, "e": 1916, "s": 1628, "text": "I would, for instance, like to see how the portfolio has changed over time for each customer compared to the previous report. To do so, I want to see the total ownership percentage for each customer regardless of Product. There are two ways I can do this: using GROUP BY AND PARTITION BY" }, { "code": null, "e": 1930, "s": 1916, "text": "Using GROUPBY" }, { "code": null, "e": 2251, "s": 1930, "text": "Very simple, what I can do is using aggregate SUM() function following by a ‘GROUP BY’ Clause. In the query, SUM() function will adds up all the values in a numeric column (OwnershipPercentage). GROUP BY clause groups all identical values in columns which are the attributes we choose, in this case Customer ID and Name." }, { "code": null, "e": 2348, "s": 2251, "text": "SELECT ID,Name,sum(p.ownershippercentage) AS onwership_percentageFROM Customer GROUP BY ID, Name" }, { "code": null, "e": 2377, "s": 2348, "text": "Using OVER and PARTITION(BY)" }, { "code": null, "e": 2722, "s": 2377, "text": "Another way to get somehow a similar result is using OVER and PARTITION(BY) function. To use the OVER and PARTITION BY clauses, you simply need to specify the column that you want your aggregated results to be partitioned by. The Over(partition by) clause will ask SQL to only add up the values inside each partition (Customer ID in this case)." }, { "code": null, "e": 2860, "s": 2722, "text": "SELECT ID, Name,ProductID,OwnershipPercentage,sum(OwnershipPercentage) over(partition by ID) as total_ownership_percentageFROM Customer c" }, { "code": null, "e": 3004, "s": 2860, "text": "With the above query, I will get a column called total_ownership_percentage which is the total of owership percentage values for each customer." }, { "code": null, "e": 3679, "s": 3004, "text": "Now you may have realized the differences between the output of GROUP BY and OVER(PARTITION BY). GROUP BY essentially reduces the number of returned records by rolling the data up using the attribute we specify. OVER(PARTITION BY) meanwhile provides rolled-up data without rolling up all the records. In this case, by using PARTITION BY, I will be able to return the OwnershipPercentage per given Product per Customer; and the total percentage per Customer in a same row. This would mean that I will have repeating data for the total OwnershipPercentage per Customer but the good thing is, no data has been lost during the aggregation — as opposed to the case with GROUP BY." }, { "code": null, "e": 3801, "s": 3679, "text": "SELECT ID,Name, p.OwnershipPercentage,max(c.OwnershipPercentage) as ownership_percentage FROM Customer c GROUP BY ID,Name" }, { "code": null, "e": 4177, "s": 3801, "text": "Using the above code, I will receive this message: Column ‘Customer.OwnershipPercentage’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. This is because GROUP BY will only return unique results per group and the SELECT list can only consist aggregate functions or columns that are part of the GROUP BY clause." }, { "code": null, "e": 4450, "s": 4177, "text": "So depending on what you want to get, you can use different functions to get the optimal output. Go for GROUP BY when you need one unique record per group, and PARTITION BY would be the best opion when you do not want to lose any data but still want to do the aggregation." }, { "code": null, "e": 4485, "s": 4450, "text": "Using aggregate MAX() and GROUP BY" }, { "code": null, "e": 4629, "s": 4485, "text": "Here is another scenario using MAX(). Let’s assume I now want to know the most recently added product and its OwnershipPercentage per Customer." }, { "code": null, "e": 4781, "s": 4629, "text": "One solution for this is applying aggregate Max() function and GROUP BY in a sub-query. A sub-query is a SELECT Statement within another SQL Statement." }, { "code": null, "e": 5005, "s": 4781, "text": "select c.Name, c.ownershippercentage,c.Effective_date as effective_datefrom Customer cinner join (select Name, max(Effective_date) as max_datefrom Customer group by Name) don c.Name = d.Nameand c.Effective_date = d.max_date" }, { "code": null, "e": 5521, "s": 5005, "text": "The sub-query will return a table which I called “d”. With this sub-query, I get the latest Effective Date for each Customer in Table “d”. From that, I perform a JOIN between Table “Customer” and Table “d” to derive the OwnershipPercentage for that latest effective date. The above query will give you the desired output but is not the optimal solution. We had to use a JOIN statement and a combination of aggregate MAX() and GROUP BY in a sub-query which increases the complexity. Find below a more efficient code:" }, { "code": null, "e": 5699, "s": 5521, "text": "SELECT c.ID, c.Name, c.ProductID, c.OwnershipPercentage, c.Effective_DateFROM Customer cWHERE c.Effective_Date = (SELECT MAX(p.Effective_Date) FROM Customer p WHERE p.ID = C.ID)" }, { "code": null, "e": 5750, "s": 5699, "text": "Either way will give you the same result as below:" } ]
Interactive Geospatial AI Visualization in Jupyter Notebook | by Juan Nathaniel | Towards Data Science
Getting to know your data is key to building and deploying a robust AI/ML system in production. It is, therefore, imperative to perform a good Exploratory Data Analysis (EDA) beforehand prior to formulating an AI/ML solution. However, performing an EDA on Geospatial dataset may seem daunting and, often times, challenging, especially if you have to navigate through vast areas and many data layers for analysis. Fret not, with sufficient practice, you will get the hang of it and this post will hopefully help you get started on that! Table of Content: InstallationIntroduction to WidgetCreating a Simple MapCustomizing Your MapIntroduction to Layers, Raster, and VectorAdding Layer Installation Introduction to Widget Creating a Simple Map Customizing Your Map Introduction to Layers, Raster, and Vector Adding Layer For this tutorial on interactive geospatial data visualization in Jupyter Notebook, we are going to install ipyleaflet library. conda install -c conda-forge ipyleaflet Leaflet is one of the most popular JavaScript libraries for visualizing geospatial data. It is widely adopted by large institutions such as OpenStreetMap and MapBox. If you are looking for alternative to ipyleaflet, you can consider folium python package to assist you in the visualization of an interactive leaflet map. Now that we have covered the setting up phase, let’s deep dive into the topic for this post. What do you mean by interactive visualization in Jupyter? How can a widget achieve this? Most importantly, what is a widget? These questions will inevitably pop up when you start reading this post. For those of you who are familiar, take the next section as a quick refresher. Interactive Visualization? it simply means the ability to interact with your visualization in real-time. Take the following GIF for example. You are able to interact with the slider through a visual mean. Jupyter Widget? they are called “special objects” that can be initialized and displayed on the notebook. They are also bidirectional, meaning that a widget does not just display, but can take in user inputs that will subsequently trigger new computation. The most important thing is that they are extensible. Jupyter widget allows for other libraries to build additional features on top of its functionality, such as, our ipyleaflet. Now, we are ready to handle ipyleaflet. To start with, lets display a basic map of the world. First, we will need to import the ipyleaflet library and its Map object. from ipyleaflet import Map Then, we build and visualize the Map object given the coordinates of the center point and the zoom levels. Map(center = (60, -2.2), zoom = 2, min_zoom = 1, max_zoom = 20) In the GIF above, you are able to interact with the newly created map by scrolling and panning around the output visuals. Nicely done! We can also customize our map by styling the basemap, for example. First, we import another object called basemaps. from ipyleaflet import Map, basemaps Then we add in visualization to our Map object as follows. map = Map(center=(60,-2.2), zoom=2, basemap=basemaps.Stamen.Terrain) The map becomes prettier with the customized terrain basemaps. There are plenty of customization available. Do checkout their API reference for a more detailed explanation. Now, this will be where most of your EDA will take place. I’m going to showcase how to add layers and how to manipulate them. But first thing first. What are Layers? Layers are used to display geographic datasets. Their purpose is to separate different geographic information that may or may not correlate with each other. To showcase a map of a city, for example, you might want to display a layer of the basemap (highlighted earlier), the road network in the city, the housing places, the elevation level, and the presence of water bodies & recreational areas. Now, What is a Raster or Vector? Raster data is stored as a grid of values (think of an image with pixels) while vector data represents a specific feature such as a point, line, or polygon. The figure below provides a handy illustration to know what are layers, and the difference between raster / vector data. If you want a more detailed explanation on this topic, do checkout my other blog post below. towardsdatascience.com Last but not least, an interactive geospatial map is incomplete without the ability to add your own layers. Let’s first add a Raster layer by calling the add_layer() method. from ipyleaflet import basemap_to_tiles as btt, basemaps, Mapraster = btt(basemaps.NASAGIBS.ModisTerraTrueColorCR, "2019-06-24")map.add_layer(raster)map If you choose to remove this layer, then you can simply call the remove_layer() method. map.remove_layer(raster)map But what if you do not want to keep adding or removing layers by writing a code. You can do so on the map itself by adding a layer control. from ipyleaflet import LayersControlmap.add_control(LayersControl()) You can now have more controls over your layer in the map itself! That’s it for an introduction to interactive geospatial visualization on Jupyter Notebook. I will create a second part soon to discuss more advanced techniques such as map splitting, adding data from GeoJSON and other file format, etc. Stay tuned! Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization.
[ { "code": null, "e": 708, "s": 172, "text": "Getting to know your data is key to building and deploying a robust AI/ML system in production. It is, therefore, imperative to perform a good Exploratory Data Analysis (EDA) beforehand prior to formulating an AI/ML solution. However, performing an EDA on Geospatial dataset may seem daunting and, often times, challenging, especially if you have to navigate through vast areas and many data layers for analysis. Fret not, with sufficient practice, you will get the hang of it and this post will hopefully help you get started on that!" }, { "code": null, "e": 726, "s": 708, "text": "Table of Content:" }, { "code": null, "e": 856, "s": 726, "text": "InstallationIntroduction to WidgetCreating a Simple MapCustomizing Your MapIntroduction to Layers, Raster, and VectorAdding Layer" }, { "code": null, "e": 869, "s": 856, "text": "Installation" }, { "code": null, "e": 892, "s": 869, "text": "Introduction to Widget" }, { "code": null, "e": 914, "s": 892, "text": "Creating a Simple Map" }, { "code": null, "e": 935, "s": 914, "text": "Customizing Your Map" }, { "code": null, "e": 978, "s": 935, "text": "Introduction to Layers, Raster, and Vector" }, { "code": null, "e": 991, "s": 978, "text": "Adding Layer" }, { "code": null, "e": 1119, "s": 991, "text": "For this tutorial on interactive geospatial data visualization in Jupyter Notebook, we are going to install ipyleaflet library." }, { "code": null, "e": 1159, "s": 1119, "text": "conda install -c conda-forge ipyleaflet" }, { "code": null, "e": 1325, "s": 1159, "text": "Leaflet is one of the most popular JavaScript libraries for visualizing geospatial data. It is widely adopted by large institutions such as OpenStreetMap and MapBox." }, { "code": null, "e": 1480, "s": 1325, "text": "If you are looking for alternative to ipyleaflet, you can consider folium python package to assist you in the visualization of an interactive leaflet map." }, { "code": null, "e": 1573, "s": 1480, "text": "Now that we have covered the setting up phase, let’s deep dive into the topic for this post." }, { "code": null, "e": 1698, "s": 1573, "text": "What do you mean by interactive visualization in Jupyter? How can a widget achieve this? Most importantly, what is a widget?" }, { "code": null, "e": 1850, "s": 1698, "text": "These questions will inevitably pop up when you start reading this post. For those of you who are familiar, take the next section as a quick refresher." }, { "code": null, "e": 2055, "s": 1850, "text": "Interactive Visualization? it simply means the ability to interact with your visualization in real-time. Take the following GIF for example. You are able to interact with the slider through a visual mean." }, { "code": null, "e": 2489, "s": 2055, "text": "Jupyter Widget? they are called “special objects” that can be initialized and displayed on the notebook. They are also bidirectional, meaning that a widget does not just display, but can take in user inputs that will subsequently trigger new computation. The most important thing is that they are extensible. Jupyter widget allows for other libraries to build additional features on top of its functionality, such as, our ipyleaflet." }, { "code": null, "e": 2583, "s": 2489, "text": "Now, we are ready to handle ipyleaflet. To start with, lets display a basic map of the world." }, { "code": null, "e": 2656, "s": 2583, "text": "First, we will need to import the ipyleaflet library and its Map object." }, { "code": null, "e": 2683, "s": 2656, "text": "from ipyleaflet import Map" }, { "code": null, "e": 2790, "s": 2683, "text": "Then, we build and visualize the Map object given the coordinates of the center point and the zoom levels." }, { "code": null, "e": 2854, "s": 2790, "text": "Map(center = (60, -2.2), zoom = 2, min_zoom = 1, max_zoom = 20)" }, { "code": null, "e": 2989, "s": 2854, "text": "In the GIF above, you are able to interact with the newly created map by scrolling and panning around the output visuals. Nicely done!" }, { "code": null, "e": 3056, "s": 2989, "text": "We can also customize our map by styling the basemap, for example." }, { "code": null, "e": 3105, "s": 3056, "text": "First, we import another object called basemaps." }, { "code": null, "e": 3142, "s": 3105, "text": "from ipyleaflet import Map, basemaps" }, { "code": null, "e": 3201, "s": 3142, "text": "Then we add in visualization to our Map object as follows." }, { "code": null, "e": 3270, "s": 3201, "text": "map = Map(center=(60,-2.2), zoom=2, basemap=basemaps.Stamen.Terrain)" }, { "code": null, "e": 3333, "s": 3270, "text": "The map becomes prettier with the customized terrain basemaps." }, { "code": null, "e": 3443, "s": 3333, "text": "There are plenty of customization available. Do checkout their API reference for a more detailed explanation." }, { "code": null, "e": 3569, "s": 3443, "text": "Now, this will be where most of your EDA will take place. I’m going to showcase how to add layers and how to manipulate them." }, { "code": null, "e": 3592, "s": 3569, "text": "But first thing first." }, { "code": null, "e": 4006, "s": 3592, "text": "What are Layers? Layers are used to display geographic datasets. Their purpose is to separate different geographic information that may or may not correlate with each other. To showcase a map of a city, for example, you might want to display a layer of the basemap (highlighted earlier), the road network in the city, the housing places, the elevation level, and the presence of water bodies & recreational areas." }, { "code": null, "e": 4196, "s": 4006, "text": "Now, What is a Raster or Vector? Raster data is stored as a grid of values (think of an image with pixels) while vector data represents a specific feature such as a point, line, or polygon." }, { "code": null, "e": 4317, "s": 4196, "text": "The figure below provides a handy illustration to know what are layers, and the difference between raster / vector data." }, { "code": null, "e": 4410, "s": 4317, "text": "If you want a more detailed explanation on this topic, do checkout my other blog post below." }, { "code": null, "e": 4433, "s": 4410, "text": "towardsdatascience.com" }, { "code": null, "e": 4541, "s": 4433, "text": "Last but not least, an interactive geospatial map is incomplete without the ability to add your own layers." }, { "code": null, "e": 4607, "s": 4541, "text": "Let’s first add a Raster layer by calling the add_layer() method." }, { "code": null, "e": 4760, "s": 4607, "text": "from ipyleaflet import basemap_to_tiles as btt, basemaps, Mapraster = btt(basemaps.NASAGIBS.ModisTerraTrueColorCR, \"2019-06-24\")map.add_layer(raster)map" }, { "code": null, "e": 4848, "s": 4760, "text": "If you choose to remove this layer, then you can simply call the remove_layer() method." }, { "code": null, "e": 4876, "s": 4848, "text": "map.remove_layer(raster)map" }, { "code": null, "e": 5016, "s": 4876, "text": "But what if you do not want to keep adding or removing layers by writing a code. You can do so on the map itself by adding a layer control." }, { "code": null, "e": 5085, "s": 5016, "text": "from ipyleaflet import LayersControlmap.add_control(LayersControl())" }, { "code": null, "e": 5151, "s": 5085, "text": "You can now have more controls over your layer in the map itself!" }, { "code": null, "e": 5399, "s": 5151, "text": "That’s it for an introduction to interactive geospatial visualization on Jupyter Notebook. I will create a second part soon to discuss more advanced techniques such as map splitting, adding data from GeoJSON and other file format, etc. Stay tuned!" } ]
Binary tree to string with brackets - GeeksforGeeks
30 Jun, 2021 Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair “()”. Omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.Examples: Input : Preorder: [1, 2, 3, 4] 1 / \ 2 3 / 4 Output: "1(2(4))(3)" Explanation: Originally it needs to be "1(2(4) ())(3()())", but we need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)". Input : Preorder: [1, 2, 3, null, 4] 1 / \ 2 3 \ 4 Output: "1(2()(4))(3)" This is opposite of Construct Binary Tree from String with bracket representationThe idea is to do the preorder traversal of the given Binary Tree along with this, we need to make use of braces at appropriate positions. But, we also need to make sure that we omit the unnecessary braces. We print the current node and call the same given function for the left and the right children of the node in that order(if they exist). For every node encountered, the following cases are possible.Case 1: Both the left child and the right child exist for the current node. In this case, we need to put the braces () around both the left child’s preorder traversal output and the right child’s preorder traversal output.Case 2: None of the left or the right child exist for the current node. In this case, as shown in the figure below, considering empty braces for the null left and right children is redundant. Hence, we need not put braces for any of them. Case 3: Only the left child exists for the current node. As the figure below shows, putting empty braces for the right child in this case is unnecessary while considering the preorder traversal. This is because the right child will always come after the left child in the preorder traversal. Thus, omitting the empty braces for the right child also leads to same mapping between the string and the binary tree. Case 4: Only the right child exists for the current node. In this case, we need to consider the empty braces for the left child. This is because, during the preorder traversal, the left child needs to be considered first. Thus, to indicate that the child following the current node is a right child we need to put a pair of empty braces for the left child. C++ Java Python3 C# Javascript /* C++ program to construct string from binary tree*/#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} // Function to construct string from binary treevoid treeToString(Node* root, string& str){ // bases case if (root == NULL) return; // push the root data as character str.push_back(root->data + '0'); // if leaf node, then return if (!root->left && !root->right) return; // for left subtree str.push_back('('); treeToString(root->left, str); str.push_back(')'); // only if right child is present to // avoid extra parenthesis if (root->right) { str.push_back('('); treeToString(root->right, str); str.push_back(')'); }} // Driver Codeint main(){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); string str = ""; treeToString(root, str); cout << str;} // Java program to construct string from binary treeclass GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */static class Node{ int data; Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function to construct string from binary treestatic void treeToString(Node root){ // bases case if (root == null) return; // push the root data as character str += (Character.valueOf((char) (root.data + '0'))); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); }} // Driver Codepublic static void main(String[] args){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = ""; treeToString(root); System.out.println(str);}} // This code is contributed by 29AjayKumar # Python3 program to construct string from binary tree # A binary tree node has data, pointer to left# child and a pointer to right childclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to construct string from binary treedef treeToString(root: Node, string: list): # base case if root is None: return # push the root data as character string.append(str(root.data)) # if leaf node, then return if not root.left and not root.right: return # for left subtree string.append('(') treeToString(root.left, string) string.append(')') # only if right child is present to # avoid extra parenthesis if root.right: string.append('(') treeToString(root.right, string) string.append(')') # Driver Codeif __name__ == "__main__": # Let us construct below tree # 1 # / \ # 2 3 # / \ \ # 4 5 6 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) string = [] treeToString(root, string) print(''.join(string)) # This code is contributed by# sanjeev2552 // C# program to construct string from binary treeusing System; class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */public class Node{ public int data; public Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function to construct string from binary treestatic void treeToString(Node root){ // bases case if (root == null) return; // push the root data as character str += (char)(root.data + '0'); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); }} // Driver Codepublic static void Main(String[] args){ /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = ""; treeToString(root); Console.WriteLine(str);}} // This code is contributed by Princi Singh <script> // JavaScript program to construct string from binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let str; /* Helper function that allocates a new node */ function newNode(data) { let node = new Node(data); return (node); } // Function to construct string from binary tree function treeToString(root) { // bases case if (root == null) return; // push the root data as character str += String.fromCharCode(root.data + '0'.charCodeAt()); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); } } /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = ""; treeToString(root); document.write(str); </script> Output: 1(2(4)(5))(3()(6)) Time complexity: O(n) The preorder traversal is done over the n nodes. Space complexity: O(n). The depth of the recursion tree can go upto n in case of a skewed tree. YouTubeGeeksforGeeks500K subscribersBinary tree to string with brackets | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:59•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ymIgl_tFAwQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar princi singh sanjeev2552 rameshtravel07 Strings Tree Strings Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties)
[ { "code": null, "e": 25192, "s": 25164, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25522, "s": 25192, "text": "Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair “()”. Omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.Examples: " }, { "code": null, "e": 25891, "s": 25522, "text": "Input : Preorder: [1, 2, 3, 4]\n 1\n / \\\n 2 3\n / \n 4 \nOutput: \"1(2(4))(3)\"\nExplanation: Originally it needs to be \"1(2(4)\n())(3()())\", but we need to omit all the \nunnecessary empty parenthesis pairs. \nAnd it will be \"1(2(4))(3)\".\n\nInput : Preorder: [1, 2, 3, null, 4]\n 1\n / \\\n 2 3\n \\ \n 4 \nOutput: \"1(2()(4))(3)\"" }, { "code": null, "e": 26842, "s": 25893, "text": "This is opposite of Construct Binary Tree from String with bracket representationThe idea is to do the preorder traversal of the given Binary Tree along with this, we need to make use of braces at appropriate positions. But, we also need to make sure that we omit the unnecessary braces. We print the current node and call the same given function for the left and the right children of the node in that order(if they exist). For every node encountered, the following cases are possible.Case 1: Both the left child and the right child exist for the current node. In this case, we need to put the braces () around both the left child’s preorder traversal output and the right child’s preorder traversal output.Case 2: None of the left or the right child exist for the current node. In this case, as shown in the figure below, considering empty braces for the null left and right children is redundant. Hence, we need not put braces for any of them. " }, { "code": null, "e": 27255, "s": 26842, "text": "Case 3: Only the left child exists for the current node. As the figure below shows, putting empty braces for the right child in this case is unnecessary while considering the preorder traversal. This is because the right child will always come after the left child in the preorder traversal. Thus, omitting the empty braces for the right child also leads to same mapping between the string and the binary tree. " }, { "code": null, "e": 27614, "s": 27255, "text": "Case 4: Only the right child exists for the current node. In this case, we need to consider the empty braces for the left child. This is because, during the preorder traversal, the left child needs to be considered first. Thus, to indicate that the child following the current node is a right child we need to put a pair of empty braces for the left child. " }, { "code": null, "e": 27620, "s": 27616, "text": "C++" }, { "code": null, "e": 27625, "s": 27620, "text": "Java" }, { "code": null, "e": 27633, "s": 27625, "text": "Python3" }, { "code": null, "e": 27636, "s": 27633, "text": "C#" }, { "code": null, "e": 27647, "s": 27636, "text": "Javascript" }, { "code": "/* C++ program to construct string from binary tree*/#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node */Node* newNode(int data){ Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node);} // Function to construct string from binary treevoid treeToString(Node* root, string& str){ // bases case if (root == NULL) return; // push the root data as character str.push_back(root->data + '0'); // if leaf node, then return if (!root->left && !root->right) return; // for left subtree str.push_back('('); treeToString(root->left, str); str.push_back(')'); // only if right child is present to // avoid extra parenthesis if (root->right) { str.push_back('('); treeToString(root->right, str); str.push_back(')'); }} // Driver Codeint main(){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); string str = \"\"; treeToString(root, str); cout << str;}", "e": 29101, "s": 27647, "text": null }, { "code": "// Java program to construct string from binary treeclass GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */static class Node{ int data; Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function to construct string from binary treestatic void treeToString(Node root){ // bases case if (root == null) return; // push the root data as character str += (Character.valueOf((char) (root.data + '0'))); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); }} // Driver Codepublic static void main(String[] args){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = \"\"; treeToString(root); System.out.println(str);}} // This code is contributed by 29AjayKumar", "e": 30578, "s": 29101, "text": null }, { "code": "# Python3 program to construct string from binary tree # A binary tree node has data, pointer to left# child and a pointer to right childclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to construct string from binary treedef treeToString(root: Node, string: list): # base case if root is None: return # push the root data as character string.append(str(root.data)) # if leaf node, then return if not root.left and not root.right: return # for left subtree string.append('(') treeToString(root.left, string) string.append(')') # only if right child is present to # avoid extra parenthesis if root.right: string.append('(') treeToString(root.right, string) string.append(')') # Driver Codeif __name__ == \"__main__\": # Let us construct below tree # 1 # / \\ # 2 3 # / \\ \\ # 4 5 6 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) string = [] treeToString(root, string) print(''.join(string)) # This code is contributed by# sanjeev2552", "e": 31828, "s": 30578, "text": null }, { "code": "// C# program to construct string from binary treeusing System; class GFG{ /* A binary tree node has data, pointer to leftchild and a pointer to right child */public class Node{ public int data; public Node left, right;};static String str; /* Helper function that allocates a new node */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);} // Function to construct string from binary treestatic void treeToString(Node root){ // bases case if (root == null) return; // push the root data as character str += (char)(root.data + '0'); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); }} // Driver Codepublic static void Main(String[] args){ /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = \"\"; treeToString(root); Console.WriteLine(str);}} // This code is contributed by Princi Singh", "e": 33302, "s": 31828, "text": null }, { "code": "<script> // JavaScript program to construct string from binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let str; /* Helper function that allocates a new node */ function newNode(data) { let node = new Node(data); return (node); } // Function to construct string from binary tree function treeToString(root) { // bases case if (root == null) return; // push the root data as character str += String.fromCharCode(root.data + '0'.charCodeAt()); // if leaf node, then return if (root.left == null && root.right == null) return; // for left subtree str += ('('); treeToString(root.left); str += (')'); // only if right child is present to // avoid extra parenthesis if (root.right != null) { str += ('('); treeToString(root.right); str += (')'); } } /* Let us construct below tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.right = newNode(6); str = \"\"; treeToString(root); document.write(str); </script>", "e": 34745, "s": 33302, "text": null }, { "code": null, "e": 34755, "s": 34745, "text": "Output: " }, { "code": null, "e": 34774, "s": 34755, "text": "1(2(4)(5))(3()(6))" }, { "code": null, "e": 34943, "s": 34774, "text": "Time complexity: O(n) The preorder traversal is done over the n nodes. Space complexity: O(n). The depth of the recursion tree can go upto n in case of a skewed tree. " }, { "code": null, "e": 35777, "s": 34943, "text": "YouTubeGeeksforGeeks500K subscribersBinary tree to string with brackets | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:59•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ymIgl_tFAwQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35791, "s": 35779, "text": "29AjayKumar" }, { "code": null, "e": 35804, "s": 35791, "text": "princi singh" }, { "code": null, "e": 35816, "s": 35804, "text": "sanjeev2552" }, { "code": null, "e": 35831, "s": 35816, "text": "rameshtravel07" }, { "code": null, "e": 35839, "s": 35831, "text": "Strings" }, { "code": null, "e": 35844, "s": 35839, "text": "Tree" }, { "code": null, "e": 35852, "s": 35844, "text": "Strings" }, { "code": null, "e": 35857, "s": 35852, "text": "Tree" }, { "code": null, "e": 35955, "s": 35857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35964, "s": 35955, "text": "Comments" }, { "code": null, "e": 35977, "s": 35964, "text": "Old Comments" }, { "code": null, "e": 36034, "s": 35977, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 36070, "s": 36034, "text": "Convert string to char array in C++" }, { "code": null, "e": 36108, "s": 36070, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 36161, "s": 36108, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 36191, "s": 36161, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 36226, "s": 36191, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 36255, "s": 36226, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 36298, "s": 36255, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 36360, "s": 36298, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" } ]
C# | SortedDictionary.Item[] Property - GeeksforGeeks
01 Feb, 2019 This property is used to get or set the value associated with the specified key. Syntax: public TValue this[TKey key] { get; set; } Here, key is the Key of the value to get or set. Property Value: The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key. Exceptions: ArgumentNullException: If the key is null. KeyNotFoundException: If the property is retrieved and key does not exist in the collection. Example: // C# code to get or set the value// associated with the specified keyusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // Displaying the key/value pairs in myDict foreach(KeyValuePair<string, string> k in myDict) { Console.WriteLine("Key = {0}, Value = {1}", k.Key, k.Value); } // Displaying the value associated // with key "Russia" Console.Write("\nValue associated with Russia: "); Console.Write(myDict["Russia"]); // Setting the value associated with key "Russia" myDict["Russia"] = "Saint Petersburg"; // Displaying the value associated // with key "Russia" Console.Write("\n\nValue associated with"+ " Russia After Setting: "); Console.Write(myDict["Russia"]); // Displaying the value associated // with key "India" Console.Write("\n\nValue associated with India: "); Console.Write(myDict["India"]); // Setting the value associated with key "India" myDict["India"] = "Mumbai"; // Displaying the value associated // with key "India" Console.Write("\n\nValue associated "+ "with India After Setting: "); Console.Write(myDict["India"]); Console.WriteLine("\n"); // Displaying the key/value pairs in myDict foreach(KeyValuePair<string, string> k1 in myDict) { Console.WriteLine("Key = {0}, Value = {1}", k1.Key, k1.Value); } }} Key = Australia, Value = Canberra Key = Belgium, Value = Brussels Key = China, Value = Beijing Key = India, Value = New Delhi Key = Netherlands, Value = Amsterdam Key = Russia, Value = Moscow Value associated with Russia: Moscow Value associated with Russia After Setting: Saint Petersburg Value associated with India: New Delhi Value associated with India After Setting: Mumbai Key = Australia, Value = Canberra Key = Belgium, Value = Brussels Key = China, Value = Beijing Key = India, Value = Mumbai Key = Netherlands, Value = Amsterdam Key = Russia, Value = Saint Petersburg Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.item?view=netframework-4.7.2 CSharp SortedDictionary Class CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Constructors Introduction to .NET Framework
[ { "code": null, "e": 25963, "s": 25935, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26044, "s": 25963, "text": "This property is used to get or set the value associated with the specified key." }, { "code": null, "e": 26052, "s": 26044, "text": "Syntax:" }, { "code": null, "e": 26095, "s": 26052, "text": "public TValue this[TKey key] { get; set; }" }, { "code": null, "e": 26144, "s": 26095, "text": "Here, key is the Key of the value to get or set." }, { "code": null, "e": 26353, "s": 26144, "text": "Property Value: The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key." }, { "code": null, "e": 26365, "s": 26353, "text": "Exceptions:" }, { "code": null, "e": 26408, "s": 26365, "text": "ArgumentNullException: If the key is null." }, { "code": null, "e": 26501, "s": 26408, "text": "KeyNotFoundException: If the property is retrieved and key does not exist in the collection." }, { "code": null, "e": 26510, "s": 26501, "text": "Example:" }, { "code": "// C# code to get or set the value// associated with the specified keyusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // Displaying the key/value pairs in myDict foreach(KeyValuePair<string, string> k in myDict) { Console.WriteLine(\"Key = {0}, Value = {1}\", k.Key, k.Value); } // Displaying the value associated // with key \"Russia\" Console.Write(\"\\nValue associated with Russia: \"); Console.Write(myDict[\"Russia\"]); // Setting the value associated with key \"Russia\" myDict[\"Russia\"] = \"Saint Petersburg\"; // Displaying the value associated // with key \"Russia\" Console.Write(\"\\n\\nValue associated with\"+ \" Russia After Setting: \"); Console.Write(myDict[\"Russia\"]); // Displaying the value associated // with key \"India\" Console.Write(\"\\n\\nValue associated with India: \"); Console.Write(myDict[\"India\"]); // Setting the value associated with key \"India\" myDict[\"India\"] = \"Mumbai\"; // Displaying the value associated // with key \"India\" Console.Write(\"\\n\\nValue associated \"+ \"with India After Setting: \"); Console.Write(myDict[\"India\"]); Console.WriteLine(\"\\n\"); // Displaying the key/value pairs in myDict foreach(KeyValuePair<string, string> k1 in myDict) { Console.WriteLine(\"Key = {0}, Value = {1}\", k1.Key, k1.Value); } }}", "e": 28622, "s": 26510, "text": null }, { "code": null, "e": 29206, "s": 28622, "text": "Key = Australia, Value = Canberra\nKey = Belgium, Value = Brussels\nKey = China, Value = Beijing\nKey = India, Value = New Delhi\nKey = Netherlands, Value = Amsterdam\nKey = Russia, Value = Moscow\n\nValue associated with Russia: Moscow\n\nValue associated with Russia After Setting: Saint Petersburg\n\nValue associated with India: New Delhi\n\nValue associated with India After Setting: Mumbai\n\nKey = Australia, Value = Canberra\nKey = Belgium, Value = Brussels\nKey = China, Value = Beijing\nKey = India, Value = Mumbai\nKey = Netherlands, Value = Amsterdam\nKey = Russia, Value = Saint Petersburg\n" }, { "code": null, "e": 29217, "s": 29206, "text": "Reference:" }, { "code": null, "e": 29336, "s": 29217, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.item?view=netframework-4.7.2" }, { "code": null, "e": 29366, "s": 29336, "text": "CSharp SortedDictionary Class" }, { "code": null, "e": 29391, "s": 29366, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 29394, "s": 29391, "text": "C#" }, { "code": null, "e": 29492, "s": 29394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29507, "s": 29492, "text": "C# | Delegates" }, { "code": null, "e": 29530, "s": 29507, "text": "C# | Method Overriding" }, { "code": null, "e": 29552, "s": 29530, "text": "C# | Abstract Classes" }, { "code": null, "e": 29598, "s": 29552, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29621, "s": 29598, "text": "Extension Method in C#" }, { "code": null, "e": 29643, "s": 29621, "text": "C# | Class and Object" }, { "code": null, "e": 29665, "s": 29643, "text": "C# | Replace() Method" }, { "code": null, "e": 29705, "s": 29665, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29723, "s": 29705, "text": "C# | Constructors" } ]
How to Create a Foolproof Interactive Terminal Menu With Bash Scripts | by Shinichi Okada | Towards Data Science
If you are thinking of creating an interactive menu for your next Bash Script project, you are at the right place. In this article, we will create a simple menu template with colors for ease of navigation. Terminal commands use options to pass parameters to a program. These options can be a dash followed by one letter or two dashes with a word. If the option takes an argument it is called a switch, or otherwise, it is called a flag. Using a menu system for the terminal command makes it easy to navigate if your app has multilayers of commands. I used this method to create a terminal radio with colors added. The main menu function holds two menu items but you can add more for your project. The echo -e option allows us to use backslashes to escape characters, for example, a new line \n or a tab \t, if you need them. The echo -n option omits the trailing newline. Without the -n option, the cursor goes to the next line as you see in this image. All menus will contain the case statement to hold different choices. It makes it readable and more manageable than using multiple if statements. If a user select 1, it will show the sub-menu. You can change CMD1 to any menu name. Option 0 will exit the script and any other letters, *, will show a warning, and exit with the status of 1. The first sub-menu item, SUBCMD1, holds a subcommand that shows a sub-sub-menu. Once the sub-sub-menu completes the action, it will show the submenu again. The second menu item, Go Back to Main Menu sends you back to the main menu using the menu function in the case statement. We add simple functions for the first and second items in the sub-sub-menu. The third and fourth items will return to the submenu and main menu. We are repeating the same for 0 and * so let’s create common functions in the next section. Let’s create functions for the Exit and Wrong option: Then we can apply them to 0 and * in our case statements. case $ans in...0) fn_bye ;;*) fn_fail ;;esac... So far the menu is plain. Let’s add colors to our menus in the next section. These color functions can take an argument. For example: $(greenprint '1)') SUBCMD1$(magentaprint '2)') Go Back to Main Menu$(redprint '0)') Exit We use $(command) inside the quotes. It runs the command and replaces its output. For our menu, we are going to use magenta for Go Back to Main Menu and red for Exit, etc to make it consistent throughout the menu. Also, we will add different colors to menu names. $(magentaprint 'MAIN MENU')$(blueprint 'CMD1 SUBMENU')$(yellowprint 'SUB-SUBMENU') Let’s put it all together. In the final section of this article, you can test the script with an embedded interactive terminal console. Please have a go at navigating the different menu points. The following is the final code in action. I used this method in my terminal radio called tera. Please install it and see how I applied these menu systems in a real-life application. You can be creative and use emojis or Figlet letters for the menu items as well. An interactive menu system makes it easier to navigate through a complex menu system than a normal option parser system if your application has multilayered menu systems. I hope you can apply this code to your next Bash script projects. If you liked my article and would like to receive my newsletter, please sign up. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 378, "s": 172, "text": "If you are thinking of creating an interactive menu for your next Bash Script project, you are at the right place. In this article, we will create a simple menu template with colors for ease of navigation." }, { "code": null, "e": 609, "s": 378, "text": "Terminal commands use options to pass parameters to a program. These options can be a dash followed by one letter or two dashes with a word. If the option takes an argument it is called a switch, or otherwise, it is called a flag." }, { "code": null, "e": 786, "s": 609, "text": "Using a menu system for the terminal command makes it easy to navigate if your app has multilayers of commands. I used this method to create a terminal radio with colors added." }, { "code": null, "e": 869, "s": 786, "text": "The main menu function holds two menu items but you can add more for your project." }, { "code": null, "e": 1126, "s": 869, "text": "The echo -e option allows us to use backslashes to escape characters, for example, a new line \\n or a tab \\t, if you need them. The echo -n option omits the trailing newline. Without the -n option, the cursor goes to the next line as you see in this image." }, { "code": null, "e": 1271, "s": 1126, "text": "All menus will contain the case statement to hold different choices. It makes it readable and more manageable than using multiple if statements." }, { "code": null, "e": 1464, "s": 1271, "text": "If a user select 1, it will show the sub-menu. You can change CMD1 to any menu name. Option 0 will exit the script and any other letters, *, will show a warning, and exit with the status of 1." }, { "code": null, "e": 1742, "s": 1464, "text": "The first sub-menu item, SUBCMD1, holds a subcommand that shows a sub-sub-menu. Once the sub-sub-menu completes the action, it will show the submenu again. The second menu item, Go Back to Main Menu sends you back to the main menu using the menu function in the case statement." }, { "code": null, "e": 1979, "s": 1742, "text": "We add simple functions for the first and second items in the sub-sub-menu. The third and fourth items will return to the submenu and main menu. We are repeating the same for 0 and * so let’s create common functions in the next section." }, { "code": null, "e": 2033, "s": 1979, "text": "Let’s create functions for the Exit and Wrong option:" }, { "code": null, "e": 2091, "s": 2033, "text": "Then we can apply them to 0 and * in our case statements." }, { "code": null, "e": 2151, "s": 2091, "text": "case $ans in...0) fn_bye ;;*) fn_fail ;;esac..." }, { "code": null, "e": 2228, "s": 2151, "text": "So far the menu is plain. Let’s add colors to our menus in the next section." }, { "code": null, "e": 2285, "s": 2228, "text": "These color functions can take an argument. For example:" }, { "code": null, "e": 2374, "s": 2285, "text": "$(greenprint '1)') SUBCMD1$(magentaprint '2)') Go Back to Main Menu$(redprint '0)') Exit" }, { "code": null, "e": 2456, "s": 2374, "text": "We use $(command) inside the quotes. It runs the command and replaces its output." }, { "code": null, "e": 2638, "s": 2456, "text": "For our menu, we are going to use magenta for Go Back to Main Menu and red for Exit, etc to make it consistent throughout the menu. Also, we will add different colors to menu names." }, { "code": null, "e": 2721, "s": 2638, "text": "$(magentaprint 'MAIN MENU')$(blueprint 'CMD1 SUBMENU')$(yellowprint 'SUB-SUBMENU')" }, { "code": null, "e": 2915, "s": 2721, "text": "Let’s put it all together. In the final section of this article, you can test the script with an embedded interactive terminal console. Please have a go at navigating the different menu points." }, { "code": null, "e": 2958, "s": 2915, "text": "The following is the final code in action." }, { "code": null, "e": 3098, "s": 2958, "text": "I used this method in my terminal radio called tera. Please install it and see how I applied these menu systems in a real-life application." }, { "code": null, "e": 3179, "s": 3098, "text": "You can be creative and use emojis or Figlet letters for the menu items as well." }, { "code": null, "e": 3350, "s": 3179, "text": "An interactive menu system makes it easier to navigate through a complex menu system than a normal option parser system if your application has multilayered menu systems." }, { "code": null, "e": 3416, "s": 3350, "text": "I hope you can apply this code to your next Bash script projects." }, { "code": null, "e": 3497, "s": 3416, "text": "If you liked my article and would like to receive my newsletter, please sign up." } ]
Bitwise and (or &) of a range - GeeksforGeeks
24 Mar, 2022 Given two non-negative long integers, x and y given x <= y, the task is to find bit-wise and of all integers from x and y, i.e., we need to compute value of x & (x+1) & ... & (y-1) & y.7 Examples: Input : x = 12, y = 15 Output : 12 12 & 13 & 14 & 15 = 12 Input : x = 10, y = 20 Output : 0 A simple solution is to traverse all numbers from x to y and do bit-wise and of all numbers in range.An efficient solution is to follow following steps. 1) Find position of Most Significant Bit (MSB) in both numbers. 2) If positions of MSB are different, then result is 0. 3) If positions are same. Let positions be msb_p. ......a) We add 2msb_p to result. ......b) We subtract 2msb_p from x and y, ......c) Repeat steps 1, 2 and 3 for new values of x and y. Example 1 : x = 10, y = 20 Result is initially 0. Position of MSB in x = 3 Position of MSB in y = 4 Since positions are different, return result. Example 2 : x = 17, y = 19 Result is initially 0. Position of MSB in x = 4 Position of MSB in y = 4 Since positions are same, we compute 24. We add 24 to result. Result becomes 16. We subtract this value from x and y. New value of x = x - 24 = 17 - 16 = 1 New value of y = y - 24 = 19 - 16 = 3 Position of MSB in new x = 1 Position of MSB in new y = 2 Since positions are different, we return result. C++ Java Python3 C# PHP Javascript // An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // Find position of MSB in n. For example if n = 17,// then position of MSB is 4. If n = 7, value of MSB// is 3int msbPos(ll n){ int msb_p = -1; while (n) { n = n>>1; msb_p++; } return msb_p;} // Function to find Bit-wise & of all numbers from x// to y.ll andOperator(ll x, ll y){ ll res = 0; // Initialize result while (x && y) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result ll msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res;} // Driver codeint main(){ ll x = 10, y = 15; cout << andOperator(x, y); return 0;} // An efficient Java program to find bit-wise// & of all numbers from x to y.class GFG { // Find position of MSB in n. For example // if n = 17, then position of MSB is 4. // If n = 7, value of MSB is 3 static int msbPos(long n) { int msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise & of all // numbers from x to y. static long andOperator(long x, long y) { long res = 0; // Initialize result while (x > 0 && y > 0) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result long msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver code public static void main(String[] args) { long x = 10, y = 15; System.out.print(andOperator(x, y)); }} // This code is contributed by Anant Agarwal. # An efficient Python program to find# bit-wise & of all numbers from x to y. # Find position of MSB in n. For example# if n = 17, then position of MSB is 4.# If n = 7, value of MSB is 3def msbPos(n): msb_p = -1 while (n > 0): n = n >> 1 msb_p += 1 return msb_p # Function to find Bit-wise & of# all numbers from x to y.def andOperator(x, y): res = 0 # Initialize result while (x > 0 and y > 0): # Find positions of MSB in x and y msb_p1 = msbPos(x) msb_p2 = msbPos(y) # If positions are not same, return if (msb_p1 != msb_p2): break # Add 2^msb_p1 to result msb_val = (1 << msb_p1) res = res + msb_val # subtract 2^msb_p1 from x and y. x = x - msb_val y = y - msb_val return res # Driver codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Anant Agarwal. // An efficient C# program to find bit-wise & of all// numbers from x to y.using System; class GFG{ // Find position of MSB in n. // For example if n = 17, // then position of MSB is 4. // If n = 7, value of MSB // is 3 static int msbPos(long n) { int msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise // & of all numbers from x // to y. static long andOperator(long x, long y) { // Initialize result long res = 0; while (x > 0 && y > 0) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result long msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver code public static void Main() { long x = 10, y = 15; Console.WriteLine(andOperator(x, y)); }} // This code is contributed by Anant Agarwal. <?php// An efficient C++ program// to find bit-wise & of all// numbers from x to y. // Find position of MSB in n.// For example if n = 17, then// position of MSB is 4. If n = 7,// value of MSB is 3function msbPos($n){ $msb_p = -1; while ($n > 0) { $n = $n >> 1; $msb_p++; } return $msb_p;} // Function to find Bit-wise &// of all numbers from x to y.function andOperator($x, $y){ $res = 0; // Initialize result while ($x > 0 && $y > 0) { // Find positions of // MSB in x and y $msb_p1 = msbPos($x); $msb_p2 = msbPos($y); // If positions are not // same, return if ($msb_p1 != $msb_p2) break; // Add 2^msb_p1 to result $msb_val = (1 << $msb_p1); $res = $res + $msb_val; // subtract 2^msb_p1 // from x and y. $x = $x - $msb_val; $y = $y - $msb_val; } return $res;} // Driver code$x = 10;$y = 15;echo andOperator($x, $y); // This code is contributed// by ihritik?> <script> // Javascript program to find bit-wise// & of all numbers from x to y. // Find position of MSB in n. For example // if n = 17, then position of MSB is 4. // If n = 7, value of MSB is 3 function msbPos(n) { let msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise & of all // numbers from x to y. function andOperator(x, y) { let res = 0; // Initialize result while (x > 0 && y > 0) { // Find positions of MSB in x and y let msb_p1 = msbPos(x); let msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result let msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver Code let x = 10, y = 15; document.write(andOperator(x, y)); // This code is contributed by avijitmondal1998.</script> 8 More efficient solution Flip the LSB of b.And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer Flip the LSB of b. And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer if the number greater than ‘a’ again flip lsb if it is not then that’s the answer C++ Python3 // An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // Function to find Bit-wise & of all numbers from x// to y.ll andOperator(ll x, ll y){ // Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it for(int i=0; i<(int)log2(y)+1;i++) { //repeat till x >= y, otherwise return the answer. if (y <= x) { return y; } if (y & (1 << i)) { y &= ~(1UL << i); } } return y;} // Driver codeint main(){ ll x = 10, y = 15; cout << andOperator(x, y); return 0;} # An efficient Python program to find bit-wise & of# all numbers from x to y. # Importing math module for using logarithmimport math # Function to find Bit-wise & of all numbers from x# to y.def andOperator(x, y): # Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it for i in range(int(math.log2(y) + 1)): # repeat till x >= y, otherwise return the answer if(y <= x): return y if(y & 1 << i): y = y & (~(1<<i)) return y # Driver codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Pushpesh Raj 8 Another Approach We know that if a number num is a power of 2 then (num &(num – 1)) is equal to 0. So if a is less than 2^k and b is greater than or equal to 2^k, then the & of all values in between a and b should be zero as (2^k & (2^k – 1)) is equal to 0. So, if both a and b lies within the same number of bits then only answer wont be zero. Now, in every case last bit is bound to be zero because even if a and b are 2 side by side numbers last bit will be different. Similarly 2nd last bit will be zero if difference between a and b is greater than 2 and this goes on for every bit. Now, take example a = 1100(12) and b = 1111(15), then last bit should be zero of the answer. For 2nd last bit we need to check whether a/2 == b/2 because if they are equal then we know that b – a <= 2. So if a/2 and b/2 is not equal then we proceed. Now, 3rd last bit should have a difference of 4 which can be checked by a/ 4 != b/4. Hence we check every bit from last until a!=b and in every step we modify a/=2(a >> 1) and b/=2(b >> 1) to reduce a bit from end. Run a while loop as long as a != b and a > 0Right shift a by 1 and right shift b by 1increment shiftcountafter while loop return left * 2^(shiftcount) Run a while loop as long as a != b and a > 0 Right shift a by 1 and right shift b by 1 increment shiftcount after while loop return left * 2^(shiftcount) C++ Python3 // An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;#define int long long int // Function to find Bit-wise & of all numbers from x// to y.int andOperator(int a, int b) { // ShiftCount variables counts till which bit every value will convert to 0 int shiftcount = 0; //Iterate through every bit of a and b simultaneously //If a == b then we know that beyond that the and value will remain constant while(a != b and a > 0) { shiftcount++; a = a >> 1; b = b >> 1; } return int64_t(a << shiftcount);} // Driver codeint32_t main() { int a = 10, b = 15; cout << andOperator(a, b); return 0;} # An efficient Python program to find bit-wise & of# all numbers from x to y. # Function to find Bit-wise & of all numbers from x# to y.def andOperator(a,b): # ShiftCount variables counts till which bit every value will convert to 0 shiftcount=0 # Iterate through every bit of a and b simultaneously # If a == b then we know that beyond that the and value will remain constant while(a!=b and a>0): shiftcount=shiftcount+1 a=a>>1 b=b>>1 return a<<shiftcount# Driver codea, b =10, 15print(andOperator(a, b)) # This code is contributed by Pushpesh Raj Bibhu Pala ihritik SHUBHAMSINGH10 nayansachdeva7361 ApurvaRaj avijitmondal1998 moumenhamada30 longcodex pushpeshrajdx01 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Find the element that appears once 1's and 2's complement of a Binary Number
[ { "code": null, "e": 26277, "s": 26249, "text": "\n24 Mar, 2022" }, { "code": null, "e": 26476, "s": 26277, "text": "Given two non-negative long integers, x and y given x <= y, the task is to find bit-wise and of all integers from x and y, i.e., we need to compute value of x & (x+1) & ... & (y-1) & y.7 Examples: " }, { "code": null, "e": 26574, "s": 26476, "text": "Input : x = 12, y = 15\nOutput : 12 \n12 & 13 & 14 & 15 = 12 \n\nInput : x = 10, y = 20\nOutput : 0 " }, { "code": null, "e": 27036, "s": 26576, "text": "A simple solution is to traverse all numbers from x to y and do bit-wise and of all numbers in range.An efficient solution is to follow following steps. 1) Find position of Most Significant Bit (MSB) in both numbers. 2) If positions of MSB are different, then result is 0. 3) If positions are same. Let positions be msb_p. ......a) We add 2msb_p to result. ......b) We subtract 2msb_p from x and y, ......c) Repeat steps 1, 2 and 3 for new values of x and y. " }, { "code": null, "e": 27592, "s": 27036, "text": "Example 1 :\nx = 10, y = 20\nResult is initially 0.\nPosition of MSB in x = 3\nPosition of MSB in y = 4\nSince positions are different, return result.\n\nExample 2 :\nx = 17, y = 19\nResult is initially 0.\nPosition of MSB in x = 4\nPosition of MSB in y = 4\nSince positions are same, we compute 24.\n\nWe add 24 to result. \nResult becomes 16.\n\nWe subtract this value from x and y.\nNew value of x = x - 24 = 17 - 16 = 1\nNew value of y = y - 24 = 19 - 16 = 3\n\nPosition of MSB in new x = 1\nPosition of MSB in new y = 2\nSince positions are different, we return result." }, { "code": null, "e": 27598, "s": 27594, "text": "C++" }, { "code": null, "e": 27603, "s": 27598, "text": "Java" }, { "code": null, "e": 27611, "s": 27603, "text": "Python3" }, { "code": null, "e": 27614, "s": 27611, "text": "C#" }, { "code": null, "e": 27618, "s": 27614, "text": "PHP" }, { "code": null, "e": 27629, "s": 27618, "text": "Javascript" }, { "code": "// An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // Find position of MSB in n. For example if n = 17,// then position of MSB is 4. If n = 7, value of MSB// is 3int msbPos(ll n){ int msb_p = -1; while (n) { n = n>>1; msb_p++; } return msb_p;} // Function to find Bit-wise & of all numbers from x// to y.ll andOperator(ll x, ll y){ ll res = 0; // Initialize result while (x && y) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result ll msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res;} // Driver codeint main(){ ll x = 10, y = 15; cout << andOperator(x, y); return 0;}", "e": 28644, "s": 27629, "text": null }, { "code": "// An efficient Java program to find bit-wise// & of all numbers from x to y.class GFG { // Find position of MSB in n. For example // if n = 17, then position of MSB is 4. // If n = 7, value of MSB is 3 static int msbPos(long n) { int msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise & of all // numbers from x to y. static long andOperator(long x, long y) { long res = 0; // Initialize result while (x > 0 && y > 0) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result long msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver code public static void main(String[] args) { long x = 10, y = 15; System.out.print(andOperator(x, y)); }} // This code is contributed by Anant Agarwal.", "e": 29932, "s": 28644, "text": null }, { "code": "# An efficient Python program to find# bit-wise & of all numbers from x to y. # Find position of MSB in n. For example# if n = 17, then position of MSB is 4.# If n = 7, value of MSB is 3def msbPos(n): msb_p = -1 while (n > 0): n = n >> 1 msb_p += 1 return msb_p # Function to find Bit-wise & of# all numbers from x to y.def andOperator(x, y): res = 0 # Initialize result while (x > 0 and y > 0): # Find positions of MSB in x and y msb_p1 = msbPos(x) msb_p2 = msbPos(y) # If positions are not same, return if (msb_p1 != msb_p2): break # Add 2^msb_p1 to result msb_val = (1 << msb_p1) res = res + msb_val # subtract 2^msb_p1 from x and y. x = x - msb_val y = y - msb_val return res # Driver codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Anant Agarwal.", "e": 30854, "s": 29932, "text": null }, { "code": "// An efficient C# program to find bit-wise & of all// numbers from x to y.using System; class GFG{ // Find position of MSB in n. // For example if n = 17, // then position of MSB is 4. // If n = 7, value of MSB // is 3 static int msbPos(long n) { int msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise // & of all numbers from x // to y. static long andOperator(long x, long y) { // Initialize result long res = 0; while (x > 0 && y > 0) { // Find positions of MSB in x and y int msb_p1 = msbPos(x); int msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result long msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver code public static void Main() { long x = 10, y = 15; Console.WriteLine(andOperator(x, y)); }} // This code is contributed by Anant Agarwal.", "e": 32141, "s": 30854, "text": null }, { "code": "<?php// An efficient C++ program// to find bit-wise & of all// numbers from x to y. // Find position of MSB in n.// For example if n = 17, then// position of MSB is 4. If n = 7,// value of MSB is 3function msbPos($n){ $msb_p = -1; while ($n > 0) { $n = $n >> 1; $msb_p++; } return $msb_p;} // Function to find Bit-wise &// of all numbers from x to y.function andOperator($x, $y){ $res = 0; // Initialize result while ($x > 0 && $y > 0) { // Find positions of // MSB in x and y $msb_p1 = msbPos($x); $msb_p2 = msbPos($y); // If positions are not // same, return if ($msb_p1 != $msb_p2) break; // Add 2^msb_p1 to result $msb_val = (1 << $msb_p1); $res = $res + $msb_val; // subtract 2^msb_p1 // from x and y. $x = $x - $msb_val; $y = $y - $msb_val; } return $res;} // Driver code$x = 10;$y = 15;echo andOperator($x, $y); // This code is contributed// by ihritik?>", "e": 33161, "s": 32141, "text": null }, { "code": "<script> // Javascript program to find bit-wise// & of all numbers from x to y. // Find position of MSB in n. For example // if n = 17, then position of MSB is 4. // If n = 7, value of MSB is 3 function msbPos(n) { let msb_p = -1; while (n > 0) { n = n >> 1; msb_p++; } return msb_p; } // Function to find Bit-wise & of all // numbers from x to y. function andOperator(x, y) { let res = 0; // Initialize result while (x > 0 && y > 0) { // Find positions of MSB in x and y let msb_p1 = msbPos(x); let msb_p2 = msbPos(y); // If positions are not same, return if (msb_p1 != msb_p2) break; // Add 2^msb_p1 to result let msb_val = (1 << msb_p1); res = res + msb_val; // subtract 2^msb_p1 from x and y. x = x - msb_val; y = y - msb_val; } return res; } // Driver Code let x = 10, y = 15; document.write(andOperator(x, y)); // This code is contributed by avijitmondal1998.</script>", "e": 34378, "s": 33161, "text": null }, { "code": null, "e": 34380, "s": 34378, "text": "8" }, { "code": null, "e": 34406, "s": 34380, "text": "More efficient solution " }, { "code": null, "e": 34567, "s": 34406, "text": "Flip the LSB of b.And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer" }, { "code": null, "e": 34586, "s": 34567, "text": "Flip the LSB of b." }, { "code": null, "e": 34729, "s": 34586, "text": "And check if the new number is in range(a < number < b) or notif the number greater than ‘a’ again flip lsbif it is not then that’s the answer" }, { "code": null, "e": 34775, "s": 34729, "text": "if the number greater than ‘a’ again flip lsb" }, { "code": null, "e": 34811, "s": 34775, "text": "if it is not then that’s the answer" }, { "code": null, "e": 34815, "s": 34811, "text": "C++" }, { "code": null, "e": 34823, "s": 34815, "text": "Python3" }, { "code": "// An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // Function to find Bit-wise & of all numbers from x// to y.ll andOperator(ll x, ll y){ // Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it for(int i=0; i<(int)log2(y)+1;i++) { //repeat till x >= y, otherwise return the answer. if (y <= x) { return y; } if (y & (1 << i)) { y &= ~(1UL << i); } } return y;} // Driver codeint main(){ ll x = 10, y = 15; cout << andOperator(x, y); return 0;}", "e": 35470, "s": 34823, "text": null }, { "code": "# An efficient Python program to find bit-wise & of# all numbers from x to y. # Importing math module for using logarithmimport math # Function to find Bit-wise & of all numbers from x# to y.def andOperator(x, y): # Iterate over all bits of y, starting from the lsb, if it's equal to 1, flip it for i in range(int(math.log2(y) + 1)): # repeat till x >= y, otherwise return the answer if(y <= x): return y if(y & 1 << i): y = y & (~(1<<i)) return y # Driver codex, y = 10, 15print(andOperator(x, y)) # This code is contributed by Pushpesh Raj", "e": 36076, "s": 35470, "text": null }, { "code": null, "e": 36078, "s": 36076, "text": "8" }, { "code": null, "e": 36095, "s": 36078, "text": "Another Approach" }, { "code": null, "e": 37132, "s": 36095, "text": "We know that if a number num is a power of 2 then (num &(num – 1)) is equal to 0. So if a is less than 2^k and b is greater than or equal to 2^k, then the & of all values in between a and b should be zero as (2^k & (2^k – 1)) is equal to 0. So, if both a and b lies within the same number of bits then only answer wont be zero. Now, in every case last bit is bound to be zero because even if a and b are 2 side by side numbers last bit will be different. Similarly 2nd last bit will be zero if difference between a and b is greater than 2 and this goes on for every bit. Now, take example a = 1100(12) and b = 1111(15), then last bit should be zero of the answer. For 2nd last bit we need to check whether a/2 == b/2 because if they are equal then we know that b – a <= 2. So if a/2 and b/2 is not equal then we proceed. Now, 3rd last bit should have a difference of 4 which can be checked by a/ 4 != b/4. Hence we check every bit from last until a!=b and in every step we modify a/=2(a >> 1) and b/=2(b >> 1) to reduce a bit from end." }, { "code": null, "e": 37283, "s": 37132, "text": "Run a while loop as long as a != b and a > 0Right shift a by 1 and right shift b by 1increment shiftcountafter while loop return left * 2^(shiftcount)" }, { "code": null, "e": 37328, "s": 37283, "text": "Run a while loop as long as a != b and a > 0" }, { "code": null, "e": 37370, "s": 37328, "text": "Right shift a by 1 and right shift b by 1" }, { "code": null, "e": 37391, "s": 37370, "text": "increment shiftcount" }, { "code": null, "e": 37437, "s": 37391, "text": "after while loop return left * 2^(shiftcount)" }, { "code": null, "e": 37441, "s": 37437, "text": "C++" }, { "code": null, "e": 37449, "s": 37441, "text": "Python3" }, { "code": "// An efficient C++ program to find bit-wise & of all// numbers from x to y.#include<bits/stdc++.h>using namespace std;#define int long long int // Function to find Bit-wise & of all numbers from x// to y.int andOperator(int a, int b) { // ShiftCount variables counts till which bit every value will convert to 0 int shiftcount = 0; //Iterate through every bit of a and b simultaneously //If a == b then we know that beyond that the and value will remain constant while(a != b and a > 0) { shiftcount++; a = a >> 1; b = b >> 1; } return int64_t(a << shiftcount);} // Driver codeint32_t main() { int a = 10, b = 15; cout << andOperator(a, b); return 0;}", "e": 38169, "s": 37449, "text": null }, { "code": "# An efficient Python program to find bit-wise & of# all numbers from x to y. # Function to find Bit-wise & of all numbers from x# to y.def andOperator(a,b): # ShiftCount variables counts till which bit every value will convert to 0 shiftcount=0 # Iterate through every bit of a and b simultaneously # If a == b then we know that beyond that the and value will remain constant while(a!=b and a>0): shiftcount=shiftcount+1 a=a>>1 b=b>>1 return a<<shiftcount# Driver codea, b =10, 15print(andOperator(a, b)) # This code is contributed by Pushpesh Raj", "e": 38776, "s": 38169, "text": null }, { "code": null, "e": 38787, "s": 38776, "text": "Bibhu Pala" }, { "code": null, "e": 38795, "s": 38787, "text": "ihritik" }, { "code": null, "e": 38810, "s": 38795, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 38828, "s": 38810, "text": "nayansachdeva7361" }, { "code": null, "e": 38838, "s": 38828, "text": "ApurvaRaj" }, { "code": null, "e": 38855, "s": 38838, "text": "avijitmondal1998" }, { "code": null, "e": 38870, "s": 38855, "text": "moumenhamada30" }, { "code": null, "e": 38880, "s": 38870, "text": "longcodex" }, { "code": null, "e": 38896, "s": 38880, "text": "pushpeshrajdx01" }, { "code": null, "e": 38906, "s": 38896, "text": "Bit Magic" }, { "code": null, "e": 38916, "s": 38906, "text": "Bit Magic" }, { "code": null, "e": 39014, "s": 38916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39044, "s": 39014, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 39090, "s": 39044, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 39130, "s": 39090, "text": "Binary representation of a given number" }, { "code": null, "e": 39183, "s": 39130, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 39234, "s": 39183, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 39285, "s": 39234, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 39328, "s": 39285, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 39344, "s": 39328, "text": "Bit Fields in C" }, { "code": null, "e": 39379, "s": 39344, "text": "Find the element that appears once" } ]
PyTorch - Introduction to Convents
Convents is all about building the CNN model from scratch. The network architecture will contain a combination of following steps − Conv2d MaxPool2d Rectified Linear Unit View Linear Layer Training the model is the same process like image classification problems. The following code snippet completes the procedure of a training model on the provided dataset − def fit(epoch,model,data_loader,phase = 'training',volatile = False): if phase == 'training': model.train() if phase == 'training': model.train() if phase == 'validation': model.eval() volatile=True running_loss = 0.0 running_correct = 0 for batch_idx , (data,target) in enumerate(data_loader): if is_cuda: data,target = data.cuda(),target.cuda() data , target = Variable(data,volatile),Variable(target) if phase == 'training': optimizer.zero_grad() output = model(data) loss = F.nll_loss(output,target) running_loss + = F.nll_loss(output,target,size_average = False).data[0] preds = output.data.max(dim = 1,keepdim = True)[1] running_correct + = preds.eq(target.data.view_as(preds)).cpu().sum() if phase == 'training': loss.backward() optimizer.step() loss = running_loss/len(data_loader.dataset) accuracy = 100. * running_correct/len(data_loader.dataset) print(f'{phase} loss is {loss:{5}.{2}} and {phase} accuracy is {running_correct}/{len(data_loader.dataset)}{accuracy:{return loss,accuracy}}) The method includes different logic for training and validation. There are two primary reasons for using different modes − In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase. In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase. For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases. For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases. Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2259, "text": "Convents is all about building the CNN model from scratch. The network architecture will contain a combination of following steps −" }, { "code": null, "e": 2398, "s": 2391, "text": "Conv2d" }, { "code": null, "e": 2408, "s": 2398, "text": "MaxPool2d" }, { "code": null, "e": 2430, "s": 2408, "text": "Rectified Linear Unit" }, { "code": null, "e": 2435, "s": 2430, "text": "View" }, { "code": null, "e": 2448, "s": 2435, "text": "Linear Layer" }, { "code": null, "e": 2620, "s": 2448, "text": "Training the model is the same process like image classification problems. The following code snippet completes the procedure of a training model on the provided dataset −" }, { "code": null, "e": 3815, "s": 2620, "text": "def fit(epoch,model,data_loader,phase \n= 'training',volatile = False):\n if phase == 'training':\n model.train()\n if phase == 'training':\n model.train()\n if phase == 'validation':\n model.eval()\n volatile=True\n running_loss = 0.0\n running_correct = 0\n for batch_idx , (data,target) in enumerate(data_loader):\n if is_cuda:\n data,target = data.cuda(),target.cuda()\n data , target = Variable(data,volatile),Variable(target)\n if phase == 'training':\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output,target)\n running_loss + = \n F.nll_loss(output,target,size_average = \n False).data[0]\n preds = output.data.max(dim = 1,keepdim = True)[1]\n running_correct + = \n preds.eq(target.data.view_as(preds)).cpu().sum()\n if phase == 'training':\n loss.backward()\n optimizer.step()\n loss = running_loss/len(data_loader.dataset)\n accuracy = 100. * running_correct/len(data_loader.dataset)\n print(f'{phase} loss is {loss:{5}.{2}} and {phase} accuracy is {running_correct}/{len(data_loader.dataset)}{accuracy:{return loss,accuracy}})" }, { "code": null, "e": 3938, "s": 3815, "text": "The method includes different logic for training and validation. There are two primary reasons for using different modes −" }, { "code": null, "e": 4053, "s": 3938, "text": "In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase." }, { "code": null, "e": 4168, "s": 4053, "text": "In train mode, dropout removes a percentage of values, which should not happen in the validation or testing phase." }, { "code": null, "e": 4329, "s": 4168, "text": "For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases." }, { "code": null, "e": 4490, "s": 4329, "text": "For training mode, we calculate gradients and change the model's parameters value, but back propagation is not required during the testing or validation phases." }, { "code": null, "e": 4497, "s": 4490, "text": " Print" }, { "code": null, "e": 4508, "s": 4497, "text": " Add Notes" } ]
ConcurrentModificationException in Java with Examples - GeeksforGeeks
02 Apr, 2020 ConcurrentModificationException in Multi threaded environment In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown. If this exception is detected, then the results of the iteration are undefined.Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators. If this exception is detected, then the results of the iteration are undefined. Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators. For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed. ConcurrentModificationException in Single threaded environment Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment. If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException. For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException. Example: In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing, // Java program to show// ConcurrentModificationException import java.util.Iterator;import java.util.ArrayList; public class modificationError { public static void main(String args[]) { // Creating an object of ArrayList Object ArrayList<String> arr = new ArrayList<String>(); arr.add("One"); arr.add("Two"); arr.add("Three"); arr.add("Four"); try { // Printing the elements System.out.println( "ArrayList: "); Iterator<String> iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + ", "); // ConcurrentModificationException // is raised here as an element // is added during the iteration System.out.println( "\n\nTrying to add" + " an element in " + "between iteration\n"); arr.add("Five"); } } catch (Exception e) { System.out.println(e); } }} ArrayList: One, Trying to add an element in between iteration java.util.ConcurrentModificationException How to avoid ConcurrentModificationException? To avoid this exception, Simply we can do the modifications once the iteration is done, or Implement the concept of the synchronized block or method Example: Let’s see how to resolve this exception by simply changing the place of modification. // Java program to show// ConcurrentModificationException import java.util.Iterator;import java.util.ArrayList; public class modificationError { public static void main(String args[]) { // Creating an object of ArrayList Object ArrayList<String> arr = new ArrayList<String>(); arr.add("One"); arr.add("Two"); arr.add("Three"); arr.add("Four"); try { // Printing the elements System.out.println( "ArrayList: "); Iterator<String> iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + ", "); } // No exception is raised as // a modification is done // after the iteration System.out.println( "\n\nTrying to add" + " an element in " + "between iteration: " + arr.add("Five")); // Printing the elements System.out.println( "\nUpdated ArrayList: "); iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + ", "); } } catch (Exception e) { System.out.println(e); } }} ArrayList: One, Two, Three, Four, Trying to add an element in between iteration: true Updated ArrayList: One, Two, Three, Four, Five, From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated. Java-Exception Handling Java-Exceptions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Overriding in Java Set in Java
[ { "code": null, "e": 24524, "s": 24496, "text": "\n02 Apr, 2020" }, { "code": null, "e": 24586, "s": 24524, "text": "ConcurrentModificationException in Multi threaded environment" }, { "code": null, "e": 24815, "s": 24586, "text": "In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown." }, { "code": null, "e": 25024, "s": 24815, "text": "If this exception is detected, then the results of the iteration are undefined.Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators." }, { "code": null, "e": 25104, "s": 25024, "text": "If this exception is detected, then the results of the iteration are undefined." }, { "code": null, "e": 25234, "s": 25104, "text": "Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators." }, { "code": null, "e": 25406, "s": 25234, "text": "For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed." }, { "code": null, "e": 25469, "s": 25406, "text": "ConcurrentModificationException in Single threaded environment" }, { "code": null, "e": 25678, "s": 25469, "text": "Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment." }, { "code": null, "e": 25810, "s": 25678, "text": "If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException." }, { "code": null, "e": 25989, "s": 25810, "text": "For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException." }, { "code": null, "e": 26139, "s": 25989, "text": "Example: In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing," }, { "code": "// Java program to show// ConcurrentModificationException import java.util.Iterator;import java.util.ArrayList; public class modificationError { public static void main(String args[]) { // Creating an object of ArrayList Object ArrayList<String> arr = new ArrayList<String>(); arr.add(\"One\"); arr.add(\"Two\"); arr.add(\"Three\"); arr.add(\"Four\"); try { // Printing the elements System.out.println( \"ArrayList: \"); Iterator<String> iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + \", \"); // ConcurrentModificationException // is raised here as an element // is added during the iteration System.out.println( \"\\n\\nTrying to add\" + \" an element in \" + \"between iteration\\n\"); arr.add(\"Five\"); } } catch (Exception e) { System.out.println(e); } }}", "e": 27289, "s": 26139, "text": null }, { "code": null, "e": 27398, "s": 27289, "text": "ArrayList: \nOne, \n\nTrying to add an element in between iteration\n\njava.util.ConcurrentModificationException\n" }, { "code": null, "e": 27444, "s": 27398, "text": "How to avoid ConcurrentModificationException?" }, { "code": null, "e": 27469, "s": 27444, "text": "To avoid this exception," }, { "code": null, "e": 27535, "s": 27469, "text": "Simply we can do the modifications once the iteration is done, or" }, { "code": null, "e": 27593, "s": 27535, "text": "Implement the concept of the synchronized block or method" }, { "code": null, "e": 27688, "s": 27593, "text": "Example: Let’s see how to resolve this exception by simply changing the place of modification." }, { "code": "// Java program to show// ConcurrentModificationException import java.util.Iterator;import java.util.ArrayList; public class modificationError { public static void main(String args[]) { // Creating an object of ArrayList Object ArrayList<String> arr = new ArrayList<String>(); arr.add(\"One\"); arr.add(\"Two\"); arr.add(\"Three\"); arr.add(\"Four\"); try { // Printing the elements System.out.println( \"ArrayList: \"); Iterator<String> iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + \", \"); } // No exception is raised as // a modification is done // after the iteration System.out.println( \"\\n\\nTrying to add\" + \" an element in \" + \"between iteration: \" + arr.add(\"Five\")); // Printing the elements System.out.println( \"\\nUpdated ArrayList: \"); iter = arr.iterator(); while (iter.hasNext()) { System.out.print(iter.next() + \", \"); } } catch (Exception e) { System.out.println(e); } }}", "e": 29067, "s": 27688, "text": null }, { "code": null, "e": 29207, "s": 29067, "text": "ArrayList: \nOne, Two, Three, Four, \n\nTrying to add an element in between iteration: true\n\nUpdated ArrayList: \nOne, Two, Three, Four, Five,\n" }, { "code": null, "e": 29337, "s": 29207, "text": "From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated." }, { "code": null, "e": 29361, "s": 29337, "text": "Java-Exception Handling" }, { "code": null, "e": 29377, "s": 29361, "text": "Java-Exceptions" }, { "code": null, "e": 29382, "s": 29377, "text": "Java" }, { "code": null, "e": 29387, "s": 29382, "text": "Java" }, { "code": null, "e": 29485, "s": 29387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29494, "s": 29485, "text": "Comments" }, { "code": null, "e": 29507, "s": 29494, "text": "Old Comments" }, { "code": null, "e": 29539, "s": 29507, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29558, "s": 29539, "text": "Interfaces in Java" }, { "code": null, "e": 29589, "s": 29558, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29607, "s": 29589, "text": "ArrayList in Java" }, { "code": null, "e": 29658, "s": 29607, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29690, "s": 29658, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29710, "s": 29690, "text": "Stack Class in Java" }, { "code": null, "e": 29729, "s": 29710, "text": "LinkedList in Java" }, { "code": null, "e": 29748, "s": 29729, "text": "Overriding in Java" } ]
Lua - Basic Syntax
Let us start creating our first Lua program! Lua provides a mode called interactive mode. In this mode, you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just the lua command. Once you type in this, press Enter and the interactive mode will be started as shown below. $ lua -i $ Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio quit to end; cd, dir and edit also available You can print something using the following statement − print("test") Once you press enter, you will get the following output − test Invoking the interpreter with a Lua file name parameter begins execution of the file and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Lua program. All Lua files will have extension .lua. So put the following source code in a test.lua file. print("test") Assuming, lua environment is setup correctly, let’s run the program using the following code − $ lua test.lua We will get the following output − test Let's try another way to execute a Lua program. Below is the modified test.lua file − #!/usr/local/bin/lua print("test") Here, we have assumed that you have Lua interpreter available in your /usr/local/bin directory. The first line is ignored by the interpreter, if it starts with # sign. Now, try to run this program as follows − $ chmod a+rx test.lua $./test.lua We will get the following output. test Let us now see the basic structure of Lua program, so that it will be easy for you to understand the basic building blocks of the Lua programming language. A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Lua statement consists of three tokens − io.write("Hello world, from ",_VERSION,"!\n") The individual tokens are − io.write ( "Hello world, from ",_VERSION,"!\n" ) Comments are like helping text in your Lua program and they are ignored by the interpreter. They start with --[[ and terminates with the characters --]] as shown below − --[[ my first program in Lua --]] A Lua identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter ‘A to Z’ or ‘a to z’ or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). Lua does not allow punctuation characters such as @, $, and % within identifiers. Lua is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Lua. Here are some examples of the acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal The following list shows few of the reserved words in Lua. These reserved words may not be used as constants or variables or any other identifier names. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Lua interpreter totally ignores it. Whitespace is the term used in Lua to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int ends, and the next element begins. Therefore, in the following statement − local age There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges --get the total fruit No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose. 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2148, "s": 2103, "text": "Let us start creating our first Lua program!" }, { "code": null, "e": 2451, "s": 2148, "text": "Lua provides a mode called interactive mode. In this mode, you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just the lua command. Once you type in this, press Enter and the interactive mode will be started as shown below." }, { "code": null, "e": 2561, "s": 2451, "text": "$ lua -i \n$ Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio\nquit to end; cd, dir and edit also available\n" }, { "code": null, "e": 2617, "s": 2561, "text": "You can print something using the following statement −" }, { "code": null, "e": 2631, "s": 2617, "text": "print(\"test\")" }, { "code": null, "e": 2689, "s": 2631, "text": "Once you press enter, you will get the following output −" }, { "code": null, "e": 2695, "s": 2689, "text": "test\n" }, { "code": null, "e": 2890, "s": 2695, "text": "Invoking the interpreter with a Lua file name parameter begins execution of the file and continues until the script is finished. When the script is finished, the interpreter is no longer active." }, { "code": null, "e": 3018, "s": 2890, "text": "Let us write a simple Lua program. All Lua files will have extension .lua. So put the following source code in a test.lua file." }, { "code": null, "e": 3032, "s": 3018, "text": "print(\"test\")" }, { "code": null, "e": 3127, "s": 3032, "text": "Assuming, lua environment is setup correctly, let’s run the program using the following code −" }, { "code": null, "e": 3143, "s": 3127, "text": "$ lua test.lua\n" }, { "code": null, "e": 3178, "s": 3143, "text": "We will get the following output −" }, { "code": null, "e": 3184, "s": 3178, "text": "test\n" }, { "code": null, "e": 3270, "s": 3184, "text": "Let's try another way to execute a Lua program. Below is the modified test.lua file −" }, { "code": null, "e": 3306, "s": 3270, "text": "#!/usr/local/bin/lua\n\nprint(\"test\")" }, { "code": null, "e": 3516, "s": 3306, "text": "Here, we have assumed that you have Lua interpreter available in your /usr/local/bin directory. The first line is ignored by the interpreter, if it starts with # sign. Now, try to run this program as follows −" }, { "code": null, "e": 3551, "s": 3516, "text": "$ chmod a+rx test.lua\n$./test.lua\n" }, { "code": null, "e": 3585, "s": 3551, "text": "We will get the following output." }, { "code": null, "e": 3591, "s": 3585, "text": "test\n" }, { "code": null, "e": 3747, "s": 3591, "text": "Let us now see the basic structure of Lua program, so that it will be easy for you to understand the basic building blocks of the Lua programming language." }, { "code": null, "e": 3947, "s": 3747, "text": "A Lua program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Lua statement consists of three tokens −" }, { "code": null, "e": 3994, "s": 3947, "text": "io.write(\"Hello world, from \",_VERSION,\"!\\n\")\n" }, { "code": null, "e": 4022, "s": 3994, "text": "The individual tokens are −" }, { "code": null, "e": 4075, "s": 4022, "text": "io.write\n(\n \"Hello world, from \",_VERSION,\"!\\n\"\n)\n" }, { "code": null, "e": 4245, "s": 4075, "text": "Comments are like helping text in your Lua program and they are ignored by the interpreter. They start with --[[ and terminates with the characters --]] as shown below −" }, { "code": null, "e": 4280, "s": 4245, "text": "--[[ my first program in Lua --]]\n" }, { "code": null, "e": 4523, "s": 4280, "text": "A Lua identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter ‘A to Z’ or ‘a to z’ or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9)." }, { "code": null, "e": 4771, "s": 4523, "text": "Lua does not allow punctuation characters such as @, $, and % within identifiers. Lua is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Lua. Here are some examples of the acceptable identifiers −" }, { "code": null, "e": 4873, "s": 4771, "text": "mohd zara abc move_name a_123\nmyname50 _temp j a23b9 retVal\n" }, { "code": null, "e": 5026, "s": 4873, "text": "The following list shows few of the reserved words in Lua. These reserved words may not be used as constants or variables or any other identifier names." }, { "code": null, "e": 5154, "s": 5026, "text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and a Lua interpreter totally ignores it." }, { "code": null, "e": 5467, "s": 5154, "text": "Whitespace is the term used in Lua to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the interpreter to identify where one element in a statement, such as int ends, and the next element begins. Therefore, in the following statement −" }, { "code": null, "e": 5478, "s": 5467, "text": "local age\n" }, { "code": null, "e": 5666, "s": 5478, "text": "There must be at least one whitespace character (usually a space) between local and age for the interpreter to be able to distinguish them. On the other hand, in the following statement −" }, { "code": null, "e": 5716, "s": 5666, "text": "fruit = apples + oranges --get the total fruit\n" }, { "code": null, "e": 5876, "s": 5716, "text": "No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose." }, { "code": null, "e": 5909, "s": 5876, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 5923, "s": 5909, "text": " Manish Gupta" }, { "code": null, "e": 5956, "s": 5923, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 5972, "s": 5956, "text": " Sanjeev Mittal" }, { "code": null, "e": 6007, "s": 5972, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6023, "s": 6007, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 6030, "s": 6023, "text": " Print" }, { "code": null, "e": 6041, "s": 6030, "text": " Add Notes" } ]
SHA-256 Hash in Java
29 Apr, 2022 Definition: In Cryptography, SHA is cryptographic hash function which takes input as 20 Bytes and rendered the hash value in hexadecimal number, 40 digits long approx.Message Digest Class: To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text, they are: MD5SHA-1SHA-256 MD5 SHA-1 SHA-256 This Algorithms are initialized in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array.BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation. This representation is converted into hex format to get the MessageDigest Examples: Input : hello world Output: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 Input : GeeksForGeeks Output: 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade Input : K1t4fo0V Output: 0a979e43f4874eb24b740c0157994e34636eed0425688161cc58e8b26b1dcf4e Java import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; // Java program to calculate SHA hash value class GFG2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { // Static getInstance method is called with hashing SHA MessageDigest md = MessageDigest.getInstance("SHA-256"); // digest() method called // to calculate message digest of an input // and return array of byte return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { // Convert byte array into signum representation BigInteger number = new BigInteger(1, hash); // Convert message digest into hex value StringBuilder hexString = new StringBuilder(number.toString(16)); // Pad with leading zeros while (hexString.length() < 64) { hexString.insert(0, '0'); } return hexString.toString(); } // Driver code public static void main(String args[]) { try { System.out.println("HashCode Generated by SHA-256 for:"); String s1 = "GeeksForGeeks"; System.out.println("\n" + s1 + " : " + toHexString(getSHA(s1))); String s2 = "hello world"; System.out.println("\n" + s2 + " : " + toHexString(getSHA(s2))); String s3 = "K1t4fo0V"; System.out.println("\n" + s3 + " : " + toHexString(getSHA(s3))); } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown for incorrect algorithm: " + e); } }} Output: HashCode Generated by SHA-256 for: GeeksForGeeks : 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade hello world : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 K1t4fo0V : a979e43f4874eb24b740c0157994e34636eed0425688161cc58e8b26b1dcf4e Application: CryptographyData Integrity Cryptography Data Integrity paulsmithkc iamprasoonthewarrior cryptography Hash Java-Functions Java Hash Java cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2022" }, { "code": null, "e": 461, "s": 54, "text": "Definition: In Cryptography, SHA is cryptographic hash function which takes input as 20 Bytes and rendered the hash value in hexadecimal number, 40 digits long approx.Message Digest Class: To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.MessagDigest Class provides following cryptographic hash function to find hash value of a text, they are: " }, { "code": null, "e": 477, "s": 461, "text": "MD5SHA-1SHA-256" }, { "code": null, "e": 481, "s": 477, "text": "MD5" }, { "code": null, "e": 487, "s": 481, "text": "SHA-1" }, { "code": null, "e": 495, "s": 487, "text": "SHA-256" }, { "code": null, "e": 843, "s": 495, "text": "This Algorithms are initialized in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array.BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation. This representation is converted into hex format to get the MessageDigest" }, { "code": null, "e": 854, "s": 843, "text": "Examples: " }, { "code": null, "e": 1133, "s": 854, "text": "Input : hello world\nOutput: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\n\nInput : GeeksForGeeks\nOutput: 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade\n\nInput : K1t4fo0V\nOutput: 0a979e43f4874eb24b740c0157994e34636eed0425688161cc58e8b26b1dcf4e" }, { "code": null, "e": 1138, "s": 1133, "text": "Java" }, { "code": "import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; // Java program to calculate SHA hash value class GFG2 { public static byte[] getSHA(String input) throws NoSuchAlgorithmException { // Static getInstance method is called with hashing SHA MessageDigest md = MessageDigest.getInstance(\"SHA-256\"); // digest() method called // to calculate message digest of an input // and return array of byte return md.digest(input.getBytes(StandardCharsets.UTF_8)); } public static String toHexString(byte[] hash) { // Convert byte array into signum representation BigInteger number = new BigInteger(1, hash); // Convert message digest into hex value StringBuilder hexString = new StringBuilder(number.toString(16)); // Pad with leading zeros while (hexString.length() < 64) { hexString.insert(0, '0'); } return hexString.toString(); } // Driver code public static void main(String args[]) { try { System.out.println(\"HashCode Generated by SHA-256 for:\"); String s1 = \"GeeksForGeeks\"; System.out.println(\"\\n\" + s1 + \" : \" + toHexString(getSHA(s1))); String s2 = \"hello world\"; System.out.println(\"\\n\" + s2 + \" : \" + toHexString(getSHA(s2))); String s3 = \"K1t4fo0V\"; System.out.println(\"\\n\" + s3 + \" : \" + toHexString(getSHA(s3))); } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown for incorrect algorithm: \" + e); } }}", "e": 2920, "s": 1138, "text": null }, { "code": null, "e": 2928, "s": 2920, "text": "Output:" }, { "code": null, "e": 3200, "s": 2928, "text": "HashCode Generated by SHA-256 for:\n\nGeeksForGeeks : 112e476505aab51b05aeb2246c02a11df03e1187e886f7c55d4e9935c290ade\n\nhello world : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\n\nK1t4fo0V : a979e43f4874eb24b740c0157994e34636eed0425688161cc58e8b26b1dcf4e" }, { "code": null, "e": 3215, "s": 3200, "text": "Application: " }, { "code": null, "e": 3242, "s": 3215, "text": "CryptographyData Integrity" }, { "code": null, "e": 3255, "s": 3242, "text": "Cryptography" }, { "code": null, "e": 3270, "s": 3255, "text": "Data Integrity" }, { "code": null, "e": 3284, "s": 3272, "text": "paulsmithkc" }, { "code": null, "e": 3305, "s": 3284, "text": "iamprasoonthewarrior" }, { "code": null, "e": 3318, "s": 3305, "text": "cryptography" }, { "code": null, "e": 3323, "s": 3318, "text": "Hash" }, { "code": null, "e": 3338, "s": 3323, "text": "Java-Functions" }, { "code": null, "e": 3343, "s": 3338, "text": "Java" }, { "code": null, "e": 3348, "s": 3343, "text": "Hash" }, { "code": null, "e": 3353, "s": 3348, "text": "Java" }, { "code": null, "e": 3366, "s": 3353, "text": "cryptography" }, { "code": null, "e": 3464, "s": 3366, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3515, "s": 3464, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3546, "s": 3515, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3565, "s": 3546, "text": "Interfaces in Java" }, { "code": null, "e": 3595, "s": 3565, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3610, "s": 3595, "text": "Stream In Java" }, { "code": null, "e": 3628, "s": 3610, "text": "ArrayList in Java" }, { "code": null, "e": 3648, "s": 3628, "text": "Collections in Java" }, { "code": null, "e": 3672, "s": 3648, "text": "Singleton Class in Java" }, { "code": null, "e": 3704, "s": 3672, "text": "Multidimensional Arrays in Java" } ]
Python program to print Pascal’s Triangle
04 Jun, 2021 Pascal’s triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal’s triangle. Example: Input: N = 5 Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Method 1: Using nCr formula i.e. n!/(n-r)!r! After using nCr formula, the pictorial representation becomes: 0C0 1C0 1C1 2C0 2C1 2C2 3C0 3C1 3C2 3C3 Algorithm: Take a number of rows to be printed, lets assume it to be n Make outer iteration i from 0 to n times to print the rows. Make inner iteration for j from 0 to (N – 1). Print single blank space ” “. Close inner loop (j loop) //its needed for left spacing. Make inner iteration for j from 0 to i. Print nCr of i and j. Close inner loop. Print newline character (\n) after each inner iteration. Implementation: Python3 # Print Pascal's Triangle in Pythonfrom math import factorial # input nn = 5for i in range(n): for j in range(n-i+1): # for left spacing print(end=" ") for j in range(i+1): # nCr = n!/((n-r)!*r!) print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ") # for new line print() Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time complexity: O(N2) Method 2: We can optimize the above code by the following concept of a Binomial Coefficient, the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1). C(line, i) = C(line, i-1) * (line - i + 1) / i Implementations: Python3 # Print Pascal's Triangle in Python # input nn = 5 for i in range(1, n+1): for j in range(0, n-i+1): print(' ', end='') # first element is always 1 C = 1 for j in range(1, i+1): # first value in a line is always 1 print(' ', C, sep='', end='') # using Binomial Coefficient C = C * (i - j) // j print() Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time complexity: O(N2) Method 3: This is the most optimized approach to print Pascal’s triangle, this approach is based on powers of 11. 11**0 = 1 11**1 = 11 11**2 = 121 11**3 = 1331 Implementation: Python3 # Print Pascal's Triangle in Python # input nn = 5 # iterarte upto nfor i in range(n): # adjust space print(' '*(n-i), end='') # compute power of 11 print(' '.join(map(str, str(11**i)))) Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Time Complexity: O(N) However, this approach is applicable up to n=5 only. Vishank Shah pattern-printing Python Pattern-printing Technical Scripter 2020 Python Python Programs Technical Scripter pattern-printing 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jun, 2021" }, { "code": null, "e": 182, "s": 52, "text": "Pascal’s triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal’s triangle." }, { "code": null, "e": 191, "s": 182, "text": "Example:" }, { "code": null, "e": 262, "s": 191, "text": "Input: N = 5\nOutput:\n 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1" }, { "code": null, "e": 307, "s": 262, "text": "Method 1: Using nCr formula i.e. n!/(n-r)!r!" }, { "code": null, "e": 370, "s": 307, "text": "After using nCr formula, the pictorial representation becomes:" }, { "code": null, "e": 445, "s": 370, "text": " 0C0\n 1C0 1C1\n 2C0 2C1 2C2\n 3C0 3C1 3C2 3C3" }, { "code": null, "e": 456, "s": 445, "text": "Algorithm:" }, { "code": null, "e": 516, "s": 456, "text": "Take a number of rows to be printed, lets assume it to be n" }, { "code": null, "e": 576, "s": 516, "text": "Make outer iteration i from 0 to n times to print the rows." }, { "code": null, "e": 622, "s": 576, "text": "Make inner iteration for j from 0 to (N – 1)." }, { "code": null, "e": 652, "s": 622, "text": "Print single blank space ” “." }, { "code": null, "e": 709, "s": 652, "text": "Close inner loop (j loop) //its needed for left spacing." }, { "code": null, "e": 749, "s": 709, "text": "Make inner iteration for j from 0 to i." }, { "code": null, "e": 771, "s": 749, "text": "Print nCr of i and j." }, { "code": null, "e": 789, "s": 771, "text": "Close inner loop." }, { "code": null, "e": 846, "s": 789, "text": "Print newline character (\\n) after each inner iteration." }, { "code": null, "e": 862, "s": 846, "text": "Implementation:" }, { "code": null, "e": 870, "s": 862, "text": "Python3" }, { "code": "# Print Pascal's Triangle in Pythonfrom math import factorial # input nn = 5for i in range(n): for j in range(n-i+1): # for left spacing print(end=\" \") for j in range(i+1): # nCr = n!/((n-r)!*r!) print(factorial(i)//(factorial(j)*factorial(i-j)), end=\" \") # for new line print()", "e": 1193, "s": 870, "text": null }, { "code": null, "e": 1201, "s": 1193, "text": "Output:" }, { "code": null, "e": 1251, "s": 1201, "text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1" }, { "code": null, "e": 1274, "s": 1251, "text": "Time complexity: O(N2)" }, { "code": null, "e": 1529, "s": 1274, "text": "Method 2: We can optimize the above code by the following concept of a Binomial Coefficient, the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to calculate C(line, i) using C(line, i-1)." }, { "code": null, "e": 1576, "s": 1529, "text": "C(line, i) = C(line, i-1) * (line - i + 1) / i" }, { "code": null, "e": 1593, "s": 1576, "text": "Implementations:" }, { "code": null, "e": 1601, "s": 1593, "text": "Python3" }, { "code": "# Print Pascal's Triangle in Python # input nn = 5 for i in range(1, n+1): for j in range(0, n-i+1): print(' ', end='') # first element is always 1 C = 1 for j in range(1, i+1): # first value in a line is always 1 print(' ', C, sep='', end='') # using Binomial Coefficient C = C * (i - j) // j print()", "e": 1956, "s": 1601, "text": null }, { "code": null, "e": 1964, "s": 1956, "text": "Output:" }, { "code": null, "e": 2014, "s": 1964, "text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1" }, { "code": null, "e": 2037, "s": 2014, "text": "Time complexity: O(N2)" }, { "code": null, "e": 2151, "s": 2037, "text": "Method 3: This is the most optimized approach to print Pascal’s triangle, this approach is based on powers of 11." }, { "code": null, "e": 2197, "s": 2151, "text": "11**0 = 1\n11**1 = 11\n11**2 = 121\n11**3 = 1331" }, { "code": null, "e": 2213, "s": 2197, "text": "Implementation:" }, { "code": null, "e": 2221, "s": 2213, "text": "Python3" }, { "code": "# Print Pascal's Triangle in Python # input nn = 5 # iterarte upto nfor i in range(n): # adjust space print(' '*(n-i), end='') # compute power of 11 print(' '.join(map(str, str(11**i))))", "e": 2421, "s": 2221, "text": null }, { "code": null, "e": 2429, "s": 2421, "text": "Output:" }, { "code": null, "e": 2479, "s": 2429, "text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1" }, { "code": null, "e": 2501, "s": 2479, "text": "Time Complexity: O(N)" }, { "code": null, "e": 2554, "s": 2501, "text": "However, this approach is applicable up to n=5 only." }, { "code": null, "e": 2567, "s": 2554, "text": "Vishank Shah" }, { "code": null, "e": 2584, "s": 2567, "text": "pattern-printing" }, { "code": null, "e": 2608, "s": 2584, "text": "Python Pattern-printing" }, { "code": null, "e": 2632, "s": 2608, "text": "Technical Scripter 2020" }, { "code": null, "e": 2639, "s": 2632, "text": "Python" }, { "code": null, "e": 2655, "s": 2639, "text": "Python Programs" }, { "code": null, "e": 2674, "s": 2655, "text": "Technical Scripter" }, { "code": null, "e": 2691, "s": 2674, "text": "pattern-printing" }, { "code": null, "e": 2789, "s": 2691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2821, "s": 2789, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2848, "s": 2821, "text": "Python Classes and Objects" }, { "code": null, "e": 2869, "s": 2848, "text": "Python OOPs Concepts" }, { "code": null, "e": 2892, "s": 2869, "text": "Introduction To PYTHON" }, { "code": null, "e": 2948, "s": 2892, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2970, "s": 2948, "text": "Defaultdict in Python" }, { "code": null, "e": 3009, "s": 2970, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3047, "s": 3009, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3084, "s": 3047, "text": "Python Program for Fibonacci numbers" } ]
Substring Reverse Pattern
21 May, 2021 Given string str, the task is to print the pattern given in the examples below: Examples: Input: str = “geeks” Output: geeks *kee* **e** The reverse of “geeks” is “skeeg” Replace the first and last characters with ‘*’ i.e. *kee* Replace the second and second last character in the modified string i.e. **e** And so on. Input: str = “first” Output: first *sri* **r** Approach: Print the unmodified string. Reverse the string and initialize i = 0 and j = n – 1. Replace s[i] = ‘*’ and s[j] = ‘*’ and update i = i + 1 and j = j – 1 then print the modified string. Repeat the above steps while j – i > 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the required pattern#include <bits/stdc++.h>using namespace std; // Function to print the required patternvoid printPattern(char s[], int n){ // Print the unmodified string cout << s << "\n"; // Reverse the string int i = 0, j = n - 2; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character by '*' then // second and second last character and so on // until the string has characters remaining i = 0; j = n - 2; while (j - i > 1) { s[i] = s[j] = '*'; cout << s << "\n"; i++; j--; }} // Driver codeint main(){ char s[] = "geeks"; int n = sizeof(s) / sizeof(s[0]); printPattern(s, n); return 0;} // Java program to print the required patternclass GFG{ // Function to print the required patternstatic void printPattern(char[] s, int n){ // Print the unmodified string System.out.println(s); // Reverse the string int i = 0, j = n - 1; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character // by '*' then second and second last // character and so on until the string // has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; System.out.println(s); i++; j--; }} // Driver Codepublic static void main(String []args){ char[] s = "geeks".toCharArray(); int n = s.length; printPattern(s, n);}} // This code is contributed by Rituraj Jain # Python3 program to print the required pattern # Function to print the required patterndef printPattern(s, n): # Print the unmodified string print(''.join(s)) # Reverse the string i, j = 0, n - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 # Replace the first and last character # by '*' then second and second last # character and so on until the string # has characters remaining i, j = 0, n - 1 while j - i > 1: s[i], s[j] = '*', '*' print(''.join(s)) i += 1 j -= 1 # Driver codeif __name__ == "__main__": s = "geeks" n = len(s) printPattern(list(s), n) # This code is contributed# by Rituraj Jain // C# program to print the required patternusing System; class GFG{ // Function to print the required patternstatic void printPattern(char[] s, int n){ // Print the unmodified string Console.WriteLine(s); // Reverse the string int i = 0, j = n - 1; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character // by '*' then second and second last // character and so on until the string // has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; Console.WriteLine(s); i++; j--; }} // Driver Codepublic static void Main(String []args){ char[] s = "geeks".ToCharArray(); int n = s.Length; printPattern(s, n);}} // This code is contributed by 29AjayKumar <script> // Javascript program to print the required pattern // Function to print the required patternfunction printPattern(s, n){ // Print the unmodified string document.write( s.join('') + "<br>"); // Reverse the string var i = 0, j = n - 1; while (i < j) { var c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character by '*' then // second and second last character and so on // until the string has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; document.write( s.join('') + "<br>"); i++; j--; }} // Driver codevar s = "geeks".split('');var n = s.length;printPattern(s, n); </script> geeks *kee* **e** rituraj_jain 29AjayKumar importantly pattern-printing Reverse substring C Programs Strings Technical Scripter Strings pattern-printing Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 May, 2021" }, { "code": null, "e": 132, "s": 52, "text": "Given string str, the task is to print the pattern given in the examples below:" }, { "code": null, "e": 144, "s": 132, "text": "Examples: " }, { "code": null, "e": 373, "s": 144, "text": "Input: str = “geeks” Output: geeks *kee* **e** The reverse of “geeks” is “skeeg” Replace the first and last characters with ‘*’ i.e. *kee* Replace the second and second last character in the modified string i.e. **e** And so on." }, { "code": null, "e": 421, "s": 373, "text": "Input: str = “first” Output: first *sri* **r** " }, { "code": null, "e": 432, "s": 421, "text": "Approach: " }, { "code": null, "e": 461, "s": 432, "text": "Print the unmodified string." }, { "code": null, "e": 516, "s": 461, "text": "Reverse the string and initialize i = 0 and j = n – 1." }, { "code": null, "e": 617, "s": 516, "text": "Replace s[i] = ‘*’ and s[j] = ‘*’ and update i = i + 1 and j = j – 1 then print the modified string." }, { "code": null, "e": 657, "s": 617, "text": "Repeat the above steps while j – i > 1." }, { "code": null, "e": 709, "s": 657, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 713, "s": 709, "text": "C++" }, { "code": null, "e": 718, "s": 713, "text": "Java" }, { "code": null, "e": 726, "s": 718, "text": "Python3" }, { "code": null, "e": 729, "s": 726, "text": "C#" }, { "code": null, "e": 740, "s": 729, "text": "Javascript" }, { "code": "// C++ program to print the required pattern#include <bits/stdc++.h>using namespace std; // Function to print the required patternvoid printPattern(char s[], int n){ // Print the unmodified string cout << s << \"\\n\"; // Reverse the string int i = 0, j = n - 2; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character by '*' then // second and second last character and so on // until the string has characters remaining i = 0; j = n - 2; while (j - i > 1) { s[i] = s[j] = '*'; cout << s << \"\\n\"; i++; j--; }} // Driver codeint main(){ char s[] = \"geeks\"; int n = sizeof(s) / sizeof(s[0]); printPattern(s, n); return 0;}", "e": 1527, "s": 740, "text": null }, { "code": "// Java program to print the required patternclass GFG{ // Function to print the required patternstatic void printPattern(char[] s, int n){ // Print the unmodified string System.out.println(s); // Reverse the string int i = 0, j = n - 1; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character // by '*' then second and second last // character and so on until the string // has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; System.out.println(s); i++; j--; }} // Driver Codepublic static void main(String []args){ char[] s = \"geeks\".toCharArray(); int n = s.length; printPattern(s, n);}} // This code is contributed by Rituraj Jain", "e": 2369, "s": 1527, "text": null }, { "code": "# Python3 program to print the required pattern # Function to print the required patterndef printPattern(s, n): # Print the unmodified string print(''.join(s)) # Reverse the string i, j = 0, n - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 # Replace the first and last character # by '*' then second and second last # character and so on until the string # has characters remaining i, j = 0, n - 1 while j - i > 1: s[i], s[j] = '*', '*' print(''.join(s)) i += 1 j -= 1 # Driver codeif __name__ == \"__main__\": s = \"geeks\" n = len(s) printPattern(list(s), n) # This code is contributed# by Rituraj Jain", "e": 3092, "s": 2369, "text": null }, { "code": "// C# program to print the required patternusing System; class GFG{ // Function to print the required patternstatic void printPattern(char[] s, int n){ // Print the unmodified string Console.WriteLine(s); // Reverse the string int i = 0, j = n - 1; while (i < j) { char c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character // by '*' then second and second last // character and so on until the string // has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; Console.WriteLine(s); i++; j--; }} // Driver Codepublic static void Main(String []args){ char[] s = \"geeks\".ToCharArray(); int n = s.Length; printPattern(s, n);}} // This code is contributed by 29AjayKumar", "e": 3943, "s": 3092, "text": null }, { "code": "<script> // Javascript program to print the required pattern // Function to print the required patternfunction printPattern(s, n){ // Print the unmodified string document.write( s.join('') + \"<br>\"); // Reverse the string var i = 0, j = n - 1; while (i < j) { var c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; } // Replace the first and last character by '*' then // second and second last character and so on // until the string has characters remaining i = 0; j = n - 1; while (j - i > 1) { s[i] = s[j] = '*'; document.write( s.join('') + \"<br>\"); i++; j--; }} // Driver codevar s = \"geeks\".split('');var n = s.length;printPattern(s, n); </script>", "e": 4696, "s": 3943, "text": null }, { "code": null, "e": 4714, "s": 4696, "text": "geeks\n*kee*\n**e**" }, { "code": null, "e": 4729, "s": 4716, "text": "rituraj_jain" }, { "code": null, "e": 4741, "s": 4729, "text": "29AjayKumar" }, { "code": null, "e": 4753, "s": 4741, "text": "importantly" }, { "code": null, "e": 4770, "s": 4753, "text": "pattern-printing" }, { "code": null, "e": 4778, "s": 4770, "text": "Reverse" }, { "code": null, "e": 4788, "s": 4778, "text": "substring" }, { "code": null, "e": 4799, "s": 4788, "text": "C Programs" }, { "code": null, "e": 4807, "s": 4799, "text": "Strings" }, { "code": null, "e": 4826, "s": 4807, "text": "Technical Scripter" }, { "code": null, "e": 4834, "s": 4826, "text": "Strings" }, { "code": null, "e": 4851, "s": 4834, "text": "pattern-printing" }, { "code": null, "e": 4859, "s": 4851, "text": "Reverse" } ]
Path endsWith() method in Java with Examples
23 Jul, 2019 endswith() method of java.nio.file.Path usec to check if this path object ends with the given path or string which we passed as parameter.There are two types of endsWith() methods. endsWith(String other) method of java.nio.file.Path used to check if this path ends with a Path, constructed by converting the given path string which we passed as a parameter to this method. For example, this path “dir1/file1” ends with “dir1/file1” and “file1”. It does not end with “1” or “/file1”. Note that trailing separators are not taken into account, and so invoking this method on the Path”dir1/file1′′ with the String “file1/” returns true.Syntax:default boolean endsWith(String other) Parameters: This method accepts a single parameter other which is the given path string.Return value: This method returns true if this path ends with the given path; otherwise false.Exception: This method throws InvalidPathException If the path string cannot be converted to a Path.Below programs illustrate endsWith(String other) method:Program 1:// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\temp\\Spring"); // create a string object String passedPath = "Spring"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}Output:endsWith(Path other) method of java.nio.file.Path used to check if this path ends with the given path as parameter to method or not.This method return true if this path ends with the given path; otherwise false.If the passed path has N elements, and no root component and this path have N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.If the passed path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is filesystem-specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.If the given path is associated with a different FileSystem to this path then false is returned.Syntax:boolean endsWith(Path other) Parameters: This method accepts a single parameter other which is the given path.Return value: This method return true if this path ends with the given path; otherwise false.Below programs illustrate endsWith(Path other) method:Program 1:// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\eclipse" + "\\plugins" + "\\javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( "javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}Output: endsWith(String other) method of java.nio.file.Path used to check if this path ends with a Path, constructed by converting the given path string which we passed as a parameter to this method. For example, this path “dir1/file1” ends with “dir1/file1” and “file1”. It does not end with “1” or “/file1”. Note that trailing separators are not taken into account, and so invoking this method on the Path”dir1/file1′′ with the String “file1/” returns true.Syntax:default boolean endsWith(String other) Parameters: This method accepts a single parameter other which is the given path string.Return value: This method returns true if this path ends with the given path; otherwise false.Exception: This method throws InvalidPathException If the path string cannot be converted to a Path.Below programs illustrate endsWith(String other) method:Program 1:// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\temp\\Spring"); // create a string object String passedPath = "Spring"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}Output: Syntax: default boolean endsWith(String other) Parameters: This method accepts a single parameter other which is the given path string. Return value: This method returns true if this path ends with the given path; otherwise false. Exception: This method throws InvalidPathException If the path string cannot be converted to a Path. Below programs illustrate endsWith(String other) method:Program 1: // Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\temp\\Spring"); // create a string object String passedPath = "Spring"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }} endsWith(Path other) method of java.nio.file.Path used to check if this path ends with the given path as parameter to method or not.This method return true if this path ends with the given path; otherwise false.If the passed path has N elements, and no root component and this path have N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.If the passed path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is filesystem-specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.If the given path is associated with a different FileSystem to this path then false is returned.Syntax:boolean endsWith(Path other) Parameters: This method accepts a single parameter other which is the given path.Return value: This method return true if this path ends with the given path; otherwise false.Below programs illustrate endsWith(Path other) method:Program 1:// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\eclipse" + "\\plugins" + "\\javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( "javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }}Output: Syntax: boolean endsWith(Path other) Parameters: This method accepts a single parameter other which is the given path. Return value: This method return true if this path ends with the given path; otherwise false. Below programs illustrate endsWith(Path other) method:Program 1: // Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("D:\\eclipse" + "\\plugins" + "\\javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( "javax.xml.rpc_1.1.0.v201209140446" + "\\lib"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println("Path ends with " + passedPath + " :" + check); }} References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.lang.String) https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.nio.file.Path) Java-Functions Java-Path java.nio.file package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jul, 2019" }, { "code": null, "e": 234, "s": 53, "text": "endswith() method of java.nio.file.Path usec to check if this path object ends with the given path or string which we passed as parameter.There are two types of endsWith() methods." }, { "code": null, "e": 3972, "s": 234, "text": "endsWith(String other) method of java.nio.file.Path used to check if this path ends with a Path, constructed by converting the given path string which we passed as a parameter to this method. For example, this path “dir1/file1” ends with “dir1/file1” and “file1”. It does not end with “1” or “/file1”. Note that trailing separators are not taken into account, and so invoking this method on the Path”dir1/file1′′ with the String “file1/” returns true.Syntax:default boolean endsWith(String other)\nParameters: This method accepts a single parameter other which is the given path string.Return value: This method returns true if this path ends with the given path; otherwise false.Exception: This method throws InvalidPathException If the path string cannot be converted to a Path.Below programs illustrate endsWith(String other) method:Program 1:// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"\\\\temp\\\\Spring\"); // create a string object String passedPath = \"Spring\"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}Output:endsWith(Path other) method of java.nio.file.Path used to check if this path ends with the given path as parameter to method or not.This method return true if this path ends with the given path; otherwise false.If the passed path has N elements, and no root component and this path have N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.If the passed path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is filesystem-specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.If the given path is associated with a different FileSystem to this path then false is returned.Syntax:boolean endsWith(Path other)\nParameters: This method accepts a single parameter other which is the given path.Return value: This method return true if this path ends with the given path; otherwise false.Below programs illustrate endsWith(Path other) method:Program 1:// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"D:\\\\eclipse\" + \"\\\\plugins\" + \"\\\\javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( \"javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}Output:" }, { "code": null, "e": 5460, "s": 3972, "text": "endsWith(String other) method of java.nio.file.Path used to check if this path ends with a Path, constructed by converting the given path string which we passed as a parameter to this method. For example, this path “dir1/file1” ends with “dir1/file1” and “file1”. It does not end with “1” or “/file1”. Note that trailing separators are not taken into account, and so invoking this method on the Path”dir1/file1′′ with the String “file1/” returns true.Syntax:default boolean endsWith(String other)\nParameters: This method accepts a single parameter other which is the given path string.Return value: This method returns true if this path ends with the given path; otherwise false.Exception: This method throws InvalidPathException If the path string cannot be converted to a Path.Below programs illustrate endsWith(String other) method:Program 1:// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"\\\\temp\\\\Spring\"); // create a string object String passedPath = \"Spring\"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}Output:" }, { "code": null, "e": 5468, "s": 5460, "text": "Syntax:" }, { "code": null, "e": 5508, "s": 5468, "text": "default boolean endsWith(String other)\n" }, { "code": null, "e": 5597, "s": 5508, "text": "Parameters: This method accepts a single parameter other which is the given path string." }, { "code": null, "e": 5692, "s": 5597, "text": "Return value: This method returns true if this path ends with the given path; otherwise false." }, { "code": null, "e": 5793, "s": 5692, "text": "Exception: This method throws InvalidPathException If the path string cannot be converted to a Path." }, { "code": null, "e": 5860, "s": 5793, "text": "Below programs illustrate endsWith(String other) method:Program 1:" }, { "code": "// Java program to demonstrate// Path.endsWith(String other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"\\\\temp\\\\Spring\"); // create a string object String passedPath = \"Spring\"; // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}", "e": 6496, "s": 5860, "text": null }, { "code": null, "e": 8747, "s": 6496, "text": "endsWith(Path other) method of java.nio.file.Path used to check if this path ends with the given path as parameter to method or not.This method return true if this path ends with the given path; otherwise false.If the passed path has N elements, and no root component and this path have N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.If the passed path has a root component then this path ends with the given path if the root component of this path ends with the root component of the given path, and the corresponding elements of both paths are equal. Whether or not the root component of this path ends with the root component of the given path is filesystem-specific. If this path does not have a root component and the given path has a root component then this path does not end with the given path.If the given path is associated with a different FileSystem to this path then false is returned.Syntax:boolean endsWith(Path other)\nParameters: This method accepts a single parameter other which is the given path.Return value: This method return true if this path ends with the given path; otherwise false.Below programs illustrate endsWith(Path other) method:Program 1:// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"D:\\\\eclipse\" + \"\\\\plugins\" + \"\\\\javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( \"javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}Output:" }, { "code": null, "e": 8755, "s": 8747, "text": "Syntax:" }, { "code": null, "e": 8785, "s": 8755, "text": "boolean endsWith(Path other)\n" }, { "code": null, "e": 8867, "s": 8785, "text": "Parameters: This method accepts a single parameter other which is the given path." }, { "code": null, "e": 8961, "s": 8867, "text": "Return value: This method return true if this path ends with the given path; otherwise false." }, { "code": null, "e": 9026, "s": 8961, "text": "Below programs illustrate endsWith(Path other) method:Program 1:" }, { "code": "// Java program to demonstrate// java.nio.file.Path.(Path other) method import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"D:\\\\eclipse\" + \"\\\\plugins\" + \"\\\\javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // create a path object which we will pass // to endsWith method to check functionality // of endsWith(Path other) method Path passedPath = Paths.get( \"javax.xml.rpc_1.1.0.v201209140446\" + \"\\\\lib\"); // call endsWith() to check path object // ends with passedPath or not boolean check = path.endsWith(passedPath); // print result System.out.println(\"Path ends with \" + passedPath + \" :\" + check); }}", "e": 9989, "s": 9026, "text": null }, { "code": null, "e": 10001, "s": 9989, "text": "References:" }, { "code": null, "e": 10095, "s": 10001, "text": "https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.lang.String)" }, { "code": null, "e": 10191, "s": 10095, "text": "https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#endsWith(java.nio.file.Path)" }, { "code": null, "e": 10206, "s": 10191, "text": "Java-Functions" }, { "code": null, "e": 10216, "s": 10206, "text": "Java-Path" }, { "code": null, "e": 10238, "s": 10216, "text": "java.nio.file package" }, { "code": null, "e": 10243, "s": 10238, "text": "Java" }, { "code": null, "e": 10248, "s": 10243, "text": "Java" } ]
Java Swing | GroupLayout Class
20 May, 2022 GroupLayout is a LayoutManager that hierarchically group the components and arranges them in a Container. Grouping is done by using the instances of the Group class. It is generally used for developing a GUI ( Graphic User Interface) builders such as Matisse, the GUI builder provided with the NetBeans IDE. GroupLayout Class supports two types of groups: A sequential group positions its child elements sequentially, one after another. A parallel group aligns its child elements in different ways. Constructor of the class: GroupLayout(Container host): It is used to create a GroupLayout for the specified Container. Commonly Used Methods: addLayoutComponent(Component comp, Object cons): Notify that a Component has been added to the parent container.getHonorsVisibility(): Returns whether component visibility is considered when sizing and positioning components.maximumLayoutSize(Container parent): Returns the maximum size for the specified container.getLayoutAlignmentX(along horizontal axis): It returns the alignment along the x axis.minimumLayoutSize(Container parent): Returns the minimum size for the specified container.getLayoutStyle(): Returns the LayoutStyle used for calculating the preferred gap between components. addLayoutComponent(Component comp, Object cons): Notify that a Component has been added to the parent container. getHonorsVisibility(): Returns whether component visibility is considered when sizing and positioning components. maximumLayoutSize(Container parent): Returns the maximum size for the specified container. getLayoutAlignmentX(along horizontal axis): It returns the alignment along the x axis. minimumLayoutSize(Container parent): Returns the minimum size for the specified container. getLayoutStyle(): Returns the LayoutStyle used for calculating the preferred gap between components. Below programs illustrate the use of GroupLayout class: The following program illustrates the use of GropuLayout by arranging JLabel components in a JFrame, whose instance class is “GroupLayoutDemo”. We create 2 JLabel components named “headerLabel“, “statusLabel” and create 3 JButton components named “btn1“, “btn2“, “btn3” then add them to the JFrame by using add() method. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method. Java // Java Program to illustrate the GroupLayout classimport java.awt.*;import java.awt.event.*;import javax.swing.*; // creating a class GroupLayoutDemopublic class GroupLayoutDemo { // Declaration of objects // of JFrame class private JFrame mainFrame; // Declaration of objects // of JLabel class private JLabel headerLabel, statusLabel, msglabel; // Declaration of objects // of JPanel class private JPanel controlPanel; // create a class GroupLayoutDemo public GroupLayoutDemo() { // used to prepare GUI prepareGUI(); } public static void main(String[] args) { // Creating Object of "GroupLayoutDemo" class GroupLayoutDemo GroupLayoutDemo = new GroupLayoutDemo(); // to show the group layout demo GroupLayoutDemo.showGroupLayoutDemo(); } private void prepareGUI() { // Initialization of object // "mainframe" of JFrame class. mainFrame = new JFrame("Java GroupLayout Examples"); // Function to set the // size of JFrame. mainFrame.setSize(400, 400); // Function to set the // layout of JFrame. mainFrame.setLayout(new GridLayout(3, 1)); // Initialization of object // "headerLabel" of JLabel class. headerLabel = new JLabel("", JLabel.CENTER); // Initialization of object // "statusLabel" of JLabel class. statusLabel = new JLabel("", JLabel.CENTER); // Function to set the // size of JFrame. statusLabel.setSize(350, 100); // to add action WindowListner in JFrame mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); // Initialization of object // "controlPanel" of JPanel class. controlPanel = new JPanel(); // Function to set the // layout of JFrame. controlPanel.setLayout(new FlowLayout()); // Adding Jlabel "headerlabel" // on JFrame. mainFrame.add(headerLabel); // Adding JPanel "controlPanel" // on JFrame. mainFrame.add(controlPanel); // Adding JLabel "statusLabel" // on JFrame. mainFrame.add(statusLabel); // Function to set the visible of JFrame. mainFrame.setVisible(true); } private void showGroupLayoutDemo() { // Function to set the text // on the header of JFrame. headerLabel.setText("Layout in action: GroupLayout"); // Creating Object of // "Panel" class JPanel panel = new JPanel(); // Function to set the size of JFrame. panel.setSize(200, 200); // Creating Object of // "layout" class GroupLayout layout = new GroupLayout(panel); // it used to set Auto // Create Gaps layout.setAutoCreateGaps(true); // it used to set Auto // Create Container Gaps layout.setAutoCreateContainerGaps(true); // Creating Object // of "btn1" class JButton btn1 = new JButton("Button 1"); // Creating Object of // "btn2" class JButton btn2 = new JButton("Button 2"); // Creating Object of "btn3" class JButton btn3 = new JButton("Button 3"); // It used to set the // Horizontal group layout.setHorizontalGroup(layout.createSequentialGroup() // Adding the JButton "btn1" .addComponent(btn1) // Adding the sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) // Adding the JButton "btn2" .addComponent(btn2) // Adding the JButton "btn3" .addComponent(btn3)))); // set the vertical layout group layout.setVerticalGroup(layout.createSequentialGroup() // Adding the JButton "btn1" .addComponent(btn1) // Adding the JButton "btn2" .addComponent(btn2) // Adding the JButton "btn3" .addComponent(btn3)); // Function to set the Layout of JFrame. panel.setLayout(layout); // Adding the control panel controlPanel.add(panel); // Function to set the visible of JFrame. mainFrame.setVisible(true); }} Output: The following program illustrates the use of GropuLayout by arranging JLabel components in a JFrame, whose instance class is “GroupLayoutExample”. We create 1 JLabel , 1 JTextField and 2 JCheckbox components. Two JButton components are also created as “FindButton“, “CancelButton” and then add them to the JFrame by using add() method. The layout is set by using setLayout() method. Java // Java Program to illustrate the GroupLayout classimport java.awt.Component;import javax.swing.*;import static javax.swing.GroupLayout.Alignment.*; // creating a class GroupLayoutExamplepublic class GroupLayoutExample { // Main Method public static void main(String[] args) { // Function to set the Default Look // And Feel Decorated of JFrame. JFrame.setDefaultLookAndFeelDecorated(true); // Creating Object of // "JFrame" class JFrame frame = new JFrame("GroupLayoutExample"); // Function to set the Default // Close Operation of JFrame. frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Creating Object of "JLabel" class JLabel label = new JLabel("Label:"); // Creating Object of // "JTextField" class JTextField textField = new JTextField(); // Creating Object of // "JCheckBox" class JCheckBox checkBox1 = new JCheckBox("CheckBox1"); // Creating Object of "JCheckBox" class JCheckBox checkBox2 = new JCheckBox("CheckBox2"); // Creating Object of "JButton" class JButton findButton = new JButton("Button 1"); // Creating Object of "JButton" class JButton cancelButton = new JButton("Button 2"); // used to set the Border of a checkBox1 checkBox1.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // used to set the Border of a checkBox2 checkBox2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // Creating Object of "GroupLayout" class GroupLayout layout = new GroupLayout(frame.getContentPane()); // to get the content pane frame.getContentPane().setLayout(layout); // it used to set Auto Create Gaps layout.setAutoCreateGaps(true); // it used to set Auto Create Container Gaps layout.setAutoCreateContainerGaps(true); // it used to set the horizontal group layout.setHorizontalGroup(layout.createSequentialGroup() // Adding the label .addComponent(label) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the textfield .addComponent(textField) // Adding the Sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the checkBox1 .addComponent(checkBox1)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the checkBox2 .addComponent(checkBox2)))) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the findButton .addComponent(findButton) // Adding the CancelButton .addComponent(cancelButton))); layout.linkSize(SwingConstants.HORIZONTAL, findButton, cancelButton); layout.setVerticalGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE) // Adding the label .addComponent(label) // Adding the textField .addComponent(textField) // Adding the findButton .addComponent(findButton)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE) // Adding the checkBox1 .addComponent(checkBox1) // Adding the checkBox2 .addComponent(checkBox2)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE))) // Adding the CancelButton .addComponent(cancelButton))); frame.pack(); frame.show(); }} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/GroupLayout.html akshaysingh98088 rkbhola5 java-swing 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": "\n20 May, 2022" }, { "code": null, "e": 384, "s": 28, "text": "GroupLayout is a LayoutManager that hierarchically group the components and arranges them in a Container. Grouping is done by using the instances of the Group class. It is generally used for developing a GUI ( Graphic User Interface) builders such as Matisse, the GUI builder provided with the NetBeans IDE. GroupLayout Class supports two types of groups:" }, { "code": null, "e": 465, "s": 384, "text": "A sequential group positions its child elements sequentially, one after another." }, { "code": null, "e": 527, "s": 465, "text": "A parallel group aligns its child elements in different ways." }, { "code": null, "e": 554, "s": 527, "text": "Constructor of the class: " }, { "code": null, "e": 647, "s": 554, "text": "GroupLayout(Container host): It is used to create a GroupLayout for the specified Container." }, { "code": null, "e": 671, "s": 647, "text": "Commonly Used Methods: " }, { "code": null, "e": 1263, "s": 671, "text": "addLayoutComponent(Component comp, Object cons): Notify that a Component has been added to the parent container.getHonorsVisibility(): Returns whether component visibility is considered when sizing and positioning components.maximumLayoutSize(Container parent): Returns the maximum size for the specified container.getLayoutAlignmentX(along horizontal axis): It returns the alignment along the x axis.minimumLayoutSize(Container parent): Returns the minimum size for the specified container.getLayoutStyle(): Returns the LayoutStyle used for calculating the preferred gap between components." }, { "code": null, "e": 1376, "s": 1263, "text": "addLayoutComponent(Component comp, Object cons): Notify that a Component has been added to the parent container." }, { "code": null, "e": 1490, "s": 1376, "text": "getHonorsVisibility(): Returns whether component visibility is considered when sizing and positioning components." }, { "code": null, "e": 1581, "s": 1490, "text": "maximumLayoutSize(Container parent): Returns the maximum size for the specified container." }, { "code": null, "e": 1668, "s": 1581, "text": "getLayoutAlignmentX(along horizontal axis): It returns the alignment along the x axis." }, { "code": null, "e": 1759, "s": 1668, "text": "minimumLayoutSize(Container parent): Returns the minimum size for the specified container." }, { "code": null, "e": 1860, "s": 1759, "text": "getLayoutStyle(): Returns the LayoutStyle used for calculating the preferred gap between components." }, { "code": null, "e": 1918, "s": 1860, "text": "Below programs illustrate the use of GroupLayout class: " }, { "code": null, "e": 2374, "s": 1918, "text": "The following program illustrates the use of GropuLayout by arranging JLabel components in a JFrame, whose instance class is “GroupLayoutDemo”. We create 2 JLabel components named “headerLabel“, “statusLabel” and create 3 JButton components named “btn1“, “btn2“, “btn3” then add them to the JFrame by using add() method. We set the size and visibility of the frame by using setSize() and setVisible() method. The layout is set by using setLayout() method." }, { "code": null, "e": 2379, "s": 2374, "text": "Java" }, { "code": "// Java Program to illustrate the GroupLayout classimport java.awt.*;import java.awt.event.*;import javax.swing.*; // creating a class GroupLayoutDemopublic class GroupLayoutDemo { // Declaration of objects // of JFrame class private JFrame mainFrame; // Declaration of objects // of JLabel class private JLabel headerLabel, statusLabel, msglabel; // Declaration of objects // of JPanel class private JPanel controlPanel; // create a class GroupLayoutDemo public GroupLayoutDemo() { // used to prepare GUI prepareGUI(); } public static void main(String[] args) { // Creating Object of \"GroupLayoutDemo\" class GroupLayoutDemo GroupLayoutDemo = new GroupLayoutDemo(); // to show the group layout demo GroupLayoutDemo.showGroupLayoutDemo(); } private void prepareGUI() { // Initialization of object // \"mainframe\" of JFrame class. mainFrame = new JFrame(\"Java GroupLayout Examples\"); // Function to set the // size of JFrame. mainFrame.setSize(400, 400); // Function to set the // layout of JFrame. mainFrame.setLayout(new GridLayout(3, 1)); // Initialization of object // \"headerLabel\" of JLabel class. headerLabel = new JLabel(\"\", JLabel.CENTER); // Initialization of object // \"statusLabel\" of JLabel class. statusLabel = new JLabel(\"\", JLabel.CENTER); // Function to set the // size of JFrame. statusLabel.setSize(350, 100); // to add action WindowListner in JFrame mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); // Initialization of object // \"controlPanel\" of JPanel class. controlPanel = new JPanel(); // Function to set the // layout of JFrame. controlPanel.setLayout(new FlowLayout()); // Adding Jlabel \"headerlabel\" // on JFrame. mainFrame.add(headerLabel); // Adding JPanel \"controlPanel\" // on JFrame. mainFrame.add(controlPanel); // Adding JLabel \"statusLabel\" // on JFrame. mainFrame.add(statusLabel); // Function to set the visible of JFrame. mainFrame.setVisible(true); } private void showGroupLayoutDemo() { // Function to set the text // on the header of JFrame. headerLabel.setText(\"Layout in action: GroupLayout\"); // Creating Object of // \"Panel\" class JPanel panel = new JPanel(); // Function to set the size of JFrame. panel.setSize(200, 200); // Creating Object of // \"layout\" class GroupLayout layout = new GroupLayout(panel); // it used to set Auto // Create Gaps layout.setAutoCreateGaps(true); // it used to set Auto // Create Container Gaps layout.setAutoCreateContainerGaps(true); // Creating Object // of \"btn1\" class JButton btn1 = new JButton(\"Button 1\"); // Creating Object of // \"btn2\" class JButton btn2 = new JButton(\"Button 2\"); // Creating Object of \"btn3\" class JButton btn3 = new JButton(\"Button 3\"); // It used to set the // Horizontal group layout.setHorizontalGroup(layout.createSequentialGroup() // Adding the JButton \"btn1\" .addComponent(btn1) // Adding the sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) // Adding the JButton \"btn2\" .addComponent(btn2) // Adding the JButton \"btn3\" .addComponent(btn3)))); // set the vertical layout group layout.setVerticalGroup(layout.createSequentialGroup() // Adding the JButton \"btn1\" .addComponent(btn1) // Adding the JButton \"btn2\" .addComponent(btn2) // Adding the JButton \"btn3\" .addComponent(btn3)); // Function to set the Layout of JFrame. panel.setLayout(layout); // Adding the control panel controlPanel.add(panel); // Function to set the visible of JFrame. mainFrame.setVisible(true); }}", "e": 6863, "s": 2379, "text": null }, { "code": null, "e": 6871, "s": 6863, "text": "Output:" }, { "code": null, "e": 7254, "s": 6871, "text": "The following program illustrates the use of GropuLayout by arranging JLabel components in a JFrame, whose instance class is “GroupLayoutExample”. We create 1 JLabel , 1 JTextField and 2 JCheckbox components. Two JButton components are also created as “FindButton“, “CancelButton” and then add them to the JFrame by using add() method. The layout is set by using setLayout() method." }, { "code": null, "e": 7259, "s": 7254, "text": "Java" }, { "code": "// Java Program to illustrate the GroupLayout classimport java.awt.Component;import javax.swing.*;import static javax.swing.GroupLayout.Alignment.*; // creating a class GroupLayoutExamplepublic class GroupLayoutExample { // Main Method public static void main(String[] args) { // Function to set the Default Look // And Feel Decorated of JFrame. JFrame.setDefaultLookAndFeelDecorated(true); // Creating Object of // \"JFrame\" class JFrame frame = new JFrame(\"GroupLayoutExample\"); // Function to set the Default // Close Operation of JFrame. frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Creating Object of \"JLabel\" class JLabel label = new JLabel(\"Label:\"); // Creating Object of // \"JTextField\" class JTextField textField = new JTextField(); // Creating Object of // \"JCheckBox\" class JCheckBox checkBox1 = new JCheckBox(\"CheckBox1\"); // Creating Object of \"JCheckBox\" class JCheckBox checkBox2 = new JCheckBox(\"CheckBox2\"); // Creating Object of \"JButton\" class JButton findButton = new JButton(\"Button 1\"); // Creating Object of \"JButton\" class JButton cancelButton = new JButton(\"Button 2\"); // used to set the Border of a checkBox1 checkBox1.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // used to set the Border of a checkBox2 checkBox2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); // Creating Object of \"GroupLayout\" class GroupLayout layout = new GroupLayout(frame.getContentPane()); // to get the content pane frame.getContentPane().setLayout(layout); // it used to set Auto Create Gaps layout.setAutoCreateGaps(true); // it used to set Auto Create Container Gaps layout.setAutoCreateContainerGaps(true); // it used to set the horizontal group layout.setHorizontalGroup(layout.createSequentialGroup() // Adding the label .addComponent(label) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the textfield .addComponent(textField) // Adding the Sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the checkBox1 .addComponent(checkBox1)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the checkBox2 .addComponent(checkBox2)))) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the findButton .addComponent(findButton) // Adding the CancelButton .addComponent(cancelButton))); layout.linkSize(SwingConstants.HORIZONTAL, findButton, cancelButton); layout.setVerticalGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE) // Adding the label .addComponent(label) // Adding the textField .addComponent(textField) // Adding the findButton .addComponent(findButton)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(LEADING) // Adding the sequential Group .addGroup(layout.createSequentialGroup() // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE) // Adding the checkBox1 .addComponent(checkBox1) // Adding the checkBox2 .addComponent(checkBox2)) // Adding the Parallel Group .addGroup(layout.createParallelGroup(BASELINE))) // Adding the CancelButton .addComponent(cancelButton))); frame.pack(); frame.show(); }}", "e": 11326, "s": 7259, "text": null }, { "code": null, "e": 11334, "s": 11326, "text": "Output:" }, { "code": null, "e": 11505, "s": 11334, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/GroupLayout.html " }, { "code": null, "e": 11522, "s": 11505, "text": "akshaysingh98088" }, { "code": null, "e": 11531, "s": 11522, "text": "rkbhola5" }, { "code": null, "e": 11542, "s": 11531, "text": "java-swing" }, { "code": null, "e": 11547, "s": 11542, "text": "Java" }, { "code": null, "e": 11552, "s": 11547, "text": "Java" }, { "code": null, "e": 11650, "s": 11552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11665, "s": 11650, "text": "Stream In Java" }, { "code": null, "e": 11686, "s": 11665, "text": "Introduction to Java" }, { "code": null, "e": 11707, "s": 11686, "text": "Constructors in Java" }, { "code": null, "e": 11726, "s": 11707, "text": "Exceptions in Java" }, { "code": null, "e": 11743, "s": 11726, "text": "Generics in Java" }, { "code": null, "e": 11773, "s": 11743, "text": "Functional Interfaces in Java" }, { "code": null, "e": 11799, "s": 11773, "text": "Java Programming Examples" }, { "code": null, "e": 11815, "s": 11799, "text": "Strings in Java" }, { "code": null, "e": 11852, "s": 11815, "text": "Differences between JDK, JRE and JVM" } ]
Python | Pandas Index.tolist()
24 Dec, 2018 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.tolist() function return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period). Syntax: Index.tolist() Parameters : None Returns : list Example #1: Use Index.tolist() function to convert the index into a list. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'], name ='Student') # Print the Indexprint(idx) Output : Let’s convert the index into a List. # convert the index into a listidx.tolist() Output : Example #2: Use Index.tolist() function to convert the index into a python list. # importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['2000-01-02', '2000-02-05', '2000-05-11', '2001-02-11', '2005-11-12']) # Print the Indexprint(idx) Output : Let’s convert the index into a List. # convert the index into a listidx.tolist() Output : Python pandas-indexing 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "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": 441, "s": 242, "text": "Pandas Index.tolist() function return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period)." }, { "code": null, "e": 464, "s": 441, "text": "Syntax: Index.tolist()" }, { "code": null, "e": 482, "s": 464, "text": "Parameters : None" }, { "code": null, "e": 497, "s": 482, "text": "Returns : list" }, { "code": null, "e": 571, "s": 497, "text": "Example #1: Use Index.tolist() function to convert the index into a list." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'], name ='Student') # Print the Indexprint(idx)", "e": 767, "s": 571, "text": null }, { "code": null, "e": 776, "s": 767, "text": "Output :" }, { "code": null, "e": 813, "s": 776, "text": "Let’s convert the index into a List." }, { "code": "# convert the index into a listidx.tolist()", "e": 857, "s": 813, "text": null }, { "code": null, "e": 866, "s": 857, "text": "Output :" }, { "code": null, "e": 948, "s": 866, "text": " Example #2: Use Index.tolist() function to convert the index into a python list." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['2000-01-02', '2000-02-05', '2000-05-11', '2001-02-11', '2005-11-12']) # Print the Indexprint(idx)", "e": 1156, "s": 948, "text": null }, { "code": null, "e": 1165, "s": 1156, "text": "Output :" }, { "code": null, "e": 1202, "s": 1165, "text": "Let’s convert the index into a List." }, { "code": "# convert the index into a listidx.tolist()", "e": 1246, "s": 1202, "text": null }, { "code": null, "e": 1255, "s": 1246, "text": "Output :" }, { "code": null, "e": 1278, "s": 1255, "text": "Python pandas-indexing" }, { "code": null, "e": 1292, "s": 1278, "text": "Python-pandas" }, { "code": null, "e": 1299, "s": 1292, "text": "Python" }, { "code": null, "e": 1397, "s": 1299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1415, "s": 1397, "text": "Python Dictionary" }, { "code": null, "e": 1457, "s": 1415, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1479, "s": 1457, "text": "Enumerate() in Python" }, { "code": null, "e": 1511, "s": 1479, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1540, "s": 1511, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1567, "s": 1540, "text": "Python Classes and Objects" }, { "code": null, "e": 1588, "s": 1567, "text": "Python OOPs Concepts" }, { "code": null, "e": 1611, "s": 1588, "text": "Introduction To PYTHON" }, { "code": null, "e": 1647, "s": 1611, "text": "Convert integer to string in Python" } ]
Method Class | getName() Method in Java
05 Dec, 2018 The getName() method of java.lang.reflect.Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Syntax: public String getName() Return Value: It returns the name of the method, as String. Example: Method:public void getValue(){} getName() returns: getValue Explanation: The getName() function on object of above method returns name of method which is getValue. Method:public void paint(){} getName() returns: paint Below programs illustrates getName() method of Method class: Example 1: Print name of all methods of Method Object. /** Program Demonstrate how to apply getName() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = GFG.class; // get list of methods Method[] methods = classobj.getMethods(); // get the name of every method present in the list for (Method method : methods) { String MethodName = method.getName(); System.out.println("Name of the method: " + MethodName); } } catch (Exception e) { e.printStackTrace(); } } // method name setValue public static int setValue() { System.out.println("setValue"); return 24; } // method name getValue public String getValue() { System.out.println("getValue"); return "getValue"; } // method name setManyValues public void setManyValues() { System.out.println("setManyValues"); }} Name of the method: main Name of the method: getValue Name of the method: setValue Name of the method: setManyValues Name of the method: wait Name of the method: wait Name of the method: wait Name of the method: equals Name of the method: toString Name of the method: hashCode Name of the method: getClass Name of the method: notify Name of the method: notifyAll Example 2: Program to check whether class contains a certain specific method. /** Program Demonstrate how to apply getName() method* of Method Class within a class*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { String checkMethod = "method1"; try { // create class object Class classobj = democlass.class; // get list of methods Method[] methods = classobj.getMethods(); // get the name of every method present in the list for (Method method : methods) { String MethodName = method.getName(); if (MethodName.equals(checkMethod)) { System.out.println("Class Object Contains" + " Method whose name is " + MethodName); } } } catch (Exception e) { e.printStackTrace(); } }}// a simple classclass democlass { public int method1() { return 24; } public String method2() { return "Happy hours"; } public void method3() { System.out.println("Happy hours"); }} Class Object Contains Method whose name is method1 Reference:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getName– piyush25pv Java-Functions java-lang-reflect-package Java-Method Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2018" }, { "code": null, "e": 261, "s": 28, "text": "The getName() method of java.lang.reflect.Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects." }, { "code": null, "e": 269, "s": 261, "text": "Syntax:" }, { "code": null, "e": 293, "s": 269, "text": "public String getName()" }, { "code": null, "e": 353, "s": 293, "text": "Return Value: It returns the name of the method, as String." }, { "code": null, "e": 362, "s": 353, "text": "Example:" }, { "code": null, "e": 582, "s": 362, "text": "Method:public void getValue(){}\ngetName() returns: getValue\nExplanation: The getName() function on object of above method returns name of method\nwhich is getValue.\n\nMethod:public void paint(){}\ngetName() returns: paint\n" }, { "code": null, "e": 643, "s": 582, "text": "Below programs illustrates getName() method of Method class:" }, { "code": null, "e": 698, "s": 643, "text": "Example 1: Print name of all methods of Method Object." }, { "code": "/** Program Demonstrate how to apply getName() method* of Method Class.*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = GFG.class; // get list of methods Method[] methods = classobj.getMethods(); // get the name of every method present in the list for (Method method : methods) { String MethodName = method.getName(); System.out.println(\"Name of the method: \" + MethodName); } } catch (Exception e) { e.printStackTrace(); } } // method name setValue public static int setValue() { System.out.println(\"setValue\"); return 24; } // method name getValue public String getValue() { System.out.println(\"getValue\"); return \"getValue\"; } // method name setManyValues public void setManyValues() { System.out.println(\"setManyValues\"); }}", "e": 1814, "s": 698, "text": null }, { "code": null, "e": 2178, "s": 1814, "text": "Name of the method: main\nName of the method: getValue\nName of the method: setValue\nName of the method: setManyValues\nName of the method: wait\nName of the method: wait\nName of the method: wait\nName of the method: equals\nName of the method: toString\nName of the method: hashCode\nName of the method: getClass\nName of the method: notify\nName of the method: notifyAll\n" }, { "code": null, "e": 2256, "s": 2178, "text": "Example 2: Program to check whether class contains a certain specific method." }, { "code": "/** Program Demonstrate how to apply getName() method* of Method Class within a class*/import java.lang.reflect.Method; public class GFG { // Main method public static void main(String[] args) { String checkMethod = \"method1\"; try { // create class object Class classobj = democlass.class; // get list of methods Method[] methods = classobj.getMethods(); // get the name of every method present in the list for (Method method : methods) { String MethodName = method.getName(); if (MethodName.equals(checkMethod)) { System.out.println(\"Class Object Contains\" + \" Method whose name is \" + MethodName); } } } catch (Exception e) { e.printStackTrace(); } }}// a simple classclass democlass { public int method1() { return 24; } public String method2() { return \"Happy hours\"; } public void method3() { System.out.println(\"Happy hours\"); }}", "e": 3434, "s": 2256, "text": null }, { "code": null, "e": 3486, "s": 3434, "text": "Class Object Contains Method whose name is method1\n" }, { "code": null, "e": 3577, "s": 3486, "text": "Reference:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getName–" }, { "code": null, "e": 3588, "s": 3577, "text": "piyush25pv" }, { "code": null, "e": 3603, "s": 3588, "text": "Java-Functions" }, { "code": null, "e": 3629, "s": 3603, "text": "java-lang-reflect-package" }, { "code": null, "e": 3647, "s": 3629, "text": "Java-Method Class" }, { "code": null, "e": 3652, "s": 3647, "text": "Java" }, { "code": null, "e": 3657, "s": 3652, "text": "Java" }, { "code": null, "e": 3755, "s": 3657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3806, "s": 3755, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3837, "s": 3806, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3867, "s": 3837, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3885, "s": 3867, "text": "ArrayList in Java" }, { "code": null, "e": 3905, "s": 3885, "text": "Collections in Java" }, { "code": null, "e": 3920, "s": 3905, "text": "Stream In Java" }, { "code": null, "e": 3952, "s": 3920, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3976, "s": 3952, "text": "Singleton Class in Java" }, { "code": null, "e": 3988, "s": 3976, "text": "Set in Java" } ]
std::equal_to in C++ with Examples
16 Jul, 2021 The std::equal_to allows the equality comparison to be used as a function, which means that it can be passed as an argument to templates and functions. This is not possible with the equality operator == since operators cannot be passed as parameters.Header File: #include <functional.h> Template Class: template struct equal_to : binary_function { // Declaration of the equal operation bool operator() (const T& x, const T& y) const { return x==y; } // Type of first parameter typedef T first_argument_type; // Type of second parameter typedef T second_argument_type; // The result is returned // as bool type typedef bool result_type; } Syntax: std::equal_to <int> () Parameter: This function accepts the type of the arguments T, as the parameter, to be compared by the functional call.Return Type: It return a boolean value depending upon condition(let a & b are 2 element): True: If a is equals to b. False: If a is not equals to b. Below is the illustration of std::equal_to in C++:Program 1: CPP // C++ code to illustrate std::equal_to#include <algorithm>#include <functional>#include <iostream>#include <vector>using namespace std; // Driver Codeint main(){ // Initialise vectors vector<int> v1 = { 50, 55, 60, 65, 70 }; vector<int> v2 = { 50, 55, 85, 65, 70 }; // Declaring pointer of pairs pair<vector<int>::iterator, vector<int>::iterator> pairs1; // Use mismatch() function to // search first mismatch between // v1 and v2 pairs1 = mismatch(v1.begin(), v1.end(), v2.begin(), equal_to<int>()); // Print the mismatch pair cout << "The 1st mismatch element" << " of 1st container : "; cout << *pairs1.first << endl; cout << "The 1st mismatch element" << " of 2nd container : "; cout << *pairs1.second << endl; return 0;} The 1st mismatch element of 1st container : 60 The 1st mismatch element of 2nd container : 85 Program 2: CPP // C++ program to illustrate std::equals_to#include <algorithm>#include <functional>#include <iostream>using namespace std; // Templatetemplate <typename A, typename B, typename U = std::equal_to<int> > // Function to check if a = b or notbool f(A a, B b, U u = U()){ return u(a, b);} // Driver Codeint main(){ int X = 1, Y = 2; // If X is equals to Y or not cout << std::boolalpha; cout << f(X, Y) << '\n'; X = -1, Y = -1; // If X is equals to Y or not cout << f(X, Y) << '\n'; return 0;} false true Reference: http://www.cplusplus.com/reference/functional/equal_to/ sagartomar9927 C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 293, "s": 28, "text": "The std::equal_to allows the equality comparison to be used as a function, which means that it can be passed as an argument to templates and functions. This is not possible with the equality operator == since operators cannot be passed as parameters.Header File: " }, { "code": null, "e": 317, "s": 293, "text": "#include <functional.h>" }, { "code": null, "e": 335, "s": 317, "text": "Template Class: " }, { "code": null, "e": 731, "s": 335, "text": "template struct equal_to : binary_function\n{\n \n // Declaration of the equal operation\n bool operator() (const T& x,\n const T& y) \n const \n { \n return x==y;\n }\n\n // Type of first parameter\n typedef T first_argument_type;\n\n // Type of second parameter\n typedef T second_argument_type;\n\n // The result is returned\n // as bool type\n typedef bool result_type;\n}" }, { "code": null, "e": 741, "s": 731, "text": "Syntax: " }, { "code": null, "e": 764, "s": 741, "text": "std::equal_to <int> ()" }, { "code": null, "e": 974, "s": 764, "text": "Parameter: This function accepts the type of the arguments T, as the parameter, to be compared by the functional call.Return Type: It return a boolean value depending upon condition(let a & b are 2 element): " }, { "code": null, "e": 1001, "s": 974, "text": "True: If a is equals to b." }, { "code": null, "e": 1033, "s": 1001, "text": "False: If a is not equals to b." }, { "code": null, "e": 1096, "s": 1033, "text": "Below is the illustration of std::equal_to in C++:Program 1: " }, { "code": null, "e": 1100, "s": 1096, "text": "CPP" }, { "code": "// C++ code to illustrate std::equal_to#include <algorithm>#include <functional>#include <iostream>#include <vector>using namespace std; // Driver Codeint main(){ // Initialise vectors vector<int> v1 = { 50, 55, 60, 65, 70 }; vector<int> v2 = { 50, 55, 85, 65, 70 }; // Declaring pointer of pairs pair<vector<int>::iterator, vector<int>::iterator> pairs1; // Use mismatch() function to // search first mismatch between // v1 and v2 pairs1 = mismatch(v1.begin(), v1.end(), v2.begin(), equal_to<int>()); // Print the mismatch pair cout << \"The 1st mismatch element\" << \" of 1st container : \"; cout << *pairs1.first << endl; cout << \"The 1st mismatch element\" << \" of 2nd container : \"; cout << *pairs1.second << endl; return 0;}", "e": 1994, "s": 1100, "text": null }, { "code": null, "e": 2088, "s": 1994, "text": "The 1st mismatch element of 1st container : 60\nThe 1st mismatch element of 2nd container : 85" }, { "code": null, "e": 2103, "s": 2090, "text": "Program 2: " }, { "code": null, "e": 2107, "s": 2103, "text": "CPP" }, { "code": "// C++ program to illustrate std::equals_to#include <algorithm>#include <functional>#include <iostream>using namespace std; // Templatetemplate <typename A, typename B, typename U = std::equal_to<int> > // Function to check if a = b or notbool f(A a, B b, U u = U()){ return u(a, b);} // Driver Codeint main(){ int X = 1, Y = 2; // If X is equals to Y or not cout << std::boolalpha; cout << f(X, Y) << '\\n'; X = -1, Y = -1; // If X is equals to Y or not cout << f(X, Y) << '\\n'; return 0;}", "e": 2637, "s": 2107, "text": null }, { "code": null, "e": 2648, "s": 2637, "text": "false\ntrue" }, { "code": null, "e": 2718, "s": 2650, "text": "Reference: http://www.cplusplus.com/reference/functional/equal_to/ " }, { "code": null, "e": 2733, "s": 2718, "text": "sagartomar9927" }, { "code": null, "e": 2737, "s": 2733, "text": "C++" }, { "code": null, "e": 2750, "s": 2737, "text": "C++ Programs" }, { "code": null, "e": 2754, "s": 2750, "text": "CPP" } ]
Implement your own tail (Read last n lines of a huge file)
29 May, 2017 Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Interview We strongly recommend you to minimize your browser and try this yourself first. The problem mainly focuses on below things – 1. The program should not read entire file.2. The program should handle incoming dynamic data and returns last n lines at any point.3. The program should not close input stream before reading last n lines. Below is its C++ implementation // C++ program to implement your own tail#include <bits/stdc++.h>using namespace std; #define SIZE 100 // Utility function to sleep for n secondsvoid sleep(unsigned int n){ clock_t goal = n * 1000 + clock(); while (goal > clock());} // function to read last n lines from the file// at any point without reading the entire filevoid tail(FILE* in, int n){ int count = 0; // To count '\n' characters // unsigned long long pos (stores upto 2^64 – 1 // chars) assuming that long long int takes 8 // bytes unsigned long long pos; char str[2*SIZE]; // Go to End of file if (fseek(in, 0, SEEK_END)) perror("fseek() failed"); else { // pos will contain no. of chars in // input file. pos = ftell(in); // search for '\n' characters while (pos) { // Move 'pos' away from end of file. if (!fseek(in, --pos, SEEK_SET)) { if (fgetc(in) == '\n') // stop reading when n newlines // is found if (count++ == n) break; } else perror("fseek() failed"); } // print last n lines printf("Printing last %d lines -\n", n); while (fgets(str, sizeof(str), in)) printf("%s", str); } printf("\n\n");} // Creates a file and prints and calls tail() for // 10 different values of n (from 1 to 10)int main(){ FILE* fp; char buffer[SIZE]; // Open file in binary mode // wb+ mode for reading and writing simultaneously fp = fopen("input.txt", "wb+"); if (fp == NULL) { printf("Error while opening file"); exit(EXIT_FAILURE); } srand(time(NULL)); // Dynamically add lines to input file // and call tail() each time for (int index = 1; index <= 10; index++) { /* generate random logs to print in input file*/ for (int i = 0; i < SIZE - 1; i++) buffer[i] = rand() % 26 + 65; // A-Z buffer[SIZE] = '\0'; /* code to print timestamp in logs */ // get current calendar time time_t ltime = time(NULL); // asctime() returns a pointer to a string // which represents the day and time char* date = asctime(localtime(<ime)); // replace the '\n' character in the date string // with '\0' to print on the same line. date[strlen(date)-1] = '\0'; /* Note in text mode '\n' appends two characters, so we have opened file in binary mode */ fprintf(fp, "\nLine #%d [%s] - %s", index, date, buffer); // flush the input stream before calling tail fflush(fp); // read last index lines from the file tail(fp, index); // sleep for 3 seconds // note difference in timestamps in logs sleep(3); } /* close the file before ending program */ fclose(fp); return 0;} Some points to Note –1. This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” and dynamically write data to it 10 times and calls tail() function every time. 2. We should avoid using fseek() and ftell() for huge files(in GBs) as they operate on file positions of type long int. Use _fseeki64(), _ftelli64() instead. 3. unsigned long has max allowed value of 232 – 1 (Assuming that unsigned long takes 4 bytes). It can be used for files size of less than 4 GB file. 4. unsigned long long has max allowed value of 264 – 1 (Assuming that unsigned long long takes 8 bytes). It can be used for files size over 4 GB. This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above cpp-file-handling C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n29 May, 2017" }, { "code": null, "e": 376, "s": 52, "text": "Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files." }, { "code": null, "e": 405, "s": 376, "text": "Source : Microsoft Interview" }, { "code": null, "e": 485, "s": 405, "text": "We strongly recommend you to minimize your browser and try this yourself first." }, { "code": null, "e": 530, "s": 485, "text": "The problem mainly focuses on below things –" }, { "code": null, "e": 736, "s": 530, "text": "1. The program should not read entire file.2. The program should handle incoming dynamic data and returns last n lines at any point.3. The program should not close input stream before reading last n lines." }, { "code": null, "e": 768, "s": 736, "text": "Below is its C++ implementation" }, { "code": "// C++ program to implement your own tail#include <bits/stdc++.h>using namespace std; #define SIZE 100 // Utility function to sleep for n secondsvoid sleep(unsigned int n){ clock_t goal = n * 1000 + clock(); while (goal > clock());} // function to read last n lines from the file// at any point without reading the entire filevoid tail(FILE* in, int n){ int count = 0; // To count '\\n' characters // unsigned long long pos (stores upto 2^64 – 1 // chars) assuming that long long int takes 8 // bytes unsigned long long pos; char str[2*SIZE]; // Go to End of file if (fseek(in, 0, SEEK_END)) perror(\"fseek() failed\"); else { // pos will contain no. of chars in // input file. pos = ftell(in); // search for '\\n' characters while (pos) { // Move 'pos' away from end of file. if (!fseek(in, --pos, SEEK_SET)) { if (fgetc(in) == '\\n') // stop reading when n newlines // is found if (count++ == n) break; } else perror(\"fseek() failed\"); } // print last n lines printf(\"Printing last %d lines -\\n\", n); while (fgets(str, sizeof(str), in)) printf(\"%s\", str); } printf(\"\\n\\n\");} // Creates a file and prints and calls tail() for // 10 different values of n (from 1 to 10)int main(){ FILE* fp; char buffer[SIZE]; // Open file in binary mode // wb+ mode for reading and writing simultaneously fp = fopen(\"input.txt\", \"wb+\"); if (fp == NULL) { printf(\"Error while opening file\"); exit(EXIT_FAILURE); } srand(time(NULL)); // Dynamically add lines to input file // and call tail() each time for (int index = 1; index <= 10; index++) { /* generate random logs to print in input file*/ for (int i = 0; i < SIZE - 1; i++) buffer[i] = rand() % 26 + 65; // A-Z buffer[SIZE] = '\\0'; /* code to print timestamp in logs */ // get current calendar time time_t ltime = time(NULL); // asctime() returns a pointer to a string // which represents the day and time char* date = asctime(localtime(<ime)); // replace the '\\n' character in the date string // with '\\0' to print on the same line. date[strlen(date)-1] = '\\0'; /* Note in text mode '\\n' appends two characters, so we have opened file in binary mode */ fprintf(fp, \"\\nLine #%d [%s] - %s\", index, date, buffer); // flush the input stream before calling tail fflush(fp); // read last index lines from the file tail(fp, index); // sleep for 3 seconds // note difference in timestamps in logs sleep(3); } /* close the file before ending program */ fclose(fp); return 0;}", "e": 3765, "s": 768, "text": null }, { "code": null, "e": 4017, "s": 3765, "text": "Some points to Note –1. This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” and dynamically write data to it 10 times and calls tail() function every time." }, { "code": null, "e": 4175, "s": 4017, "text": "2. We should avoid using fseek() and ftell() for huge files(in GBs) as they operate on file positions of type long int. Use _fseeki64(), _ftelli64() instead." }, { "code": null, "e": 4324, "s": 4175, "text": "3. unsigned long has max allowed value of 232 – 1 (Assuming that unsigned long takes 4 bytes). It can be used for files size of less than 4 GB file." }, { "code": null, "e": 4470, "s": 4324, "text": "4. unsigned long long has max allowed value of 264 – 1 (Assuming that unsigned long long takes 8 bytes). It can be used for files size over 4 GB." }, { "code": null, "e": 4638, "s": 4470, "text": "This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 4656, "s": 4638, "text": "cpp-file-handling" }, { "code": null, "e": 4667, "s": 4656, "text": "C Language" }, { "code": null, "e": 4671, "s": 4667, "text": "C++" }, { "code": null, "e": 4675, "s": 4671, "text": "CPP" }, { "code": null, "e": 4773, "s": 4675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4790, "s": 4773, "text": "Substring in C++" }, { "code": null, "e": 4812, "s": 4790, "text": "Function Pointer in C" }, { "code": null, "e": 4847, "s": 4812, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 4893, "s": 4847, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 4938, "s": 4893, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 4956, "s": 4938, "text": "Vector in C++ STL" }, { "code": null, "e": 4999, "s": 4956, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 5045, "s": 4999, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 5088, "s": 5045, "text": "Set in C++ Standard Template Library (STL)" } ]
C program to swap adjacent characters of a String
09 Jun, 2022 Given a string str, the task is to swap adjacent characters of this string in C. Examples: Input: str = "geeks" Output: NA Not possible as the string length is odd Input: str = "geek" Output: egke Approach: Check if the length of the string is even or odd.If the length is odd, swapping cannot be done.If the length is even, take each character of the string one by one and swap it with the adjacent character. Check if the length of the string is even or odd. If the length is odd, swapping cannot be done. If the length is even, take each character of the string one by one and swap it with the adjacent character. Below is the implementation of the above approach: C // C program to swap// adjacent characters of a String #include <stdio.h>#include <string.h> // Function to swap adjacent charactersvoid swap(char* str){ char c = 0; int length = 0, i = 0; // Find the length of the string length = strlen(str); // Check if the length of the string // is even or odd if (length % 2 == 0) { // swap the characters with // the adjacent character for (i = 0; i < length; i += 2) { c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } // Print the swapped character string printf("%s\n", str); } else { // Print NA as the string length is odd printf("NA\n"); }} // Driver codeint main(){ // Get the string char str1[] = "Geek"; char str2[] = "Geeks"; swap(str1); swap(str2); return 0;} eGke NA Time complexity: O(length(str)) Auxiliary space: O(1) kabitac45 hasani Swap-Program C Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? C++ Program to check Prime Number Producer Consumer Problem in C Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jun, 2022" }, { "code": null, "e": 119, "s": 28, "text": "Given a string str, the task is to swap adjacent characters of this string in C. Examples:" }, { "code": null, "e": 226, "s": 119, "text": "Input: str = \"geeks\"\nOutput: NA\nNot possible as the string length is odd\n\nInput: str = \"geek\"\nOutput: egke" }, { "code": null, "e": 236, "s": 226, "text": "Approach:" }, { "code": null, "e": 440, "s": 236, "text": "Check if the length of the string is even or odd.If the length is odd, swapping cannot be done.If the length is even, take each character of the string one by one and swap it with the adjacent character." }, { "code": null, "e": 490, "s": 440, "text": "Check if the length of the string is even or odd." }, { "code": null, "e": 537, "s": 490, "text": "If the length is odd, swapping cannot be done." }, { "code": null, "e": 646, "s": 537, "text": "If the length is even, take each character of the string one by one and swap it with the adjacent character." }, { "code": null, "e": 698, "s": 646, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 700, "s": 698, "text": "C" }, { "code": "// C program to swap// adjacent characters of a String #include <stdio.h>#include <string.h> // Function to swap adjacent charactersvoid swap(char* str){ char c = 0; int length = 0, i = 0; // Find the length of the string length = strlen(str); // Check if the length of the string // is even or odd if (length % 2 == 0) { // swap the characters with // the adjacent character for (i = 0; i < length; i += 2) { c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } // Print the swapped character string printf(\"%s\\n\", str); } else { // Print NA as the string length is odd printf(\"NA\\n\"); }} // Driver codeint main(){ // Get the string char str1[] = \"Geek\"; char str2[] = \"Geeks\"; swap(str1); swap(str2); return 0;}", "e": 1558, "s": 700, "text": null }, { "code": null, "e": 1566, "s": 1558, "text": "eGke\nNA" }, { "code": null, "e": 1598, "s": 1566, "text": "Time complexity: O(length(str))" }, { "code": null, "e": 1620, "s": 1598, "text": "Auxiliary space: O(1)" }, { "code": null, "e": 1630, "s": 1620, "text": "kabitac45" }, { "code": null, "e": 1637, "s": 1630, "text": "hasani" }, { "code": null, "e": 1650, "s": 1637, "text": "Swap-Program" }, { "code": null, "e": 1661, "s": 1650, "text": "C Programs" }, { "code": null, "e": 1669, "s": 1661, "text": "Strings" }, { "code": null, "e": 1677, "s": 1669, "text": "Strings" }, { "code": null, "e": 1775, "s": 1677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1810, "s": 1775, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 1851, "s": 1810, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 1910, "s": 1851, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 1944, "s": 1910, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 1975, "s": 1944, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 2021, "s": 1975, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 2046, "s": 2021, "text": "Reverse a string in Java" }, { "code": null, "e": 2106, "s": 2046, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 2121, "s": 2106, "text": "C++ Data Types" } ]
How to generate a vector with random values in C++?
24 Nov, 2020 Vectors are dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. It can also be created with random value using the generate function and rand() function. Below is the template of both the STL functions: Syntax: int rand(void): It returns a pseudo-random number in the range of 0 to RAND_MAX.RAND_MAX: is a constant whose default value that may vary between implementations but it is granted to be at least 32767. void generate(ForwardIterator first, ForwardIterator last, Generator gen) where, first: Forward iterator pointing to the first element of the container. last: Forward iterator pointing to the last element of the container. gen: A generator function, based upon which values will be assigned. Returns Value: Since, it has a void return type, so it does not return any value. In order to have different random vectors each time, run this program, the idea is to use srand() function. Otherwise, the output vector will be the same after each compilation. Syntax: void srand(unsigned seed): This function seeds the pseudo-random number generator used by rand() with the value seed. Below is the implementation of the above approach: C++ // C++ program to generate the vector// with random values#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Size of vector int size = 5; // Initialize the vector with // initial values as 0 vector<int> V(size, 0); // use srand() for different outputs srand(time(0)); // Generate value using generate // function generate(V.begin(), V.end(), rand); cout << "The elements of vector are:\n"; // Print the values in the vector for (int i = 0; i < size; i++) { cout << V[i] << " "; } return 0;} The elements of vector are: 995552582 698831766 2088692742 1348138651 64302615 cpp-random cpp-vector C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Nov, 2020" }, { "code": null, "e": 322, "s": 52, "text": "Vectors are dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. It can also be created with random value using the generate function and rand() function." }, { "code": null, "e": 371, "s": 322, "text": "Below is the template of both the STL functions:" }, { "code": null, "e": 379, "s": 371, "text": "Syntax:" }, { "code": null, "e": 581, "s": 379, "text": "int rand(void): It returns a pseudo-random number in the range of 0 to RAND_MAX.RAND_MAX: is a constant whose default value that may vary between implementations but it is granted to be at least 32767." }, { "code": null, "e": 655, "s": 581, "text": "void generate(ForwardIterator first, ForwardIterator last, Generator gen)" }, { "code": null, "e": 662, "s": 655, "text": "where," }, { "code": null, "e": 734, "s": 662, "text": "first: Forward iterator pointing to the first element of the container." }, { "code": null, "e": 804, "s": 734, "text": "last: Forward iterator pointing to the last element of the container." }, { "code": null, "e": 873, "s": 804, "text": "gen: A generator function, based upon which values will be assigned." }, { "code": null, "e": 955, "s": 873, "text": "Returns Value: Since, it has a void return type, so it does not return any value." }, { "code": null, "e": 1133, "s": 955, "text": "In order to have different random vectors each time, run this program, the idea is to use srand() function. Otherwise, the output vector will be the same after each compilation." }, { "code": null, "e": 1141, "s": 1133, "text": "Syntax:" }, { "code": null, "e": 1259, "s": 1141, "text": "void srand(unsigned seed): This function seeds the pseudo-random number generator used by rand() with the value seed." }, { "code": null, "e": 1310, "s": 1259, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1314, "s": 1310, "text": "C++" }, { "code": "// C++ program to generate the vector// with random values#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Size of vector int size = 5; // Initialize the vector with // initial values as 0 vector<int> V(size, 0); // use srand() for different outputs srand(time(0)); // Generate value using generate // function generate(V.begin(), V.end(), rand); cout << \"The elements of vector are:\\n\"; // Print the values in the vector for (int i = 0; i < size; i++) { cout << V[i] << \" \"; } return 0;}", "e": 1893, "s": 1314, "text": null }, { "code": null, "e": 1973, "s": 1893, "text": "The elements of vector are:\n995552582 698831766 2088692742 1348138651 64302615\n" }, { "code": null, "e": 1984, "s": 1973, "text": "cpp-random" }, { "code": null, "e": 1995, "s": 1984, "text": "cpp-vector" }, { "code": null, "e": 1999, "s": 1995, "text": "C++" }, { "code": null, "e": 2012, "s": 1999, "text": "C++ Programs" }, { "code": null, "e": 2016, "s": 2012, "text": "CPP" }, { "code": null, "e": 2114, "s": 2016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2138, "s": 2114, "text": "Sorting a vector in C++" }, { "code": null, "e": 2158, "s": 2138, "text": "Polymorphism in C++" }, { "code": null, "e": 2191, "s": 2158, "text": "Friend class and function in C++" }, { "code": null, "e": 2235, "s": 2191, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 2260, "s": 2235, "text": "std::string class in C++" }, { "code": null, "e": 2295, "s": 2260, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 2329, "s": 2295, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 2373, "s": 2329, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 2432, "s": 2373, "text": "How to return multiple values from a function in C or C++?" } ]
Introduction to 3D Plotting with Matplotlib
08 Feb, 2022 In this article, we will be learning about 3D plotting with Matplotlib. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, Matplotlib.pyplot.gca(), etc. In the below code, we will be creating an empty canvas at first. After that, we will be defining the axes of our 3D plot where we define that the projection of the plot will be in “3D” format. This helps us to create the 3D empty axes figure in the canvas. After this, if we show the plot using plt.show(), then it would look like the one shown in the output. Example: Creating an empty 3D figure using Matplotlib Python3 # importing numpy package from# python libraryimport numpy as np # importing matplotlib.pyplot package from# pythonimport matplotlib.pyplot as plt # Creating an empty figure# or plotfig = plt.figure() # Defining the axes as a# 3D axes so that we can plot 3D# data into it.ax = plt.axes(projection="3d") # Showing the above plotplt.show() Output: Now, we have a basic idea about how to create a 3D plot on an empty canvas. Let us move to some 3D plotting examples. Example 1: In the below example, we will be taking a simple curve in our 3D plot. Along with that, we will be plotting a range of points that have X-coordinate, Y-coordinate as well as Z-coordinate. Python3 # importing numpy packageimport numpy as np # importing matplotlib packageimport matplotlib.pyplot as plt # importing mplot3d from# mpl_toolkitsfrom mpl_toolkits import mplot3d # creating an empty canvasfig = plt.figure() # defining the axes with the projection# as 3D so as to plot 3D graphsax = plt.axes(projection="3d") # creating a wide range of points x,y,zx=[0,1,2,3,4,5,6]y=[0,1,4,9,16,25,36]z=[0,1,4,9,16,25,36] # plotting a 3D line graph with X-coordinate,# Y-coordinate and Z-coordinate respectivelyax.plot3D(x, y, z, 'red') # plotting a scatter plot with X-coordinate,# Y-coordinate and Z-coordinate respectively# and defining the points color as cividis# and defining c as z which basically is a# defination of 2D array in which rows are RGB#or RGBAax.scatter3D(x, y, z, c=z, cmap='cividis'); # Showing the above plotplt.show() Output: Explanation: In the above example, first, we are importing packages from the python library in order to have a 3D plot in our empty canvas. So, for that, we are importing numpy, matplotlib.pyplot, and mpl_toolkits. After importing all the necessary packages, we are creating an empty figure using plt.figure(). After that, we are defining the axis of the plot where we are specifying that the plot will be of 3D projection. After that, we are taking 3 arrays with a wide range of arbitrary points which will act as X, Y, and Z coordinates for plotting the graph respectively. Now after initializing the points, we are plotting a 3D plot using ax.plot3D() where we are using x,y,z as the X, Y, and Z coordinates respectively and the color of the line will be red. All these things are sent as parameters inside the bracket. After that, we are also plotting a scatter plot with the same set of values and as we progress with each point, the color of the points will be based on the values that the coordinates contain. After this, we are showing the above plot. Example 2: In this example, we will be learning about how to do 3D plotting using figure.gca(). Here we will be creating a sine curve and a cosine curve with the values of x and y ranging from -5 to 5 with a gap of 1. Let us look at the code to understand the implementation. Python3 # importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from# pythonimport numpy as np # creating a range of values for# x,y,x1,y1 from -5 to 5 with# a space of 1 between the elementsx = np.arange(-5,5,1)y = np.arange(-5,5,1) # creating a range of values for# x,y,x1,y1 from -5 to 5 with# a space of 0.6 between the elementsx1= np.arange(-5,5,0.6)y1= np.arange(-5,5,0.6) # Creating a mesh grid with x ,y and x1,# y1 which creates an n-dimensional# arrayx, y = np.meshgrid(x, y)x1,y1= np.meshgrid(x1,y1) # Creating a sine function with the# range of values from the meshgridz = np.sin(x * np.pi/2 ) # Creating a cosine function with the# range of values from the meshgridz1= np.cos(x1* np.pi/2) # Creating an empty figure for# 3D plottingfig = plt.figure() # using fig.gca, we are creating a 3D# projection plot in the empty figureax = fig.gca(projection="3d") # Creating a wireframe plot with the x,y and# z-coordinates respectively along with the# color as redsurf = ax.plot_wireframe(x, y, z, color="red") # Creating a wireframe plot with the points# x1,y1,z1 along with the plot line as greensurf1 =ax.plot_wireframe(x1, y1, z1, color="green") #showing the above plotplt.show() Output: Explanation: In this example, we are importing two packages matplotlib.pyplot and NumPy from python. After that, we are creating a wide range of values with various variables such as x, y,x1,x2. Now there is a catch over here. The first set of x,y have values from -5 to 5 with each of the elements having a difference of 1 from each other. The second set of elements also ranges from -5 to 5 with each element having a difference of 0.6 from each other. The difference that it creates is, the first graph will have steep curves since the difference between the points is more, whereas, in the second set, the graph will be smoother as compared to the first one because we are taking a wide range of points more than x and y. That’s why the second curve(cosine curve) is smoother than the first curve. Using meshgrid, we are returning coordinate matrices from coordinate vectors. MeshGrid makes N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, where there is a 1-Dimensional array. Now, we are creating the sine and the cosine curves with the help of z and z1 respectively. After that, we are creating an empty figure where we will be plotting out 3D plot. Using fig.gca, we are defining that the plots that we are going to make will be of 3D projection using projection=’3d’. Using plot_wireframe we are creating a 3D sine and cosine curve(of different colors) with the above points created by us. Finally, we are showing the above plot. Example 3: In the last and the final example, we will be creating two 3D graphs in a single figure/canvas, where we will be our 3D points. So let us move into our code implementation. Python3 #importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from pythonimport numpy as np # creating an empty figure for plottingfig = plt.figure() # defining a sub-plot with 1x2 axis and defining# it as first plot with projection as 3Dax = fig.add_subplot(1, 2, 1, projection='3d') # creating a range of 12 elements in both# X and YX = np.arange(12)Y = np.linspace(12, 1) # Creating a mesh grid of X and YX, Y = np.meshgrid(X, Y) # Creating an expression X and Y and# storing it in ZZ = X*2+Y*3; # Creating a wireframe plot with the 3 sets of# values X,Y and Zax.plot_wireframe(X, Y, Z) # Creating my second subplot with 1x2 axis and defining# it as the second plot with projection as 3Dax = fig.add_subplot(1, 2, 2, projection='3d') # defining a set of points for X,Y and ZX1 = [1,2,1,4,3,2,7,5,9]Y1 = [8,2,7,4,3,6,1,8,9]Z1 = [1,2,4,7,9,6,7,6,9] # Plotting 3 points X1,Y1,Z1 with# color as greenax.plot(X1, Y1, Z1,color='green') # Showing the above plotplt.show() Output: Explanation: In the above example, we will be working with 2 3D graphs. So for that, we will be creating two subplots in a single canvas or figure. In the code, we have initialized the packages matplotlib.pyplot, and NumPy from python as usual. Then we are creating an empty figure where two 3D plots will be plotted. Now we are creating the first subplot. After that, we are taking X, Y which contain a series of points, and with them, we are creating a meshgrid which is made up of two 1D dimensional arrays and is used for matrix indexing to create an nD array. Then, using the values of X and Y, we are creating Z by forming an expression. Using plot_wireframe we are plotting the points in the 3D axis. After that, we move to the second plot, where we define the 2nd subplot parameters. Then, we are creating a wide range of elements and storing them in the form of arrays in X1, Y1, and Z1. After that, we are plotting the graph with the above points, and later we are showing the figure containing the 2 3D graphs. Here we will look at how to create a surface plot and a tri-surface plot. Here, we are integrating both the plots into a single figure so that we can understand the concept of subplots along with that of plots for a wide range of points to be plotted. So let us move to the implementation of the concept. Unlike wireframe plots, these plot’s surfaces will be filled with color. Example: Python3 #importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from pythonimport numpy as np # creating an empty figure for plottingfig = plt.figure() # defining a sub-plot with 1x2 axis and defining# it as first plot with projection as 3Dax = fig.add_subplot(1, 2, 1, projection='3d') # creating a range of values for# x1,y1 from -1 to 1 with# a space of 0.1 between the elements so that# we can create a single curve in the plotx1= np.arange(-1,1,0.1)y1= np.arange(-1,1,0.1) # Creating a mesh grid with x ,y and x1,# y1 which creates an n-dimensional# arrayx1,y1= np.meshgrid(x1,y1) # Creating a cosine function with the# range of values from the meshgridz1= np.cos(x1* np.pi/2) # Creating a wireframe plot with the points# x1,y1,z1 along with the plot line as redax.plot_surface(x1, y1, z1, color="red") # Creating my second subplot with 1x2 axis and defining# it as the second plot with projection as 3Dax = fig.add_subplot(1, 2, 2, projection='3d') # defining a set of points for X1,Y1 and Z1X1 = [1,2,1,4,3,2,7,5,9]Y1 = [8,2,7,4,3,6,1,8,9]Z1 = [1,2,4,7,9,6,7,6,9] # Plotting 3 points X1,Y1,Z1 with# color as purpleax.plot_trisurf(X1, Y1, Z1,color='purple') # Showing the above plotplt.show() Output: Explanation: After importing all the necessary packages(numpy,matplotlib.pyplot), we are creating an empty figure using plt.figure(), we are adding subplots to the above figure where we are taking 1,2,1 as parameters along with the projection as 3D. This enables us to create a plot of 1×2 size, and we define it as the first plot. Then we are creating a wide range of values from -1 to 1, evenly spaced with a difference of 0.1and storing them in x1 and y1. Then, using meshgrid, we are creating an nD array for both x1 and y1. Using the values of x1 we are creating a cosine curve and storing the set of values in z1. With the help of ax.plot_surface(), we are plotting a surface plot defining x1,y1, and z1 points along with the color of the surface plot as red. After that, we are defining the second plot with the same size i.e 1×2, and defining it as the second plot. We are using variables X1, Y1, and Z1 to create a set of points and store them in these lists. Using ax.plot_trisurf() we are defining the points of X1, Y1, and Z1 and the color of the graph as purple. Finally, we are showing the above plot. Here, we will be looking at contour and filled contour plots. Since both the plots are similar type, we are using a subplot again for plotting the points. Contour plot is a way of showing a 3D graph by plotting constant z-slices. Filled contour fills the areas that were shown by the line in contour plots. Python3 # importing axes3d from mpl_toolkits.mplot# module in pythonfrom mpl_toolkits.mplot3d import axes3d # importing matplotlib package from pythonimport matplotlib.pyplot as plt #importing numpy package from# python libraryimport numpy as np # Creating an empty figurefig = plt.figure() # Creating a subplot where we are# defining the projection as 3D projectionax = fig.add_subplot(1,2,1, projection='3d') # Creating a set of testing data using# get_test_data from axes3d module in# python. It creates a set of nD arrays# for each of the variables X,Y,ZX, Y, Z = axes3d.get_test_data(0.07)#Plotting the contour plot with the# following range of nD arraysplot = ax.contour(X, Y, Z) # Adding a second subplot in our figure with# the projection as a 3D projectionax=fig.add_subplot(1,2,2,projection='3d') # Adding a range of values to the variables X1,Y1X1=[1,2,3,4,5,6,7]Y1=[1,2,3,4,5,6,7] # Creating a meshgrid of X1 and Y1X1, Y1 = np.meshgrid(X1,Y1)# Creating an expression for Z1 with the# help of X1 and Y1Z1=(X1+4)*5+(Y1-5)/2 # Creating a contour plotplot2 = ax.contourf(X1, Y1, Z1) # Showing the above plotplt.show() Output: Explanation: The first step is to import all the necessary packages for plotting the above plot. Apart from matplotlib.pyplot and NumPy, we are importing another package which is mpl_toolkits.mplot3d. After that, we are creating an empty figure where we will have our 2 3D subplots. After that, we are adding the first subplot of the size 1×2 and define the first subplot. After that, we use 3 variables and with the help of get_test_data we are creating an automated meshgrid that will help us to plot the points in the plot. Using ax.contour(X,Y,Z) we are creating a contour plot with the following range of values. After that, we define the 2nd plot of the same size. A filled contour plot does not require a meshgrid. It can be created with a simple range of values in X1, Y1, Z1. Z1 is formed with the help of an expression created using X1 and Y1. Using ax.contourf(X1,Y1,Z1) we are plotting a filled contour plot. In the end, we are showing the above figure with 2 subplots. Here, we will be exploring a polygon plot. This plot is different from the ones that were plotted in the earlier examples. In this plot, we will be plotting a continuous set of points at different axes points of z. Let’s move to the implementation. Example: Python3 # import Axes3D from mpl_toolkits.mplot3d# from pythonfrom mpl_toolkits.mplot3d import Axes3D # importing PolyCollection from# matplotlib.collections modulefrom matplotlib.collections import PolyCollection #importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from# pythonimport numpy as np # Creating an empty figurefig = plt.figure() # Creating a 3D projection using# fig.gcaax = fig.gca(projection='3d') # Creating a wide range of elements# using numpy package from pythonxs = np.arange(0, 1, 0.1)# Creating an empty listverts = []# Creating a range of values on# Z-Axiszs = [0.0, 0.2, 0.4, 0.6,0.8]# Looping through all the values in zs# and creating random values in ys using# np.random.rand() which creates a range of# elements in ys and we are appending each of them# inside verts[]for z in zs: ys = np.random.rand(len(xs)) verts.append(list(zip(xs, ys)))# using polycollection, we are providing a# series of vertices to poly so as to# plot our required plotpoly = PolyCollection(verts)# Using add_collection3d, we are plotting# ur required polygon plot where we define# zs with the range of values we defined in our# list zs and also the zdir as Y-Axisax.add_collection3d(poly,zs=zs,zdir='y')# Showing the required plotplt.show() Output: Explanation: In this example, we need to import 4 different packages to create this plot(Numpy, matplotlib.pyplot, polycollection,Axes3d). After that, we will be creating an empty figure where we will plot the above graph. Using arange and a series of some of the arbitrary values we are creating a list of values in x and z.now we are loopinf through z where for each value of z we are getting a random list of numbers for y of the same length as that of x. Now for each z, we are plotting x vs y along the line. Using PolyCollection , we are taking all the plots together with the same color in each of the plot. With the help of add_collection3d we are determining that the plot is to be plotted in the x-z axis and also defining zs=0. Finally, we are showing the above plot. Here, we will be learning about the quiver plot in matplotlib. A quiver plot helps us to plot a 3d field of arrows in order to define the specified points. We can customize the arrows in various ways. Let us look into the code implementation. Example: Python3 # import axes3d from mpl_toolkits.mplot3dfrom mpl_toolkits.mplot3d import axes3d # import matplotlib.pyplot from pythonimport matplotlib.pyplot as plt # import numpy from pythonimport numpy as np # Creating an empty figure# to plot a 3D graphfig = plt.figure() # Creating a 3Dprojection for# our 3D plots using fig.gcaax = fig.gca(projection='3d') # Creating a meshgrid for the range# of values in X,Y,Zx, y, z = np.meshgrid([1,2,5,2,4,8,3,3,1],[6,4,3,1,6,2,7,8,2],[1,2,5,2,4,8,3,3,1]) # Creating expressions for u,v,w# with the help of x,y and z# which will form the direction vectorsu = x*2+y*3+z*3v = (x+3)*(y+5)*(z+7)w = x+y+z # Creating a quiver plot with length of the direction# vector length as 0.2 ad normalise as trueax.quiver(x, y, z, u, v, w, length=0.2, normalize=True) #showing the above plotplt.show() Output: Explanation: In the above code, we are importing all the necessary packages at the top(matplotlib.pyplot,numpy,mpl_toolkit.mplot3d). Then we are creating an empty figure with the help of plt.figure(). With the help of fig.gca(projection=’3d’), we are specifying the projection as 3D i.e 3D plotting. Using meshgrid we are creating an N-D array with X, Y, and Z. In the quiver plot, plotting the points is not the only task. We need to specify the components of the direction of vectors. So for that, we are taking u,v,z which are formed through different expressions created using X, Y, and Z. Using ax.quiver() we are plotting the quiver plot where we specify the length of each quiver as 0.1 and in order for arrows to be of the same length, we define normalize as True. Here, we will be taking a set of 2D points to be plotted in a specific axis in our 3D plot because we cannot plot a 2D point in a 3D plane with all the coordinates. So a specific axis needs to be defined for plotting the 2D points. So let’s see the code of the plot. Python3 # importing numpy packageimport numpy as np# importing matplotlib packageimport matplotlib.pyplot as plt # Creating an empty canvas(figure)fig = plt.figure() # Using the gca function, we are defining# the current axes as a 3D projectionax = fig.gca(projection='3d') # Labelling X-Axisax.set_xlabel('X-Axis') # Labelling Y-Axisax.set_ylabel('Y-Axis') # Labelling Z-Axisax.set_zlabel('Z-Axis') # Creating 10 values for Xx = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8] # Creating 10 values for Yy = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8] # Creating 10 random values for Yz=[1,2,4,5,6,7,8,9,10,11] # zdir='z' fixes all the points to zs=0 and# (x,y) points are ploted in the x-y axis# of the graphax.plot(x, y, zs=0, zdir='z') # zdir='y' fixes all the points to zs=0 and# (x,y) points are ploted in the x-z axis of the# graphax.plot(x, y, zs=0, zdir='y') # Showing the above plotplt.show() Output: Explanation: In this example, we are plotting 2D data on a 3D plot in Matplotlib. For this, we need NumPy and matplotlib.pyplot for creating the set of values and plotting them in 3D projection. After importing all the necessary packages, we are creating a wide range of values in X, Y, and Z. Now with the help of ax.plot() we are plotting our 2D points, where we specify the two sets to be plotted as a parameter inside ax.plot() along with the axis in which they are to be plotted. adnanirshad158 akshaysingh98088 sagar0719kumar kashishsoda Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Feb, 2022" }, { "code": null, "e": 341, "s": 54, "text": "In this article, we will be learning about 3D plotting with Matplotlib. There are various ways through which we can create a 3D plot using matplotlib such as creating an empty canvas and adding axes to it where you define the projection as a 3D projection, Matplotlib.pyplot.gca(), etc." }, { "code": null, "e": 701, "s": 341, "text": "In the below code, we will be creating an empty canvas at first. After that, we will be defining the axes of our 3D plot where we define that the projection of the plot will be in “3D” format. This helps us to create the 3D empty axes figure in the canvas. After this, if we show the plot using plt.show(), then it would look like the one shown in the output." }, { "code": null, "e": 755, "s": 701, "text": "Example: Creating an empty 3D figure using Matplotlib" }, { "code": null, "e": 763, "s": 755, "text": "Python3" }, { "code": "# importing numpy package from# python libraryimport numpy as np # importing matplotlib.pyplot package from# pythonimport matplotlib.pyplot as plt # Creating an empty figure# or plotfig = plt.figure() # Defining the axes as a# 3D axes so that we can plot 3D# data into it.ax = plt.axes(projection=\"3d\") # Showing the above plotplt.show()", "e": 1101, "s": 763, "text": null }, { "code": null, "e": 1110, "s": 1101, "text": "Output: " }, { "code": null, "e": 1229, "s": 1110, "text": "Now, we have a basic idea about how to create a 3D plot on an empty canvas. Let us move to some 3D plotting examples. " }, { "code": null, "e": 1240, "s": 1229, "text": "Example 1:" }, { "code": null, "e": 1430, "s": 1240, "text": "In the below example, we will be taking a simple curve in our 3D plot. Along with that, we will be plotting a range of points that have X-coordinate, Y-coordinate as well as Z-coordinate. " }, { "code": null, "e": 1438, "s": 1430, "text": "Python3" }, { "code": "# importing numpy packageimport numpy as np # importing matplotlib packageimport matplotlib.pyplot as plt # importing mplot3d from# mpl_toolkitsfrom mpl_toolkits import mplot3d # creating an empty canvasfig = plt.figure() # defining the axes with the projection# as 3D so as to plot 3D graphsax = plt.axes(projection=\"3d\") # creating a wide range of points x,y,zx=[0,1,2,3,4,5,6]y=[0,1,4,9,16,25,36]z=[0,1,4,9,16,25,36] # plotting a 3D line graph with X-coordinate,# Y-coordinate and Z-coordinate respectivelyax.plot3D(x, y, z, 'red') # plotting a scatter plot with X-coordinate,# Y-coordinate and Z-coordinate respectively# and defining the points color as cividis# and defining c as z which basically is a# defination of 2D array in which rows are RGB#or RGBAax.scatter3D(x, y, z, c=z, cmap='cividis'); # Showing the above plotplt.show()", "e": 2278, "s": 1438, "text": null }, { "code": null, "e": 2286, "s": 2278, "text": "Output:" }, { "code": null, "e": 2300, "s": 2286, "text": "Explanation: " }, { "code": null, "e": 2502, "s": 2300, "text": "In the above example, first, we are importing packages from the python library in order to have a 3D plot in our empty canvas. So, for that, we are importing numpy, matplotlib.pyplot, and mpl_toolkits." }, { "code": null, "e": 2598, "s": 2502, "text": "After importing all the necessary packages, we are creating an empty figure using plt.figure()." }, { "code": null, "e": 2711, "s": 2598, "text": "After that, we are defining the axis of the plot where we are specifying that the plot will be of 3D projection." }, { "code": null, "e": 3050, "s": 2711, "text": "After that, we are taking 3 arrays with a wide range of arbitrary points which will act as X, Y, and Z coordinates for plotting the graph respectively. Now after initializing the points, we are plotting a 3D plot using ax.plot3D() where we are using x,y,z as the X, Y, and Z coordinates respectively and the color of the line will be red." }, { "code": null, "e": 3110, "s": 3050, "text": "All these things are sent as parameters inside the bracket." }, { "code": null, "e": 3304, "s": 3110, "text": "After that, we are also plotting a scatter plot with the same set of values and as we progress with each point, the color of the points will be based on the values that the coordinates contain." }, { "code": null, "e": 3347, "s": 3304, "text": "After this, we are showing the above plot." }, { "code": null, "e": 3358, "s": 3347, "text": "Example 2:" }, { "code": null, "e": 3624, "s": 3358, "text": "In this example, we will be learning about how to do 3D plotting using figure.gca(). Here we will be creating a sine curve and a cosine curve with the values of x and y ranging from -5 to 5 with a gap of 1. Let us look at the code to understand the implementation. " }, { "code": null, "e": 3632, "s": 3624, "text": "Python3" }, { "code": "# importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from# pythonimport numpy as np # creating a range of values for# x,y,x1,y1 from -5 to 5 with# a space of 1 between the elementsx = np.arange(-5,5,1)y = np.arange(-5,5,1) # creating a range of values for# x,y,x1,y1 from -5 to 5 with# a space of 0.6 between the elementsx1= np.arange(-5,5,0.6)y1= np.arange(-5,5,0.6) # Creating a mesh grid with x ,y and x1,# y1 which creates an n-dimensional# arrayx, y = np.meshgrid(x, y)x1,y1= np.meshgrid(x1,y1) # Creating a sine function with the# range of values from the meshgridz = np.sin(x * np.pi/2 ) # Creating a cosine function with the# range of values from the meshgridz1= np.cos(x1* np.pi/2) # Creating an empty figure for# 3D plottingfig = plt.figure() # using fig.gca, we are creating a 3D# projection plot in the empty figureax = fig.gca(projection=\"3d\") # Creating a wireframe plot with the x,y and# z-coordinates respectively along with the# color as redsurf = ax.plot_wireframe(x, y, z, color=\"red\") # Creating a wireframe plot with the points# x1,y1,z1 along with the plot line as greensurf1 =ax.plot_wireframe(x1, y1, z1, color=\"green\") #showing the above plotplt.show()", "e": 4859, "s": 3632, "text": null }, { "code": null, "e": 4867, "s": 4859, "text": "Output:" }, { "code": null, "e": 4880, "s": 4867, "text": "Explanation:" }, { "code": null, "e": 4968, "s": 4880, "text": "In this example, we are importing two packages matplotlib.pyplot and NumPy from python." }, { "code": null, "e": 5669, "s": 4968, "text": "After that, we are creating a wide range of values with various variables such as x, y,x1,x2. Now there is a catch over here. The first set of x,y have values from -5 to 5 with each of the elements having a difference of 1 from each other. The second set of elements also ranges from -5 to 5 with each element having a difference of 0.6 from each other. The difference that it creates is, the first graph will have steep curves since the difference between the points is more, whereas, in the second set, the graph will be smoother as compared to the first one because we are taking a wide range of points more than x and y. That’s why the second curve(cosine curve) is smoother than the first curve." }, { "code": null, "e": 5985, "s": 5669, "text": "Using meshgrid, we are returning coordinate matrices from coordinate vectors. MeshGrid makes N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, where there is a 1-Dimensional array. Now, we are creating the sine and the cosine curves with the help of z and z1 respectively." }, { "code": null, "e": 6350, "s": 5985, "text": "After that, we are creating an empty figure where we will be plotting out 3D plot. Using fig.gca, we are defining that the plots that we are going to make will be of 3D projection using projection=’3d’. Using plot_wireframe we are creating a 3D sine and cosine curve(of different colors) with the above points created by us. Finally, we are showing the above plot." }, { "code": null, "e": 6361, "s": 6350, "text": "Example 3:" }, { "code": null, "e": 6535, "s": 6361, "text": "In the last and the final example, we will be creating two 3D graphs in a single figure/canvas, where we will be our 3D points. So let us move into our code implementation. " }, { "code": null, "e": 6543, "s": 6535, "text": "Python3" }, { "code": "#importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from pythonimport numpy as np # creating an empty figure for plottingfig = plt.figure() # defining a sub-plot with 1x2 axis and defining# it as first plot with projection as 3Dax = fig.add_subplot(1, 2, 1, projection='3d') # creating a range of 12 elements in both# X and YX = np.arange(12)Y = np.linspace(12, 1) # Creating a mesh grid of X and YX, Y = np.meshgrid(X, Y) # Creating an expression X and Y and# storing it in ZZ = X*2+Y*3; # Creating a wireframe plot with the 3 sets of# values X,Y and Zax.plot_wireframe(X, Y, Z) # Creating my second subplot with 1x2 axis and defining# it as the second plot with projection as 3Dax = fig.add_subplot(1, 2, 2, projection='3d') # defining a set of points for X,Y and ZX1 = [1,2,1,4,3,2,7,5,9]Y1 = [8,2,7,4,3,6,1,8,9]Z1 = [1,2,4,7,9,6,7,6,9] # Plotting 3 points X1,Y1,Z1 with# color as greenax.plot(X1, Y1, Z1,color='green') # Showing the above plotplt.show()", "e": 7548, "s": 6543, "text": null }, { "code": null, "e": 7556, "s": 7548, "text": "Output:" }, { "code": null, "e": 7570, "s": 7556, "text": "Explanation: " }, { "code": null, "e": 7802, "s": 7570, "text": "In the above example, we will be working with 2 3D graphs. So for that, we will be creating two subplots in a single canvas or figure. In the code, we have initialized the packages matplotlib.pyplot, and NumPy from python as usual." }, { "code": null, "e": 7914, "s": 7802, "text": "Then we are creating an empty figure where two 3D plots will be plotted. Now we are creating the first subplot." }, { "code": null, "e": 8122, "s": 7914, "text": "After that, we are taking X, Y which contain a series of points, and with them, we are creating a meshgrid which is made up of two 1D dimensional arrays and is used for matrix indexing to create an nD array." }, { "code": null, "e": 8265, "s": 8122, "text": "Then, using the values of X and Y, we are creating Z by forming an expression. Using plot_wireframe we are plotting the points in the 3D axis." }, { "code": null, "e": 8349, "s": 8265, "text": "After that, we move to the second plot, where we define the 2nd subplot parameters." }, { "code": null, "e": 8454, "s": 8349, "text": "Then, we are creating a wide range of elements and storing them in the form of arrays in X1, Y1, and Z1." }, { "code": null, "e": 8579, "s": 8454, "text": "After that, we are plotting the graph with the above points, and later we are showing the figure containing the 2 3D graphs." }, { "code": null, "e": 8957, "s": 8579, "text": "Here we will look at how to create a surface plot and a tri-surface plot. Here, we are integrating both the plots into a single figure so that we can understand the concept of subplots along with that of plots for a wide range of points to be plotted. So let us move to the implementation of the concept. Unlike wireframe plots, these plot’s surfaces will be filled with color." }, { "code": null, "e": 8967, "s": 8957, "text": "Example: " }, { "code": null, "e": 8975, "s": 8967, "text": "Python3" }, { "code": "#importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from pythonimport numpy as np # creating an empty figure for plottingfig = plt.figure() # defining a sub-plot with 1x2 axis and defining# it as first plot with projection as 3Dax = fig.add_subplot(1, 2, 1, projection='3d') # creating a range of values for# x1,y1 from -1 to 1 with# a space of 0.1 between the elements so that# we can create a single curve in the plotx1= np.arange(-1,1,0.1)y1= np.arange(-1,1,0.1) # Creating a mesh grid with x ,y and x1,# y1 which creates an n-dimensional# arrayx1,y1= np.meshgrid(x1,y1) # Creating a cosine function with the# range of values from the meshgridz1= np.cos(x1* np.pi/2) # Creating a wireframe plot with the points# x1,y1,z1 along with the plot line as redax.plot_surface(x1, y1, z1, color=\"red\") # Creating my second subplot with 1x2 axis and defining# it as the second plot with projection as 3Dax = fig.add_subplot(1, 2, 2, projection='3d') # defining a set of points for X1,Y1 and Z1X1 = [1,2,1,4,3,2,7,5,9]Y1 = [8,2,7,4,3,6,1,8,9]Z1 = [1,2,4,7,9,6,7,6,9] # Plotting 3 points X1,Y1,Z1 with# color as purpleax.plot_trisurf(X1, Y1, Z1,color='purple') # Showing the above plotplt.show()", "e": 10210, "s": 8975, "text": null }, { "code": null, "e": 10219, "s": 10210, "text": "Output: " }, { "code": null, "e": 10232, "s": 10219, "text": "Explanation:" }, { "code": null, "e": 10551, "s": 10232, "text": "After importing all the necessary packages(numpy,matplotlib.pyplot), we are creating an empty figure using plt.figure(), we are adding subplots to the above figure where we are taking 1,2,1 as parameters along with the projection as 3D. This enables us to create a plot of 1×2 size, and we define it as the first plot." }, { "code": null, "e": 10678, "s": 10551, "text": "Then we are creating a wide range of values from -1 to 1, evenly spaced with a difference of 0.1and storing them in x1 and y1." }, { "code": null, "e": 10748, "s": 10678, "text": "Then, using meshgrid, we are creating an nD array for both x1 and y1." }, { "code": null, "e": 10839, "s": 10748, "text": "Using the values of x1 we are creating a cosine curve and storing the set of values in z1." }, { "code": null, "e": 10985, "s": 10839, "text": "With the help of ax.plot_surface(), we are plotting a surface plot defining x1,y1, and z1 points along with the color of the surface plot as red." }, { "code": null, "e": 11188, "s": 10985, "text": "After that, we are defining the second plot with the same size i.e 1×2, and defining it as the second plot. We are using variables X1, Y1, and Z1 to create a set of points and store them in these lists." }, { "code": null, "e": 11335, "s": 11188, "text": "Using ax.plot_trisurf() we are defining the points of X1, Y1, and Z1 and the color of the graph as purple. Finally, we are showing the above plot." }, { "code": null, "e": 11643, "s": 11335, "text": "Here, we will be looking at contour and filled contour plots. Since both the plots are similar type, we are using a subplot again for plotting the points. Contour plot is a way of showing a 3D graph by plotting constant z-slices. Filled contour fills the areas that were shown by the line in contour plots. " }, { "code": null, "e": 11651, "s": 11643, "text": "Python3" }, { "code": "# importing axes3d from mpl_toolkits.mplot# module in pythonfrom mpl_toolkits.mplot3d import axes3d # importing matplotlib package from pythonimport matplotlib.pyplot as plt #importing numpy package from# python libraryimport numpy as np # Creating an empty figurefig = plt.figure() # Creating a subplot where we are# defining the projection as 3D projectionax = fig.add_subplot(1,2,1, projection='3d') # Creating a set of testing data using# get_test_data from axes3d module in# python. It creates a set of nD arrays# for each of the variables X,Y,ZX, Y, Z = axes3d.get_test_data(0.07)#Plotting the contour plot with the# following range of nD arraysplot = ax.contour(X, Y, Z) # Adding a second subplot in our figure with# the projection as a 3D projectionax=fig.add_subplot(1,2,2,projection='3d') # Adding a range of values to the variables X1,Y1X1=[1,2,3,4,5,6,7]Y1=[1,2,3,4,5,6,7] # Creating a meshgrid of X1 and Y1X1, Y1 = np.meshgrid(X1,Y1)# Creating an expression for Z1 with the# help of X1 and Y1Z1=(X1+4)*5+(Y1-5)/2 # Creating a contour plotplot2 = ax.contourf(X1, Y1, Z1) # Showing the above plotplt.show()", "e": 12769, "s": 11651, "text": null }, { "code": null, "e": 12777, "s": 12769, "text": "Output:" }, { "code": null, "e": 12790, "s": 12777, "text": "Explanation:" }, { "code": null, "e": 12980, "s": 12790, "text": "The first step is to import all the necessary packages for plotting the above plot. Apart from matplotlib.pyplot and NumPy, we are importing another package which is mpl_toolkits.mplot3d. " }, { "code": null, "e": 13062, "s": 12980, "text": "After that, we are creating an empty figure where we will have our 2 3D subplots." }, { "code": null, "e": 13152, "s": 13062, "text": "After that, we are adding the first subplot of the size 1×2 and define the first subplot." }, { "code": null, "e": 13397, "s": 13152, "text": "After that, we use 3 variables and with the help of get_test_data we are creating an automated meshgrid that will help us to plot the points in the plot. Using ax.contour(X,Y,Z) we are creating a contour plot with the following range of values." }, { "code": null, "e": 13700, "s": 13397, "text": "After that, we define the 2nd plot of the same size. A filled contour plot does not require a meshgrid. It can be created with a simple range of values in X1, Y1, Z1. Z1 is formed with the help of an expression created using X1 and Y1. Using ax.contourf(X1,Y1,Z1) we are plotting a filled contour plot." }, { "code": null, "e": 13761, "s": 13700, "text": "In the end, we are showing the above figure with 2 subplots." }, { "code": null, "e": 14010, "s": 13761, "text": "Here, we will be exploring a polygon plot. This plot is different from the ones that were plotted in the earlier examples. In this plot, we will be plotting a continuous set of points at different axes points of z. Let’s move to the implementation." }, { "code": null, "e": 14019, "s": 14010, "text": "Example:" }, { "code": null, "e": 14027, "s": 14019, "text": "Python3" }, { "code": "# import Axes3D from mpl_toolkits.mplot3d# from pythonfrom mpl_toolkits.mplot3d import Axes3D # importing PolyCollection from# matplotlib.collections modulefrom matplotlib.collections import PolyCollection #importing matplotlib.pyplot from# pythonimport matplotlib.pyplot as plt # importing numpy package from# pythonimport numpy as np # Creating an empty figurefig = plt.figure() # Creating a 3D projection using# fig.gcaax = fig.gca(projection='3d') # Creating a wide range of elements# using numpy package from pythonxs = np.arange(0, 1, 0.1)# Creating an empty listverts = []# Creating a range of values on# Z-Axiszs = [0.0, 0.2, 0.4, 0.6,0.8]# Looping through all the values in zs# and creating random values in ys using# np.random.rand() which creates a range of# elements in ys and we are appending each of them# inside verts[]for z in zs: ys = np.random.rand(len(xs)) verts.append(list(zip(xs, ys)))# using polycollection, we are providing a# series of vertices to poly so as to# plot our required plotpoly = PolyCollection(verts)# Using add_collection3d, we are plotting# ur required polygon plot where we define# zs with the range of values we defined in our# list zs and also the zdir as Y-Axisax.add_collection3d(poly,zs=zs,zdir='y')# Showing the required plotplt.show()", "e": 15316, "s": 14027, "text": null }, { "code": null, "e": 15325, "s": 15316, "text": "Output: " }, { "code": null, "e": 15339, "s": 15325, "text": "Explanation: " }, { "code": null, "e": 15465, "s": 15339, "text": "In this example, we need to import 4 different packages to create this plot(Numpy, matplotlib.pyplot, polycollection,Axes3d)." }, { "code": null, "e": 15785, "s": 15465, "text": "After that, we will be creating an empty figure where we will plot the above graph. Using arange and a series of some of the arbitrary values we are creating a list of values in x and z.now we are loopinf through z where for each value of z we are getting a random list of numbers for y of the same length as that of x." }, { "code": null, "e": 16065, "s": 15785, "text": "Now for each z, we are plotting x vs y along the line. Using PolyCollection , we are taking all the plots together with the same color in each of the plot. With the help of add_collection3d we are determining that the plot is to be plotted in the x-z axis and also defining zs=0." }, { "code": null, "e": 16105, "s": 16065, "text": "Finally, we are showing the above plot." }, { "code": null, "e": 16348, "s": 16105, "text": "Here, we will be learning about the quiver plot in matplotlib. A quiver plot helps us to plot a 3d field of arrows in order to define the specified points. We can customize the arrows in various ways. Let us look into the code implementation." }, { "code": null, "e": 16358, "s": 16348, "text": "Example: " }, { "code": null, "e": 16366, "s": 16358, "text": "Python3" }, { "code": "# import axes3d from mpl_toolkits.mplot3dfrom mpl_toolkits.mplot3d import axes3d # import matplotlib.pyplot from pythonimport matplotlib.pyplot as plt # import numpy from pythonimport numpy as np # Creating an empty figure# to plot a 3D graphfig = plt.figure() # Creating a 3Dprojection for# our 3D plots using fig.gcaax = fig.gca(projection='3d') # Creating a meshgrid for the range# of values in X,Y,Zx, y, z = np.meshgrid([1,2,5,2,4,8,3,3,1],[6,4,3,1,6,2,7,8,2],[1,2,5,2,4,8,3,3,1]) # Creating expressions for u,v,w# with the help of x,y and z# which will form the direction vectorsu = x*2+y*3+z*3v = (x+3)*(y+5)*(z+7)w = x+y+z # Creating a quiver plot with length of the direction# vector length as 0.2 ad normalise as trueax.quiver(x, y, z, u, v, w, length=0.2, normalize=True) #showing the above plotplt.show()", "e": 17183, "s": 16366, "text": null }, { "code": null, "e": 17192, "s": 17183, "text": "Output: " }, { "code": null, "e": 17205, "s": 17192, "text": "Explanation:" }, { "code": null, "e": 17325, "s": 17205, "text": "In the above code, we are importing all the necessary packages at the top(matplotlib.pyplot,numpy,mpl_toolkit.mplot3d)." }, { "code": null, "e": 17492, "s": 17325, "text": "Then we are creating an empty figure with the help of plt.figure(). With the help of fig.gca(projection=’3d’), we are specifying the projection as 3D i.e 3D plotting." }, { "code": null, "e": 17786, "s": 17492, "text": "Using meshgrid we are creating an N-D array with X, Y, and Z. In the quiver plot, plotting the points is not the only task. We need to specify the components of the direction of vectors. So for that, we are taking u,v,z which are formed through different expressions created using X, Y, and Z." }, { "code": null, "e": 17965, "s": 17786, "text": "Using ax.quiver() we are plotting the quiver plot where we specify the length of each quiver as 0.1 and in order for arrows to be of the same length, we define normalize as True." }, { "code": null, "e": 18233, "s": 17965, "text": "Here, we will be taking a set of 2D points to be plotted in a specific axis in our 3D plot because we cannot plot a 2D point in a 3D plane with all the coordinates. So a specific axis needs to be defined for plotting the 2D points. So let’s see the code of the plot. " }, { "code": null, "e": 18241, "s": 18233, "text": "Python3" }, { "code": "# importing numpy packageimport numpy as np# importing matplotlib packageimport matplotlib.pyplot as plt # Creating an empty canvas(figure)fig = plt.figure() # Using the gca function, we are defining# the current axes as a 3D projectionax = fig.gca(projection='3d') # Labelling X-Axisax.set_xlabel('X-Axis') # Labelling Y-Axisax.set_ylabel('Y-Axis') # Labelling Z-Axisax.set_zlabel('Z-Axis') # Creating 10 values for Xx = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8] # Creating 10 values for Yy = [1,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8] # Creating 10 random values for Yz=[1,2,4,5,6,7,8,9,10,11] # zdir='z' fixes all the points to zs=0 and# (x,y) points are ploted in the x-y axis# of the graphax.plot(x, y, zs=0, zdir='z') # zdir='y' fixes all the points to zs=0 and# (x,y) points are ploted in the x-z axis of the# graphax.plot(x, y, zs=0, zdir='y') # Showing the above plotplt.show()", "e": 19123, "s": 18241, "text": null }, { "code": null, "e": 19132, "s": 19123, "text": "Output: " }, { "code": null, "e": 19145, "s": 19132, "text": "Explanation:" }, { "code": null, "e": 19426, "s": 19145, "text": "In this example, we are plotting 2D data on a 3D plot in Matplotlib. For this, we need NumPy and matplotlib.pyplot for creating the set of values and plotting them in 3D projection. After importing all the necessary packages, we are creating a wide range of values in X, Y, and Z." }, { "code": null, "e": 19617, "s": 19426, "text": "Now with the help of ax.plot() we are plotting our 2D points, where we specify the two sets to be plotted as a parameter inside ax.plot() along with the axis in which they are to be plotted." }, { "code": null, "e": 19634, "s": 19619, "text": "adnanirshad158" }, { "code": null, "e": 19651, "s": 19634, "text": "akshaysingh98088" }, { "code": null, "e": 19666, "s": 19651, "text": "sagar0719kumar" }, { "code": null, "e": 19678, "s": 19666, "text": "kashishsoda" }, { "code": null, "e": 19685, "s": 19678, "text": "Picked" }, { "code": null, "e": 19703, "s": 19685, "text": "Python-matplotlib" }, { "code": null, "e": 19710, "s": 19703, "text": "Python" }, { "code": null, "e": 19808, "s": 19710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19840, "s": 19808, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 19867, "s": 19840, "text": "Python Classes and Objects" }, { "code": null, "e": 19888, "s": 19867, "text": "Python OOPs Concepts" }, { "code": null, "e": 19911, "s": 19888, "text": "Introduction To PYTHON" }, { "code": null, "e": 19967, "s": 19911, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 19998, "s": 19967, "text": "Python | os.path.join() method" }, { "code": null, "e": 20040, "s": 19998, "text": "Check if element exists in list in Python" }, { "code": null, "e": 20082, "s": 20040, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 20121, "s": 20082, "text": "Python | Get unique values from a list" } ]
Java program to swap first and last characters of words in a sentence
26 Dec, 2017 Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First we will create an Char array of given String by using toCharArray() method. Now we iterate the char array by using for loop. In for loop, we declare a variable whose value is dependent on i. Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space. class SwapFirstLastCharacters { static String count(String str) { // Create an equivalent char array // of given string char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length && ch[i] != ' ') i++; // Swapping char temp = ch[k]; ch[k] = ch[i - 1]; ch[i - 1] = temp; // We assume that there is only one space // between two words. } return new String(ch); } public static void main(String[] args) { String str = "geeks for geeks"; System.out.println(count(str)); }} Output: seekg rof seekg Java-Strings Java Programs Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Dec, 2017" }, { "code": null, "e": 158, "s": 52, "text": "Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example?" }, { "code": null, "e": 168, "s": 158, "text": "Examples:" }, { "code": null, "e": 217, "s": 168, "text": "Input : geeks for geeks\nOutput :seekg rof seekg\n" }, { "code": null, "e": 347, "s": 217, "text": "Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is." }, { "code": null, "e": 429, "s": 347, "text": "First we will create an Char array of given String by using toCharArray() method." }, { "code": null, "e": 478, "s": 429, "text": "Now we iterate the char array by using for loop." }, { "code": null, "e": 544, "s": 478, "text": "In for loop, we declare a variable whose value is dependent on i." }, { "code": null, "e": 739, "s": 544, "text": "Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space." }, { "code": "class SwapFirstLastCharacters { static String count(String str) { // Create an equivalent char array // of given string char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length && ch[i] != ' ') i++; // Swapping char temp = ch[k]; ch[k] = ch[i - 1]; ch[i - 1] = temp; // We assume that there is only one space // between two words. } return new String(ch); } public static void main(String[] args) { String str = \"geeks for geeks\"; System.out.println(count(str)); }}", "e": 1572, "s": 739, "text": null }, { "code": null, "e": 1580, "s": 1572, "text": "Output:" }, { "code": null, "e": 1597, "s": 1580, "text": "seekg rof seekg\n" }, { "code": null, "e": 1610, "s": 1597, "text": "Java-Strings" }, { "code": null, "e": 1624, "s": 1610, "text": "Java Programs" }, { "code": null, "e": 1632, "s": 1624, "text": "Strings" }, { "code": null, "e": 1645, "s": 1632, "text": "Java-Strings" }, { "code": null, "e": 1653, "s": 1645, "text": "Strings" } ]
struct module in Python
12 Jan, 2017 This module performs conversions between Python values and C structs represented as Python bytes objects. Format strings are the mechanism used to specify the expected layout when packing and unpacking data. Module struct is available in Python 3.x and not on 2.x, thus these codes will run on Python3 interpreter. Struct Functions struct.pack()Syntax: struct.pack(format, v1, v2, ...)Return a string containing the values v1, v2, ... , that are packed according to the given format (Format strings are the mechanism used to specify the expected layout when packing and unpacking data).The values followed by the format must be as per the format only, else struct.error is raised.import struct # Format: h is short in C type# Format: l is long in C type# Format 'hhl' stands for 'short short long'var = struct.pack('hhl',1,2,3)print(var) # Format: i is int in C type# Format 'iii' stands for 'int int int'var = struct.pack('iii',1,2,3)print(var)Output:b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00' Syntax: struct.pack(format, v1, v2, ...) Return a string containing the values v1, v2, ... , that are packed according to the given format (Format strings are the mechanism used to specify the expected layout when packing and unpacking data).The values followed by the format must be as per the format only, else struct.error is raised. import struct # Format: h is short in C type# Format: l is long in C type# Format 'hhl' stands for 'short short long'var = struct.pack('hhl',1,2,3)print(var) # Format: i is int in C type# Format 'iii' stands for 'int int int'var = struct.pack('iii',1,2,3)print(var) Output: b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00' struct.unpack()Syntax: struct.unpack(fmt, string)Return the values v1, v2, ... , that are unpacked according to the given format(1st argument). Values returned by this function are returned as tuples of size that is equal to the number of values passed through struct.pack() during packing.import struct # '?' -> _BOOL , 'h' -> short, 'i' -> int and 'l' -> longvar = struct.pack('?hil', True, 2, 5, 445)print(var) # struct.unpack() return a tuples# Variables V1, V2, V3,.. are returned as elements of tupletup = struct.unpack('?hil', var)print(tup) # q -> long long int and f -> floatvar = struct.pack('qf', 5, 2.3)print(var)tup = struct.unpack('qf', var)print(tup)Output:b'\x01\x00\x02\x00\x05\x00\x00\x00\xbd\x01\x00\x00\x00\x00\x00\x00' (True, 2, 5, 445) b'\x05\x00\x00\x00\x00\x00\x00\x0033\x13@' (5, 2.299999952316284) Note: ‘b’ in the Output stands for binary. Syntax: struct.unpack(fmt, string) Return the values v1, v2, ... , that are unpacked according to the given format(1st argument). Values returned by this function are returned as tuples of size that is equal to the number of values passed through struct.pack() during packing. import struct # '?' -> _BOOL , 'h' -> short, 'i' -> int and 'l' -> longvar = struct.pack('?hil', True, 2, 5, 445)print(var) # struct.unpack() return a tuples# Variables V1, V2, V3,.. are returned as elements of tupletup = struct.unpack('?hil', var)print(tup) # q -> long long int and f -> floatvar = struct.pack('qf', 5, 2.3)print(var)tup = struct.unpack('qf', var)print(tup) Output: b'\x01\x00\x02\x00\x05\x00\x00\x00\xbd\x01\x00\x00\x00\x00\x00\x00' (True, 2, 5, 445) b'\x05\x00\x00\x00\x00\x00\x00\x0033\x13@' (5, 2.299999952316284) Note: ‘b’ in the Output stands for binary. struct.calcsize()Syntax: struct.calcsize(fmt) fmt: format Return the size of the struct (and hence of the string) corresponding to the given format. calcsize() is important function, and is required for function such as struct.pack_into() and struct.unpack_from(), which require offset value and buffer as well.import structvar = struct.pack('?hil', True, 2, 5, 445)print(var)# Returns the size of the structureprint(struct.calcsize('?hil'))print(struct.calcsize('qf'))Output:b'\x01\x00\x02\x00\x05\x00\x00\x00\xbd\x01\x00\x00\x00\x00\x00\x00' 16 12 import structvar = struct.pack('bi', 56, 0x12131415)print(var)print(struct.calcsize('bi'))var = struct.pack('ib', 0x12131415, 56)print(var)print(struct.calcsize('ib'))Output:b'8\x00\x00\x00\x15\x14\x13\x12' 8 b'\x15\x14\x13\x128' 5 Note: The ordering of format characters may have an impact on size. Syntax: struct.calcsize(fmt) fmt: format Return the size of the struct (and hence of the string) corresponding to the given format. calcsize() is important function, and is required for function such as struct.pack_into() and struct.unpack_from(), which require offset value and buffer as well. import structvar = struct.pack('?hil', True, 2, 5, 445)print(var)# Returns the size of the structureprint(struct.calcsize('?hil'))print(struct.calcsize('qf')) Output: b'\x01\x00\x02\x00\x05\x00\x00\x00\xbd\x01\x00\x00\x00\x00\x00\x00' 16 12 import structvar = struct.pack('bi', 56, 0x12131415)print(var)print(struct.calcsize('bi'))var = struct.pack('ib', 0x12131415, 56)print(var)print(struct.calcsize('ib')) Output: b'8\x00\x00\x00\x15\x14\x13\x12' 8 b'\x15\x14\x13\x128' 5 Note: The ordering of format characters may have an impact on size. Exception struct.errorException struct.error describes what is wrong at passing arguments, when a wrong argument is passed struct.error is raised.from struct import errorprint(error)Note: This is piece of code is not useful, anywhere other than exception handling, and is used to show that ‘error’ upon interpreted shows about the class. from struct import errorprint(error) Note: This is piece of code is not useful, anywhere other than exception handling, and is used to show that ‘error’ upon interpreted shows about the class. struct.pack_into()Syntax: struct.pack_into(fmt, buffer, offset, v1, v2, ...) fmt: data type format buffer: writable buffer which starts at offset (optional) v1,v2.. : values Syntax: struct.pack_into(fmt, buffer, offset, v1, v2, ...) fmt: data type format buffer: writable buffer which starts at offset (optional) v1,v2.. : values struct.unpack_from()Syntax: struct.unpack_from(fmt, buffer[,offset = 0])fmt: data type format buffer: writable buffer which starts at offset (optional)Returns a tuple, similar to struct.unpack()import struct # ctypes in imported to create string bufferimport ctypes # SIZE of the format is calculated using calcsize()siz = struct.calcsize('hhl')print(siz) # Buffer 'buff' is createdbuff = ctypes.create_string_buffer(siz) # struct.pack() returns packed data# struct.unpack() returns unpacked datax = struct.pack('hhl', 2, 2, 3)print(x)print(struct.unpack('hhl', x)) # struct.pack_into() packs data into buff, doesn't return any value# struct.unpack_from() unpacks data from buff, returns a tuple of valuesstruct.pack_into('hhl', buff, 0, 2, 2, 3)print(struct.unpack_from('hhl', buff, 0))Output:16 b'\x02\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' (2, 2, 3) (2, 2, 3) Syntax: struct.unpack_from(fmt, buffer[,offset = 0])fmt: data type format buffer: writable buffer which starts at offset (optional) Returns a tuple, similar to struct.unpack() import struct # ctypes in imported to create string bufferimport ctypes # SIZE of the format is calculated using calcsize()siz = struct.calcsize('hhl')print(siz) # Buffer 'buff' is createdbuff = ctypes.create_string_buffer(siz) # struct.pack() returns packed data# struct.unpack() returns unpacked datax = struct.pack('hhl', 2, 2, 3)print(x)print(struct.unpack('hhl', x)) # struct.pack_into() packs data into buff, doesn't return any value# struct.unpack_from() unpacks data from buff, returns a tuple of valuesstruct.pack_into('hhl', buff, 0, 2, 2, 3)print(struct.unpack_from('hhl', buff, 0)) Output: 16 b'\x02\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00' (2, 2, 3) (2, 2, 3) Reference https://docs.python.org/2/library/struct.htmlThis article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 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 Introduction To PYTHON Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jan, 2017" }, { "code": null, "e": 367, "s": 52, "text": "This module performs conversions between Python values and C structs represented as Python bytes objects. Format strings are the mechanism used to specify the expected layout when packing and unpacking data. Module struct is available in Python 3.x and not on 2.x, thus these codes will run on Python3 interpreter." }, { "code": null, "e": 384, "s": 367, "text": "Struct Functions" }, { "code": null, "e": 1128, "s": 384, "text": "struct.pack()Syntax: \nstruct.pack(format, v1, v2, ...)Return a string containing the values v1, v2, ... , that are packed according to the given format (Format strings are the mechanism used to specify the expected layout when packing and unpacking data).The values followed by the format must be as per the format only, else struct.error is raised.import struct # Format: h is short in C type# Format: l is long in C type# Format 'hhl' stands for 'short short long'var = struct.pack('hhl',1,2,3)print(var) # Format: i is int in C type# Format 'iii' stands for 'int int int'var = struct.pack('iii',1,2,3)print(var)Output:b'\\x01\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\nb'\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00'\n" }, { "code": null, "e": 1170, "s": 1128, "text": "Syntax: \nstruct.pack(format, v1, v2, ...)" }, { "code": null, "e": 1466, "s": 1170, "text": "Return a string containing the values v1, v2, ... , that are packed according to the given format (Format strings are the mechanism used to specify the expected layout when packing and unpacking data).The values followed by the format must be as per the format only, else struct.error is raised." }, { "code": "import struct # Format: h is short in C type# Format: l is long in C type# Format 'hhl' stands for 'short short long'var = struct.pack('hhl',1,2,3)print(var) # Format: i is int in C type# Format 'iii' stands for 'int int int'var = struct.pack('iii',1,2,3)print(var)", "e": 1734, "s": 1466, "text": null }, { "code": null, "e": 1742, "s": 1734, "text": "Output:" }, { "code": null, "e": 1863, "s": 1742, "text": "b'\\x01\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\nb'\\x01\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x03\\x00\\x00\\x00'\n" }, { "code": null, "e": 2733, "s": 1863, "text": "struct.unpack()Syntax:\nstruct.unpack(fmt, string)Return the values v1, v2, ... , that are unpacked according to the given format(1st argument). Values returned by this function are returned as tuples of size that is equal to the number of values passed through struct.pack() during packing.import struct # '?' -> _BOOL , 'h' -> short, 'i' -> int and 'l' -> longvar = struct.pack('?hil', True, 2, 5, 445)print(var) # struct.unpack() return a tuples# Variables V1, V2, V3,.. are returned as elements of tupletup = struct.unpack('?hil', var)print(tup) # q -> long long int and f -> floatvar = struct.pack('qf', 5, 2.3)print(var)tup = struct.unpack('qf', var)print(tup)Output:b'\\x01\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\xbd\\x01\\x00\\x00\\x00\\x00\\x00\\x00'\n(True, 2, 5, 445)\nb'\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x0033\\x13@'\n(5, 2.299999952316284)\nNote: ‘b’ in the Output stands for binary." }, { "code": null, "e": 2768, "s": 2733, "text": "Syntax:\nstruct.unpack(fmt, string)" }, { "code": null, "e": 3010, "s": 2768, "text": "Return the values v1, v2, ... , that are unpacked according to the given format(1st argument). Values returned by this function are returned as tuples of size that is equal to the number of values passed through struct.pack() during packing." }, { "code": "import struct # '?' -> _BOOL , 'h' -> short, 'i' -> int and 'l' -> longvar = struct.pack('?hil', True, 2, 5, 445)print(var) # struct.unpack() return a tuples# Variables V1, V2, V3,.. are returned as elements of tupletup = struct.unpack('?hil', var)print(tup) # q -> long long int and f -> floatvar = struct.pack('qf', 5, 2.3)print(var)tup = struct.unpack('qf', var)print(tup)", "e": 3389, "s": 3010, "text": null }, { "code": null, "e": 3397, "s": 3389, "text": "Output:" }, { "code": null, "e": 3550, "s": 3397, "text": "b'\\x01\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\xbd\\x01\\x00\\x00\\x00\\x00\\x00\\x00'\n(True, 2, 5, 445)\nb'\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x0033\\x13@'\n(5, 2.299999952316284)\n" }, { "code": null, "e": 3593, "s": 3550, "text": "Note: ‘b’ in the Output stands for binary." }, { "code": null, "e": 4443, "s": 3593, "text": "struct.calcsize()Syntax:\nstruct.calcsize(fmt)\nfmt: format Return the size of the struct (and hence of the string) corresponding to the given format. calcsize() is important function, and is required for function such as struct.pack_into() and struct.unpack_from(), which require offset value and buffer as well.import structvar = struct.pack('?hil', True, 2, 5, 445)print(var)# Returns the size of the structureprint(struct.calcsize('?hil'))print(struct.calcsize('qf'))Output:b'\\x01\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\xbd\\x01\\x00\\x00\\x00\\x00\\x00\\x00'\n16\n12\nimport structvar = struct.pack('bi', 56, 0x12131415)print(var)print(struct.calcsize('bi'))var = struct.pack('ib', 0x12131415, 56)print(var)print(struct.calcsize('ib'))Output:b'8\\x00\\x00\\x00\\x15\\x14\\x13\\x12'\n8\nb'\\x15\\x14\\x13\\x128'\n5\nNote: The ordering of format characters may have an impact on size." }, { "code": null, "e": 4485, "s": 4443, "text": "Syntax:\nstruct.calcsize(fmt)\nfmt: format " }, { "code": null, "e": 4739, "s": 4485, "text": "Return the size of the struct (and hence of the string) corresponding to the given format. calcsize() is important function, and is required for function such as struct.pack_into() and struct.unpack_from(), which require offset value and buffer as well." }, { "code": "import structvar = struct.pack('?hil', True, 2, 5, 445)print(var)# Returns the size of the structureprint(struct.calcsize('?hil'))print(struct.calcsize('qf'))", "e": 4898, "s": 4739, "text": null }, { "code": null, "e": 4906, "s": 4898, "text": "Output:" }, { "code": null, "e": 4981, "s": 4906, "text": "b'\\x01\\x00\\x02\\x00\\x05\\x00\\x00\\x00\\xbd\\x01\\x00\\x00\\x00\\x00\\x00\\x00'\n16\n12\n" }, { "code": "import structvar = struct.pack('bi', 56, 0x12131415)print(var)print(struct.calcsize('bi'))var = struct.pack('ib', 0x12131415, 56)print(var)print(struct.calcsize('ib'))", "e": 5149, "s": 4981, "text": null }, { "code": null, "e": 5157, "s": 5149, "text": "Output:" }, { "code": null, "e": 5216, "s": 5157, "text": "b'8\\x00\\x00\\x00\\x15\\x14\\x13\\x12'\n8\nb'\\x15\\x14\\x13\\x128'\n5\n" }, { "code": null, "e": 5284, "s": 5216, "text": "Note: The ordering of format characters may have an impact on size." }, { "code": null, "e": 5622, "s": 5284, "text": "Exception struct.errorException struct.error describes what is wrong at passing arguments, when a wrong argument is passed struct.error is raised.from struct import errorprint(error)Note: This is piece of code is not useful, anywhere other than exception handling, and is used to show that ‘error’ upon interpreted shows about the class." }, { "code": "from struct import errorprint(error)", "e": 5659, "s": 5622, "text": null }, { "code": null, "e": 5815, "s": 5659, "text": "Note: This is piece of code is not useful, anywhere other than exception handling, and is used to show that ‘error’ upon interpreted shows about the class." }, { "code": null, "e": 5990, "s": 5815, "text": "struct.pack_into()Syntax:\nstruct.pack_into(fmt, buffer, offset, v1, v2, ...)\nfmt: data type format\nbuffer: writable buffer which starts at offset (optional)\nv1,v2.. : values " }, { "code": null, "e": 6147, "s": 5990, "text": "Syntax:\nstruct.pack_into(fmt, buffer, offset, v1, v2, ...)\nfmt: data type format\nbuffer: writable buffer which starts at offset (optional)\nv1,v2.. : values " }, { "code": null, "e": 7038, "s": 6147, "text": "struct.unpack_from()Syntax:\nstruct.unpack_from(fmt, buffer[,offset = 0])fmt: data type format\nbuffer: writable buffer which starts at offset (optional)Returns a tuple, similar to struct.unpack()import struct # ctypes in imported to create string bufferimport ctypes # SIZE of the format is calculated using calcsize()siz = struct.calcsize('hhl')print(siz) # Buffer 'buff' is createdbuff = ctypes.create_string_buffer(siz) # struct.pack() returns packed data# struct.unpack() returns unpacked datax = struct.pack('hhl', 2, 2, 3)print(x)print(struct.unpack('hhl', x)) # struct.pack_into() packs data into buff, doesn't return any value# struct.unpack_from() unpacks data from buff, returns a tuple of valuesstruct.pack_into('hhl', buff, 0, 2, 2, 3)print(struct.unpack_from('hhl', buff, 0))Output:16\nb'\\x02\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n(2, 2, 3)\n(2, 2, 3)\n" }, { "code": null, "e": 7170, "s": 7038, "text": "Syntax:\nstruct.unpack_from(fmt, buffer[,offset = 0])fmt: data type format\nbuffer: writable buffer which starts at offset (optional)" }, { "code": null, "e": 7214, "s": 7170, "text": "Returns a tuple, similar to struct.unpack()" }, { "code": "import struct # ctypes in imported to create string bufferimport ctypes # SIZE of the format is calculated using calcsize()siz = struct.calcsize('hhl')print(siz) # Buffer 'buff' is createdbuff = ctypes.create_string_buffer(siz) # struct.pack() returns packed data# struct.unpack() returns unpacked datax = struct.pack('hhl', 2, 2, 3)print(x)print(struct.unpack('hhl', x)) # struct.pack_into() packs data into buff, doesn't return any value# struct.unpack_from() unpacks data from buff, returns a tuple of valuesstruct.pack_into('hhl', buff, 0, 2, 2, 3)print(struct.unpack_from('hhl', buff, 0))", "e": 7813, "s": 7214, "text": null }, { "code": null, "e": 7821, "s": 7813, "text": "Output:" }, { "code": null, "e": 7913, "s": 7821, "text": "16\nb'\\x02\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n(2, 2, 3)\n(2, 2, 3)\n" }, { "code": null, "e": 8270, "s": 7913, "text": "Reference https://docs.python.org/2/library/struct.htmlThis article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8395, "s": 8270, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8402, "s": 8395, "text": "Python" }, { "code": null, "e": 8500, "s": 8402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8518, "s": 8500, "text": "Python Dictionary" }, { "code": null, "e": 8560, "s": 8518, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8582, "s": 8560, "text": "Enumerate() in Python" }, { "code": null, "e": 8608, "s": 8582, "text": "Python String | replace()" }, { "code": null, "e": 8640, "s": 8608, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8669, "s": 8640, "text": "*args and **kwargs in Python" }, { "code": null, "e": 8696, "s": 8669, "text": "Python Classes and Objects" }, { "code": null, "e": 8719, "s": 8696, "text": "Introduction To PYTHON" }, { "code": null, "e": 8740, "s": 8719, "text": "Python OOPs Concepts" } ]
Python | Tabbed panel in kivy
18 Oct, 2021 Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications Kivy Tutorial – Learn Kivy with Examples. The TabbedPanel widget manages different widgets in tabs, with a header area for the actual tab buttons and a content area for showing the current tab content. The TabbedPanel provides one default tab. To use it must import :from kivy.uix.tabbedpanel import TabbedPanel Basic Approach: 1) import kivy 2) import kivy App 3) import floatlayout 4) import tabbedpanel 5) set minimum version(optional) 6) Create Tabbed panel class 7) create the App class 8) create .kv file: # create multiple tabs in it. # Do there functioning also. 9) return the widget/layout etc class 10) Run an instance of the class Implementation Of Approach: .py file # Program to explain how to create tabbed panel App in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to use this must have to import itfrom kivy.uix.tabbedpanel import TabbedPanel # Floatlayout allows us to place the elements# relatively based on the current window# size and height especially in mobilesfrom kivy.uix.floatlayout import FloatLayout # Create Tabbed class class Tab(TabbedPanel): pass # create App classclass TabbedPanelApp(App): def build(self): return Tab() # run the Appif __name__ == '__main__': TabbedPanelApp().run() .kv file # .kv file of tabbed panel <Tab>: # creating the size # and the alignment of the tab size_hint: .5, .5 pos_hint: {'center_x': .5, 'center_y': .5} do_default_tab: False # Create tab 1 TabbedPanelItem: text: 'Tab 1' Label: text: "First tab" # Create 2nd tab TabbedPanelItem: text: 'Tab 2' BoxLayout: Label: text: 'Press button' Button: text: 'Click it' # Create 3rd tab TabbedPanelItem: text: 'Tab 3' RstDocument: text: '\n'.join(("How are you GFG's???")) Output: Tab 1: Tab 2: Tab 3: saurabh1990aror Python-gui Python-kivy 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 Oct, 2021" }, { "code": null, "e": 263, "s": 28, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications" }, { "code": null, "e": 306, "s": 263, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 466, "s": 306, "text": "The TabbedPanel widget manages different widgets in tabs, with a header area for the actual tab buttons and a content area for showing the current tab content." }, { "code": null, "e": 508, "s": 466, "text": "The TabbedPanel provides one default tab." }, { "code": null, "e": 576, "s": 508, "text": "To use it must import :from kivy.uix.tabbedpanel import TabbedPanel" }, { "code": null, "e": 921, "s": 576, "text": "Basic Approach:\n1) import kivy\n2) import kivy App\n3) import floatlayout\n4) import tabbedpanel\n5) set minimum version(optional)\n6) Create Tabbed panel class\n7) create the App class\n8) create .kv file:\n # create multiple tabs in it.\n # Do there functioning also.\n9) return the widget/layout etc class\n10) Run an instance of the class\n" }, { "code": null, "e": 949, "s": 921, "text": "Implementation Of Approach:" }, { "code": null, "e": 958, "s": 949, "text": ".py file" }, { "code": "# Program to explain how to create tabbed panel App in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # to use this must have to import itfrom kivy.uix.tabbedpanel import TabbedPanel # Floatlayout allows us to place the elements# relatively based on the current window# size and height especially in mobilesfrom kivy.uix.floatlayout import FloatLayout # Create Tabbed class class Tab(TabbedPanel): pass # create App classclass TabbedPanelApp(App): def build(self): return Tab() # run the Appif __name__ == '__main__': TabbedPanelApp().run()", "e": 1816, "s": 958, "text": null }, { "code": null, "e": 1825, "s": 1816, "text": ".kv file" }, { "code": "# .kv file of tabbed panel <Tab>: # creating the size # and the alignment of the tab size_hint: .5, .5 pos_hint: {'center_x': .5, 'center_y': .5} do_default_tab: False # Create tab 1 TabbedPanelItem: text: 'Tab 1' Label: text: \"First tab\" # Create 2nd tab TabbedPanelItem: text: 'Tab 2' BoxLayout: Label: text: 'Press button' Button: text: 'Click it' # Create 3rd tab TabbedPanelItem: text: 'Tab 3' RstDocument: text: '\\n'.join((\"How are you GFG's???\"))", "e": 2438, "s": 1825, "text": null }, { "code": null, "e": 2446, "s": 2438, "text": "Output:" }, { "code": null, "e": 2453, "s": 2446, "text": "Tab 1:" }, { "code": null, "e": 2460, "s": 2453, "text": "Tab 2:" }, { "code": null, "e": 2467, "s": 2460, "text": "Tab 3:" }, { "code": null, "e": 2483, "s": 2467, "text": "saurabh1990aror" }, { "code": null, "e": 2494, "s": 2483, "text": "Python-gui" }, { "code": null, "e": 2506, "s": 2494, "text": "Python-kivy" }, { "code": null, "e": 2513, "s": 2506, "text": "Python" } ]
Time Complexity where loop variable is incremented by 1, 2, 3, 4 ..
30 Oct, 2015 What is the time complexity of below code? void fun(int n){ int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; }} The loop variable ‘i’ is incremented by 1, 2, 3, 4, ... until i becomes greater than or equal to n. The value of i is x(x+1)/2 after x iterations. So if loop runs x times, then x(x+1)/2 < n. Therefore time complexity can be written as Θ(√n). This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Analysis Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Analysis of Algorithms | Set 4 (Analysis of Loops) Analysis of different sorting techniques Time complexities of different data structures Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Time Complexity and Space Complexity SQL Interview Questions
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Oct, 2015" }, { "code": null, "e": 95, "s": 52, "text": "What is the time complexity of below code?" }, { "code": "void fun(int n){ int j = 1, i = 0; while (i < n) { // Some O(1) task i = i + j; j++; }}", "e": 209, "s": 95, "text": null }, { "code": null, "e": 309, "s": 209, "text": "The loop variable ‘i’ is incremented by 1, 2, 3, 4, ... until i becomes greater than or equal to n." }, { "code": null, "e": 451, "s": 309, "text": "The value of i is x(x+1)/2 after x iterations. So if loop runs x times, then x(x+1)/2 < n. Therefore time complexity can be written as Θ(√n)." }, { "code": null, "e": 620, "s": 451, "text": "This article is contributed by Piyush Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 629, "s": 620, "text": "Analysis" }, { "code": null, "e": 638, "s": 629, "text": "Articles" }, { "code": null, "e": 736, "s": 638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 787, "s": 736, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 824, "s": 787, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 875, "s": 824, "text": "Analysis of Algorithms | Set 4 (Analysis of Loops)" }, { "code": null, "e": 916, "s": 875, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 963, "s": 916, "text": "Time complexities of different data structures" }, { "code": null, "e": 1013, "s": 963, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 1060, "s": 1013, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 1096, "s": 1060, "text": "find command in Linux with examples" }, { "code": null, "e": 1133, "s": 1096, "text": "Time Complexity and Space Complexity" } ]
How to draw an arc on a tkinter canvas?
The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas. To draw an arc on a tkinter Canvas, we will use the create_arc() method of the Canvas and supply it with a set of coordinates to draw the arc. We can use create_arc() to create an arc item, which can be a chord, a pieslice, or a simple arc. Import the required libraries and create an instance of tkinter frame. Import the required libraries and create an instance of tkinter frame. Set the size of the frame using root.geometry method. Set the size of the frame using root.geometry method. Create a Canvas widget and set its height and width. Also, set its background color with bg="blue". Create a Canvas widget and set its height and width. Also, set its background color with bg="blue". Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150. Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150. Finally, run the mainloop of the application window. Finally, run the mainloop of the application window. # Import the required libraries from tkinter import * # Create an instance of Tkinter Frame root = Tk() # Set the geometry root.geometry("700x350") # Create a Canvas with a background color C = Canvas(root, bg="blue", height=250, width=600) # Coordinates for the arc coord = 100, 50, 500, 300 # Create the arc with extent=150 arc = C.create_arc(coord, start=0, extent=150, fill="red") C.pack(side=TOP, padx=50, pady=50) root.mainloop() On execution, it will produce the following output −
[ { "code": null, "e": 1337, "s": 1187, "text": "The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas." }, { "code": null, "e": 1578, "s": 1337, "text": "To draw an arc on a tkinter Canvas, we will use the create_arc() method of the Canvas and supply it with a set of coordinates to draw the arc. We can use create_arc() to create an arc item, which can be a chord, a pieslice, or a simple arc." }, { "code": null, "e": 1649, "s": 1578, "text": "Import the required libraries and create an instance of tkinter frame." }, { "code": null, "e": 1720, "s": 1649, "text": "Import the required libraries and create an instance of tkinter frame." }, { "code": null, "e": 1774, "s": 1720, "text": "Set the size of the frame using root.geometry method." }, { "code": null, "e": 1828, "s": 1774, "text": "Set the size of the frame using root.geometry method." }, { "code": null, "e": 1928, "s": 1828, "text": "Create a Canvas widget and set its height and width. Also, set its background color with bg=\"blue\"." }, { "code": null, "e": 2028, "s": 1928, "text": "Create a Canvas widget and set its height and width. Also, set its background color with bg=\"blue\"." }, { "code": null, "e": 2179, "s": 2028, "text": "Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150." }, { "code": null, "e": 2330, "s": 2179, "text": "Next, use the create_arc method to draw an arc. Supply the coordinates of the arc and also define the extent of the arc. Here, we have set extent=150." }, { "code": null, "e": 2383, "s": 2330, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 2436, "s": 2383, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 2879, "s": 2436, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of Tkinter Frame\nroot = Tk()\n\n# Set the geometry\nroot.geometry(\"700x350\")\n\n# Create a Canvas with a background color\nC = Canvas(root, bg=\"blue\", height=250, width=600)\n\n# Coordinates for the arc\ncoord = 100, 50, 500, 300\n\n# Create the arc with extent=150\narc = C.create_arc(coord, start=0, extent=150, fill=\"red\")\n\nC.pack(side=TOP, padx=50, pady=50)\n\nroot.mainloop()" }, { "code": null, "e": 2932, "s": 2879, "text": "On execution, it will produce the following output −" } ]
Parsing and converting HTML documents to XML format using Python
23 Aug, 2021 In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module. Using Beautifulsoup module. In this approach, we will use Python’s lxml library to parse the HTML document and write it to an encoded string representation of the XML tree.The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that as it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API. Installation: pip install lxml We need to provide the path to open the HTML document to read and parse it using the html.fromstring(str) function, returning a single element/document tree. This function parses a document from the given string. This always creates a correct HTML document, which means the parent node is <html>, and there is a body and possibly a head. htmldoc = html.fromstring(inp.read()) And write the parsed HTML element/document tree to an encoded string representation of its XML tree using the etree.tostring() function. out.write(etree.tostring(htmldoc)) Html file used: input. Code: Python3 # Import the required libraryfrom lxml import html, etree # Main Functionif __name__ == '__main__': # Provide the path of the html file file = "input.html" # Open the html file and Parse it, # returning a single element/document. with open(file, 'r', encoding='utf-8') as inp: htmldoc = html.fromstring(inp.read()) # Open a output.xml file and write the # element/document to an encoded string # representation of its XML tree. with open("output.xml", 'wb') as out: out.write(etree.tostring(htmldoc)) Output: In this approach, we will use the BeautifulSoup module to parse the raw HTML document using html.parser and modify the parsed document and write it to an XML file. Provide the path to open the HTML file and read the HTML file and Parse it using BeautifulSoup’s html.parser, returning an object of the parsed document. BeautifulSoup(inp, ‘html.parser’) To remove the DocType HTML, we need to first get the string representation of the document using soup.prettify() and then split the document by lines using splitlines(), returning a list of lines. soup.prettify().splitlines() Code: Python3 # Import the required libraryfrom bs4 import BeautifulSoup # Main Functionif __name__ == '__main__': # Provide the path of the html file file = "input.html" # Open the html file and Parse it # using Beautiful soup's html.parser. with open(file, 'r', encoding='utf-8') as inp: soup = BeautifulSoup(inp, 'html.parser') # Split the document by lines and join the lines # from index 1 to remove the doctype Html as it is # present in index 0 from the parsed document. lines = soup.prettify().splitlines() content = "\n".join(lines[1:]) # Open a output.xml file and write the modified content. with open("output.xml", 'w', encoding='utf-8') as out: out.write(content) Output: Picked Python-XML 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 | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 133, "s": 28, "text": "In this article, we are going to see how to parse and convert HTML documents to XML format using Python." }, { "code": null, "e": 163, "s": 133, "text": "It can be done in these ways:" }, { "code": null, "e": 182, "s": 163, "text": "Using Ixml module." }, { "code": null, "e": 210, "s": 182, "text": "Using Beautifulsoup module." }, { "code": null, "e": 642, "s": 210, "text": "In this approach, we will use Python’s lxml library to parse the HTML document and write it to an encoded string representation of the XML tree.The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that as it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API." }, { "code": null, "e": 656, "s": 642, "text": "Installation:" }, { "code": null, "e": 673, "s": 656, "text": "pip install lxml" }, { "code": null, "e": 1011, "s": 673, "text": "We need to provide the path to open the HTML document to read and parse it using the html.fromstring(str) function, returning a single element/document tree. This function parses a document from the given string. This always creates a correct HTML document, which means the parent node is <html>, and there is a body and possibly a head." }, { "code": null, "e": 1049, "s": 1011, "text": "htmldoc = html.fromstring(inp.read())" }, { "code": null, "e": 1186, "s": 1049, "text": "And write the parsed HTML element/document tree to an encoded string representation of its XML tree using the etree.tostring() function." }, { "code": null, "e": 1221, "s": 1186, "text": "out.write(etree.tostring(htmldoc))" }, { "code": null, "e": 1244, "s": 1221, "text": "Html file used: input." }, { "code": null, "e": 1250, "s": 1244, "text": "Code:" }, { "code": null, "e": 1258, "s": 1250, "text": "Python3" }, { "code": "# Import the required libraryfrom lxml import html, etree # Main Functionif __name__ == '__main__': # Provide the path of the html file file = \"input.html\" # Open the html file and Parse it, # returning a single element/document. with open(file, 'r', encoding='utf-8') as inp: htmldoc = html.fromstring(inp.read()) # Open a output.xml file and write the # element/document to an encoded string # representation of its XML tree. with open(\"output.xml\", 'wb') as out: out.write(etree.tostring(htmldoc))", "e": 1810, "s": 1258, "text": null }, { "code": null, "e": 1818, "s": 1810, "text": "Output:" }, { "code": null, "e": 2136, "s": 1818, "text": "In this approach, we will use the BeautifulSoup module to parse the raw HTML document using html.parser and modify the parsed document and write it to an XML file. Provide the path to open the HTML file and read the HTML file and Parse it using BeautifulSoup’s html.parser, returning an object of the parsed document." }, { "code": null, "e": 2170, "s": 2136, "text": "BeautifulSoup(inp, ‘html.parser’)" }, { "code": null, "e": 2367, "s": 2170, "text": "To remove the DocType HTML, we need to first get the string representation of the document using soup.prettify() and then split the document by lines using splitlines(), returning a list of lines." }, { "code": null, "e": 2396, "s": 2367, "text": "soup.prettify().splitlines()" }, { "code": null, "e": 2402, "s": 2396, "text": "Code:" }, { "code": null, "e": 2410, "s": 2402, "text": "Python3" }, { "code": "# Import the required libraryfrom bs4 import BeautifulSoup # Main Functionif __name__ == '__main__': # Provide the path of the html file file = \"input.html\" # Open the html file and Parse it # using Beautiful soup's html.parser. with open(file, 'r', encoding='utf-8') as inp: soup = BeautifulSoup(inp, 'html.parser') # Split the document by lines and join the lines # from index 1 to remove the doctype Html as it is # present in index 0 from the parsed document. lines = soup.prettify().splitlines() content = \"\\n\".join(lines[1:]) # Open a output.xml file and write the modified content. with open(\"output.xml\", 'w', encoding='utf-8') as out: out.write(content)", "e": 3138, "s": 2410, "text": null }, { "code": null, "e": 3146, "s": 3138, "text": "Output:" }, { "code": null, "e": 3153, "s": 3146, "text": "Picked" }, { "code": null, "e": 3164, "s": 3153, "text": "Python-XML" }, { "code": null, "e": 3171, "s": 3164, "text": "Python" }, { "code": null, "e": 3269, "s": 3171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3301, "s": 3269, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3328, "s": 3301, "text": "Python Classes and Objects" }, { "code": null, "e": 3359, "s": 3328, "text": "Python | os.path.join() method" }, { "code": null, "e": 3382, "s": 3359, "text": "Introduction To PYTHON" }, { "code": null, "e": 3403, "s": 3382, "text": "Python OOPs Concepts" }, { "code": null, "e": 3459, "s": 3403, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3501, "s": 3459, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3543, "s": 3501, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3582, "s": 3543, "text": "Python | Get unique values from a list" } ]
Find the Nth term of the series 1, 2, 6, 21, 88, 445. . .
14 Jan, 2022 Given a positive integer N. The task is to find Nth term of the series: 1, 2, 6, 21, 88, 445, . . . Examples: Input: N = 3Output: 6 Input: N = 6Output: 445 Approach: The given sequence follows the following pattern- 1, (1 * 1 + 1 = 2), (2 * 2 + 2 = 6), (6 * 3 + 3 = 21), (21 * 4 + 4 = 88), (88 * 5 + 5 = 445), ... Below steps can be used to solve the problem- For each iterative i, multiplying its previous element with i (Initially the element will be 1) And add multiplied elements with i. Finally, return the Nth term of the series. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...#include <bits/stdc++.h>using namespace std; // Function to return Nth term// of the seriesint nthTerm(int N){ // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term;} // Driver Codeint main(){ // Get the value of N int N = 6; cout << nthTerm(N); return 0;} // Java program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...class GFG{ // Function to return Nth term // of the series static int nthTerm(int N) { // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code public static void main(String args[]) { // Get the value of N int N = 6; System.out.println(nthTerm(N)); } } // This code is contributed by saurabh_jaiswal. # Python code for the above approach # Function to return Nth term# of the seriesdef nthTerm(N): # Initializing a variable term = 1; # Loop to iterate from 1 to N-1 for i in range(1, N): # Multiplying and adding previous # element with i term = term * i + i; # returning the Nth term return term; # Driver Code # Get the value of NN = 6;print(nthTerm(N)); # This code is contributed by Saurabh Jaiswal // C# program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...using System;class GFG{ // Function to return Nth term // of the series static int nthTerm(int N) { // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code public static void Main() { // Get the value of N int N = 6; Console.Write(nthTerm(N)); } } // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to return Nth term // of the series function nthTerm(N) { // Initializing a variable let term = 1; // Loop to iterate from 1 to N-1 for (let i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code // Get the value of N let N = 6; document.write(nthTerm(N)); // This code is contributed by Potta Lokesh </script> 445 Time Complexity: O(N) Auxiliary Space: O(1) lokeshpotta20 _saurabh_jaiswal samim2000 series Mathematical Pattern Searching Mathematical series Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Check if an URL is valid or not using Regular Expression Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2022" }, { "code": null, "e": 100, "s": 28, "text": "Given a positive integer N. The task is to find Nth term of the series:" }, { "code": null, "e": 128, "s": 100, "text": "1, 2, 6, 21, 88, 445, . . ." }, { "code": null, "e": 138, "s": 128, "text": "Examples:" }, { "code": null, "e": 160, "s": 138, "text": "Input: N = 3Output: 6" }, { "code": null, "e": 184, "s": 160, "text": "Input: N = 6Output: 445" }, { "code": null, "e": 195, "s": 184, "text": "Approach: " }, { "code": null, "e": 245, "s": 195, "text": "The given sequence follows the following pattern-" }, { "code": null, "e": 344, "s": 245, "text": "1, (1 * 1 + 1 = 2), (2 * 2 + 2 = 6), (6 * 3 + 3 = 21), (21 * 4 + 4 = 88), (88 * 5 + 5 = 445), ... " }, { "code": null, "e": 390, "s": 344, "text": "Below steps can be used to solve the problem-" }, { "code": null, "e": 486, "s": 390, "text": "For each iterative i, multiplying its previous element with i (Initially the element will be 1)" }, { "code": null, "e": 522, "s": 486, "text": "And add multiplied elements with i." }, { "code": null, "e": 566, "s": 522, "text": "Finally, return the Nth term of the series." }, { "code": null, "e": 616, "s": 566, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 620, "s": 616, "text": "C++" }, { "code": null, "e": 625, "s": 620, "text": "Java" }, { "code": null, "e": 633, "s": 625, "text": "Python3" }, { "code": null, "e": 636, "s": 633, "text": "C#" }, { "code": null, "e": 647, "s": 636, "text": "Javascript" }, { "code": "// C++ program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...#include <bits/stdc++.h>using namespace std; // Function to return Nth term// of the seriesint nthTerm(int N){ // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term;} // Driver Codeint main(){ // Get the value of N int N = 6; cout << nthTerm(N); return 0;}", "e": 1202, "s": 647, "text": null }, { "code": "// Java program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...class GFG{ // Function to return Nth term // of the series static int nthTerm(int N) { // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code public static void main(String args[]) { // Get the value of N int N = 6; System.out.println(nthTerm(N)); } } // This code is contributed by saurabh_jaiswal.", "e": 1927, "s": 1202, "text": null }, { "code": "# Python code for the above approach # Function to return Nth term# of the seriesdef nthTerm(N): # Initializing a variable term = 1; # Loop to iterate from 1 to N-1 for i in range(1, N): # Multiplying and adding previous # element with i term = term * i + i; # returning the Nth term return term; # Driver Code # Get the value of NN = 6;print(nthTerm(N)); # This code is contributed by Saurabh Jaiswal", "e": 2378, "s": 1927, "text": null }, { "code": "// C# program to find N-th term// of the series-// 1, 2, 6, 21, 88, 445...using System;class GFG{ // Function to return Nth term // of the series static int nthTerm(int N) { // Initializing a variable int term = 1; // Loop to iterate from 1 to N-1 for (int i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code public static void Main() { // Get the value of N int N = 6; Console.Write(nthTerm(N)); } } // This code is contributed by Samim Hossain Mondal.", "e": 2997, "s": 2378, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to return Nth term // of the series function nthTerm(N) { // Initializing a variable let term = 1; // Loop to iterate from 1 to N-1 for (let i = 1; i < N; i++) { // Multiplying and adding previous // element with i term = term * i + i; } // returning the Nth term return term; } // Driver Code // Get the value of N let N = 6; document.write(nthTerm(N)); // This code is contributed by Potta Lokesh </script>", "e": 3704, "s": 2997, "text": null }, { "code": null, "e": 3708, "s": 3704, "text": "445" }, { "code": null, "e": 3730, "s": 3708, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3752, "s": 3730, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3766, "s": 3752, "text": "lokeshpotta20" }, { "code": null, "e": 3783, "s": 3766, "text": "_saurabh_jaiswal" }, { "code": null, "e": 3793, "s": 3783, "text": "samim2000" }, { "code": null, "e": 3800, "s": 3793, "text": "series" }, { "code": null, "e": 3813, "s": 3800, "text": "Mathematical" }, { "code": null, "e": 3831, "s": 3813, "text": "Pattern Searching" }, { "code": null, "e": 3844, "s": 3831, "text": "Mathematical" }, { "code": null, "e": 3851, "s": 3844, "text": "series" }, { "code": null, "e": 3869, "s": 3851, "text": "Pattern Searching" }, { "code": null, "e": 3967, "s": 3869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3999, "s": 3967, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4045, "s": 3999, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 4089, "s": 4045, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 4138, "s": 4089, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 4180, "s": 4138, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 4216, "s": 4180, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 4259, "s": 4216, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 4301, "s": 4259, "text": "Check if a string is substring of another" }, { "code": null, "e": 4358, "s": 4301, "text": "Check if an URL is valid or not using Regular Expression" } ]
How can we run MySQL statements in batch mode?
We need to create a .sql file for running MySQL in batch mode. This file will contain the MySQL statements. Suppose I have hh.sql file in which I have written the statement select * from hh. With the help of the following command, we can run this file in batch mode − C:\Program Files\MySQL\bin>mysql -u root -p gaurav < hh.sql Enter password: ***** id 1 2 Here Gaurav is the database name that contains the table hh. Whenever you’ll run this command it will ask for the password and then give the output.
[ { "code": null, "e": 1455, "s": 1187, "text": "We need to create a .sql file for running MySQL in batch mode. This file will contain the MySQL statements. Suppose I have hh.sql file in which I have written the statement select * from hh. With the help of the following command, we can run this file in batch mode −" }, { "code": null, "e": 1537, "s": 1455, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p gaurav < hh.sql\nEnter password: *****" }, { "code": null, "e": 1544, "s": 1537, "text": "id\n1\n2" }, { "code": null, "e": 1693, "s": 1544, "text": "Here Gaurav is the database name that contains the table hh. Whenever you’ll run this command it will ask for the password and then give the output." } ]
Segregating negative and positive maintaining order and O(1) space
06 Jul, 2022 Segregation of negative and positive numbers in an array without using extra space, and maintaining insertion order and in O(n^2) time complexity.Examples: Input :9 12 11 -13 -5 6 -7 5 -3 -6 Output :-13 -5 -7 -3 -6 12 11 6 5 Input :5 11 -13 6 -7 5 Output :-13 -7 11 6 5 We have discussed this problem below posts. ers-beginning-positive-end-constant-extra-space/”>Rearrange positive and negative numbers without maintaining order.Rearrange positive and negative numbers with constant extra space ers-beginning-positive-end-constant-extra-space/”>Rearrange positive and negative numbers without maintaining order. Rearrange positive and negative numbers with constant extra space This post discusses a new approach that takes O(1) extra space. We first count total negative numbers, then move negative numbers one by one to the correct position. C++ Java C# Python 3 PHP Javascript // C++ program to move all negative numbers// to beginning and positive numbers to end// keeping order.#include <iostream>using namespace std; void segregate(int arr[], int n){ // Count negative numbers int count_negative = 0; for (int i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all negative // numbers are moved to the beginning int i = 0, j = i + 1; while (i != count_negative) { // If number is negative, update // position of next positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move it to // index j and increment j. else if (arr[i] > 0 && j < n) { swap(arr[i], arr[j]); j++; } }} int main(){ int count_negative = 0; int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = sizeof(arr) / sizeof(arr[0]); segregate(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Java program to move all// negative numbers to beginning// and positive numbers to end// keeping order.class GFG{static void segregate(int arr[], int n){ // Count negative numbersint count_negative = 0;for (int i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all// negative numbers are// moved to the beginningint i = 0, j = i + 1;while (i != count_negative){ // If number is negative, // update position of next // positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move // it to index j and increment j. else if (arr[i] > 0 && j < n) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; }}} // Driver codepublic static void main(String[] args){ int count_negative = 0; int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.length; segregate(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");}} // This code is contributed// by ChitraNayal // C# program to move all// negative numbers to beginning// and positive numbers to end// keeping order.using System; class GFG{static void segregate(int[] arr, int n){ // Count negative numbersint count_negative = 0,i;for (i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all// negative numbers are// moved to the beginningi = 0;int j = i + 1;while (i != count_negative){ // If number is negative, // update position of next // positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move // it to index j and increment j. else if (arr[i] > 0 && j < n) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; }}} // Driver codepublic static void Main(){ int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.Length; segregate(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");}} // This code is contributed// by ChitraNayal # Python 3 program to move all# negative numbers to beginning# and positive numbers to end# keeping order. def segregate(arr, n): # Count negative numbers count_negative = 0 for i in range(n): if (arr[i] < 0): count_negative += 1 # Run a loop until all # negative numbers are # moved to the beginning i = 0 j = i + 1 while (i != count_negative): # If number is negative, # update position of next # positive number. if (arr[i] < 0) : i += 1 j = i + 1 # If number is positive, move # it to index j and increment j. elif (arr[i] > 0 and j < n): t = arr[i] arr[i] = arr[j] arr[j] = t j += 1 # Driver Codecount_negative = 0arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6 ]segregate(arr, 9)for i in range(9): print(arr[i] , end =" ") # This code is contributed# by ChitraNayal <?php// PHP program to move all// negative numbers to// beginning and positive// numbers to end keeping order. function segregate(&$arr, $n){ // Count negative numbers $count_negative = 0; for ($i = 0; $i < $n; $i++) if ($arr[$i] < 0) $count_negative++; // Run a loop until all // negative numbers are // moved to the beginning $i = 0; $j = $i + 1; while ($i != $count_negative) { // If number is negative, // update position of next // positive number. if ($arr[$i] < 0) { $i++; $j = $i + 1; } // If number is positive, move // it to index j and increment j. else if ($arr[$i] > 0 && $j < $n) { $t = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $t; $j++; } }} // Driver Code$count_negative = 0;$arr = array(-12, 11, -13, -5, 6, -7, 5, -3, -6);$n = sizeof($arr);segregate($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] ." "; // This code is contributed// by ChitraNayal?> <script>// JavaScript program to move all negative numbers// to beginning and positive numbers to end// keeping order.function segregate(arr, n){ // Count negative numbers let count_negative = 0; for (let i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all negative // numbers are moved to the beginning let i = 0, j = i + 1; while (i != count_negative) { // If number is negative, update // position of next positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move it to // index j and increment j. else if (arr[i] > 0 && j < n) { let t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; } }} let count_negative = 0; let arr = [ -12, 11, -13, -5, 6, -7, 5, -3, -6 ]; let n = arr.length; segregate(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi.</script> Output: -12 -13 -5 -7 -3 -6 11 6 5 Time Complexity: O(n2) Auxiliary Space: O(1) ukasp surbhityagi15 surindertarika1234 akheniad array-rearrange Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Next Greater Element What is Data Structure: Types, Classifications and Applications Move all negative numbers to beginning and positive to end with constant extra space Count pairs with given sum Find subarray with given sum | Set 1 (Nonnegative Numbers)
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 211, "s": 54, "text": "Segregation of negative and positive numbers in an array without using extra space, and maintaining insertion order and in O(n^2) time complexity.Examples: " }, { "code": null, "e": 341, "s": 211, "text": "Input :9\n 12 11 -13 -5 6 -7 5 -3 -6\nOutput :-13 -5 -7 -3 -6 12 11 6 5 \n\nInput :5\n 11 -13 6 -7 5\nOutput :-13 -7 11 6 5" }, { "code": null, "e": 387, "s": 343, "text": "We have discussed this problem below posts." }, { "code": null, "e": 569, "s": 387, "text": "ers-beginning-positive-end-constant-extra-space/”>Rearrange positive and negative numbers without maintaining order.Rearrange positive and negative numbers with constant extra space" }, { "code": null, "e": 686, "s": 569, "text": "ers-beginning-positive-end-constant-extra-space/”>Rearrange positive and negative numbers without maintaining order." }, { "code": null, "e": 752, "s": 686, "text": "Rearrange positive and negative numbers with constant extra space" }, { "code": null, "e": 918, "s": 752, "text": "This post discusses a new approach that takes O(1) extra space. We first count total negative numbers, then move negative numbers one by one to the correct position." }, { "code": null, "e": 922, "s": 918, "text": "C++" }, { "code": null, "e": 927, "s": 922, "text": "Java" }, { "code": null, "e": 930, "s": 927, "text": "C#" }, { "code": null, "e": 939, "s": 930, "text": "Python 3" }, { "code": null, "e": 943, "s": 939, "text": "PHP" }, { "code": null, "e": 954, "s": 943, "text": "Javascript" }, { "code": "// C++ program to move all negative numbers// to beginning and positive numbers to end// keeping order.#include <iostream>using namespace std; void segregate(int arr[], int n){ // Count negative numbers int count_negative = 0; for (int i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all negative // numbers are moved to the beginning int i = 0, j = i + 1; while (i != count_negative) { // If number is negative, update // position of next positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move it to // index j and increment j. else if (arr[i] > 0 && j < n) { swap(arr[i], arr[j]); j++; } }} int main(){ int count_negative = 0; int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = sizeof(arr) / sizeof(arr[0]); segregate(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \";}", "e": 1968, "s": 954, "text": null }, { "code": "// Java program to move all// negative numbers to beginning// and positive numbers to end// keeping order.class GFG{static void segregate(int arr[], int n){ // Count negative numbersint count_negative = 0;for (int i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all// negative numbers are// moved to the beginningint i = 0, j = i + 1;while (i != count_negative){ // If number is negative, // update position of next // positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move // it to index j and increment j. else if (arr[i] > 0 && j < n) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; }}} // Driver codepublic static void main(String[] args){ int count_negative = 0; int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.length; segregate(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");}} // This code is contributed// by ChitraNayal", "e": 3044, "s": 1968, "text": null }, { "code": "// C# program to move all// negative numbers to beginning// and positive numbers to end// keeping order.using System; class GFG{static void segregate(int[] arr, int n){ // Count negative numbersint count_negative = 0,i;for (i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all// negative numbers are// moved to the beginningi = 0;int j = i + 1;while (i != count_negative){ // If number is negative, // update position of next // positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move // it to index j and increment j. else if (arr[i] > 0 && j < n) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; }}} // Driver codepublic static void Main(){ int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = arr.Length; segregate(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");}} // This code is contributed// by ChitraNayal", "e": 4087, "s": 3044, "text": null }, { "code": "# Python 3 program to move all# negative numbers to beginning# and positive numbers to end# keeping order. def segregate(arr, n): # Count negative numbers count_negative = 0 for i in range(n): if (arr[i] < 0): count_negative += 1 # Run a loop until all # negative numbers are # moved to the beginning i = 0 j = i + 1 while (i != count_negative): # If number is negative, # update position of next # positive number. if (arr[i] < 0) : i += 1 j = i + 1 # If number is positive, move # it to index j and increment j. elif (arr[i] > 0 and j < n): t = arr[i] arr[i] = arr[j] arr[j] = t j += 1 # Driver Codecount_negative = 0arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6 ]segregate(arr, 9)for i in range(9): print(arr[i] , end =\" \") # This code is contributed# by ChitraNayal", "e": 5039, "s": 4087, "text": null }, { "code": "<?php// PHP program to move all// negative numbers to// beginning and positive// numbers to end keeping order. function segregate(&$arr, $n){ // Count negative numbers $count_negative = 0; for ($i = 0; $i < $n; $i++) if ($arr[$i] < 0) $count_negative++; // Run a loop until all // negative numbers are // moved to the beginning $i = 0; $j = $i + 1; while ($i != $count_negative) { // If number is negative, // update position of next // positive number. if ($arr[$i] < 0) { $i++; $j = $i + 1; } // If number is positive, move // it to index j and increment j. else if ($arr[$i] > 0 && $j < $n) { $t = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $t; $j++; } }} // Driver Code$count_negative = 0;$arr = array(-12, 11, -13, -5, 6, -7, 5, -3, -6);$n = sizeof($arr);segregate($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] .\" \"; // This code is contributed// by ChitraNayal?>", "e": 6130, "s": 5039, "text": null }, { "code": "<script>// JavaScript program to move all negative numbers// to beginning and positive numbers to end// keeping order.function segregate(arr, n){ // Count negative numbers let count_negative = 0; for (let i = 0; i < n; i++) if (arr[i] < 0) count_negative++; // Run a loop until all negative // numbers are moved to the beginning let i = 0, j = i + 1; while (i != count_negative) { // If number is negative, update // position of next positive number. if (arr[i] < 0) { i++; j = i + 1; } // If number is positive, move it to // index j and increment j. else if (arr[i] > 0 && j < n) { let t = arr[i]; arr[i] = arr[j]; arr[j] = t; j++; } }} let count_negative = 0; let arr = [ -12, 11, -13, -5, 6, -7, 5, -3, -6 ]; let n = arr.length; segregate(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by Surbhi Tyagi.</script>", "e": 7188, "s": 6130, "text": null }, { "code": null, "e": 7197, "s": 7188, "text": "Output: " }, { "code": null, "e": 7225, "s": 7197, "text": "-12 -13 -5 -7 -3 -6 11 6 5 " }, { "code": null, "e": 7248, "s": 7225, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 7270, "s": 7248, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7276, "s": 7270, "text": "ukasp" }, { "code": null, "e": 7290, "s": 7276, "text": "surbhityagi15" }, { "code": null, "e": 7309, "s": 7290, "text": "surindertarika1234" }, { "code": null, "e": 7318, "s": 7309, "text": "akheniad" }, { "code": null, "e": 7334, "s": 7318, "text": "array-rearrange" }, { "code": null, "e": 7341, "s": 7334, "text": "Arrays" }, { "code": null, "e": 7348, "s": 7341, "text": "Arrays" }, { "code": null, "e": 7446, "s": 7348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7478, "s": 7446, "text": "Introduction to Data Structures" }, { "code": null, "e": 7525, "s": 7478, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7550, "s": 7525, "text": "Window Sliding Technique" }, { "code": null, "e": 7581, "s": 7550, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7639, "s": 7581, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 7660, "s": 7639, "text": "Next Greater Element" }, { "code": null, "e": 7724, "s": 7660, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7809, "s": 7724, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 7836, "s": 7809, "text": "Count pairs with given sum" } ]
How to build an HTML table using ReactJS from arrays ?
07 Apr, 2021 If we have an array and want to build an HTML table of it using ReactJS we can use the map function. The map() method iterates through each element of the array and will convert it into a table row. First, we will create a table tag then first, we will iterate through the heading/column names of the table and convert them into a table header using the <th> tag. Then we will iterate through the table data and convert them into each row as a table body using the <td> tag. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React, { Component } from 'react'; class App extends Component { render() { var heading = ['Name', 'City', 'Course']; var body = [['Kapil', 'Jaipur', 'MCA'], ['Aakash', 'Hisar', 'Btech'], ['Mani', 'Ranchi', 'MSc'], ['Yash', 'Udaipur', 'Mtech'] ]; return ( <div > <Table heading={heading} body={body} />, </div> ); }} class Table extends Component { render() { var heading = this.props.heading; var body = this.props.body; return ( <table style={{ width: 500 }}> <thead> <tr> {heading.map(head => <th>{head}</th>)} </tr> </thead> <tbody> {body.map(row => <TableRow row={row} />)} </tbody> </table> ); }} class TableRow extends Component { render() { var row = this.props.row; return ( <tr> {row.map(val => <td>{val}</td>)} </tr> ) }} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: As we can see from the output we use <th> tag for the heading and <td> tag for the remaining rows. The map function iterating through each row and returning a row, and it is adding to the table. HTML-Questions Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 503, "s": 28, "text": "If we have an array and want to build an HTML table of it using ReactJS we can use the map function. The map() method iterates through each element of the array and will convert it into a table row. First, we will create a table tag then first, we will iterate through the heading/column names of the table and convert them into a table header using the <th> tag. Then we will iterate through the table data and convert them into each row as a table body using the <td> tag." }, { "code": null, "e": 531, "s": 503, "text": "Creating React Application:" }, { "code": null, "e": 626, "s": 531, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 690, "s": 626, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 722, "s": 690, "text": "npx create-react-app foldername" }, { "code": null, "e": 835, "s": 722, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 935, "s": 835, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 949, "s": 935, "text": "cd foldername" }, { "code": null, "e": 1001, "s": 949, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1131, "s": 1001, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1138, "s": 1131, "text": "App.js" }, { "code": "import React, { Component } from 'react'; class App extends Component { render() { var heading = ['Name', 'City', 'Course']; var body = [['Kapil', 'Jaipur', 'MCA'], ['Aakash', 'Hisar', 'Btech'], ['Mani', 'Ranchi', 'MSc'], ['Yash', 'Udaipur', 'Mtech'] ]; return ( <div > <Table heading={heading} body={body} />, </div> ); }} class Table extends Component { render() { var heading = this.props.heading; var body = this.props.body; return ( <table style={{ width: 500 }}> <thead> <tr> {heading.map(head => <th>{head}</th>)} </tr> </thead> <tbody> {body.map(row => <TableRow row={row} />)} </tbody> </table> ); }} class TableRow extends Component { render() { var row = this.props.row; return ( <tr> {row.map(val => <td>{val}</td>)} </tr> ) }} export default App;", "e": 2288, "s": 1138, "text": null }, { "code": null, "e": 2401, "s": 2288, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2411, "s": 2401, "text": "npm start" }, { "code": null, "e": 2510, "s": 2411, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2705, "s": 2510, "text": "As we can see from the output we use <th> tag for the heading and <td> tag for the remaining rows. The map function iterating through each row and returning a row, and it is adding to the table." }, { "code": null, "e": 2720, "s": 2705, "text": "HTML-Questions" }, { "code": null, "e": 2727, "s": 2720, "text": "Picked" }, { "code": null, "e": 2743, "s": 2727, "text": "React-Questions" }, { "code": null, "e": 2751, "s": 2743, "text": "ReactJS" }, { "code": null, "e": 2768, "s": 2751, "text": "Web Technologies" }, { "code": null, "e": 2866, "s": 2768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2904, "s": 2866, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2923, "s": 2904, "text": "ReactJS setState()" }, { "code": null, "e": 2991, "s": 2923, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 3026, "s": 2991, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 3047, "s": 3026, "text": "ReactJS defaultProps" }, { "code": null, "e": 3080, "s": 3047, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3142, "s": 3080, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3203, "s": 3142, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3253, "s": 3203, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Count the numbers divisible by 'M' in a given range - GeeksforGeeks
26 Apr, 2022 A and B are two numbers which define a range, where A <= B. Find the total numbers in the given range [A ... B] divisible by ‘M’Examples: Input : A = 25, B = 100, M = 30 Output : 3 Explanation : In the given range [25 - 100], 30, 60 and 90 are divisible by 30 Input : A = 6, B = 15, M = 3 Output : 4 Explanation : In the given range [6 - 15], 6, 9, 12 and 15 are divisible by 3 Method 1 : [Brute-force] Run a loop from A to B. If a number divisible by ‘M’ is found, increment counter.Below is the implementation of above method: C++ Java Python3 C# PHP Javascript // Program to count the numbers divisible by// M in a given range#include <bits/stdc++.h>using namespace std; int countDivisibles(int A, int B, int M){ // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter;} // Driver codeint main(){ // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result cout << countDivisibles(A, B, M) << endl; return 0;} // Java program to count the numbers divisible by// M in a given rangeimport java.io.*; class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter; } // driver program public static void main(String[] args) { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result System.out.println(countDivisibles(A, B, M)); }} // Contributed by Pramod Kumar # Program to count the numbers# divisible by M in a given range def countDivisibles(A, B, M): # Variable to store the counter counter = 0; # Running a loop from A to B # and check if a number is # divisible by M. for i in range(A, B): if (i % M == 0): counter = counter + 1 return counter # Driver code# A and B define the range,# M is the dividendA = 30B = 100M = 30 # Printing the resultprint(countDivisibles(A, B, M)) # This code is contributed by Sam007. // C# program to count the numbers// divisible by M in a given rangeusing System; public class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter; } // driver program public static void Main() { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result Console.WriteLine(countDivisibles(A, B, M)); }} // This code is contributed by Sam007 <?php// PHP Program to count the// numbers divisible by// M in a given range function countDivisibles($A, $B, $M){ // Variable to store the counter $counter = 0; // Running a loop from // A to B and check // if a number is // divisible by M. for ($i = $A; $i <= $B; $i++) if ($i % $M == 0) $counter++; return $counter;} // Driver Code // A and B define the range, // M is the dividend $A = 30; $B = 100; $M = 30; // Printing the result echo countDivisibles($A, $B, $M), "\n"; // This code is contributed by ajit?> <script>// Javascript Program to count the// numbers divisible by// M in a given range function countDivisibles(A, B, M){ // Variable to store the counter let counter = 0; // Running a loop from // A to B and check // if a number is // divisible by M. for (let i = A; i <= B; i++) if (i % M == 0) counter++; return counter;} // Driver Code // A and B define the range, // M is the dividend let A = 30; let B = 100; let M = 30; // Printing the result document.write(countDivisibles(A, B, M)); // This code is contributed by gfgking.</script> Output: 3 Method 2 : [Better] The loop can be modified by incrementing the iterator ‘M’ times after the first divisible is found. Also, if ‘A’ is less than ‘M’, it can be changed to ‘M’, because a number less than ‘M’ can not be divided by it.Method 3 : [Efficient] Let B = b * M and A = a * M The count of numbers divisible by 'M' between A and B will be equal to b - a. Example: A = 25, B = 70, M = 10. Now, a = 2, b = 7. Count = 7 - 2 = 5. It can be observed that, if A is divisible by M, ‘b – a’ will exclude the count for A, so the count will be less by 1. Thus, in this case we add 1 explicitly.Example when A is divisible by M: A = 30, B = 70, M = 10. Now, a = 3, b = 7. Count = 7 - 3 = 4. But, Count should be 5. Thus, we will add 1 explicitly. Below is the implementation of the above method : C++ Java Python3 C# PHP Javascript // C++ program to count the numbers divisible by// M in a given range#include <bits/stdc++.h>using namespace std; // Function to count the numbers divisible by// M in a given rangeint countDivisibles(int A, int B, int M){ // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M);} // driver programint main(){ // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result cout << (countDivisibles(A, B, M));} // This code is contributed by subham348. // Java program to count the numbers divisible by// M in a given rangeimport java.io.*; class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M); } // driver program public static void main(String[] args) { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result System.out.println(countDivisibles(A, B, M)); }} // Contributed by Pramod Kumar # Program to count the numbers divisible# by M in a given range # Returns count of numbers in [A B] that# are divisible by M.def countDivisibles(A, B, M): # Add 1 explicitly as A is divisible by M if (A % M == 0): return ((B / M) - (A / M)) + 1 # A is not divisible by M return ((B / M) - (A / M)) # Driver Code# A and B define the range, M# is the dividendA = 30B = 70M = 10 # Printing the resultprint(countDivisibles(A, B, M)) # This code is contributed by Sam007 // C# program to count the numbers// divisible by M in a given rangeusing System; public class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M); } // driver program public static void Main() { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result Console.WriteLine(countDivisibles(A, B, M)); }} // This code is contributed by Sam007 <?php// PHP Program to count the numbers// divisible by M in a given range // Returns count of numbers in// [A B] that are divisible by M.function countDivisibles($A, $B, $M){ // Add 1 explicitly as A // is divisible by M if ($A % $M == 0) return ($B / $M) - ($A / $M) + 1; // A is not divisible by M return ($B / $M) - ($A / $M);} // Driver Code // A and B define the range, // M is the divident $A = 30; $B = 70; $M = 10; // Printing the result echo countDivisibles($A, $B, $M) ; return 0; // This code is contributed by nitin mittal.?> // Javascript Program to count the numbers// divisible by M in a given range // Returns count of numbers in// [A B] that are divisible by M.function countDivisibles(A, B, M){ // Add 1 explicitly as A // is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M);} // Driver Code // A and B define the range, // M is the divident let A = 30; let B = 70; let M = 10; // Printing the result document.write(countDivisibles(A, B, M)); // This code is contributed by gfgking 3 This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 jit_t nitin mittal dsairam17 gfgking subham348 surindertarika1234 simmytarika5 divisibility Samsung Mathematical Samsung Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Euclidean algorithms (Basic and Extended) Sieve of Eratosthenes Program for Decimal to Binary Conversion
[ { "code": null, "e": 25392, "s": 25364, "text": "\n26 Apr, 2022" }, { "code": null, "e": 25532, "s": 25392, "text": "A and B are two numbers which define a range, where A <= B. Find the total numbers in the given range [A ... B] divisible by ‘M’Examples: " }, { "code": null, "e": 25775, "s": 25532, "text": "Input : A = 25, B = 100, M = 30\nOutput : 3\nExplanation : In the given range [25 - 100], \n30, 60 and 90 are divisible by 30\n\nInput : A = 6, B = 15, M = 3\nOutput : 4\nExplanation : In the given range [6 - 15],\n6, 9, 12 and 15 are divisible by 3" }, { "code": null, "e": 25931, "s": 25777, "text": "Method 1 : [Brute-force] Run a loop from A to B. If a number divisible by ‘M’ is found, increment counter.Below is the implementation of above method: " }, { "code": null, "e": 25935, "s": 25931, "text": "C++" }, { "code": null, "e": 25940, "s": 25935, "text": "Java" }, { "code": null, "e": 25948, "s": 25940, "text": "Python3" }, { "code": null, "e": 25951, "s": 25948, "text": "C#" }, { "code": null, "e": 25955, "s": 25951, "text": "PHP" }, { "code": null, "e": 25966, "s": 25955, "text": "Javascript" }, { "code": "// Program to count the numbers divisible by// M in a given range#include <bits/stdc++.h>using namespace std; int countDivisibles(int A, int B, int M){ // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter;} // Driver codeint main(){ // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result cout << countDivisibles(A, B, M) << endl; return 0;}", "e": 26548, "s": 25966, "text": null }, { "code": "// Java program to count the numbers divisible by// M in a given rangeimport java.io.*; class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter; } // driver program public static void main(String[] args) { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result System.out.println(countDivisibles(A, B, M)); }} // Contributed by Pramod Kumar", "e": 27329, "s": 26548, "text": null }, { "code": "# Program to count the numbers# divisible by M in a given range def countDivisibles(A, B, M): # Variable to store the counter counter = 0; # Running a loop from A to B # and check if a number is # divisible by M. for i in range(A, B): if (i % M == 0): counter = counter + 1 return counter # Driver code# A and B define the range,# M is the dividendA = 30B = 100M = 30 # Printing the resultprint(countDivisibles(A, B, M)) # This code is contributed by Sam007.", "e": 27834, "s": 27329, "text": null }, { "code": "// C# program to count the numbers// divisible by M in a given rangeusing System; public class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Variable to store the counter int counter = 0; // Running a loop from A to B and check // if a number is divisible by M. for (int i = A; i <= B; i++) if (i % M == 0) counter++; return counter; } // driver program public static void Main() { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result Console.WriteLine(countDivisibles(A, B, M)); }} // This code is contributed by Sam007", "e": 28610, "s": 27834, "text": null }, { "code": "<?php// PHP Program to count the// numbers divisible by// M in a given range function countDivisibles($A, $B, $M){ // Variable to store the counter $counter = 0; // Running a loop from // A to B and check // if a number is // divisible by M. for ($i = $A; $i <= $B; $i++) if ($i % $M == 0) $counter++; return $counter;} // Driver Code // A and B define the range, // M is the dividend $A = 30; $B = 100; $M = 30; // Printing the result echo countDivisibles($A, $B, $M), \"\\n\"; // This code is contributed by ajit?>", "e": 29199, "s": 28610, "text": null }, { "code": "<script>// Javascript Program to count the// numbers divisible by// M in a given range function countDivisibles(A, B, M){ // Variable to store the counter let counter = 0; // Running a loop from // A to B and check // if a number is // divisible by M. for (let i = A; i <= B; i++) if (i % M == 0) counter++; return counter;} // Driver Code // A and B define the range, // M is the dividend let A = 30; let B = 100; let M = 30; // Printing the result document.write(countDivisibles(A, B, M)); // This code is contributed by gfgking.</script>", "e": 29815, "s": 29199, "text": null }, { "code": null, "e": 29825, "s": 29815, "text": "Output: " }, { "code": null, "e": 29827, "s": 29825, "text": "3" }, { "code": null, "e": 30085, "s": 29827, "text": "Method 2 : [Better] The loop can be modified by incrementing the iterator ‘M’ times after the first divisible is found. Also, if ‘A’ is less than ‘M’, it can be changed to ‘M’, because a number less than ‘M’ can not be divided by it.Method 3 : [Efficient] " }, { "code": null, "e": 30267, "s": 30085, "text": "Let B = b * M and\n A = a * M\nThe count of numbers divisible by\n'M' between A and B will be equal\nto b - a.\n\nExample:\nA = 25, B = 70, M = 10.\nNow, a = 2, b = 7.\nCount = 7 - 2 = 5." }, { "code": null, "e": 30461, "s": 30267, "text": "It can be observed that, if A is divisible by M, ‘b – a’ will exclude the count for A, so the count will be less by 1. Thus, in this case we add 1 explicitly.Example when A is divisible by M: " }, { "code": null, "e": 30579, "s": 30461, "text": "A = 30, B = 70, M = 10.\nNow, a = 3, b = 7.\nCount = 7 - 3 = 4.\nBut, Count should be 5. Thus, we will\nadd 1 explicitly." }, { "code": null, "e": 30632, "s": 30579, "text": "Below is the implementation of the above method : " }, { "code": null, "e": 30636, "s": 30632, "text": "C++" }, { "code": null, "e": 30641, "s": 30636, "text": "Java" }, { "code": null, "e": 30649, "s": 30641, "text": "Python3" }, { "code": null, "e": 30652, "s": 30649, "text": "C#" }, { "code": null, "e": 30656, "s": 30652, "text": "PHP" }, { "code": null, "e": 30667, "s": 30656, "text": "Javascript" }, { "code": "// C++ program to count the numbers divisible by// M in a given range#include <bits/stdc++.h>using namespace std; // Function to count the numbers divisible by// M in a given rangeint countDivisibles(int A, int B, int M){ // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M);} // driver programint main(){ // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result cout << (countDivisibles(A, B, M));} // This code is contributed by subham348.", "e": 31278, "s": 30667, "text": null }, { "code": "// Java program to count the numbers divisible by// M in a given rangeimport java.io.*; class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M); } // driver program public static void main(String[] args) { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result System.out.println(countDivisibles(A, B, M)); }} // Contributed by Pramod Kumar", "e": 31975, "s": 31278, "text": null }, { "code": "# Program to count the numbers divisible# by M in a given range # Returns count of numbers in [A B] that# are divisible by M.def countDivisibles(A, B, M): # Add 1 explicitly as A is divisible by M if (A % M == 0): return ((B / M) - (A / M)) + 1 # A is not divisible by M return ((B / M) - (A / M)) # Driver Code# A and B define the range, M# is the dividendA = 30B = 70M = 10 # Printing the resultprint(countDivisibles(A, B, M)) # This code is contributed by Sam007", "e": 32466, "s": 31975, "text": null }, { "code": "// C# program to count the numbers// divisible by M in a given rangeusing System; public class GFG { // Function to count the numbers divisible by // M in a given range static int countDivisibles(int A, int B, int M) { // Add 1 explicitly as A is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M); } // driver program public static void Main() { // A and B define the range, M is the dividend int A = 30, B = 100, M = 30; // Printing the result Console.WriteLine(countDivisibles(A, B, M)); }} // This code is contributed by Sam007", "e": 33158, "s": 32466, "text": null }, { "code": "<?php// PHP Program to count the numbers// divisible by M in a given range // Returns count of numbers in// [A B] that are divisible by M.function countDivisibles($A, $B, $M){ // Add 1 explicitly as A // is divisible by M if ($A % $M == 0) return ($B / $M) - ($A / $M) + 1; // A is not divisible by M return ($B / $M) - ($A / $M);} // Driver Code // A and B define the range, // M is the divident $A = 30; $B = 70; $M = 10; // Printing the result echo countDivisibles($A, $B, $M) ; return 0; // This code is contributed by nitin mittal.?>", "e": 33778, "s": 33158, "text": null }, { "code": "// Javascript Program to count the numbers// divisible by M in a given range // Returns count of numbers in// [A B] that are divisible by M.function countDivisibles(A, B, M){ // Add 1 explicitly as A // is divisible by M if (A % M == 0) return (B / M) - (A / M) + 1; // A is not divisible by M return (B / M) - (A / M);} // Driver Code // A and B define the range, // M is the divident let A = 30; let B = 70; let M = 10; // Printing the result document.write(countDivisibles(A, B, M)); // This code is contributed by gfgking", "e": 34376, "s": 33778, "text": null }, { "code": null, "e": 34378, "s": 34376, "text": "3" }, { "code": null, "e": 34802, "s": 34378, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34809, "s": 34802, "text": "Sam007" }, { "code": null, "e": 34815, "s": 34809, "text": "jit_t" }, { "code": null, "e": 34828, "s": 34815, "text": "nitin mittal" }, { "code": null, "e": 34838, "s": 34828, "text": "dsairam17" }, { "code": null, "e": 34846, "s": 34838, "text": "gfgking" }, { "code": null, "e": 34856, "s": 34846, "text": "subham348" }, { "code": null, "e": 34875, "s": 34856, "text": "surindertarika1234" }, { "code": null, "e": 34888, "s": 34875, "text": "simmytarika5" }, { "code": null, "e": 34901, "s": 34888, "text": "divisibility" }, { "code": null, "e": 34909, "s": 34901, "text": "Samsung" }, { "code": null, "e": 34922, "s": 34909, "text": "Mathematical" }, { "code": null, "e": 34930, "s": 34922, "text": "Samsung" }, { "code": null, "e": 34943, "s": 34930, "text": "Mathematical" }, { "code": null, "e": 35041, "s": 34943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35050, "s": 35041, "text": "Comments" }, { "code": null, "e": 35063, "s": 35050, "text": "Old Comments" }, { "code": null, "e": 35105, "s": 35063, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 35148, "s": 35105, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 35172, "s": 35148, "text": "Merge two sorted arrays" }, { "code": null, "e": 35186, "s": 35172, "text": "Prime Numbers" }, { "code": null, "e": 35235, "s": 35186, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35269, "s": 35235, "text": "Program for factorial of a number" }, { "code": null, "e": 35290, "s": 35269, "text": "Operators in C / C++" }, { "code": null, "e": 35332, "s": 35290, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 35354, "s": 35332, "text": "Sieve of Eratosthenes" } ]
AutoML for Object Detection: How to Train a Model to Identify Potholes | by Déborah Mesquita | Towards Data Science
Initial algorithm selection and hyperparameter optimization are activities that I personally don’t like doing. If you’re like me then maybe you’ll like Automated Machine Learning (AutoML), a technique where we can let the scripts do these time-consuming ML tasks for us. The Azure Machine Learning (AML) is a cloud service with features that make it easier to prepare and create datasets, train models and deploy them as web services. Recently the AML team released the AutoML for Images feature for Public Preview. Today we’ll use this feature to train an object detection model to identify potholes in roads. During the article I’ll give a brief review of some AML and object detection concepts, so you don’t need to be totally familiar with them to follow along. This tutorial is heavily based on this example from Azure and you can check the Jupyter notebook I coded here. Cool, let’s get started! Object detection datasets are interesting because they are made of tabular data (the annotations of the bounding boxes) and also image data (.png, .jpeg etc). The COCO format is a popular format for object detection datasets and we’ll download the pothole dataset (Pothole Dataset. Shared By. Atikur Rahman Chitholian. November 2020. License. ODbL v1.0) using this format. Azure Machine Learning uses the TabularDataset format, so the first thing we’ll need to do is to convert from COCO to TabularDataset. After the conversion we’ll choose a object detection algorithm and finally train the model. I got the dataset from Roboflow. It has 665 images of roads with the potholes labeled and was created and shared by Atikur Rahman Chitholian as part of his undergraduate thesis. The Roboflow team re-shuffled the images into a 70/20/10 train-valid-test splits. Each split is has two main components: _annotations.coco.json, a JSON file with images, categories and annotations metadata The image themselves (.jpg files) This is how the COCO annotations keys look like: images: has information about the images of the dataset (id, filename, size, etc.) categories: the name and id of the categories of the bounding boxes annotations: has information about the objects, containing the bounding boxes coordinates (in this dataset they’re in absolute coordinates), the image_id and the category_id of the object Now it’s time to start working with AML. The first thing you need to do is to create an Azure Machine Learning Workspace. You can do it using the web interface on https://portal.azure.com. We need a compute instance to run the notebooks and later run the train experiment, so go ahead and create one inside your workspace. AutoML models for image tasks require GPU compute instances. You can create a compute instance using the web interface as well. I’ve downloaded and extracted the dataset inside the ./potholeObjects folder. Each split has it’s on folder and inside them we have the images and the JSON files. You need to upload the images and the JSON file to a Datastore so that AML can access them. Datastores are abstraction of cloud data sources. When you create a AML workspace, a AzureBlobDatastore is created and set as default. We’ll use this default Datastore and upload the images there. The annotations are in the COCO format (JSON) but the TabularDataset requires it to be in JSON Lines. The TabularDataset has the same metadata but organized in different keys. This is how a TabularDataset for object detection looks like: { "image_url":"AmlDatastore://data_directory/../Image_name.image_format", "image_details":{ "format":"image_format", "width":"image_width", "height":"image_height" }, "label":[ { "label":"class_name_1", "topX":"xmin/width", "topY":"ymin/height", "bottomX":"xmax/width", "bottomY":"ymax/height", "isCrowd":"isCrowd" }, { "label":"class_name_2", "topX":"xmin/width", "topY":"ymin/height", "bottomX":"xmax/width", "bottomY":"ymax/height", "isCrowd":"isCrowd" }, "..." ]} Fortunately the Microsoft engineers wrote a script to convert from COCO: https://github.com/Azure/azureml-examples/blob/1a41978d7ddc1d1f831236ff0c5c970b86727b44/python-sdk/tutorials/automl-with-azureml/image-object-detection/coco2jsonl.py The image_url key of this file needs to point to the image files in the Datastore we’re using (the default one). We specify that using the base_url parameter of the coco2jsonl.py script. # Generate training jsonl file from coco file!python coco2jsonl.py \--input_coco_file_path "./potholeObjects/train/_annotations.coco.json" \--output_dir "./potholeObjects/train" --output_file_name "train_pothole_from_coco.jsonl" \--task_type "ObjectDetection" \--base_url "AmlDatastore://{datastore_name}/potholeObjects/train/" We’ll run the same command for the validation set. Now the next step is to upload the files to the Datastore and create the Datasets inside AML. Don’t confuse Datasets with Datastores. Datasets are versioned packaged data objects, usually created based on files in a Datastore. We’ll create the Datasets from the JSON Lines files. You’ll also do that for both training and validation splits. If everying went well you can see the images preview inside AML. Inside AML, everything you run is called an Experiment. To train the model using AutoML you’ll create an experiment, point to the compute target it’s suppose to run on and provide the configuration for the AutoML parameters. Let’s first create the experiment and get the computer instance from the workspace: Here I’ll run the experiment using yolov5 default parameters. You need to provide the hyperparameters, the compute target, the training data and the validation data (as the example says, the validation dataset is optional). Now we can finally submit the experiment: automl_image_run = experiment.submit(automl_config_yolov5) You can monitor the experiments using the Workspace web interface: Here I’m using only a dict with a single model and using the default paramters, but you can explore parameters and tunning settings. Here is an example from Microsoft tutorial: This yolov5 model is trained using Pytorch, so we can download the model and check the predictions using the Jupyter notebook. Mine took 56min to train. The first thing you need to do to get the model is to register the best run in the workspace so you can access the model thought it. Now we can download the model.pt file and run the inference. To do that we’ll use the code from the azureml-contrib-automl-dnn-vision package: I used the code from the Microsoft tutorial to visualize the bounding boxes. Here is the result for a test image: Cool right? Azure Machine Learning is a good tool to get you started with machine learning (well, deep learning in our case) because it hides away a lot of complexity. Now with the AutoML feature you don’t even have to think about training different models at different moments because the tunning settings can do that for us. You can check the Jupyter notebook with all the code here. The next step in the pipeline would be to deploy the model as web service. If you’re curious you can check how to do that using the Microsoft tutorial as well. Thanks for reading! :D Pothole Dataset. Shared By. Atikur Rahman Chitholian. November 2020. License. ODbL v1.0 Pothole Dataset. Shared By. Atikur Rahman Chitholian. November 2020. License. ODbL v1.0
[ { "code": null, "e": 443, "s": 172, "text": "Initial algorithm selection and hyperparameter optimization are activities that I personally don’t like doing. If you’re like me then maybe you’ll like Automated Machine Learning (AutoML), a technique where we can let the scripts do these time-consuming ML tasks for us." }, { "code": null, "e": 783, "s": 443, "text": "The Azure Machine Learning (AML) is a cloud service with features that make it easier to prepare and create datasets, train models and deploy them as web services. Recently the AML team released the AutoML for Images feature for Public Preview. Today we’ll use this feature to train an object detection model to identify potholes in roads." }, { "code": null, "e": 1049, "s": 783, "text": "During the article I’ll give a brief review of some AML and object detection concepts, so you don’t need to be totally familiar with them to follow along. This tutorial is heavily based on this example from Azure and you can check the Jupyter notebook I coded here." }, { "code": null, "e": 1074, "s": 1049, "text": "Cool, let’s get started!" }, { "code": null, "e": 1581, "s": 1074, "text": "Object detection datasets are interesting because they are made of tabular data (the annotations of the bounding boxes) and also image data (.png, .jpeg etc). The COCO format is a popular format for object detection datasets and we’ll download the pothole dataset (Pothole Dataset. Shared By. Atikur Rahman Chitholian. November 2020. License. ODbL v1.0) using this format. Azure Machine Learning uses the TabularDataset format, so the first thing we’ll need to do is to convert from COCO to TabularDataset." }, { "code": null, "e": 1673, "s": 1581, "text": "After the conversion we’ll choose a object detection algorithm and finally train the model." }, { "code": null, "e": 1933, "s": 1673, "text": "I got the dataset from Roboflow. It has 665 images of roads with the potholes labeled and was created and shared by Atikur Rahman Chitholian as part of his undergraduate thesis. The Roboflow team re-shuffled the images into a 70/20/10 train-valid-test splits." }, { "code": null, "e": 1972, "s": 1933, "text": "Each split is has two main components:" }, { "code": null, "e": 2057, "s": 1972, "text": "_annotations.coco.json, a JSON file with images, categories and annotations metadata" }, { "code": null, "e": 2091, "s": 2057, "text": "The image themselves (.jpg files)" }, { "code": null, "e": 2140, "s": 2091, "text": "This is how the COCO annotations keys look like:" }, { "code": null, "e": 2223, "s": 2140, "text": "images: has information about the images of the dataset (id, filename, size, etc.)" }, { "code": null, "e": 2291, "s": 2223, "text": "categories: the name and id of the categories of the bounding boxes" }, { "code": null, "e": 2479, "s": 2291, "text": "annotations: has information about the objects, containing the bounding boxes coordinates (in this dataset they’re in absolute coordinates), the image_id and the category_id of the object" }, { "code": null, "e": 2668, "s": 2479, "text": "Now it’s time to start working with AML. The first thing you need to do is to create an Azure Machine Learning Workspace. You can do it using the web interface on https://portal.azure.com." }, { "code": null, "e": 2930, "s": 2668, "text": "We need a compute instance to run the notebooks and later run the train experiment, so go ahead and create one inside your workspace. AutoML models for image tasks require GPU compute instances. You can create a compute instance using the web interface as well." }, { "code": null, "e": 3093, "s": 2930, "text": "I’ve downloaded and extracted the dataset inside the ./potholeObjects folder. Each split has it’s on folder and inside them we have the images and the JSON files." }, { "code": null, "e": 3382, "s": 3093, "text": "You need to upload the images and the JSON file to a Datastore so that AML can access them. Datastores are abstraction of cloud data sources. When you create a AML workspace, a AzureBlobDatastore is created and set as default. We’ll use this default Datastore and upload the images there." }, { "code": null, "e": 3620, "s": 3382, "text": "The annotations are in the COCO format (JSON) but the TabularDataset requires it to be in JSON Lines. The TabularDataset has the same metadata but organized in different keys. This is how a TabularDataset for object detection looks like:" }, { "code": null, "e": 4234, "s": 3620, "text": "{ \"image_url\":\"AmlDatastore://data_directory/../Image_name.image_format\", \"image_details\":{ \"format\":\"image_format\", \"width\":\"image_width\", \"height\":\"image_height\" }, \"label\":[ { \"label\":\"class_name_1\", \"topX\":\"xmin/width\", \"topY\":\"ymin/height\", \"bottomX\":\"xmax/width\", \"bottomY\":\"ymax/height\", \"isCrowd\":\"isCrowd\" }, { \"label\":\"class_name_2\", \"topX\":\"xmin/width\", \"topY\":\"ymin/height\", \"bottomX\":\"xmax/width\", \"bottomY\":\"ymax/height\", \"isCrowd\":\"isCrowd\" }, \"...\" ]}" }, { "code": null, "e": 4473, "s": 4234, "text": "Fortunately the Microsoft engineers wrote a script to convert from COCO: https://github.com/Azure/azureml-examples/blob/1a41978d7ddc1d1f831236ff0c5c970b86727b44/python-sdk/tutorials/automl-with-azureml/image-object-detection/coco2jsonl.py" }, { "code": null, "e": 4660, "s": 4473, "text": "The image_url key of this file needs to point to the image files in the Datastore we’re using (the default one). We specify that using the base_url parameter of the coco2jsonl.py script." }, { "code": null, "e": 4988, "s": 4660, "text": "# Generate training jsonl file from coco file!python coco2jsonl.py \\--input_coco_file_path \"./potholeObjects/train/_annotations.coco.json\" \\--output_dir \"./potholeObjects/train\" --output_file_name \"train_pothole_from_coco.jsonl\" \\--task_type \"ObjectDetection\" \\--base_url \"AmlDatastore://{datastore_name}/potholeObjects/train/\"" }, { "code": null, "e": 5319, "s": 4988, "text": "We’ll run the same command for the validation set. Now the next step is to upload the files to the Datastore and create the Datasets inside AML. Don’t confuse Datasets with Datastores. Datasets are versioned packaged data objects, usually created based on files in a Datastore. We’ll create the Datasets from the JSON Lines files." }, { "code": null, "e": 5445, "s": 5319, "text": "You’ll also do that for both training and validation splits. If everying went well you can see the images preview inside AML." }, { "code": null, "e": 5670, "s": 5445, "text": "Inside AML, everything you run is called an Experiment. To train the model using AutoML you’ll create an experiment, point to the compute target it’s suppose to run on and provide the configuration for the AutoML parameters." }, { "code": null, "e": 5754, "s": 5670, "text": "Let’s first create the experiment and get the computer instance from the workspace:" }, { "code": null, "e": 5978, "s": 5754, "text": "Here I’ll run the experiment using yolov5 default parameters. You need to provide the hyperparameters, the compute target, the training data and the validation data (as the example says, the validation dataset is optional)." }, { "code": null, "e": 6020, "s": 5978, "text": "Now we can finally submit the experiment:" }, { "code": null, "e": 6079, "s": 6020, "text": "automl_image_run = experiment.submit(automl_config_yolov5)" }, { "code": null, "e": 6146, "s": 6079, "text": "You can monitor the experiments using the Workspace web interface:" }, { "code": null, "e": 6323, "s": 6146, "text": "Here I’m using only a dict with a single model and using the default paramters, but you can explore parameters and tunning settings. Here is an example from Microsoft tutorial:" }, { "code": null, "e": 6609, "s": 6323, "text": "This yolov5 model is trained using Pytorch, so we can download the model and check the predictions using the Jupyter notebook. Mine took 56min to train. The first thing you need to do to get the model is to register the best run in the workspace so you can access the model thought it." }, { "code": null, "e": 6752, "s": 6609, "text": "Now we can download the model.pt file and run the inference. To do that we’ll use the code from the azureml-contrib-automl-dnn-vision package:" }, { "code": null, "e": 6866, "s": 6752, "text": "I used the code from the Microsoft tutorial to visualize the bounding boxes. Here is the result for a test image:" }, { "code": null, "e": 6878, "s": 6866, "text": "Cool right?" }, { "code": null, "e": 7193, "s": 6878, "text": "Azure Machine Learning is a good tool to get you started with machine learning (well, deep learning in our case) because it hides away a lot of complexity. Now with the AutoML feature you don’t even have to think about training different models at different moments because the tunning settings can do that for us." }, { "code": null, "e": 7252, "s": 7193, "text": "You can check the Jupyter notebook with all the code here." }, { "code": null, "e": 7412, "s": 7252, "text": "The next step in the pipeline would be to deploy the model as web service. If you’re curious you can check how to do that using the Microsoft tutorial as well." }, { "code": null, "e": 7435, "s": 7412, "text": "Thanks for reading! :D" }, { "code": null, "e": 7523, "s": 7435, "text": "Pothole Dataset. Shared By. Atikur Rahman Chitholian. November 2020. License. ODbL v1.0" } ]
Convert Character Matrix to Numeric Matrix in R - GeeksforGeeks
09 May, 2021 In this article, we are going to see how to convert a given character matrix to numeric in R Programming Language. Converting the Character Matrix to Numeric Matrix we will use as.numeric() & matrix() Functions. as.numeric() function: This function is used to convert a given column into a numeric value column in r language. Syntax: as.numeric(x, ...) Parameter: x: object to be coerced. Returns: The numeric type object in r language. matrix() function: This function in r language is used to create matrices. Syntax: matrix(data, nrow, ncol, byrow, dimnames) Parameter: data: is the input vector that becomes the data elements of the matrix. nrow: is the number of rows to be created. ncol: is the number of columns to be created. byrow: is a logical clue. If TRUE then the input vector elements are arranged by row. dimname: is the names assigned to the rows and columns. Returns: It will return the matrix of the provided data to the user. This is one of the simplest approach for converting a given character matrix to a numeric matrix, as under this approach user just have to need to call the as.numeric() function with the name of the given character matrix as its parameter and this will help the user to convert the character matrix to numeric vector and in the next step user has to call another function matrix() with the numeric vector (which was created by the as.numeric function) and in return, this function will be returning the numeric matrix to the user. By this, the user ends up the process to receive the numeric matrix from the matrix() function in r language. Example 1: In this example, we will be converting a given character matrix of 3 columns and 3 rows and 9 elements to a numeric matrix using as.numeric function and the matrix() function is r language. R # Creating character matrixgfg_character_matrix <- matrix(c("1","2","3","4", "5","6","7","8","9"), ncol = 3) print("Print character matrix")print(gfg_character_matrix) # Convert to numeric matrixgfg_numeric_matrix <- matrix( as.numeric(gfg_character_matrix), ncol = 3) print("Print numeric matrix")print(gfg_numeric_matrix ) Output: [1] "Print character matrix" [,1] [,2] [,3] [1,] "1" "4" "7" [2,] "2" "5" "8" [3,] "3" "6" "9" [1] "Print numeric matrix" [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 Example 2: In this example, we will be converting a given character matrix of 4 columns and 4 rows and 16 elements to a numeric matrix using as.numeric function and the matrix() function is r language. R # Creating character matrixgfg_character_matrix <- matrix(c("-4","2","8","7","-10", "-40","78","-54","74", "87","0","1","41","24", "91","11"), ncol = 4) print("Character matrix")print(gfg_character_matrix) # Convert to numeric matrixgfg_numeric_matrix <- matrix( as.numeric(gfg_character_matrix), ncol = 4) print("Numeric matrix")print(gfg_numeric_matrix ) Output: [1] "Character matrix" [,1] [,2] [,3] [,4] [1,] "-4" "-10" "74" "41" [2,] "2" "-40" "87" "24" [3,] "8" "78" "0" "91" [4,] "7" "-54" "1" "11" [1] "Numeric matrix" [,1] [,2] [,3] [,4] [1,] -4 -10 74 41 [2,] 2 -40 87 24 [3,] 8 78 0 91 [4,] 7 -54 1 11 Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n09 May, 2021" }, { "code": null, "e": 25454, "s": 25242, "text": "In this article, we are going to see how to convert a given character matrix to numeric in R Programming Language. Converting the Character Matrix to Numeric Matrix we will use as.numeric() & matrix() Functions." }, { "code": null, "e": 25568, "s": 25454, "text": "as.numeric() function: This function is used to convert a given column into a numeric value column in r language." }, { "code": null, "e": 25595, "s": 25568, "text": "Syntax: as.numeric(x, ...)" }, { "code": null, "e": 25606, "s": 25595, "text": "Parameter:" }, { "code": null, "e": 25631, "s": 25606, "text": "x: object to be coerced." }, { "code": null, "e": 25679, "s": 25631, "text": "Returns: The numeric type object in r language." }, { "code": null, "e": 25754, "s": 25679, "text": "matrix() function: This function in r language is used to create matrices." }, { "code": null, "e": 25804, "s": 25754, "text": "Syntax: matrix(data, nrow, ncol, byrow, dimnames)" }, { "code": null, "e": 25815, "s": 25804, "text": "Parameter:" }, { "code": null, "e": 25887, "s": 25815, "text": "data: is the input vector that becomes the data elements of the matrix." }, { "code": null, "e": 25930, "s": 25887, "text": "nrow: is the number of rows to be created." }, { "code": null, "e": 25976, "s": 25930, "text": "ncol: is the number of columns to be created." }, { "code": null, "e": 26062, "s": 25976, "text": "byrow: is a logical clue. If TRUE then the input vector elements are arranged by row." }, { "code": null, "e": 26118, "s": 26062, "text": "dimname: is the names assigned to the rows and columns." }, { "code": null, "e": 26187, "s": 26118, "text": "Returns: It will return the matrix of the provided data to the user." }, { "code": null, "e": 26828, "s": 26187, "text": "This is one of the simplest approach for converting a given character matrix to a numeric matrix, as under this approach user just have to need to call the as.numeric() function with the name of the given character matrix as its parameter and this will help the user to convert the character matrix to numeric vector and in the next step user has to call another function matrix() with the numeric vector (which was created by the as.numeric function) and in return, this function will be returning the numeric matrix to the user. By this, the user ends up the process to receive the numeric matrix from the matrix() function in r language." }, { "code": null, "e": 26839, "s": 26828, "text": "Example 1:" }, { "code": null, "e": 27029, "s": 26839, "text": "In this example, we will be converting a given character matrix of 3 columns and 3 rows and 9 elements to a numeric matrix using as.numeric function and the matrix() function is r language." }, { "code": null, "e": 27031, "s": 27029, "text": "R" }, { "code": "# Creating character matrixgfg_character_matrix <- matrix(c(\"1\",\"2\",\"3\",\"4\", \"5\",\"6\",\"7\",\"8\",\"9\"), ncol = 3) print(\"Print character matrix\")print(gfg_character_matrix) # Convert to numeric matrixgfg_numeric_matrix <- matrix( as.numeric(gfg_character_matrix), ncol = 3) print(\"Print numeric matrix\")print(gfg_numeric_matrix )", "e": 27422, "s": 27031, "text": null }, { "code": null, "e": 27430, "s": 27422, "text": "Output:" }, { "code": null, "e": 27646, "s": 27430, "text": "[1] \"Print character matrix\"\n [,1] [,2] [,3]\n[1,] \"1\" \"4\" \"7\" \n[2,] \"2\" \"5\" \"8\" \n[3,] \"3\" \"6\" \"9\" \n[1] \"Print numeric matrix\"\n [,1] [,2] [,3]\n[1,] 1 4 7\n[2,] 2 5 8\n[3,] 3 6 9" }, { "code": null, "e": 27657, "s": 27646, "text": "Example 2:" }, { "code": null, "e": 27848, "s": 27657, "text": "In this example, we will be converting a given character matrix of 4 columns and 4 rows and 16 elements to a numeric matrix using as.numeric function and the matrix() function is r language." }, { "code": null, "e": 27850, "s": 27848, "text": "R" }, { "code": "# Creating character matrixgfg_character_matrix <- matrix(c(\"-4\",\"2\",\"8\",\"7\",\"-10\", \"-40\",\"78\",\"-54\",\"74\", \"87\",\"0\",\"1\",\"41\",\"24\", \"91\",\"11\"), ncol = 4) print(\"Character matrix\")print(gfg_character_matrix) # Convert to numeric matrixgfg_numeric_matrix <- matrix( as.numeric(gfg_character_matrix), ncol = 4) print(\"Numeric matrix\")print(gfg_numeric_matrix )", "e": 28337, "s": 27850, "text": null }, { "code": null, "e": 28345, "s": 28337, "text": "Output:" }, { "code": null, "e": 28644, "s": 28345, "text": "[1] \"Character matrix\"\n [,1] [,2] [,3] [,4]\n[1,] \"-4\" \"-10\" \"74\" \"41\"\n[2,] \"2\" \"-40\" \"87\" \"24\"\n[3,] \"8\" \"78\" \"0\" \"91\"\n[4,] \"7\" \"-54\" \"1\" \"11\"\n[1] \"Numeric matrix\"\n [,1] [,2] [,3] [,4]\n[1,] -4 -10 74 41\n[2,] 2 -40 87 24\n[3,] 8 78 0 91\n[4,] 7 -54 1 11" }, { "code": null, "e": 28651, "s": 28644, "text": "Picked" }, { "code": null, "e": 28669, "s": 28651, "text": "R Matrix-Programs" }, { "code": null, "e": 28678, "s": 28669, "text": "R-Matrix" }, { "code": null, "e": 28689, "s": 28678, "text": "R Language" }, { "code": null, "e": 28700, "s": 28689, "text": "R Programs" }, { "code": null, "e": 28798, "s": 28700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28850, "s": 28798, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28888, "s": 28850, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28923, "s": 28888, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28981, "s": 28923, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29030, "s": 28981, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29088, "s": 29030, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29137, "s": 29088, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29187, "s": 29137, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29230, "s": 29187, "text": "Replace Specific Characters in String in R" } ]
DirectX - Creating App
This chapter involves the process of creating new application with DirectX using Visual Studio Code Editor. Following steps should be followed for creating an app in DirectX − Here we will start by constructing a DirectX project with a walk through of the basic steps to get a working application. To create a DirectX “non-desktop” application, a special type of project called a “DirectX App” is used. This step involves opening a Visual Studio 2013, select File → New Project and select as “DirectX App” which comes under category of “Visual C++”, “Store App”, “Universal App”. Once the project is created, you will see a lot of files being populated. This is clearly visible in snapshot mentioned below − User can delete various files to make up a sample app and explore the features to see how a fully-functioning DirectX app is set up as per the attributes required. As mentioned in the snapshot above, a file is created named “App.cpp”. #include <stdio.h> // include the standard input/output header file int main(void) { // our program starts here printf("Hello World!"); // print "Hello World!" into the console return 0; // return 0 to windows } The function main() marks the start of the application and works with Windows Operating System. The function main() marks the start of the application and works with Windows Operating System. main() function should be included where the program usually starts. main() function should be included where the program usually starts. Windows can feed the required parameters to get things done smoothly. Windows can feed the required parameters to get things done smoothly. There are specific parameters which can be included usually considered as secondary parameters. There are specific parameters which can be included usually considered as secondary parameters. Print Add Notes Bookmark this page
[ { "code": null, "e": 2474, "s": 2298, "text": "This chapter involves the process of creating new application with DirectX using Visual Studio Code Editor. Following steps should be followed for creating an app in DirectX −" }, { "code": null, "e": 2596, "s": 2474, "text": "Here we will start by constructing a DirectX project with a walk through of the basic steps to get a working application." }, { "code": null, "e": 2878, "s": 2596, "text": "To create a DirectX “non-desktop” application, a special type of project called a “DirectX App” is used. This step involves opening a Visual Studio 2013, select File → New Project and select as “DirectX App” which comes under category of “Visual C++”, “Store App”, “Universal App”." }, { "code": null, "e": 3006, "s": 2878, "text": "Once the project is created, you will see a lot of files being populated. This is clearly visible in snapshot mentioned below −" }, { "code": null, "e": 3170, "s": 3006, "text": "User can delete various files to make up a sample app and explore the features to see how a fully-functioning DirectX app is set up as per the attributes required." }, { "code": null, "e": 3241, "s": 3170, "text": "As mentioned in the snapshot above, a file is created named “App.cpp”." }, { "code": null, "e": 3460, "s": 3241, "text": "#include <stdio.h> // include the standard input/output header file\nint main(void) { // our program starts here\n printf(\"Hello World!\"); // print \"Hello World!\" into the console\n return 0; // return 0 to windows\n}\n" }, { "code": null, "e": 3556, "s": 3460, "text": "The function main() marks the start of the application and works with Windows Operating System." }, { "code": null, "e": 3652, "s": 3556, "text": "The function main() marks the start of the application and works with Windows Operating System." }, { "code": null, "e": 3721, "s": 3652, "text": "main() function should be included where the program usually starts." }, { "code": null, "e": 3790, "s": 3721, "text": "main() function should be included where the program usually starts." }, { "code": null, "e": 3860, "s": 3790, "text": "Windows can feed the required parameters to get things done smoothly." }, { "code": null, "e": 3930, "s": 3860, "text": "Windows can feed the required parameters to get things done smoothly." }, { "code": null, "e": 4026, "s": 3930, "text": "There are specific parameters which can be included usually considered as secondary parameters." }, { "code": null, "e": 4122, "s": 4026, "text": "There are specific parameters which can be included usually considered as secondary parameters." }, { "code": null, "e": 4129, "s": 4122, "text": " Print" }, { "code": null, "e": 4140, "s": 4129, "text": " Add Notes" } ]
Deploy and Monitor your ML Application with Flask and WhyLabs | by Felipe de Pontes Adachi | Towards Data Science
One of the best milestones in every AI builder’s journey is the day when a model is ready to graduate from training and get deployed into production. According to a recent survey done by Algorithmia, most organizations already have more than 25 models in production. This underscores how enterprises are increasingly relying on ML to improve performance as intended outside of the lab. However, the post-deployment phase can be a difficult one for your ML model. Data scientists may think that the hard part’s over once a model is deployed, but the truth is the problems have only just begun. Data errors, broken pipelines, and model performance degradation will certainly come one day or another and, when this day comes, we must be prepared to debug and troubleshoot these problems efficiently. In order to have a reliable and robust ML system, observability is an absolute must. In this article, I’d like to share an approach on how to improve the observability of your ML application by efficiently logging and monitoring your models. To demonstrate, we’ll deploy a Flask application for pattern recognition based on the well-known Iris Dataset. On the monitoring part, we’ll explore the free, starter edition of the WhyLabs Observability Platform in order to set up our own model monitoring dashboard. From the dashboard, we’ll have access to all the statistics, metrics, and performance data gathered from every part of our ML pipeline. To interact with the platform, we’ll use whylogs, an open-source data logging library developed by WhyLabs. One of the key use cases for a monitoring dashboard is when there is an unexpected change in our data quality and/or consistency. On that account, we simulate one of the most common model failure scenarios, that of feature drift, meaning that there’s a change in our input’s distribution. We then use a monitoring dashboard to see how this kind of problem can be detected and debugged. While feature drift may or may not affect your model’s performance, observing this kind of change in production should always be a reason for further inspection and, possibly, model retraining. In summary, we’ll cover the step-by-step path to: Deploy the WhyLabs-integrated Flask API Test the application Inject Feature Drift and Explore the model dashboard If this is a problem that resonates with you, we’ve made the complete code for this tutorial available here for you to reuse. You’ll need to copy it onto your machine in order to follow this example. You’ll also need a Docker and, preferably, a Python environment management tool, such as Conda or pipenv. For those interested in the details, we’ve included a very thorough description and a Jupyter Notebook as a guideline. Let’s take a look at how the different components of our system interact with each other. We’ll deploy locally a Flask application, which is responsible for serving the user with the requested predictions through a REST endpoint. Our application will also use the whylogs library to create statistical profiles of both input and output features of our application during production. These statistical properties will then be sent in microbatches to WhyLabs at fixed intervals. WhyLabs merges them automatically, creating statistical profiles on a daily basis. There are various ways to upload your logged metrics into the platform. In this example, we’re uploading them periodically in microbatches, as shown in the diagram. Another option would be to upload them at each log step. In order to monitor our application, let’s first set up a WhyLabs account. Specifically, we’ll need two pieces of information: API token Organization ID Go to https://whylabs.ai/free and grab a free account. You can follow along with the examples if you wish, but if you’re interested in only following this demonstration, you can go ahead and skip the quick start instructions. After that, you’ll be prompted to create an API token, which you’ll use to interact with your dashboard. Once you create the token, copy it and store it in a safe place. The second important information here is your org ID. Take note of it as well. WhyLabs gives you an example code of how to create a session and send data to your dashboard. You can test it as well and check if data is getting through. Otherwise, after you get your API Token and Org ID, you can just go to https://hub.whylabsapp.com/models to see your shiny new model’s dashboard. To get to this step, we used the WhyLabs API Documentation, which also provides additional information about token creation and basic examples on how to use it. Once the dashboard is up and running, we can get started on deploying the application itself. We’ll serve a Flask application with Gunicorn, packaged into a Docker container to facilitate deployment. The first step will be configuring the connection to WhyLabs. In this example, we do that through the .whylogs_flask.yaml file. The writer can be set to either output data locally or to different locations, like, for example, S3, an MLFlow path, or directly to WhyLabs. In this file, we’ll also set the project’s name and other additional information. The application assumes the existence of a set of variables, so we’ll define them in a .env file. These are loaded later using the dotenv library. Copy the content below and replace the WHYLABS_API_KEY and WHYLABS_DEFAULT_ORG_ID values to the ones you got when creating your WhyLabs account. You can keep the other variables as is. Let’s talk about some of the other existing variables. WHYLABS_DEFAULT_DATASET_ID — The ID of your Dataset. Model-1 is the default value, created automatically once you create your account. Leave it unchanged if you haven’t sent anything to WhyLabs yet. But if it’s already populated, you can change it to model-2. Just remember to set up the new model in https://hub.whylabsapp.com/models. A new model-id will be assigned to the newly-created model, and you can use it in your .env file. ROTATION_TIME — Period used to send data to WhyLabs. In real applications, we might not need such frequent updates, but for this example, we set it to a low value so we don’t have to wait that long to make sure it’s working. The application will be run from inside a Docker container, but we’ll also run some pre-scripts (to download the data and train the model) and post-scripts (to send the requests), so let’s create an environment for this tutorial. If you’re using Conda, you can create it from the environment.yml configuration file: conda env create -f environment.yml If that doesn’t work out as expected, you can also create an environment from scratch: conda create -n whylogs-flask python=3.7.11conda activate whylogs-flask And then install directly from the requirements: python -m pip install -r requirements.txt If you look carefully, one of our environment variables is called MODEL_PATH. We don’t have a model yet, so let’s create it. We’ll use sklearn to train a simple SVC classification model from the Iris dataset and save it as model.joblib. From the root of our example’s folder, we can simply call the training routine: python train.py Now we have everything to actually run our application. To build the image, we define the Dockerfile below: And then build the image and run our container: docker build --build-arg PYTHON_VERSION=3.7 -t whylabs-flask:latest .docker run --rm -p 5000:5000 -v $(pwd):/app whylabs-flask This will start our application locally on port 5000. In this example, we’re running our Flask application as a WSGI HTTP Server with Gunicorn. By setting thereload variable, we’re able to debug more effectively, automatically reloading the workers when there’s a change in code. You should see a message from gunicorn starting the server: [2021-10-12 17:53:01 +0000] [1] [INFO] Starting gunicorn 20.1.0[2021-10-12 17:53:01 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)[2021-10-12 17:53:01 +0000] [1] [INFO] Using worker: sync[2021-10-12 17:53:01 +0000] [8] [INFO] Booting worker with pid: 8[2021-10-12 17:53:01 +0000] [20] [INFO] Booting worker with pid: 20 Once the Docker container is running, we should check if the API is functional. The application has two endpoints: /api/v1/health: Returns a 200 status response if the API is up and running. /api/v1/predict: Returns a predicted class given an input feature vector. The API is properly documented with Swagger, so you can head to http:127.0.0.1:5000/apidocs to explore the documentation: From /apidocs you’ll be able to see request examples to try out both endpoints, along with curl snippets, like: curl -X GET "http://127.0.0.1:5000/api/v1/health" -H "accept: application/json"curl -X POST "http://127.0.0.1:5000/api/v1/predict" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"petal_length_cm\": 0, \"petal_width_cm\": 0, \"sepal_length_cm\": 0, \"sepal_width_cm\": 0}" You should get a “healthy” response from the first command. Likewise, the response from the prediction request should be: { "data": { "class": "Iris-virginica" }, "message": "Success"} Ok, our application is serving our requests appropriately. Now, we can just check if data is reaching our dashboard safe and sound. It’s important to remember that data is not sent immediately, along with each request done. It’s rather sent periodically, according to the ROTATION_TIME environment variable defined in the .env file. In this example, it was set to 5 minutes, which means that we’ll have to wait 5 minutes before the information is sent to our dashboard. Then, we should see a message from whylogs indicating that the upload is complete. Once the upload is complete, the received information should be available in your model’s dashboard within minutes. From your model’s dashboard, you can check if any profile was logged, and access your summary’s dashboard: So far, we have 1 profile logged and 5 features, which means data is getting through. Now, let’s explore the platform a bit more with a use-case: We’ll add some outliers to our data distribution and see how that is reflected in our dashboard. The real value of any observability platform surfaces when things go wrong. Things can go wrong in a lot of different ways, but for this demonstration let’s pick a specific one: feature drift. The drift phenomenon in the context of Machine Learning can be a lengthy subject, so in this case, we’ll limit ourselves to a basic definition of feature drift: when there is a change of distribution of the model’s input. We’ll use a collection of 150 unchanged samples from the Iris dataset to represent the normal distribution of a daily batch. Then, to represent the anomalous batch, we’ll take the same set of samples, except we’ll replace 30 of these samples for random outliers to one random input feature. We’ll proceed to request predictions with input features as follows: Day 1 — Normal data Day 2 — Modified Data (Changed Distribution) Day 3 — Normal Data The code snippet below will make 150 requests with unchanged input features. For the second day, we simply change the code to pass data_mod as the payload instead of data (line 35) and repeat the process. For this demonstration, the outliers were added to the sepal_width feature. Let’s take a brief look at some sections from our dashboard. From the inputs page, there’s a lot of useful information, such as count for the number of records in each batch, null fraction, and inferred feature type. One particularly useful piece of information is the Distribution Distance. This is a time series that shows the feature’s mean statistical distance to previous batches of data over the selected date range, using the Hellinger Distance to estimate the distances between distributions. By adding the outliers in the sepal_width feature, we see a change in the distribution distance not only for the sepal_width feature itself but also on the prediction results. Note: For the remaining features, the distance seems to increase for the last day. That was actually a mistake on my part, as I sent 1 additional record, for a total of 151 records. Since the graphs are not in scale between features, the effect of this change seems high, but when inspecting the values themselves, the additional record yielded a distribution distance of 0.02. We can further inspect the individual features by clicking on them. From the distribution graphs, we can see the drift’s effects on both class and sepal_width features. In the profiles section, we can select up to 3 dataset profiles for comparison, which is a very cool feature. In the image below, I selected a few features in each profile for comparison. As previously, the changes caused by adding the outliers are also very apparent. While we won’t be able to discuss every available feature here, some of my favorites are: Manual thresholds configuration for each feature monitor Notification scheduling for email/Slack Uploading training set as a baseline reference set Segment data during profiling Feel free to explore them on your own! The post-deployment phase of ML applications presents us with countless challenges and the process of troubleshooting these applications can still be very manual and cumbersome. In this post, we covered an example of how to ease this burden by improving our system’s observability with WhyLabs. We covered a simple example of deploying a Flask application for classification, based on the well-known Iris dataset, and integrated it with the WhyLabs platform using the whylogs data logging library. We also simulated a Feature Drift scenario by injecting outliers to our input in order to see how that is reflected in our monitoring dashboard. Even though it’s a very simple use case, this example can be easily adapted to cover more tailored scenarios. Thank you for reading, and feel free to reach out if you have any questions/suggestions! If you try it out and have questions, I’ve found the WhyLabs community on Slack very helpful and responsive.
[ { "code": null, "e": 928, "s": 46, "text": "One of the best milestones in every AI builder’s journey is the day when a model is ready to graduate from training and get deployed into production. According to a recent survey done by Algorithmia, most organizations already have more than 25 models in production. This underscores how enterprises are increasingly relying on ML to improve performance as intended outside of the lab. However, the post-deployment phase can be a difficult one for your ML model. Data scientists may think that the hard part’s over once a model is deployed, but the truth is the problems have only just begun. Data errors, broken pipelines, and model performance degradation will certainly come one day or another and, when this day comes, we must be prepared to debug and troubleshoot these problems efficiently. In order to have a reliable and robust ML system, observability is an absolute must." }, { "code": null, "e": 1597, "s": 928, "text": "In this article, I’d like to share an approach on how to improve the observability of your ML application by efficiently logging and monitoring your models. To demonstrate, we’ll deploy a Flask application for pattern recognition based on the well-known Iris Dataset. On the monitoring part, we’ll explore the free, starter edition of the WhyLabs Observability Platform in order to set up our own model monitoring dashboard. From the dashboard, we’ll have access to all the statistics, metrics, and performance data gathered from every part of our ML pipeline. To interact with the platform, we’ll use whylogs, an open-source data logging library developed by WhyLabs." }, { "code": null, "e": 2177, "s": 1597, "text": "One of the key use cases for a monitoring dashboard is when there is an unexpected change in our data quality and/or consistency. On that account, we simulate one of the most common model failure scenarios, that of feature drift, meaning that there’s a change in our input’s distribution. We then use a monitoring dashboard to see how this kind of problem can be detected and debugged. While feature drift may or may not affect your model’s performance, observing this kind of change in production should always be a reason for further inspection and, possibly, model retraining." }, { "code": null, "e": 2227, "s": 2177, "text": "In summary, we’ll cover the step-by-step path to:" }, { "code": null, "e": 2267, "s": 2227, "text": "Deploy the WhyLabs-integrated Flask API" }, { "code": null, "e": 2288, "s": 2267, "text": "Test the application" }, { "code": null, "e": 2341, "s": 2288, "text": "Inject Feature Drift and Explore the model dashboard" }, { "code": null, "e": 2766, "s": 2341, "text": "If this is a problem that resonates with you, we’ve made the complete code for this tutorial available here for you to reuse. You’ll need to copy it onto your machine in order to follow this example. You’ll also need a Docker and, preferably, a Python environment management tool, such as Conda or pipenv. For those interested in the details, we’ve included a very thorough description and a Jupyter Notebook as a guideline." }, { "code": null, "e": 2856, "s": 2766, "text": "Let’s take a look at how the different components of our system interact with each other." }, { "code": null, "e": 3326, "s": 2856, "text": "We’ll deploy locally a Flask application, which is responsible for serving the user with the requested predictions through a REST endpoint. Our application will also use the whylogs library to create statistical profiles of both input and output features of our application during production. These statistical properties will then be sent in microbatches to WhyLabs at fixed intervals. WhyLabs merges them automatically, creating statistical profiles on a daily basis." }, { "code": null, "e": 3548, "s": 3326, "text": "There are various ways to upload your logged metrics into the platform. In this example, we’re uploading them periodically in microbatches, as shown in the diagram. Another option would be to upload them at each log step." }, { "code": null, "e": 3675, "s": 3548, "text": "In order to monitor our application, let’s first set up a WhyLabs account. Specifically, we’ll need two pieces of information:" }, { "code": null, "e": 3685, "s": 3675, "text": "API token" }, { "code": null, "e": 3701, "s": 3685, "text": "Organization ID" }, { "code": null, "e": 3927, "s": 3701, "text": "Go to https://whylabs.ai/free and grab a free account. You can follow along with the examples if you wish, but if you’re interested in only following this demonstration, you can go ahead and skip the quick start instructions." }, { "code": null, "e": 4639, "s": 3927, "text": "After that, you’ll be prompted to create an API token, which you’ll use to interact with your dashboard. Once you create the token, copy it and store it in a safe place. The second important information here is your org ID. Take note of it as well. WhyLabs gives you an example code of how to create a session and send data to your dashboard. You can test it as well and check if data is getting through. Otherwise, after you get your API Token and Org ID, you can just go to https://hub.whylabsapp.com/models to see your shiny new model’s dashboard. To get to this step, we used the WhyLabs API Documentation, which also provides additional information about token creation and basic examples on how to use it." }, { "code": null, "e": 4839, "s": 4639, "text": "Once the dashboard is up and running, we can get started on deploying the application itself. We’ll serve a Flask application with Gunicorn, packaged into a Docker container to facilitate deployment." }, { "code": null, "e": 5191, "s": 4839, "text": "The first step will be configuring the connection to WhyLabs. In this example, we do that through the .whylogs_flask.yaml file. The writer can be set to either output data locally or to different locations, like, for example, S3, an MLFlow path, or directly to WhyLabs. In this file, we’ll also set the project’s name and other additional information." }, { "code": null, "e": 5523, "s": 5191, "text": "The application assumes the existence of a set of variables, so we’ll define them in a .env file. These are loaded later using the dotenv library. Copy the content below and replace the WHYLABS_API_KEY and WHYLABS_DEFAULT_ORG_ID values to the ones you got when creating your WhyLabs account. You can keep the other variables as is." }, { "code": null, "e": 5578, "s": 5523, "text": "Let’s talk about some of the other existing variables." }, { "code": null, "e": 6012, "s": 5578, "text": "WHYLABS_DEFAULT_DATASET_ID — The ID of your Dataset. Model-1 is the default value, created automatically once you create your account. Leave it unchanged if you haven’t sent anything to WhyLabs yet. But if it’s already populated, you can change it to model-2. Just remember to set up the new model in https://hub.whylabsapp.com/models. A new model-id will be assigned to the newly-created model, and you can use it in your .env file." }, { "code": null, "e": 6237, "s": 6012, "text": "ROTATION_TIME — Period used to send data to WhyLabs. In real applications, we might not need such frequent updates, but for this example, we set it to a low value so we don’t have to wait that long to make sure it’s working." }, { "code": null, "e": 6553, "s": 6237, "text": "The application will be run from inside a Docker container, but we’ll also run some pre-scripts (to download the data and train the model) and post-scripts (to send the requests), so let’s create an environment for this tutorial. If you’re using Conda, you can create it from the environment.yml configuration file:" }, { "code": null, "e": 6589, "s": 6553, "text": "conda env create -f environment.yml" }, { "code": null, "e": 6676, "s": 6589, "text": "If that doesn’t work out as expected, you can also create an environment from scratch:" }, { "code": null, "e": 6748, "s": 6676, "text": "conda create -n whylogs-flask python=3.7.11conda activate whylogs-flask" }, { "code": null, "e": 6797, "s": 6748, "text": "And then install directly from the requirements:" }, { "code": null, "e": 6839, "s": 6797, "text": "python -m pip install -r requirements.txt" }, { "code": null, "e": 7156, "s": 6839, "text": "If you look carefully, one of our environment variables is called MODEL_PATH. We don’t have a model yet, so let’s create it. We’ll use sklearn to train a simple SVC classification model from the Iris dataset and save it as model.joblib. From the root of our example’s folder, we can simply call the training routine:" }, { "code": null, "e": 7172, "s": 7156, "text": "python train.py" }, { "code": null, "e": 7280, "s": 7172, "text": "Now we have everything to actually run our application. To build the image, we define the Dockerfile below:" }, { "code": null, "e": 7328, "s": 7280, "text": "And then build the image and run our container:" }, { "code": null, "e": 7456, "s": 7328, "text": "docker build --build-arg PYTHON_VERSION=3.7 -t whylabs-flask:latest .docker run --rm -p 5000:5000 -v $(pwd):/app whylabs-flask" }, { "code": null, "e": 7736, "s": 7456, "text": "This will start our application locally on port 5000. In this example, we’re running our Flask application as a WSGI HTTP Server with Gunicorn. By setting thereload variable, we’re able to debug more effectively, automatically reloading the workers when there’s a change in code." }, { "code": null, "e": 7796, "s": 7736, "text": "You should see a message from gunicorn starting the server:" }, { "code": null, "e": 8125, "s": 7796, "text": "[2021-10-12 17:53:01 +0000] [1] [INFO] Starting gunicorn 20.1.0[2021-10-12 17:53:01 +0000] [1] [INFO] Listening at: http://0.0.0.0:5000 (1)[2021-10-12 17:53:01 +0000] [1] [INFO] Using worker: sync[2021-10-12 17:53:01 +0000] [8] [INFO] Booting worker with pid: 8[2021-10-12 17:53:01 +0000] [20] [INFO] Booting worker with pid: 20" }, { "code": null, "e": 8240, "s": 8125, "text": "Once the Docker container is running, we should check if the API is functional. The application has two endpoints:" }, { "code": null, "e": 8316, "s": 8240, "text": "/api/v1/health: Returns a 200 status response if the API is up and running." }, { "code": null, "e": 8390, "s": 8316, "text": "/api/v1/predict: Returns a predicted class given an input feature vector." }, { "code": null, "e": 8512, "s": 8390, "text": "The API is properly documented with Swagger, so you can head to http:127.0.0.1:5000/apidocs to explore the documentation:" }, { "code": null, "e": 8624, "s": 8512, "text": "From /apidocs you’ll be able to see request examples to try out both endpoints, along with curl snippets, like:" }, { "code": null, "e": 8922, "s": 8624, "text": "curl -X GET \"http://127.0.0.1:5000/api/v1/health\" -H \"accept: application/json\"curl -X POST \"http://127.0.0.1:5000/api/v1/predict\" -H \"accept: application/json\" -H \"Content-Type: application/json\" -d \"{ \\\"petal_length_cm\\\": 0, \\\"petal_width_cm\\\": 0, \\\"sepal_length_cm\\\": 0, \\\"sepal_width_cm\\\": 0}\"" }, { "code": null, "e": 9044, "s": 8922, "text": "You should get a “healthy” response from the first command. Likewise, the response from the prediction request should be:" }, { "code": null, "e": 9114, "s": 9044, "text": "{ \"data\": { \"class\": \"Iris-virginica\" }, \"message\": \"Success\"}" }, { "code": null, "e": 9246, "s": 9114, "text": "Ok, our application is serving our requests appropriately. Now, we can just check if data is reaching our dashboard safe and sound." }, { "code": null, "e": 9667, "s": 9246, "text": "It’s important to remember that data is not sent immediately, along with each request done. It’s rather sent periodically, according to the ROTATION_TIME environment variable defined in the .env file. In this example, it was set to 5 minutes, which means that we’ll have to wait 5 minutes before the information is sent to our dashboard. Then, we should see a message from whylogs indicating that the upload is complete." }, { "code": null, "e": 9890, "s": 9667, "text": "Once the upload is complete, the received information should be available in your model’s dashboard within minutes. From your model’s dashboard, you can check if any profile was logged, and access your summary’s dashboard:" }, { "code": null, "e": 10133, "s": 9890, "text": "So far, we have 1 profile logged and 5 features, which means data is getting through. Now, let’s explore the platform a bit more with a use-case: We’ll add some outliers to our data distribution and see how that is reflected in our dashboard." }, { "code": null, "e": 10326, "s": 10133, "text": "The real value of any observability platform surfaces when things go wrong. Things can go wrong in a lot of different ways, but for this demonstration let’s pick a specific one: feature drift." }, { "code": null, "e": 10548, "s": 10326, "text": "The drift phenomenon in the context of Machine Learning can be a lengthy subject, so in this case, we’ll limit ourselves to a basic definition of feature drift: when there is a change of distribution of the model’s input." }, { "code": null, "e": 10908, "s": 10548, "text": "We’ll use a collection of 150 unchanged samples from the Iris dataset to represent the normal distribution of a daily batch. Then, to represent the anomalous batch, we’ll take the same set of samples, except we’ll replace 30 of these samples for random outliers to one random input feature. We’ll proceed to request predictions with input features as follows:" }, { "code": null, "e": 10928, "s": 10908, "text": "Day 1 — Normal data" }, { "code": null, "e": 10973, "s": 10928, "text": "Day 2 — Modified Data (Changed Distribution)" }, { "code": null, "e": 10993, "s": 10973, "text": "Day 3 — Normal Data" }, { "code": null, "e": 11274, "s": 10993, "text": "The code snippet below will make 150 requests with unchanged input features. For the second day, we simply change the code to pass data_mod as the payload instead of data (line 35) and repeat the process. For this demonstration, the outliers were added to the sepal_width feature." }, { "code": null, "e": 11491, "s": 11274, "text": "Let’s take a brief look at some sections from our dashboard. From the inputs page, there’s a lot of useful information, such as count for the number of records in each batch, null fraction, and inferred feature type." }, { "code": null, "e": 11951, "s": 11491, "text": "One particularly useful piece of information is the Distribution Distance. This is a time series that shows the feature’s mean statistical distance to previous batches of data over the selected date range, using the Hellinger Distance to estimate the distances between distributions. By adding the outliers in the sepal_width feature, we see a change in the distribution distance not only for the sepal_width feature itself but also on the prediction results." }, { "code": null, "e": 12329, "s": 11951, "text": "Note: For the remaining features, the distance seems to increase for the last day. That was actually a mistake on my part, as I sent 1 additional record, for a total of 151 records. Since the graphs are not in scale between features, the effect of this change seems high, but when inspecting the values themselves, the additional record yielded a distribution distance of 0.02." }, { "code": null, "e": 12498, "s": 12329, "text": "We can further inspect the individual features by clicking on them. From the distribution graphs, we can see the drift’s effects on both class and sepal_width features." }, { "code": null, "e": 12767, "s": 12498, "text": "In the profiles section, we can select up to 3 dataset profiles for comparison, which is a very cool feature. In the image below, I selected a few features in each profile for comparison. As previously, the changes caused by adding the outliers are also very apparent." }, { "code": null, "e": 12857, "s": 12767, "text": "While we won’t be able to discuss every available feature here, some of my favorites are:" }, { "code": null, "e": 12914, "s": 12857, "text": "Manual thresholds configuration for each feature monitor" }, { "code": null, "e": 12954, "s": 12914, "text": "Notification scheduling for email/Slack" }, { "code": null, "e": 13005, "s": 12954, "text": "Uploading training set as a baseline reference set" }, { "code": null, "e": 13035, "s": 13005, "text": "Segment data during profiling" }, { "code": null, "e": 13074, "s": 13035, "text": "Feel free to explore them on your own!" }, { "code": null, "e": 13369, "s": 13074, "text": "The post-deployment phase of ML applications presents us with countless challenges and the process of troubleshooting these applications can still be very manual and cumbersome. In this post, we covered an example of how to ease this burden by improving our system’s observability with WhyLabs." }, { "code": null, "e": 13827, "s": 13369, "text": "We covered a simple example of deploying a Flask application for classification, based on the well-known Iris dataset, and integrated it with the WhyLabs platform using the whylogs data logging library. We also simulated a Feature Drift scenario by injecting outliers to our input in order to see how that is reflected in our monitoring dashboard. Even though it’s a very simple use case, this example can be easily adapted to cover more tailored scenarios." } ]
Python - Draw Star Using Turtle Graphics - GeeksforGeeks
16 Oct, 2020 In this article, we will learn how to make a Star using Turtle Graphics in Python. For that let’s first know what is Turtle Graphics. Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways. Some commonly used methods are: forward(length): moves the pen in the forward direction by x unit. backward(length): moves the pen in the backward direction by x unit. right(angle): rotate the pen in the clockwise direction by an angle x. left(angle): rotate the pen in the anticlockwise direction by an angle x. penup(): stop drawing of the turtle pen. pendown(): start drawing of the turtle pen. First import turtle module in the idle or editor you are using. import turtle Get a screen board on which turtle will draw. ws=turtle.Screen() A screen like this will appear:- Define an instance for turtle. For a drawing, a Star executes a loop 5 times. In every iteration move the turtle 100 units forward and move it right 144 degrees. This will make up an angle 36 degrees inside a star. 5 iterations will make up a Star perfectly. Below is the python implementation of the above approach. First way : Python3 # import for turtleimport turtle # Starting a Working Screenws = turtle.Screen() # initializing a turtle instancegeekyTurtle = turtle.Turtle() # executing loop 5 times for a starfor i in range(5): # moving turtle 100 units forward geekyTurtle.forward(100) # rotating turtle 144 degree right geekyTurtle.right(144) Turtle Making A Star Alternate Approach: Python3 #import turtleimport turtle # set screenScreen = turtle.Turtle() # decide colorscir= ['red','green','blue','yellow','purple'] # decide pensizeturtle.pensize(4) # Draw star patternturtle.penup()turtle.setpos(-90,30)turtle.pendown()for i in range(5): turtle.pencolor(cir[i]) turtle.forward(200) turtle.right(144) turtle.penup()turtle.setpos(80,-140)turtle.pendown() # choose pen colorturtle.pencolor("Black")turtle.done() Output:- anshitaagarwal Python-turtle Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not
[ { "code": null, "e": 24213, "s": 24185, "text": "\n16 Oct, 2020" }, { "code": null, "e": 24347, "s": 24213, "text": "In this article, we will learn how to make a Star using Turtle Graphics in Python. For that let’s first know what is Turtle Graphics." }, { "code": null, "e": 24635, "s": 24347, "text": "Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways." }, { "code": null, "e": 24667, "s": 24635, "text": "Some commonly used methods are:" }, { "code": null, "e": 24734, "s": 24667, "text": "forward(length): moves the pen in the forward direction by x unit." }, { "code": null, "e": 24803, "s": 24734, "text": "backward(length): moves the pen in the backward direction by x unit." }, { "code": null, "e": 24874, "s": 24803, "text": "right(angle): rotate the pen in the clockwise direction by an angle x." }, { "code": null, "e": 24948, "s": 24874, "text": "left(angle): rotate the pen in the anticlockwise direction by an angle x." }, { "code": null, "e": 24989, "s": 24948, "text": "penup(): stop drawing of the turtle pen." }, { "code": null, "e": 25033, "s": 24989, "text": "pendown(): start drawing of the turtle pen." }, { "code": null, "e": 25097, "s": 25033, "text": "First import turtle module in the idle or editor you are using." }, { "code": null, "e": 25112, "s": 25097, "text": "import turtle\n" }, { "code": null, "e": 25158, "s": 25112, "text": "Get a screen board on which turtle will draw." }, { "code": null, "e": 25178, "s": 25158, "text": "ws=turtle.Screen()\n" }, { "code": null, "e": 25211, "s": 25178, "text": "A screen like this will appear:-" }, { "code": null, "e": 25242, "s": 25211, "text": "Define an instance for turtle." }, { "code": null, "e": 25289, "s": 25242, "text": "For a drawing, a Star executes a loop 5 times." }, { "code": null, "e": 25373, "s": 25289, "text": "In every iteration move the turtle 100 units forward and move it right 144 degrees." }, { "code": null, "e": 25426, "s": 25373, "text": "This will make up an angle 36 degrees inside a star." }, { "code": null, "e": 25470, "s": 25426, "text": "5 iterations will make up a Star perfectly." }, { "code": null, "e": 25528, "s": 25470, "text": "Below is the python implementation of the above approach." }, { "code": null, "e": 25540, "s": 25528, "text": "First way :" }, { "code": null, "e": 25548, "s": 25540, "text": "Python3" }, { "code": "# import for turtleimport turtle # Starting a Working Screenws = turtle.Screen() # initializing a turtle instancegeekyTurtle = turtle.Turtle() # executing loop 5 times for a starfor i in range(5): # moving turtle 100 units forward geekyTurtle.forward(100) # rotating turtle 144 degree right geekyTurtle.right(144)", "e": 25892, "s": 25548, "text": null }, { "code": null, "e": 25916, "s": 25895, "text": "Turtle Making A Star" }, { "code": null, "e": 25936, "s": 25916, "text": "Alternate Approach:" }, { "code": null, "e": 25944, "s": 25936, "text": "Python3" }, { "code": "#import turtleimport turtle # set screenScreen = turtle.Turtle() # decide colorscir= ['red','green','blue','yellow','purple'] # decide pensizeturtle.pensize(4) # Draw star patternturtle.penup()turtle.setpos(-90,30)turtle.pendown()for i in range(5): turtle.pencolor(cir[i]) turtle.forward(200) turtle.right(144) turtle.penup()turtle.setpos(80,-140)turtle.pendown() # choose pen colorturtle.pencolor(\"Black\")turtle.done()", "e": 26373, "s": 25944, "text": null }, { "code": null, "e": 26382, "s": 26373, "text": "Output:-" }, { "code": null, "e": 26399, "s": 26384, "text": "anshitaagarwal" }, { "code": null, "e": 26413, "s": 26399, "text": "Python-turtle" }, { "code": null, "e": 26420, "s": 26413, "text": "Python" }, { "code": null, "e": 26436, "s": 26420, "text": "Python Programs" }, { "code": null, "e": 26534, "s": 26436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26543, "s": 26534, "text": "Comments" }, { "code": null, "e": 26556, "s": 26543, "text": "Old Comments" }, { "code": null, "e": 26574, "s": 26556, "text": "Python Dictionary" }, { "code": null, "e": 26609, "s": 26574, "text": "Read a file line by line in Python" }, { "code": null, "e": 26631, "s": 26609, "text": "Enumerate() in Python" }, { "code": null, "e": 26663, "s": 26631, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26693, "s": 26663, "text": "Iterate over a list in Python" }, { "code": null, "e": 26736, "s": 26693, "text": "Python program to convert a list to string" }, { "code": null, "e": 26758, "s": 26736, "text": "Defaultdict in Python" }, { "code": null, "e": 26797, "s": 26758, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26843, "s": 26797, "text": "Python | Split string into list of characters" } ]
Pandas vs Tidyverse on Textual Data | by Soner Yıldırım | Towards Data Science
Textual data does not usually come in a nice and clean format so it requires a lot of preprocessing and manipulation. A substantial amount or raw data is textual so a data analysis library should be able to handle strings very well. In this article, we will compare two popular libraries in terms of working on strings. The first one is pandas, a data analysis and manipulation library for Python. The other is the tidyverse which is a collection of R packages designed for data science. We will be using the cities dataframe for the examples in Pandas. I have also created a tibble that contains the same data using the readr package in R. Pandas: The string functions and methods can be used using the str accessor. The split function splits a string at the given character. The city column includes both city and state names. We can create a new column for the state part. import pandas as pdcities.city.str.split(",")0 [Houston, TX]1 [Dallas, TX]2 [Seattle, WA]3 [Atlanta, GA] Each value in the returned series is a list of city and state. We can assign a new column to the state part by extracting it using str indexing. cities['state'] = cities.city.str.split(",").str[1] Tidyverse: Tidyverse is a collection of packages. We will be using the following packages of tidyverse to work on the cities tibble (same as dataframe in pandas) readr: Create a tibble from a csv file dplyr: Data manipulation on tibble stringr: Functions on strings cities <- mutate(cities, state = str_split_fixed(city, ",", n=2)[,2]) The mutate function of dplyr package can be used to create new columns based on the existing ones. The str_split_fixed function of stringr package splits the city column at comma. Since there are two words in each values, the n parameter is 2. Finally, we select the second part after splitting. Converting strings to upper or lower case is a common operation to have consistent values. Let’s convert the “ctg1” column to upper case letters. Pandas: The upper function is used as follows. cities['ctg1'] = cities['ctg1'].str.upper() Tidyverse: The str_to_upper function of stringr package is used as follows. cities <- mutate(cities, ctg1 = str_to_upper(ctg1)) Just like we split strings, we may also need to combine them. For instance, we can create a new category column by combining the “ctg1” and “ctg2” columns. Pandas: The cat function of str accessor is used. We specify the character to be used as separator along with the column names. cities['new_ctg'] = cities['ctg1'].str.cat(cities['ctg2'], sep="-") Tidyverse: The str_c function of the stringr package is used. cities <- mutate(cities, new_ctg = str_c(ctg1, ctg2, sep="-")) We can inspect string to check if they contains a specific character or a set of characters. Let’s create a new column indicating if the “new_ctg” column contains the letter “f”. Pandas: The function to use is pretty self-explanatory. cities["is_f"] = cities.new_ctg.str.contains("f") Tidyverse: The str_detect function of the stringr package accomplishes what the contains function of pandas does. cities <- mutate(cities, is_f = str_detect(new_ctg, "f")) Strings can be considered as a collection of characters. They do not have to be words or meaningful textual data. For instance, “foo123” is a valid string. Indexing or slicing on strings is a highly practical operations in data manipulation. We can extract any part of strings by providing the indices. Both pandas and tidyverse provide functions to extract part of strings based on an index of characters. Let’s create a new column by extracting the last two characters of the “ctg2” column. Pandas: We can pass the index from the beginning starting from 0 or from the end starting from -1. Since we need the last two, it is more convenient to use the one from the end. cities["sub_ctg2"] = cities.ctg2.str[-2:] The start and end of the desired part of string is specified by passing the related indices to the str accessor. The starting index is the second from the end (-2). The ending index is left blank to indicate the end of string. Tidyverse The same operation can be done using the str_sub function as follows: cities <- mutate(cities, sub_ctg2 = str_sub(ctg2, -2, -1)) In some cases, we may need the length of a string in terms of the number of characters it contains. How many times a particular character exists in a string can also be a useful piece of information. Pandas: The len function returns the length of a string and the count function returns the number of occurrences of a character in a string. # Length of citiescities.city.str.len()0 101 92 103 10# How many "a" exists in city namescities.city.str.count("a")0 01 22 13 2 Tidyverse: The name of the functions are quite similar to those in pandas. We just need to add “str” at the beginning. # Number of occurrencesstr_count("Houston", "o")[1] 2# Length of a stringstr_length("Houston")[1] 7 We have covered some basic operations that are commonly used to manipulate strings. Both pandas and tidyverse are highly efficient at performing such tasks. There are many more operations that can be done to manipulate or transform strings. I think what we covered in this article is enough to warm you up. In a later article, I plan to demonstrate more complex operations on strings using both pandas and tidyverse. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 404, "s": 171, "text": "Textual data does not usually come in a nice and clean format so it requires a lot of preprocessing and manipulation. A substantial amount or raw data is textual so a data analysis library should be able to handle strings very well." }, { "code": null, "e": 659, "s": 404, "text": "In this article, we will compare two popular libraries in terms of working on strings. The first one is pandas, a data analysis and manipulation library for Python. The other is the tidyverse which is a collection of R packages designed for data science." }, { "code": null, "e": 812, "s": 659, "text": "We will be using the cities dataframe for the examples in Pandas. I have also created a tibble that contains the same data using the readr package in R." }, { "code": null, "e": 820, "s": 812, "text": "Pandas:" }, { "code": null, "e": 948, "s": 820, "text": "The string functions and methods can be used using the str accessor. The split function splits a string at the given character." }, { "code": null, "e": 1047, "s": 948, "text": "The city column includes both city and state names. We can create a new column for the state part." }, { "code": null, "e": 1165, "s": 1047, "text": "import pandas as pdcities.city.str.split(\",\")0 [Houston, TX]1 [Dallas, TX]2 [Seattle, WA]3 [Atlanta, GA]" }, { "code": null, "e": 1310, "s": 1165, "text": "Each value in the returned series is a list of city and state. We can assign a new column to the state part by extracting it using str indexing." }, { "code": null, "e": 1362, "s": 1310, "text": "cities['state'] = cities.city.str.split(\",\").str[1]" }, { "code": null, "e": 1373, "s": 1362, "text": "Tidyverse:" }, { "code": null, "e": 1524, "s": 1373, "text": "Tidyverse is a collection of packages. We will be using the following packages of tidyverse to work on the cities tibble (same as dataframe in pandas)" }, { "code": null, "e": 1563, "s": 1524, "text": "readr: Create a tibble from a csv file" }, { "code": null, "e": 1598, "s": 1563, "text": "dplyr: Data manipulation on tibble" }, { "code": null, "e": 1628, "s": 1598, "text": "stringr: Functions on strings" }, { "code": null, "e": 1698, "s": 1628, "text": "cities <- mutate(cities, state = str_split_fixed(city, \",\", n=2)[,2])" }, { "code": null, "e": 1797, "s": 1698, "text": "The mutate function of dplyr package can be used to create new columns based on the existing ones." }, { "code": null, "e": 1994, "s": 1797, "text": "The str_split_fixed function of stringr package splits the city column at comma. Since there are two words in each values, the n parameter is 2. Finally, we select the second part after splitting." }, { "code": null, "e": 2085, "s": 1994, "text": "Converting strings to upper or lower case is a common operation to have consistent values." }, { "code": null, "e": 2140, "s": 2085, "text": "Let’s convert the “ctg1” column to upper case letters." }, { "code": null, "e": 2148, "s": 2140, "text": "Pandas:" }, { "code": null, "e": 2187, "s": 2148, "text": "The upper function is used as follows." }, { "code": null, "e": 2231, "s": 2187, "text": "cities['ctg1'] = cities['ctg1'].str.upper()" }, { "code": null, "e": 2242, "s": 2231, "text": "Tidyverse:" }, { "code": null, "e": 2307, "s": 2242, "text": "The str_to_upper function of stringr package is used as follows." }, { "code": null, "e": 2359, "s": 2307, "text": "cities <- mutate(cities, ctg1 = str_to_upper(ctg1))" }, { "code": null, "e": 2515, "s": 2359, "text": "Just like we split strings, we may also need to combine them. For instance, we can create a new category column by combining the “ctg1” and “ctg2” columns." }, { "code": null, "e": 2523, "s": 2515, "text": "Pandas:" }, { "code": null, "e": 2643, "s": 2523, "text": "The cat function of str accessor is used. We specify the character to be used as separator along with the column names." }, { "code": null, "e": 2711, "s": 2643, "text": "cities['new_ctg'] = cities['ctg1'].str.cat(cities['ctg2'], sep=\"-\")" }, { "code": null, "e": 2722, "s": 2711, "text": "Tidyverse:" }, { "code": null, "e": 2773, "s": 2722, "text": "The str_c function of the stringr package is used." }, { "code": null, "e": 2836, "s": 2773, "text": "cities <- mutate(cities, new_ctg = str_c(ctg1, ctg2, sep=\"-\"))" }, { "code": null, "e": 3015, "s": 2836, "text": "We can inspect string to check if they contains a specific character or a set of characters. Let’s create a new column indicating if the “new_ctg” column contains the letter “f”." }, { "code": null, "e": 3023, "s": 3015, "text": "Pandas:" }, { "code": null, "e": 3071, "s": 3023, "text": "The function to use is pretty self-explanatory." }, { "code": null, "e": 3121, "s": 3071, "text": "cities[\"is_f\"] = cities.new_ctg.str.contains(\"f\")" }, { "code": null, "e": 3132, "s": 3121, "text": "Tidyverse:" }, { "code": null, "e": 3235, "s": 3132, "text": "The str_detect function of the stringr package accomplishes what the contains function of pandas does." }, { "code": null, "e": 3293, "s": 3235, "text": "cities <- mutate(cities, is_f = str_detect(new_ctg, \"f\"))" }, { "code": null, "e": 3449, "s": 3293, "text": "Strings can be considered as a collection of characters. They do not have to be words or meaningful textual data. For instance, “foo123” is a valid string." }, { "code": null, "e": 3700, "s": 3449, "text": "Indexing or slicing on strings is a highly practical operations in data manipulation. We can extract any part of strings by providing the indices. Both pandas and tidyverse provide functions to extract part of strings based on an index of characters." }, { "code": null, "e": 3786, "s": 3700, "text": "Let’s create a new column by extracting the last two characters of the “ctg2” column." }, { "code": null, "e": 3794, "s": 3786, "text": "Pandas:" }, { "code": null, "e": 3964, "s": 3794, "text": "We can pass the index from the beginning starting from 0 or from the end starting from -1. Since we need the last two, it is more convenient to use the one from the end." }, { "code": null, "e": 4006, "s": 3964, "text": "cities[\"sub_ctg2\"] = cities.ctg2.str[-2:]" }, { "code": null, "e": 4233, "s": 4006, "text": "The start and end of the desired part of string is specified by passing the related indices to the str accessor. The starting index is the second from the end (-2). The ending index is left blank to indicate the end of string." }, { "code": null, "e": 4243, "s": 4233, "text": "Tidyverse" }, { "code": null, "e": 4313, "s": 4243, "text": "The same operation can be done using the str_sub function as follows:" }, { "code": null, "e": 4372, "s": 4313, "text": "cities <- mutate(cities, sub_ctg2 = str_sub(ctg2, -2, -1))" }, { "code": null, "e": 4572, "s": 4372, "text": "In some cases, we may need the length of a string in terms of the number of characters it contains. How many times a particular character exists in a string can also be a useful piece of information." }, { "code": null, "e": 4580, "s": 4572, "text": "Pandas:" }, { "code": null, "e": 4713, "s": 4580, "text": "The len function returns the length of a string and the count function returns the number of occurrences of a character in a string." }, { "code": null, "e": 4866, "s": 4713, "text": "# Length of citiescities.city.str.len()0 101 92 103 10# How many \"a\" exists in city namescities.city.str.count(\"a\")0 01 22 13 2" }, { "code": null, "e": 4877, "s": 4866, "text": "Tidyverse:" }, { "code": null, "e": 4985, "s": 4877, "text": "The name of the functions are quite similar to those in pandas. We just need to add “str” at the beginning." }, { "code": null, "e": 5085, "s": 4985, "text": "# Number of occurrencesstr_count(\"Houston\", \"o\")[1] 2# Length of a stringstr_length(\"Houston\")[1] 7" }, { "code": null, "e": 5242, "s": 5085, "text": "We have covered some basic operations that are commonly used to manipulate strings. Both pandas and tidyverse are highly efficient at performing such tasks." }, { "code": null, "e": 5502, "s": 5242, "text": "There are many more operations that can be done to manipulate or transform strings. I think what we covered in this article is enough to warm you up. In a later article, I plan to demonstrate more complex operations on strings using both pandas and tidyverse." } ]
A Complete Guide to Using TensorBoard with PyTorch | by Ajinkya Pahinkar | Towards Data Science
In this article, we will be integrating TensorBoard into our PyTorch project. TensorBoard is a suite of web applications for inspecting and understanding your model runs and graphs. TensorBoard currently supports five visualizations: scalars, images, audio, histograms, and graphs. In this guide, we will be covering all five except audio and also learn how to use TensorBoard for efficient hyperparameter analysis and tuning. Make sure that your PyTorch version is above 1.10. For this guide, I’m using version 1.5.1. Use this command to check your PyTorch version. Make sure that your PyTorch version is above 1.10. For this guide, I’m using version 1.5.1. Use this command to check your PyTorch version. import torchprint(torch.__version__) 2. There are two package managers to install TensordBoard — pip or Anaconda. Depending on your python version use any of the following: Pip installation command: pip install tensorboard Anaconda Installation Command: conda install -c conda-forge tensorboard Note: Having TensorFlow installed is not a prerequisite to running TensorBoard, although it is a product of the TensorFlow ecosystem, TensorBoard by itself can be used with PyTorch. In this guide, we will be using the FashionMNIST dataset (60,000 clothing images and 10 class labels for different clothing types) which is a popular dataset inbuilt in the torch vision library. It consists of images of clothes, shoes, accessories, etc. along with an integer label corresponding to each category. We will create a simple CNN classifier and then draw inferences from it. Nonetheless, this guide will help you extend the power of TensorBoard to any project in PyTorch that you might be working on including ones that are created using Custom Datasets. Note that in this guide we will not go into details of implementing the CNN model and setting up the training loops. Instead, the focus of the article will be on the bookkeeping aspect of Deep Learning projects to get visuals of the inner workings of the models(weights and biases) and the evaluation metrics(loss, accuracy, num_correct_predictions) along with hyperparameter tuning. If you are new to the PyTorch framework take a look at my other article on Implementing CNN in PyTorch(working with datasets, moving data to GPU, creating models and training loops) before moving forward. import torchimport torch.nn as nnimport torch.optim as opttorch.set_printoptions(linewidth=120)import torch.nn.functional as Fimport torchvisionimport torchvision.transforms as transformsfrom torch.utils.tensorboard import SummaryWriter The last command is the one which enables us to import the Tensorboard class. We will be creating instances of “SummaryWriter” and then add our model’s evaluation features like loss, the number of correct predictions, accuracy, etc. to it. One of the novel features of TensorBoard is that we simply have to feed our output tensors to it and it displays the plot of all those metrics, in this way TensorBoard can take care of all the plotting for us. def get_num_correct(preds, labels): return preds.argmax(dim=1).eq(labels).sum().item() This line of code helps us to get the number of correct labels after training of the model and applying the trained model to the test set. “argmax “ gets the index corresponding to the highest value in a tensor. It’s taken across the dim=1 because dim=0 corresponds to the batch of images.”eq” compares the predicted labels to the True labels in the batch and returns 1 if matched and 0 if unmatched. Finally, we take the sum of the 1’s to get total number of correct predictions. After performing operations on tensors the output is also returned as a tensor. “item” converts the one dimensional tensor of correct_predictions to a floating point value so that it can be appended to a list(total_correct) for plotting in TensorBoard(Tensors if appended to a list cannot be plotted in TensorBoard, hence we need to convert them to floating point values, append them to a list and then pass this list to TensorBoard for plotting). We create a simple CNN model by passing the images through two Convolution layers followed by a set of fully connected layers. Finally we will use a Softmax Layer at the end to predict the class labels. class CNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5) self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5) self.fc1 = nn.Linear(in_features=12*4*4, out_features=120) self.fc2 = nn.Linear(in_features=120, out_features=60) self.out = nn.Linear(in_features=60, out_features=10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, kernel_size = 2, stride = 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, kernel_size = 2, stride = 2) x = torch.flatten(x,start_dim = 1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.out(x) return x train_set = torchvision.datasets.FashionMNIST(root="./data",train = True, download=True,transform=transforms.ToTensor())train_loader = torch.utils.data.DataLoader(train_set,batch_size = 100, shuffle = True) tb = SummaryWriter()model = CNN()images, labels = next(iter(train_loader))grid = torchvision.utils.make_grid(images)tb.add_image("images", grid)tb.add_graph(model, images)tb.close() We create an instance ‘tb’ of the SummaryWriter and add images to it by using the tb.add_image function. It takes two main arguments, one for the heading of the image and another for the tensor of images. In this case, we have created a batch of 100 images and passed them to a grid which is then added to the tb instance. To the tb.add_graph function, we pass our CNN model and a single batch of input images to generate a graph of the model. After running the code a “runs” folder will be created in the project directory. All runs going ahead will be sorted in the folder by date. This way you have an efficient log of all runs which can be viewed and compared in TensorBoard. Now use the command line(I use Anaconda Prompt) to redirect into your project directory where the runs folder is present and run the following command: tensorboard --logdir runs It will then serve TensorBoard on the localhost, the link for which will be displayed in the terminal: After opening the link we will be able to see all our runs. The Images are visible under the “Images” tab. We can use regex to filter through the runs and tick those that we are interested in visualizing. Under the “Graphs” tab you will find the graph for the model. It gives details of the entire pipeline of how the dimensions of the batch of images changes after every convolution and linear layer operations. Just double click on any of the icons to grab more information from the graph. It also gives the dimensions of all the weight and bias matrices by double-clicking on any of the Conv2d or Linear layers. device = ("cuda" if torch.cuda.is_available() else cpu)model = CNN().to(device)train_loader = torch.utils.data.DataLoader(train_set,batch_size = 100, shuffle = True)optimizer = opt.Adam(model.parameters(), lr= 0.01)criterion = torch.nn.CrossEntropyLoss()tb = SummaryWriter()for epoch in range(10): total_loss = 0 total_correct = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) preds = model(images) loss = criterion(preds, labels) total_loss+= loss.item() total_correct+= get_num_correct(preds, labels) optimizer.zero_grad() loss.backward() optimizer.step() tb.add_scalar("Loss", total_loss, epoch) tb.add_scalar("Correct", total_correct, epoch) tb.add_scalar("Accuracy", total_correct/ len(train_set), epoch) tb.add_histogram("conv1.bias", model.conv1.bias, epoch) tb.add_histogram("conv1.weight", model.conv1.weight, epoch) tb.add_histogram("conv2.bias", model.conv2.bias, epoch) tb.add_histogram("conv2.weight", model.conv2.weight, epoch) print("epoch:", epoch, "total_correct:", total_correct, "loss:",total_loss)tb.close() Alternatively, we can also use a for loop to iterate through all the model parameters including the fc and softmax layers: for name, weight in model.named_parameters(): tb.add_histogram(name,weight, epoch) tb.add_histogram(f'{name}.grad',weight.grad, epoch) We run the loop for 10 epochs and at the end of the training loop, we pass augments to the tb variable we created. We have created total_loss and total_correct variable to keep track of the loss and correct predictions at the end of each epoch. Note that every “tb” takes three arguments, one for the string which will be the heading of the line chart/histogram, then the tensors containing the values to be plotted, and finally a global step. Since we are doing an epoch wise analysis, we have set it to epoch. Alternatively, it can also be set to the batch id by shifting the tb commands inside the for loop for a batch by using “enumerate” and set the step to batch_id as follows: for batch_id, (images, labels) in enumerate(train_loader):...... tb.add_scalar("Loss", total_loss, batch_id) As seen below running the command mentioned earlier to run TensorBoard will display the line graph and the histograms for the loss, num_correct_predictions, and accuracy. Moving the orange dot along the graph will give us a log of the respective metric(Accuracy/Correct/Loss) for that particular epoch. Firstly we need to change the batch_size, learning_rate, shuffle to dynamic variables. We do that by creating a dictionary as follows: from itertools import productparameters = dict( lr = [0.01, 0.001], batch_size = [32,64,128], shuffle = [True, False])param_values = [v for v in parameters.values()]print(param_values)for lr,batch_size, shuffle in product(*param_values): print(lr, batch_size, shuffle) This will allow us to get tuples of three, corresponding to all combinations of the three hyperparameters and then call a for loop on them before running each epoch loop. In this way, we will be able to have 12 runs(2(learning_rates)*3(batch_sizes)*2(shuffles)) of all the different hyperparameter combinations and compare them on TensorBoard. We will modify the training loop as follows: for run_id, (lr,batch_size, shuffle) in enumerate(product(*param_values)): print("run id:", run_id + 1) model = CNN().to(device) train_loader = torch.utils.data.DataLoader(train_set,batch_size = batch_size, shuffle = shuffle) optimizer = opt.Adam(model.parameters(), lr= lr) criterion = torch.nn.CrossEntropyLoss() comment = f' batch_size = {batch_size} lr = {lr} shuffle = {shuffle}' tb = SummaryWriter(comment=comment) for epoch in range(5): total_loss = 0 total_correct = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) preds = model(images) loss = criterion(preds, labels) total_loss+= loss.item() total_correct+= get_num_correct(preds, labels) optimizer.zero_grad() loss.backward() optimizer.step() tb.add_scalar("Loss", total_loss, epoch) tb.add_scalar("Correct", total_correct, epoch) tb.add_scalar("Accuracy", total_correct/ len(train_set), epoch) print("batch_size:",batch_size, "lr:",lr,"shuffle:",shuffle) print("epoch:", epoch, "total_correct:", total_correct, "loss:",total_loss) print("__________________________________________________________") tb.add_hparams( {"lr": lr, "bsize": batch_size, "shuffle":shuffle}, { "accuracy": total_correct/ len(train_set), "loss": total_loss, }, )tb.close() As seen above we have moved everything under the for loop to go over all different combinations of hyperparameters and at each run, we have to re-instantiate the model as well as reload the batches of the dataset. “comment” allows us to create different folders inside the runs folder depending on specified hyperparameters. We pass this comment as an argument to the SummaryWriter. Note that we will be able to see all the runs together and draw comparative analysis across all hyperparameters in TensorBoard. tb.add_scalar is the same as earlier just that we have it displayed for all runs this time. tb.add_hparams allows us to add hyperparameters inside as arguments to keep track of the training progress. It takes two dictionaries as inputs, one for the hyperparameters and another for the evaluation metrics to be analyzed. The results are mapped across all these hyperparameters. It will be clear from the graph mapping diagram at the bottom. As seen above we can filter any runs that we want or have all of them plotted on the same graph. In this way, we can draw a comparative study of the performance of the model across several hyperparameters and tune the model to the ones which give us the best performance. All details like batch size, learning rate, shuffle, and corresponding accuracy values are visible in the pop-up box. It is evident from the results that a batch size of 32, shuffle set to True, and a learning rate of 0.01 yields the best result. For demonstration purposes it’s run for only 5 epochs. Increasing the number of epochs can very well affect the result, hence it’s important to train and test with several values of epochs. This graph has the combined logs of all 12 runs so that you can use the highest accuracy and lowest loss value and trace it back to the corresponding batch size, learning rate and shuffle configurations. From the Hyperparameter Graph it is very clear that setting shuffle to False(0) tends to yield very poor results. Hence setting shuffle to always True(1) is ideal for training as it adds randomization. Feel free to play around with TensorBoard, try to add more hyperparameters to the graph to gain as much information on the pattern of loss convergence and performance of the model given various hyperparameters. We could also potentially add a set of optimizers other than Adam and draw a comparative study. In case of Sequence models like LSTMs, GRUs one can add the time-steps as well to the graph and draw insightful conclusions. Hope this article gave you a thorough insight into using TensorBoard with PyTorch. Link to code: https://github.com/ajinkya98/TensorBoard_PyTorch
[ { "code": null, "e": 598, "s": 171, "text": "In this article, we will be integrating TensorBoard into our PyTorch project. TensorBoard is a suite of web applications for inspecting and understanding your model runs and graphs. TensorBoard currently supports five visualizations: scalars, images, audio, histograms, and graphs. In this guide, we will be covering all five except audio and also learn how to use TensorBoard for efficient hyperparameter analysis and tuning." }, { "code": null, "e": 738, "s": 598, "text": "Make sure that your PyTorch version is above 1.10. For this guide, I’m using version 1.5.1. Use this command to check your PyTorch version." }, { "code": null, "e": 878, "s": 738, "text": "Make sure that your PyTorch version is above 1.10. For this guide, I’m using version 1.5.1. Use this command to check your PyTorch version." }, { "code": null, "e": 915, "s": 878, "text": "import torchprint(torch.__version__)" }, { "code": null, "e": 1051, "s": 915, "text": "2. There are two package managers to install TensordBoard — pip or Anaconda. Depending on your python version use any of the following:" }, { "code": null, "e": 1077, "s": 1051, "text": "Pip installation command:" }, { "code": null, "e": 1101, "s": 1077, "text": "pip install tensorboard" }, { "code": null, "e": 1132, "s": 1101, "text": "Anaconda Installation Command:" }, { "code": null, "e": 1173, "s": 1132, "text": "conda install -c conda-forge tensorboard" }, { "code": null, "e": 1355, "s": 1173, "text": "Note: Having TensorFlow installed is not a prerequisite to running TensorBoard, although it is a product of the TensorFlow ecosystem, TensorBoard by itself can be used with PyTorch." }, { "code": null, "e": 1922, "s": 1355, "text": "In this guide, we will be using the FashionMNIST dataset (60,000 clothing images and 10 class labels for different clothing types) which is a popular dataset inbuilt in the torch vision library. It consists of images of clothes, shoes, accessories, etc. along with an integer label corresponding to each category. We will create a simple CNN classifier and then draw inferences from it. Nonetheless, this guide will help you extend the power of TensorBoard to any project in PyTorch that you might be working on including ones that are created using Custom Datasets." }, { "code": null, "e": 2511, "s": 1922, "text": "Note that in this guide we will not go into details of implementing the CNN model and setting up the training loops. Instead, the focus of the article will be on the bookkeeping aspect of Deep Learning projects to get visuals of the inner workings of the models(weights and biases) and the evaluation metrics(loss, accuracy, num_correct_predictions) along with hyperparameter tuning. If you are new to the PyTorch framework take a look at my other article on Implementing CNN in PyTorch(working with datasets, moving data to GPU, creating models and training loops) before moving forward." }, { "code": null, "e": 2748, "s": 2511, "text": "import torchimport torch.nn as nnimport torch.optim as opttorch.set_printoptions(linewidth=120)import torch.nn.functional as Fimport torchvisionimport torchvision.transforms as transformsfrom torch.utils.tensorboard import SummaryWriter" }, { "code": null, "e": 3198, "s": 2748, "text": "The last command is the one which enables us to import the Tensorboard class. We will be creating instances of “SummaryWriter” and then add our model’s evaluation features like loss, the number of correct predictions, accuracy, etc. to it. One of the novel features of TensorBoard is that we simply have to feed our output tensors to it and it displays the plot of all those metrics, in this way TensorBoard can take care of all the plotting for us." }, { "code": null, "e": 3288, "s": 3198, "text": "def get_num_correct(preds, labels): return preds.argmax(dim=1).eq(labels).sum().item()" }, { "code": null, "e": 4217, "s": 3288, "text": "This line of code helps us to get the number of correct labels after training of the model and applying the trained model to the test set. “argmax “ gets the index corresponding to the highest value in a tensor. It’s taken across the dim=1 because dim=0 corresponds to the batch of images.”eq” compares the predicted labels to the True labels in the batch and returns 1 if matched and 0 if unmatched. Finally, we take the sum of the 1’s to get total number of correct predictions. After performing operations on tensors the output is also returned as a tensor. “item” converts the one dimensional tensor of correct_predictions to a floating point value so that it can be appended to a list(total_correct) for plotting in TensorBoard(Tensors if appended to a list cannot be plotted in TensorBoard, hence we need to convert them to floating point values, append them to a list and then pass this list to TensorBoard for plotting)." }, { "code": null, "e": 4420, "s": 4217, "text": "We create a simple CNN model by passing the images through two Convolution layers followed by a set of fully connected layers. Finally we will use a Softmax Layer at the end to predict the class labels." }, { "code": null, "e": 5179, "s": 4420, "text": "class CNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5) self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5) self.fc1 = nn.Linear(in_features=12*4*4, out_features=120) self.fc2 = nn.Linear(in_features=120, out_features=60) self.out = nn.Linear(in_features=60, out_features=10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, kernel_size = 2, stride = 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, kernel_size = 2, stride = 2) x = torch.flatten(x,start_dim = 1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.out(x) return x" }, { "code": null, "e": 5386, "s": 5179, "text": "train_set = torchvision.datasets.FashionMNIST(root=\"./data\",train = True, download=True,transform=transforms.ToTensor())train_loader = torch.utils.data.DataLoader(train_set,batch_size = 100, shuffle = True)" }, { "code": null, "e": 5568, "s": 5386, "text": "tb = SummaryWriter()model = CNN()images, labels = next(iter(train_loader))grid = torchvision.utils.make_grid(images)tb.add_image(\"images\", grid)tb.add_graph(model, images)tb.close()" }, { "code": null, "e": 6248, "s": 5568, "text": "We create an instance ‘tb’ of the SummaryWriter and add images to it by using the tb.add_image function. It takes two main arguments, one for the heading of the image and another for the tensor of images. In this case, we have created a batch of 100 images and passed them to a grid which is then added to the tb instance. To the tb.add_graph function, we pass our CNN model and a single batch of input images to generate a graph of the model. After running the code a “runs” folder will be created in the project directory. All runs going ahead will be sorted in the folder by date. This way you have an efficient log of all runs which can be viewed and compared in TensorBoard." }, { "code": null, "e": 6400, "s": 6248, "text": "Now use the command line(I use Anaconda Prompt) to redirect into your project directory where the runs folder is present and run the following command:" }, { "code": null, "e": 6426, "s": 6400, "text": "tensorboard --logdir runs" }, { "code": null, "e": 6529, "s": 6426, "text": "It will then serve TensorBoard on the localhost, the link for which will be displayed in the terminal:" }, { "code": null, "e": 6734, "s": 6529, "text": "After opening the link we will be able to see all our runs. The Images are visible under the “Images” tab. We can use regex to filter through the runs and tick those that we are interested in visualizing." }, { "code": null, "e": 7144, "s": 6734, "text": "Under the “Graphs” tab you will find the graph for the model. It gives details of the entire pipeline of how the dimensions of the batch of images changes after every convolution and linear layer operations. Just double click on any of the icons to grab more information from the graph. It also gives the dimensions of all the weight and bias matrices by double-clicking on any of the Conv2d or Linear layers." }, { "code": null, "e": 8305, "s": 7144, "text": "device = (\"cuda\" if torch.cuda.is_available() else cpu)model = CNN().to(device)train_loader = torch.utils.data.DataLoader(train_set,batch_size = 100, shuffle = True)optimizer = opt.Adam(model.parameters(), lr= 0.01)criterion = torch.nn.CrossEntropyLoss()tb = SummaryWriter()for epoch in range(10): total_loss = 0 total_correct = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) preds = model(images) loss = criterion(preds, labels) total_loss+= loss.item() total_correct+= get_num_correct(preds, labels) optimizer.zero_grad() loss.backward() optimizer.step() tb.add_scalar(\"Loss\", total_loss, epoch) tb.add_scalar(\"Correct\", total_correct, epoch) tb.add_scalar(\"Accuracy\", total_correct/ len(train_set), epoch) tb.add_histogram(\"conv1.bias\", model.conv1.bias, epoch) tb.add_histogram(\"conv1.weight\", model.conv1.weight, epoch) tb.add_histogram(\"conv2.bias\", model.conv2.bias, epoch) tb.add_histogram(\"conv2.weight\", model.conv2.weight, epoch) print(\"epoch:\", epoch, \"total_correct:\", total_correct, \"loss:\",total_loss)tb.close()" }, { "code": null, "e": 8428, "s": 8305, "text": "Alternatively, we can also use a for loop to iterate through all the model parameters including the fc and softmax layers:" }, { "code": null, "e": 8569, "s": 8428, "text": "for name, weight in model.named_parameters(): tb.add_histogram(name,weight, epoch) tb.add_histogram(f'{name}.grad',weight.grad, epoch)" }, { "code": null, "e": 9253, "s": 8569, "text": "We run the loop for 10 epochs and at the end of the training loop, we pass augments to the tb variable we created. We have created total_loss and total_correct variable to keep track of the loss and correct predictions at the end of each epoch. Note that every “tb” takes three arguments, one for the string which will be the heading of the line chart/histogram, then the tensors containing the values to be plotted, and finally a global step. Since we are doing an epoch wise analysis, we have set it to epoch. Alternatively, it can also be set to the batch id by shifting the tb commands inside the for loop for a batch by using “enumerate” and set the step to batch_id as follows:" }, { "code": null, "e": 9365, "s": 9253, "text": "for batch_id, (images, labels) in enumerate(train_loader):...... tb.add_scalar(\"Loss\", total_loss, batch_id)" }, { "code": null, "e": 9536, "s": 9365, "text": "As seen below running the command mentioned earlier to run TensorBoard will display the line graph and the histograms for the loss, num_correct_predictions, and accuracy." }, { "code": null, "e": 9668, "s": 9536, "text": "Moving the orange dot along the graph will give us a log of the respective metric(Accuracy/Correct/Loss) for that particular epoch." }, { "code": null, "e": 9803, "s": 9668, "text": "Firstly we need to change the batch_size, learning_rate, shuffle to dynamic variables. We do that by creating a dictionary as follows:" }, { "code": null, "e": 10084, "s": 9803, "text": "from itertools import productparameters = dict( lr = [0.01, 0.001], batch_size = [32,64,128], shuffle = [True, False])param_values = [v for v in parameters.values()]print(param_values)for lr,batch_size, shuffle in product(*param_values): print(lr, batch_size, shuffle)" }, { "code": null, "e": 10473, "s": 10084, "text": "This will allow us to get tuples of three, corresponding to all combinations of the three hyperparameters and then call a for loop on them before running each epoch loop. In this way, we will be able to have 12 runs(2(learning_rates)*3(batch_sizes)*2(shuffles)) of all the different hyperparameter combinations and compare them on TensorBoard. We will modify the training loop as follows:" }, { "code": null, "e": 11970, "s": 10473, "text": "for run_id, (lr,batch_size, shuffle) in enumerate(product(*param_values)): print(\"run id:\", run_id + 1) model = CNN().to(device) train_loader = torch.utils.data.DataLoader(train_set,batch_size = batch_size, shuffle = shuffle) optimizer = opt.Adam(model.parameters(), lr= lr) criterion = torch.nn.CrossEntropyLoss() comment = f' batch_size = {batch_size} lr = {lr} shuffle = {shuffle}' tb = SummaryWriter(comment=comment) for epoch in range(5): total_loss = 0 total_correct = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) preds = model(images) loss = criterion(preds, labels) total_loss+= loss.item() total_correct+= get_num_correct(preds, labels) optimizer.zero_grad() loss.backward() optimizer.step() tb.add_scalar(\"Loss\", total_loss, epoch) tb.add_scalar(\"Correct\", total_correct, epoch) tb.add_scalar(\"Accuracy\", total_correct/ len(train_set), epoch) print(\"batch_size:\",batch_size, \"lr:\",lr,\"shuffle:\",shuffle) print(\"epoch:\", epoch, \"total_correct:\", total_correct, \"loss:\",total_loss) print(\"__________________________________________________________\") tb.add_hparams( {\"lr\": lr, \"bsize\": batch_size, \"shuffle\":shuffle}, { \"accuracy\": total_correct/ len(train_set), \"loss\": total_loss, }, )tb.close()" }, { "code": null, "e": 12921, "s": 11970, "text": "As seen above we have moved everything under the for loop to go over all different combinations of hyperparameters and at each run, we have to re-instantiate the model as well as reload the batches of the dataset. “comment” allows us to create different folders inside the runs folder depending on specified hyperparameters. We pass this comment as an argument to the SummaryWriter. Note that we will be able to see all the runs together and draw comparative analysis across all hyperparameters in TensorBoard. tb.add_scalar is the same as earlier just that we have it displayed for all runs this time. tb.add_hparams allows us to add hyperparameters inside as arguments to keep track of the training progress. It takes two dictionaries as inputs, one for the hyperparameters and another for the evaluation metrics to be analyzed. The results are mapped across all these hyperparameters. It will be clear from the graph mapping diagram at the bottom." }, { "code": null, "e": 13311, "s": 12921, "text": "As seen above we can filter any runs that we want or have all of them plotted on the same graph. In this way, we can draw a comparative study of the performance of the model across several hyperparameters and tune the model to the ones which give us the best performance. All details like batch size, learning rate, shuffle, and corresponding accuracy values are visible in the pop-up box." }, { "code": null, "e": 13630, "s": 13311, "text": "It is evident from the results that a batch size of 32, shuffle set to True, and a learning rate of 0.01 yields the best result. For demonstration purposes it’s run for only 5 epochs. Increasing the number of epochs can very well affect the result, hence it’s important to train and test with several values of epochs." }, { "code": null, "e": 13834, "s": 13630, "text": "This graph has the combined logs of all 12 runs so that you can use the highest accuracy and lowest loss value and trace it back to the corresponding batch size, learning rate and shuffle configurations." }, { "code": null, "e": 14036, "s": 13834, "text": "From the Hyperparameter Graph it is very clear that setting shuffle to False(0) tends to yield very poor results. Hence setting shuffle to always True(1) is ideal for training as it adds randomization." }, { "code": null, "e": 14551, "s": 14036, "text": "Feel free to play around with TensorBoard, try to add more hyperparameters to the graph to gain as much information on the pattern of loss convergence and performance of the model given various hyperparameters. We could also potentially add a set of optimizers other than Adam and draw a comparative study. In case of Sequence models like LSTMs, GRUs one can add the time-steps as well to the graph and draw insightful conclusions. Hope this article gave you a thorough insight into using TensorBoard with PyTorch." } ]
Data Mining - Quick Guide
There is a huge amount of data available in the Information Industry. This data is of no use until it is converted into useful information. It is necessary to analyze this huge amount of data and extract useful information from it. Extraction of information is not the only process we need to perform; data mining also involves other processes such as Data Cleaning, Data Integration, Data Transformation, Data Mining, Pattern Evaluation and Data Presentation. Once all these processes are over, we would be able to use this information in many applications such as Fraud Detection, Market Analysis, Production Control, Science Exploration, etc. Data Mining is defined as extracting information from huge sets of data. In other words, we can say that data mining is the procedure of mining knowledge from data. The information or knowledge extracted so can be used for any of the following applications − Market Analysis Fraud Detection Customer Retention Production Control Science Exploration Data mining is highly useful in the following domains − Market Analysis and Management Corporate Analysis & Risk Management Fraud Detection Apart from these, data mining can also be used in the areas of production control, customer retention, science exploration, sports, astrology, and Internet Web Surf-Aid Listed below are the various fields of market where data mining is used − Customer Profiling − Data mining helps determine what kind of people buy what kind of products. Customer Profiling − Data mining helps determine what kind of people buy what kind of products. Identifying Customer Requirements − Data mining helps in identifying the best products for different customers. It uses prediction to find the factors that may attract new customers. Identifying Customer Requirements − Data mining helps in identifying the best products for different customers. It uses prediction to find the factors that may attract new customers. Cross Market Analysis − Data mining performs Association/correlations between product sales. Cross Market Analysis − Data mining performs Association/correlations between product sales. Target Marketing − Data mining helps to find clusters of model customers who share the same characteristics such as interests, spending habits, income, etc. Target Marketing − Data mining helps to find clusters of model customers who share the same characteristics such as interests, spending habits, income, etc. Determining Customer purchasing pattern − Data mining helps in determining customer purchasing pattern. Determining Customer purchasing pattern − Data mining helps in determining customer purchasing pattern. Providing Summary Information − Data mining provides us various multidimensional summary reports. Providing Summary Information − Data mining provides us various multidimensional summary reports. Data mining is used in the following fields of the Corporate Sector − Finance Planning and Asset Evaluation − It involves cash flow analysis and prediction, contingent claim analysis to evaluate assets. Finance Planning and Asset Evaluation − It involves cash flow analysis and prediction, contingent claim analysis to evaluate assets. Resource Planning − It involves summarizing and comparing the resources and spending. Resource Planning − It involves summarizing and comparing the resources and spending. Competition − It involves monitoring competitors and market directions. Competition − It involves monitoring competitors and market directions. Data mining is also used in the fields of credit card services and telecommunication to detect frauds. In fraud telephone calls, it helps to find the destination of the call, duration of the call, time of the day or week, etc. It also analyzes the patterns that deviate from expected norms. Data mining deals with the kind of patterns that can be mined. On the basis of the kind of data to be mined, there are two categories of functions involved in Data Mining − Descriptive Classification and Prediction The descriptive function deals with the general properties of data in the database. Here is the list of descriptive functions − Class/Concept Description Mining of Frequent Patterns Mining of Associations Mining of Correlations Mining of Clusters Class/Concept refers to the data to be associated with the classes or concepts. For example, in a company, the classes of items for sales include computer and printers, and concepts of customers include big spenders and budget spenders. Such descriptions of a class or a concept are called class/concept descriptions. These descriptions can be derived by the following two ways − Data Characterization − This refers to summarizing data of class under study. This class under study is called as Target Class. Data Characterization − This refers to summarizing data of class under study. This class under study is called as Target Class. Data Discrimination − It refers to the mapping or classification of a class with some predefined group or class. Data Discrimination − It refers to the mapping or classification of a class with some predefined group or class. Frequent patterns are those patterns that occur frequently in transactional data. Here is the list of kind of frequent patterns − Frequent Item Set − It refers to a set of items that frequently appear together, for example, milk and bread. Frequent Item Set − It refers to a set of items that frequently appear together, for example, milk and bread. Frequent Subsequence − A sequence of patterns that occur frequently such as purchasing a camera is followed by memory card. Frequent Subsequence − A sequence of patterns that occur frequently such as purchasing a camera is followed by memory card. Frequent Sub Structure − Substructure refers to different structural forms, such as graphs, trees, or lattices, which may be combined with item-sets or subsequences. Frequent Sub Structure − Substructure refers to different structural forms, such as graphs, trees, or lattices, which may be combined with item-sets or subsequences. Associations are used in retail sales to identify patterns that are frequently purchased together. This process refers to the process of uncovering the relationship among data and determining association rules. For example, a retailer generates an association rule that shows that 70% of time milk is sold with bread and only 30% of times biscuits are sold with bread. It is a kind of additional analysis performed to uncover interesting statistical correlations between associated-attribute-value pairs or between two item sets to analyze that if they have positive, negative or no effect on each other. Cluster refers to a group of similar kind of objects. Cluster analysis refers to forming group of objects that are very similar to each other but are highly different from the objects in other clusters. Classification is the process of finding a model that describes the data classes or concepts. The purpose is to be able to use this model to predict the class of objects whose class label is unknown. This derived model is based on the analysis of sets of training data. The derived model can be presented in the following forms − Classification (IF-THEN) Rules Decision Trees Mathematical Formulae Neural Networks The list of functions involved in these processes are as follows − Classification − It predicts the class of objects whose class label is unknown. Its objective is to find a derived model that describes and distinguishes data classes or concepts. The Derived Model is based on the analysis set of training data i.e. the data object whose class label is well known. Classification − It predicts the class of objects whose class label is unknown. Its objective is to find a derived model that describes and distinguishes data classes or concepts. The Derived Model is based on the analysis set of training data i.e. the data object whose class label is well known. Prediction − It is used to predict missing or unavailable numerical data values rather than class labels. Regression Analysis is generally used for prediction. Prediction can also be used for identification of distribution trends based on available data. Prediction − It is used to predict missing or unavailable numerical data values rather than class labels. Regression Analysis is generally used for prediction. Prediction can also be used for identification of distribution trends based on available data. Outlier Analysis − Outliers may be defined as the data objects that do not comply with the general behavior or model of the data available. Outlier Analysis − Outliers may be defined as the data objects that do not comply with the general behavior or model of the data available. Evolution Analysis − Evolution analysis refers to the description and model regularities or trends for objects whose behavior changes over time. Evolution Analysis − Evolution analysis refers to the description and model regularities or trends for objects whose behavior changes over time. We can specify a data mining task in the form of a data mining query. This query is input to the system. A data mining query is defined in terms of data mining task primitives. Note − These primitives allow us to communicate in an interactive manner with the data mining system. Here is the list of Data Mining Task Primitives − Set of task relevant data to be mined. Kind of knowledge to be mined. Background knowledge to be used in discovery process. Interestingness measures and thresholds for pattern evaluation. Representation for visualizing the discovered patterns. This is the portion of database in which the user is interested. This portion includes the following − Database Attributes Data Warehouse dimensions of interest It refers to the kind of functions to be performed. These functions are − Characterization Discrimination Association and Correlation Analysis Classification Prediction Clustering Outlier Analysis Evolution Analysis The background knowledge allows data to be mined at multiple levels of abstraction. For example, the Concept hierarchies are one of the background knowledge that allows data to be mined at multiple levels of abstraction. This is used to evaluate the patterns that are discovered by the process of knowledge discovery. There are different interesting measures for different kind of knowledge. This refers to the form in which discovered patterns are to be displayed. These representations may include the following. − Rules Tables Charts Graphs Decision Trees Cubes Data mining is not an easy task, as the algorithms used can get very complex and data is not always available at one place. It needs to be integrated from various heterogeneous data sources. These factors also create some issues. Here in this tutorial, we will discuss the major issues regarding − Mining Methodology and User Interaction Performance Issues Diverse Data Types Issues The following diagram describes the major issues. It refers to the following kinds of issues − Mining different kinds of knowledge in databases − Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery task. Mining different kinds of knowledge in databases − Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery task. Interactive mining of knowledge at multiple levels of abstraction − The data mining process needs to be interactive because it allows users to focus the search for patterns, providing and refining data mining requests based on the returned results. Interactive mining of knowledge at multiple levels of abstraction − The data mining process needs to be interactive because it allows users to focus the search for patterns, providing and refining data mining requests based on the returned results. Incorporation of background knowledge − To guide discovery process and to express the discovered patterns, the background knowledge can be used. Background knowledge may be used to express the discovered patterns not only in concise terms but at multiple levels of abstraction. Incorporation of background knowledge − To guide discovery process and to express the discovered patterns, the background knowledge can be used. Background knowledge may be used to express the discovered patterns not only in concise terms but at multiple levels of abstraction. Data mining query languages and ad hoc data mining − Data Mining Query language that allows the user to describe ad hoc mining tasks, should be integrated with a data warehouse query language and optimized for efficient and flexible data mining. Data mining query languages and ad hoc data mining − Data Mining Query language that allows the user to describe ad hoc mining tasks, should be integrated with a data warehouse query language and optimized for efficient and flexible data mining. Presentation and visualization of data mining results − Once the patterns are discovered it needs to be expressed in high level languages, and visual representations. These representations should be easily understandable. Presentation and visualization of data mining results − Once the patterns are discovered it needs to be expressed in high level languages, and visual representations. These representations should be easily understandable. Handling noisy or incomplete data − The data cleaning methods are required to handle the noise and incomplete objects while mining the data regularities. If the data cleaning methods are not there then the accuracy of the discovered patterns will be poor. Handling noisy or incomplete data − The data cleaning methods are required to handle the noise and incomplete objects while mining the data regularities. If the data cleaning methods are not there then the accuracy of the discovered patterns will be poor. Pattern evaluation − The patterns discovered should be interesting because either they represent common knowledge or lack novelty. Pattern evaluation − The patterns discovered should be interesting because either they represent common knowledge or lack novelty. There can be performance-related issues such as follows − Efficiency and scalability of data mining algorithms − In order to effectively extract the information from huge amount of data in databases, data mining algorithm must be efficient and scalable. Efficiency and scalability of data mining algorithms − In order to effectively extract the information from huge amount of data in databases, data mining algorithm must be efficient and scalable. Parallel, distributed, and incremental mining algorithms − The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate the development of parallel and distributed data mining algorithms. These algorithms divide the data into partitions which is further processed in a parallel fashion. Then the results from the partitions is merged. The incremental algorithms, update databases without mining the data again from scratch. Parallel, distributed, and incremental mining algorithms − The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate the development of parallel and distributed data mining algorithms. These algorithms divide the data into partitions which is further processed in a parallel fashion. Then the results from the partitions is merged. The incremental algorithms, update databases without mining the data again from scratch. Handling of relational and complex types of data − The database may contain complex data objects, multimedia data objects, spatial data, temporal data etc. It is not possible for one system to mine all these kind of data. Handling of relational and complex types of data − The database may contain complex data objects, multimedia data objects, spatial data, temporal data etc. It is not possible for one system to mine all these kind of data. Mining information from heterogeneous databases and global information systems − The data is available at different data sources on LAN or WAN. These data source may be structured, semi structured or unstructured. Therefore mining the knowledge from them adds challenges to data mining. Mining information from heterogeneous databases and global information systems − The data is available at different data sources on LAN or WAN. These data source may be structured, semi structured or unstructured. Therefore mining the knowledge from them adds challenges to data mining. A data warehouse exhibits the following characteristics to support the management's decision-making process − Subject Oriented − Data warehouse is subject oriented because it provides us the information around a subject rather than the organization's ongoing operations. These subjects can be product, customers, suppliers, sales, revenue, etc. The data warehouse does not focus on the ongoing operations, rather it focuses on modelling and analysis of data for decision-making. Subject Oriented − Data warehouse is subject oriented because it provides us the information around a subject rather than the organization's ongoing operations. These subjects can be product, customers, suppliers, sales, revenue, etc. The data warehouse does not focus on the ongoing operations, rather it focuses on modelling and analysis of data for decision-making. Integrated − Data warehouse is constructed by integration of data from heterogeneous sources such as relational databases, flat files etc. This integration enhances the effective analysis of data. Integrated − Data warehouse is constructed by integration of data from heterogeneous sources such as relational databases, flat files etc. This integration enhances the effective analysis of data. Time Variant − The data collected in a data warehouse is identified with a particular time period. The data in a data warehouse provides information from a historical point of view. Time Variant − The data collected in a data warehouse is identified with a particular time period. The data in a data warehouse provides information from a historical point of view. Non-volatile − Nonvolatile means the previous data is not removed when new data is added to it. The data warehouse is kept separate from the operational database therefore frequent changes in operational database is not reflected in the data warehouse. Non-volatile − Nonvolatile means the previous data is not removed when new data is added to it. The data warehouse is kept separate from the operational database therefore frequent changes in operational database is not reflected in the data warehouse. Data warehousing is the process of constructing and using the data warehouse. A data warehouse is constructed by integrating the data from multiple heterogeneous sources. It supports analytical reporting, structured and/or ad hoc queries, and decision making. Data warehousing involves data cleaning, data integration, and data consolidations. To integrate heterogeneous databases, we have the following two approaches − Query Driven Approach Update Driven Approach This is the traditional approach to integrate heterogeneous databases. This approach is used to build wrappers and integrators on top of multiple heterogeneous databases. These integrators are also known as mediators. When a query is issued to a client side, a metadata dictionary translates the query into the queries, appropriate for the individual heterogeneous site involved. When a query is issued to a client side, a metadata dictionary translates the query into the queries, appropriate for the individual heterogeneous site involved. Now these queries are mapped and sent to the local query processor. Now these queries are mapped and sent to the local query processor. The results from heterogeneous sites are integrated into a global answer set. The results from heterogeneous sites are integrated into a global answer set. This approach has the following disadvantages − The Query Driven Approach needs complex integration and filtering processes. The Query Driven Approach needs complex integration and filtering processes. It is very inefficient and very expensive for frequent queries. It is very inefficient and very expensive for frequent queries. This approach is expensive for queries that require aggregations. This approach is expensive for queries that require aggregations. Today's data warehouse systems follow update-driven approach rather than the traditional approach discussed earlier. In the update-driven approach, the information from multiple heterogeneous sources is integrated in advance and stored in a warehouse. This information is available for direct querying and analysis. This approach has the following advantages − This approach provides high performance. This approach provides high performance. The data can be copied, processed, integrated, annotated, summarized and restructured in the semantic data store in advance. The data can be copied, processed, integrated, annotated, summarized and restructured in the semantic data store in advance. Query processing does not require interface with the processing at local sources. Online Analytical Mining integrates with Online Analytical Processing with data mining and mining knowledge in multidimensional databases. Here is the diagram that shows the integration of both OLAP and OLAM − OLAM is important for the following reasons − High quality of data in data warehouses − The data mining tools are required to work on integrated, consistent, and cleaned data. These steps are very costly in the preprocessing of data. The data warehouses constructed by such preprocessing are valuable sources of high quality data for OLAP and data mining as well. High quality of data in data warehouses − The data mining tools are required to work on integrated, consistent, and cleaned data. These steps are very costly in the preprocessing of data. The data warehouses constructed by such preprocessing are valuable sources of high quality data for OLAP and data mining as well. Available information processing infrastructure surrounding data warehouses − Information processing infrastructure refers to accessing, integration, consolidation, and transformation of multiple heterogeneous databases, web-accessing and service facilities, reporting and OLAP analysis tools. Available information processing infrastructure surrounding data warehouses − Information processing infrastructure refers to accessing, integration, consolidation, and transformation of multiple heterogeneous databases, web-accessing and service facilities, reporting and OLAP analysis tools. OLAP−based exploratory data analysis − Exploratory data analysis is required for effective data mining. OLAM provides facility for data mining on various subset of data and at different levels of abstraction. OLAP−based exploratory data analysis − Exploratory data analysis is required for effective data mining. OLAM provides facility for data mining on various subset of data and at different levels of abstraction. Online selection of data mining functions − Integrating OLAP with multiple data mining functions and online analytical mining provide users with the flexibility to select desired data mining functions and swap data mining tasks dynamically. Online selection of data mining functions − Integrating OLAP with multiple data mining functions and online analytical mining provide users with the flexibility to select desired data mining functions and swap data mining tasks dynamically. Data mining is defined as extracting the information from a huge set of data. In other words we can say that data mining is mining the knowledge from data. This information can be used for any of the following applications − Market Analysis Fraud Detection Customer Retention Production Control Science Exploration Data mining engine is very essential to the data mining system. It consists of a set of functional modules that perform the following functions − Characterization Association and Correlation Analysis Classification Prediction Cluster analysis Outlier analysis Evolution analysis This is the domain knowledge. This knowledge is used to guide the search or evaluate the interestingness of the resulting patterns. Some people treat data mining same as knowledge discovery, while others view data mining as an essential step in the process of knowledge discovery. Here is the list of steps involved in the knowledge discovery process − Data Cleaning Data Integration Data Selection Data Transformation Data Mining Pattern Evaluation Knowledge Presentation User interface is the module of data mining system that helps the communication between users and the data mining system. User Interface allows the following functionalities − Interact with the system by specifying a data mining query task. Providing information to help focus the search. Mining based on the intermediate data mining results. Browse database and data warehouse schemas or data structures. Evaluate mined patterns. Visualize the patterns in different forms. Data Integration is a data preprocessing technique that merges the data from multiple heterogeneous data sources into a coherent data store. Data integration may involve inconsistent data and therefore needs data cleaning. Data cleaning is a technique that is applied to remove the noisy data and correct the inconsistencies in data. Data cleaning involves transformations to correct the wrong data. Data cleaning is performed as a data preprocessing step while preparing the data for a data warehouse. Data Selection is the process where data relevant to the analysis task are retrieved from the database. Sometimes data transformation and consolidation are performed before the data selection process. Cluster refers to a group of similar kind of objects. Cluster analysis refers to forming group of objects that are very similar to each other but are highly different from the objects in other clusters. In this step, data is transformed or consolidated into forms appropriate for mining, by performing summary or aggregation operations. Some people don’t differentiate data mining from knowledge discovery while others view data mining as an essential step in the process of knowledge discovery. Here is the list of steps involved in the knowledge discovery process − Data Cleaning − In this step, the noise and inconsistent data is removed. Data Cleaning − In this step, the noise and inconsistent data is removed. Data Integration − In this step, multiple data sources are combined. Data Integration − In this step, multiple data sources are combined. Data Selection − In this step, data relevant to the analysis task are retrieved from the database. Data Selection − In this step, data relevant to the analysis task are retrieved from the database. Data Transformation − In this step, data is transformed or consolidated into forms appropriate for mining by performing summary or aggregation operations. Data Transformation − In this step, data is transformed or consolidated into forms appropriate for mining by performing summary or aggregation operations. Data Mining − In this step, intelligent methods are applied in order to extract data patterns. Data Mining − In this step, intelligent methods are applied in order to extract data patterns. Pattern Evaluation − In this step, data patterns are evaluated. Pattern Evaluation − In this step, data patterns are evaluated. Knowledge Presentation − In this step, knowledge is represented. Knowledge Presentation − In this step, knowledge is represented. The following diagram shows the process of knowledge discovery − There is a large variety of data mining systems available. Data mining systems may integrate techniques from the following − Spatial Data Analysis Information Retrieval Pattern Recognition Image Analysis Signal Processing Computer Graphics Web Technology Business Bioinformatics A data mining system can be classified according to the following criteria − Database Technology Statistics Machine Learning Information Science Visualization Other Disciplines Apart from these, a data mining system can also be classified based on the kind of (a) databases mined, (b) knowledge mined, (c) techniques utilized, and (d) applications adapted. We can classify a data mining system according to the kind of databases mined. Database system can be classified according to different criteria such as data models, types of data, etc. And the data mining system can be classified accordingly. For example, if we classify a database according to the data model, then we may have a relational, transactional, object-relational, or data warehouse mining system. We can classify a data mining system according to the kind of knowledge mined. It means the data mining system is classified on the basis of functionalities such as − Characterization Discrimination Association and Correlation Analysis Classification Prediction Outlier Analysis Evolution Analysis We can classify a data mining system according to the kind of techniques used. We can describe these techniques according to the degree of user interaction involved or the methods of analysis employed. We can classify a data mining system according to the applications adapted. These applications are as follows − Finance Telecommunications DNA Stock Markets E-mail If a data mining system is not integrated with a database or a data warehouse system, then there will be no system to communicate with. This scheme is known as the non-coupling scheme. In this scheme, the main focus is on data mining design and on developing efficient and effective algorithms for mining the available data sets. The list of Integration Schemes is as follows − No Coupling − In this scheme, the data mining system does not utilize any of the database or data warehouse functions. It fetches the data from a particular source and processes that data using some data mining algorithms. The data mining result is stored in another file. No Coupling − In this scheme, the data mining system does not utilize any of the database or data warehouse functions. It fetches the data from a particular source and processes that data using some data mining algorithms. The data mining result is stored in another file. Loose Coupling − In this scheme, the data mining system may use some of the functions of database and data warehouse system. It fetches the data from the data respiratory managed by these systems and performs data mining on that data. It then stores the mining result either in a file or in a designated place in a database or in a data warehouse. Loose Coupling − In this scheme, the data mining system may use some of the functions of database and data warehouse system. It fetches the data from the data respiratory managed by these systems and performs data mining on that data. It then stores the mining result either in a file or in a designated place in a database or in a data warehouse. Semi−tight Coupling − In this scheme, the data mining system is linked with a database or a data warehouse system and in addition to that, efficient implementations of a few data mining primitives can be provided in the database. Semi−tight Coupling − In this scheme, the data mining system is linked with a database or a data warehouse system and in addition to that, efficient implementations of a few data mining primitives can be provided in the database. Tight coupling − In this coupling scheme, the data mining system is smoothly integrated into the database or data warehouse system. The data mining subsystem is treated as one functional component of an information system. Tight coupling − In this coupling scheme, the data mining system is smoothly integrated into the database or data warehouse system. The data mining subsystem is treated as one functional component of an information system. The Data Mining Query Language (DMQL) was proposed by Han, Fu, Wang, et al. for the DBMiner data mining system. The Data Mining Query Language is actually based on the Structured Query Language (SQL). Data Mining Query Languages can be designed to support ad hoc and interactive data mining. This DMQL provides commands for specifying primitives. The DMQL can work with databases and data warehouses as well. DMQL can be used to define data mining tasks. Particularly we examine how to define data warehouses and data marts in DMQL. Here is the syntax of DMQL for specifying task-relevant data − use database database_name or use data warehouse data_warehouse_name in relevance to att_or_dim_list from relation(s)/cube(s) [where condition] order by order_list group by grouping_list Here we will discuss the syntax for Characterization, Discrimination, Association, Classification, and Prediction. The syntax for characterization is − mine characteristics [as pattern_name] analyze {measure(s) } The analyze clause, specifies aggregate measures, such as count, sum, or count%. For example − Description describing customer purchasing habits. mine characteristics as customerPurchasing analyze count% The syntax for Discrimination is − mine comparison [as {pattern_name]} For {target_class } where {t arget_condition } {versus {contrast_class_i } where {contrast_condition_i}} analyze {measure(s) } For example, a user may define big spenders as customers who purchase items that cost $100 or more on an average; and budget spenders as customers who purchase items at less than $100 on an average. The mining of discriminant descriptions for customers from each of these categories can be specified in the DMQL as − mine comparison as purchaseGroups for bigSpenders where avg(I.price) ≥$100 versus budgetSpenders where avg(I.price)< $100 analyze count The syntax for Association is− mine associations [ as {pattern_name} ] {matching {metapattern} } For Example − mine associations as buyingHabits matching P(X:customer,W) ^ Q(X,Y) ≥ buys(X,Z) where X is key of customer relation; P and Q are predicate variables; and W, Y, and Z are object variables. The syntax for Classification is − mine classification [as pattern_name] analyze classifying_attribute_or_dimension For example, to mine patterns, classifying customer credit rating where the classes are determined by the attribute credit_rating, and mine classification is determined as classifyCustomerCreditRating. analyze credit_rating The syntax for prediction is − mine prediction [as pattern_name] analyze prediction_attribute_or_dimension {set {attribute_or_dimension_i= value_i}} To specify concept hierarchies, use the following syntax − use hierarchy <hierarchy> for <attribute_or_dimension> We use different syntaxes to define different types of hierarchies such as− -schema hierarchies define hierarchy time_hierarchy on date as [date,month quarter,year] - set-grouping hierarchies define hierarchy age_hierarchy for age on customer as level1: {young, middle_aged, senior} < level0: all level2: {20, ..., 39} < level1: young level3: {40, ..., 59} < level1: middle_aged level4: {60, ..., 89} < level1: senior -operation-derived hierarchies define hierarchy age_hierarchy for age on customer as {age_category(1), ..., age_category(5)} := cluster(default, age, 5) < all(age) -rule-based hierarchies define hierarchy profit_margin_hierarchy on item as level_1: low_profit_margin < level_0: all if (price - cost)< $50 level_1: medium-profit_margin < level_0: all if ((price - cost) > $50) and ((price - cost) ≤ $250)) level_1: high_profit_margin < level_0: all Interestingness measures and thresholds can be specified by the user with the statement − with <interest_measure_name> threshold = threshold_value For Example − with support threshold = 0.05 with confidence threshold = 0.7 We have a syntax, which allows users to specify the display of discovered patterns in one or more forms. display as <result_form> For Example − display as table As a market manager of a company, you would like to characterize the buying habits of customers who can purchase items priced at no less than $100; with respect to the customer's age, type of item purchased, and the place where the item was purchased. You would like to know the percentage of customers having that characteristic. In particular, you are only interested in purchases made in Canada, and paid with an American Express credit card. You would like to view the resulting descriptions in the form of a table. use database AllElectronics_db use hierarchy location_hierarchy for B.address mine characteristics as customerPurchasing analyze count% in relevance to C.age,I.type,I.place_made from customer C, item I, purchase P, items_sold S, branch B where I.item_ID = S.item_ID and P.cust_ID = C.cust_ID and P.method_paid = "AmEx" and B.address = "Canada" and I.price ≥ 100 with noise threshold = 5% display as table Standardizing the Data Mining Languages will serve the following purposes − Helps systematic development of data mining solutions. Helps systematic development of data mining solutions. Improves interoperability among multiple data mining systems and functions. Improves interoperability among multiple data mining systems and functions. Promotes education and rapid learning. Promotes education and rapid learning. Promotes the use of data mining systems in industry and society. Promotes the use of data mining systems in industry and society. There are two forms of data analysis that can be used for extracting models describing important classes or to predict future data trends. These two forms are as follows − Classification Prediction Classification models predict categorical class labels; and prediction models predict continuous valued functions. For example, we can build a classification model to categorize bank loan applications as either safe or risky, or a prediction model to predict the expenditures in dollars of potential customers on computer equipment given their income and occupation. Following are the examples of cases where the data analysis task is Classification − A bank loan officer wants to analyze the data in order to know which customer (loan applicant) are risky or which are safe. A bank loan officer wants to analyze the data in order to know which customer (loan applicant) are risky or which are safe. A marketing manager at a company needs to analyze a customer with a given profile, who will buy a new computer. A marketing manager at a company needs to analyze a customer with a given profile, who will buy a new computer. In both of the above examples, a model or classifier is constructed to predict the categorical labels. These labels are risky or safe for loan application data and yes or no for marketing data. Following are the examples of cases where the data analysis task is Prediction − Suppose the marketing manager needs to predict how much a given customer will spend during a sale at his company. In this example we are bothered to predict a numeric value. Therefore the data analysis task is an example of numeric prediction. In this case, a model or a predictor will be constructed that predicts a continuous-valued-function or ordered value. Note − Regression analysis is a statistical methodology that is most often used for numeric prediction. With the help of the bank loan application that we have discussed above, let us understand the working of classification. The Data Classification process includes two steps − Building the Classifier or Model Using Classifier for Classification This step is the learning step or the learning phase. This step is the learning step or the learning phase. In this step the classification algorithms build the classifier. In this step the classification algorithms build the classifier. The classifier is built from the training set made up of database tuples and their associated class labels. The classifier is built from the training set made up of database tuples and their associated class labels. Each tuple that constitutes the training set is referred to as a category or class. These tuples can also be referred to as sample, object or data points. Each tuple that constitutes the training set is referred to as a category or class. These tuples can also be referred to as sample, object or data points. In this step, the classifier is used for classification. Here the test data is used to estimate the accuracy of classification rules. The classification rules can be applied to the new data tuples if the accuracy is considered acceptable. The major issue is preparing the data for Classification and Prediction. Preparing the data involves the following activities − Data Cleaning − Data cleaning involves removing the noise and treatment of missing values. The noise is removed by applying smoothing techniques and the problem of missing values is solved by replacing a missing value with most commonly occurring value for that attribute. Data Cleaning − Data cleaning involves removing the noise and treatment of missing values. The noise is removed by applying smoothing techniques and the problem of missing values is solved by replacing a missing value with most commonly occurring value for that attribute. Relevance Analysis − Database may also have the irrelevant attributes. Correlation analysis is used to know whether any two given attributes are related. Relevance Analysis − Database may also have the irrelevant attributes. Correlation analysis is used to know whether any two given attributes are related. Data Transformation and reduction − The data can be transformed by any of the following methods. Normalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used. Generalization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies. Data Transformation and reduction − The data can be transformed by any of the following methods. Normalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used. Normalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used. Generalization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies. Generalization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies. Note − Data can also be reduced by some other methods such as wavelet transformation, binning, histogram analysis, and clustering. Here is the criteria for comparing the methods of Classification and Prediction − Accuracy − Accuracy of classifier refers to the ability of classifier. It predict the class label correctly and the accuracy of the predictor refers to how well a given predictor can guess the value of predicted attribute for a new data. Accuracy − Accuracy of classifier refers to the ability of classifier. It predict the class label correctly and the accuracy of the predictor refers to how well a given predictor can guess the value of predicted attribute for a new data. Speed − This refers to the computational cost in generating and using the classifier or predictor. Speed − This refers to the computational cost in generating and using the classifier or predictor. Robustness − It refers to the ability of classifier or predictor to make correct predictions from given noisy data. Robustness − It refers to the ability of classifier or predictor to make correct predictions from given noisy data. Scalability − Scalability refers to the ability to construct the classifier or predictor efficiently; given large amount of data. Scalability − Scalability refers to the ability to construct the classifier or predictor efficiently; given large amount of data. Interpretability − It refers to what extent the classifier or predictor understands. Interpretability − It refers to what extent the classifier or predictor understands. A decision tree is a structure that includes a root node, branches, and leaf nodes. Each internal node denotes a test on an attribute, each branch denotes the outcome of a test, and each leaf node holds a class label. The topmost node in the tree is the root node. The following decision tree is for the concept buy_computer that indicates whether a customer at a company is likely to buy a computer or not. Each internal node represents a test on an attribute. Each leaf node represents a class. The benefits of having a decision tree are as follows − It does not require any domain knowledge. It is easy to comprehend. The learning and classification steps of a decision tree are simple and fast. A machine researcher named J. Ross Quinlan in 1980 developed a decision tree algorithm known as ID3 (Iterative Dichotomiser). Later, he presented C4.5, which was the successor of ID3. ID3 and C4.5 adopt a greedy approach. In this algorithm, there is no backtracking; the trees are constructed in a top-down recursive divide-and-conquer manner. Generating a decision tree form training tuples of data partition D Algorithm : Generate_decision_tree Input: Data partition, D, which is a set of training tuples and their associated class labels. attribute_list, the set of candidate attributes. Attribute selection method, a procedure to determine the splitting criterion that best partitions that the data tuples into individual classes. This criterion includes a splitting_attribute and either a splitting point or splitting subset. Output: A Decision Tree Method create a node N; if tuples in D are all of the same class, C then return N as leaf node labeled with class C; if attribute_list is empty then return N as leaf node with labeled with majority class in D;|| majority voting apply attribute_selection_method(D, attribute_list) to find the best splitting_criterion; label node N with splitting_criterion; if splitting_attribute is discrete-valued and multiway splits allowed then // no restricted to binary trees attribute_list = splitting attribute; // remove splitting attribute for each outcome j of splitting criterion // partition the tuples and grow subtrees for each partition let Dj be the set of data tuples in D satisfying outcome j; // a partition if Dj is empty then attach a leaf labeled with the majority class in D to node N; else attach the node returned by Generate decision tree(Dj, attribute list) to node N; end for return N; Tree pruning is performed in order to remove anomalies in the training data due to noise or outliers. The pruned trees are smaller and less complex. There are two approaches to prune a tree − Pre-pruning − The tree is pruned by halting its construction early. Pre-pruning − The tree is pruned by halting its construction early. Post-pruning - This approach removes a sub-tree from a fully grown tree. Post-pruning - This approach removes a sub-tree from a fully grown tree. The cost complexity is measured by the following two parameters − Number of leaves in the tree, and Error rate of the tree. Bayesian classification is based on Bayes' Theorem. Bayesian classifiers are the statistical classifiers. Bayesian classifiers can predict class membership probabilities such as the probability that a given tuple belongs to a particular class. Bayes' Theorem is named after Thomas Bayes. There are two types of probabilities − Posterior Probability [P(H/X)] Prior Probability [P(H)] where X is data tuple and H is some hypothesis. According to Bayes' Theorem, Bayesian Belief Networks specify joint conditional probability distributions. They are also known as Belief Networks, Bayesian Networks, or Probabilistic Networks. A Belief Network allows class conditional independencies to be defined between subsets of variables. A Belief Network allows class conditional independencies to be defined between subsets of variables. It provides a graphical model of causal relationship on which learning can be performed. It provides a graphical model of causal relationship on which learning can be performed. We can use a trained Bayesian Network for classification. We can use a trained Bayesian Network for classification. There are two components that define a Bayesian Belief Network − Directed acyclic graph A set of conditional probability tables Each node in a directed acyclic graph represents a random variable. These variable may be discrete or continuous valued. These variables may correspond to the actual attribute given in the data. The following diagram shows a directed acyclic graph for six Boolean variables. The arc in the diagram allows representation of causal knowledge. For example, lung cancer is influenced by a person's family history of lung cancer, as well as whether or not the person is a smoker. It is worth noting that the variable PositiveXray is independent of whether the patient has a family history of lung cancer or that the patient is a smoker, given that we know the patient has lung cancer. The conditional probability table for the values of the variable LungCancer (LC) showing each possible combination of the values of its parent nodes, FamilyHistory (FH), and Smoker (S) is as follows − Rule-based classifier makes use of a set of IF-THEN rules for classification. We can express a rule in the following from − Let us consider a rule R1, R1: IF age = youth AND student = yes THEN buy_computer = yes Points to remember − The IF part of the rule is called rule antecedent or precondition. The IF part of the rule is called rule antecedent or precondition. The THEN part of the rule is called rule consequent. The THEN part of the rule is called rule consequent. The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed. The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed. The consequent part consists of class prediction. The consequent part consists of class prediction. Note − We can also write rule R1 as follows − R1: (age = youth) ^ (student = yes))(buys computer = yes) If the condition holds true for a given tuple, then the antecedent is satisfied. Here we will learn how to build a rule-based classifier by extracting IF-THEN rules from a decision tree. Points to remember − To extract a rule from a decision tree − One rule is created for each path from the root to the leaf node. One rule is created for each path from the root to the leaf node. To form a rule antecedent, each splitting criterion is logically ANDed. To form a rule antecedent, each splitting criterion is logically ANDed. The leaf node holds the class prediction, forming the rule consequent. The leaf node holds the class prediction, forming the rule consequent. Sequential Covering Algorithm can be used to extract IF-THEN rules form the training data. We do not require to generate a decision tree first. In this algorithm, each rule for a given class covers many of the tuples of that class. Some of the sequential Covering Algorithms are AQ, CN2, and RIPPER. As per the general strategy the rules are learned one at a time. For each time rules are learned, a tuple covered by the rule is removed and the process continues for the rest of the tuples. This is because the path to each leaf in a decision tree corresponds to a rule. Note − The Decision tree induction can be considered as learning a set of rules simultaneously. The Following is the sequential learning Algorithm where rules are learned for one class at a time. When learning a rule from a class Ci, we want the rule to cover all the tuples from class C only and no tuple form any other class. Algorithm: Sequential Covering Input: D, a data set class-labeled tuples, Att_vals, the set of all attributes and their possible values. Output: A Set of IF-THEN rules. Method: Rule_set={ }; // initial set of rules learned is empty for each class c do repeat Rule = Learn_One_Rule(D, Att_valls, c); remove tuples covered by Rule form D; until termination condition; Rule_set=Rule_set+Rule; // add a new rule to rule-set end for return Rule_Set; The rule is pruned is due to the following reason − The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required. The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required. The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples. The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples. FOIL is one of the simple and effective method for rule pruning. For a given rule R, where pos and neg is the number of positive tuples covered by R, respectively. Note − This value will increase with the accuracy of R on the pruning set. Hence, if the FOIL_Prune value is higher for the pruned version of R, then we prune R. Here we will discuss other classification methods such as Genetic Algorithms, Rough Set Approach, and Fuzzy Set Approach. The idea of genetic algorithm is derived from natural evolution. In genetic algorithm, first of all, the initial population is created. This initial population consists of randomly generated rules. We can represent each rule by a string of bits. For example, in a given training set, the samples are described by two Boolean attributes such as A1 and A2. And this given training set contains two classes such as C1 and C2. We can encode the rule IF A1 AND NOT A2 THEN C2 into a bit string 100. In this bit representation, the two leftmost bits represent the attribute A1 and A2, respectively. Likewise, the rule IF NOT A1 AND NOT A2 THEN C1 can be encoded as 001. Note − If the attribute has K values where K>2, then we can use the K bits to encode the attribute values. The classes are also encoded in the same manner. Points to remember − Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well. Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well. The fitness of a rule is assessed by its classification accuracy on a set of training samples. The fitness of a rule is assessed by its classification accuracy on a set of training samples. The genetic operators such as crossover and mutation are applied to create offspring. The genetic operators such as crossover and mutation are applied to create offspring. In crossover, the substring from pair of rules are swapped to form a new pair of rules. In crossover, the substring from pair of rules are swapped to form a new pair of rules. In mutation, randomly selected bits in a rule's string are inverted. In mutation, randomly selected bits in a rule's string are inverted. We can use the rough set approach to discover structural relationship within imprecise and noisy data. Note − This approach can only be applied on discrete-valued attributes. Therefore, continuous-valued attributes must be discretized before its use. The Rough Set Theory is based on the establishment of equivalence classes within the given training data. The tuples that forms the equivalence class are indiscernible. It means the samples are identical with respect to the attributes describing the data. There are some classes in the given real world data, which cannot be distinguished in terms of available attributes. We can use the rough sets to roughly define such classes. For a given class C, the rough set definition is approximated by two sets as follows − Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C. Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C. Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C. Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C. The following diagram shows the Upper and Lower Approximation of class C − Fuzzy Set Theory is also called Possibility Theory. This theory was proposed by Lotfi Zadeh in 1965 as an alternative the two-value logic and probability theory. This theory allows us to work at a high level of abstraction. It also provides us the means for dealing with imprecise measurement of data. The fuzzy set theory also allows us to deal with vague or inexact facts. For example, being a member of a set of high incomes is in exact (e.g. if $50,000 is high then what about $49,000 and $48,000). Unlike the traditional CRISP set where the element either belong to S or its complement but in fuzzy set theory the element can belong to more than one fuzzy set. For example, the income value $49,000 belongs to both the medium and high fuzzy sets but to differing degrees. Fuzzy set notation for this income value is as follows − mmedium_income($49k)=0.15 and mhigh_income($49k)=0.96 where ‘m’ is the membership function that operates on the fuzzy sets of medium_income and high_income respectively. This notation can be shown diagrammatically as follows − Cluster is a group of objects that belongs to the same class. In other words, similar objects are grouped in one cluster and dissimilar objects are grouped in another cluster. Clustering is the process of making a group of abstract objects into classes of similar objects. Points to Remember A cluster of data objects can be treated as one group. A cluster of data objects can be treated as one group. While doing cluster analysis, we first partition the set of data into groups based on data similarity and then assign the labels to the groups. While doing cluster analysis, we first partition the set of data into groups based on data similarity and then assign the labels to the groups. The main advantage of clustering over classification is that, it is adaptable to changes and helps single out useful features that distinguish different groups. The main advantage of clustering over classification is that, it is adaptable to changes and helps single out useful features that distinguish different groups. Clustering analysis is broadly used in many applications such as market research, pattern recognition, data analysis, and image processing. Clustering analysis is broadly used in many applications such as market research, pattern recognition, data analysis, and image processing. Clustering can also help marketers discover distinct groups in their customer base. And they can characterize their customer groups based on the purchasing patterns. Clustering can also help marketers discover distinct groups in their customer base. And they can characterize their customer groups based on the purchasing patterns. In the field of biology, it can be used to derive plant and animal taxonomies, categorize genes with similar functionalities and gain insight into structures inherent to populations. In the field of biology, it can be used to derive plant and animal taxonomies, categorize genes with similar functionalities and gain insight into structures inherent to populations. Clustering also helps in identification of areas of similar land use in an earth observation database. It also helps in the identification of groups of houses in a city according to house type, value, and geographic location. Clustering also helps in identification of areas of similar land use in an earth observation database. It also helps in the identification of groups of houses in a city according to house type, value, and geographic location. Clustering also helps in classifying documents on the web for information discovery. Clustering also helps in classifying documents on the web for information discovery. Clustering is also used in outlier detection applications such as detection of credit card fraud. Clustering is also used in outlier detection applications such as detection of credit card fraud. As a data mining function, cluster analysis serves as a tool to gain insight into the distribution of data to observe characteristics of each cluster. As a data mining function, cluster analysis serves as a tool to gain insight into the distribution of data to observe characteristics of each cluster. The following points throw light on why clustering is required in data mining − Scalability − We need highly scalable clustering algorithms to deal with large databases. Scalability − We need highly scalable clustering algorithms to deal with large databases. Ability to deal with different kinds of attributes − Algorithms should be capable to be applied on any kind of data such as interval-based (numerical) data, categorical, and binary data. Ability to deal with different kinds of attributes − Algorithms should be capable to be applied on any kind of data such as interval-based (numerical) data, categorical, and binary data. Discovery of clusters with attribute shape − The clustering algorithm should be capable of detecting clusters of arbitrary shape. They should not be bounded to only distance measures that tend to find spherical cluster of small sizes. Discovery of clusters with attribute shape − The clustering algorithm should be capable of detecting clusters of arbitrary shape. They should not be bounded to only distance measures that tend to find spherical cluster of small sizes. High dimensionality − The clustering algorithm should not only be able to handle low-dimensional data but also the high dimensional space. High dimensionality − The clustering algorithm should not only be able to handle low-dimensional data but also the high dimensional space. Ability to deal with noisy data − Databases contain noisy, missing or erroneous data. Some algorithms are sensitive to such data and may lead to poor quality clusters. Ability to deal with noisy data − Databases contain noisy, missing or erroneous data. Some algorithms are sensitive to such data and may lead to poor quality clusters. Interpretability − The clustering results should be interpretable, comprehensible, and usable. Interpretability − The clustering results should be interpretable, comprehensible, and usable. Clustering methods can be classified into the following categories − Partitioning Method Hierarchical Method Density-based Method Grid-Based Method Model-Based Method Constraint-based Method Suppose we are given a database of ‘n’ objects and the partitioning method constructs ‘k’ partition of data. Each partition will represent a cluster and k ≤ n. It means that it will classify the data into k groups, which satisfy the following requirements − Each group contains at least one object. Each group contains at least one object. Each object must belong to exactly one group. Each object must belong to exactly one group. Points to remember − For a given number of partitions (say k), the partitioning method will create an initial partitioning. For a given number of partitions (say k), the partitioning method will create an initial partitioning. Then it uses the iterative relocation technique to improve the partitioning by moving objects from one group to other. Then it uses the iterative relocation technique to improve the partitioning by moving objects from one group to other. This method creates a hierarchical decomposition of the given set of data objects. We can classify hierarchical methods on the basis of how the hierarchical decomposition is formed. There are two approaches here − Agglomerative Approach Divisive Approach This approach is also known as the bottom-up approach. In this, we start with each object forming a separate group. It keeps on merging the objects or groups that are close to one another. It keep on doing so until all of the groups are merged into one or until the termination condition holds. This approach is also known as the top-down approach. In this, we start with all of the objects in the same cluster. In the continuous iteration, a cluster is split up into smaller clusters. It is down until each object in one cluster or the termination condition holds. This method is rigid, i.e., once a merging or splitting is done, it can never be undone. Here are the two approaches that are used to improve the quality of hierarchical clustering − Perform careful analysis of object linkages at each hierarchical partitioning. Perform careful analysis of object linkages at each hierarchical partitioning. Integrate hierarchical agglomeration by first using a hierarchical agglomerative algorithm to group objects into micro-clusters, and then performing macro-clustering on the micro-clusters. Integrate hierarchical agglomeration by first using a hierarchical agglomerative algorithm to group objects into micro-clusters, and then performing macro-clustering on the micro-clusters. This method is based on the notion of density. The basic idea is to continue growing the given cluster as long as the density in the neighborhood exceeds some threshold, i.e., for each data point within a given cluster, the radius of a given cluster has to contain at least a minimum number of points. In this, the objects together form a grid. The object space is quantized into finite number of cells that form a grid structure. Advantages The major advantage of this method is fast processing time. The major advantage of this method is fast processing time. It is dependent only on the number of cells in each dimension in the quantized space. It is dependent only on the number of cells in each dimension in the quantized space. In this method, a model is hypothesized for each cluster to find the best fit of data for a given model. This method locates the clusters by clustering the density function. It reflects spatial distribution of the data points. This method also provides a way to automatically determine the number of clusters based on standard statistics, taking outlier or noise into account. It therefore yields robust clustering methods. In this method, the clustering is performed by the incorporation of user or application-oriented constraints. A constraint refers to the user expectation or the properties of desired clustering results. Constraints provide us with an interactive way of communication with the clustering process. Constraints can be specified by the user or the application requirement. Text databases consist of huge collection of documents. They collect these information from several sources such as news articles, books, digital libraries, e-mail messages, web pages, etc. Due to increase in the amount of information, the text databases are growing rapidly. In many of the text databases, the data is semi-structured. For example, a document may contain a few structured fields, such as title, author, publishing_date, etc. But along with the structure data, the document also contains unstructured text components, such as abstract and contents. Without knowing what could be in the documents, it is difficult to formulate effective queries for analyzing and extracting useful information from the data. Users require tools to compare the documents and rank their importance and relevance. Therefore, text mining has become popular and an essential theme in data mining. Information retrieval deals with the retrieval of information from a large number of text-based documents. Some of the database systems are not usually present in information retrieval systems because both handle different kinds of data. Examples of information retrieval system include − Online Library catalogue system Online Document Management Systems Web Search Systems etc. Note − The main problem in an information retrieval system is to locate relevant documents in a document collection based on a user's query. This kind of user's query consists of some keywords describing an information need. In such search problems, the user takes an initiative to pull relevant information out from a collection. This is appropriate when the user has ad-hoc information need, i.e., a short-term need. But if the user has a long-term information need, then the retrieval system can also take an initiative to push any newly arrived information item to the user. This kind of access to information is called Information Filtering. And the corresponding systems are known as Filtering Systems or Recommender Systems. We need to check the accuracy of a system when it retrieves a number of documents on the basis of user's input. Let the set of documents relevant to a query be denoted as {Relevant} and the set of retrieved document as {Retrieved}. The set of documents that are relevant and retrieved can be denoted as {Relevant} ∩ {Retrieved}. This can be shown in the form of a Venn diagram as follows − There are three fundamental measures for assessing the quality of text retrieval − Precision Recall F-score Precision is the percentage of retrieved documents that are in fact relevant to the query. Precision can be defined as − Precision= |{Relevant} ∩ {Retrieved}| / |{Retrieved}| Recall is the percentage of documents that are relevant to the query and were in fact retrieved. Recall is defined as − Recall = |{Relevant} ∩ {Retrieved}| / |{Relevant}| F-score is the commonly used trade-off. The information retrieval system often needs to trade-off for precision or vice versa. F-score is defined as harmonic mean of recall or precision as follows − F-score = recall x precision / (recall + precision) / 2 The World Wide Web contains huge amounts of information that provides a rich source for data mining. The web poses great challenges for resource and knowledge discovery based on the following observations − The web is too huge − The size of the web is very huge and rapidly increasing. This seems that the web is too huge for data warehousing and data mining. The web is too huge − The size of the web is very huge and rapidly increasing. This seems that the web is too huge for data warehousing and data mining. Complexity of Web pages − The web pages do not have unifying structure. They are very complex as compared to traditional text document. There are huge amount of documents in digital library of web. These libraries are not arranged according to any particular sorted order. Complexity of Web pages − The web pages do not have unifying structure. They are very complex as compared to traditional text document. There are huge amount of documents in digital library of web. These libraries are not arranged according to any particular sorted order. Web is dynamic information source − The information on the web is rapidly updated. The data such as news, stock markets, weather, sports, shopping, etc., are regularly updated. Web is dynamic information source − The information on the web is rapidly updated. The data such as news, stock markets, weather, sports, shopping, etc., are regularly updated. Diversity of user communities − The user community on the web is rapidly expanding. These users have different backgrounds, interests, and usage purposes. There are more than 100 million workstations that are connected to the Internet and still rapidly increasing. Diversity of user communities − The user community on the web is rapidly expanding. These users have different backgrounds, interests, and usage purposes. There are more than 100 million workstations that are connected to the Internet and still rapidly increasing. Relevancy of Information − It is considered that a particular person is generally interested in only small portion of the web, while the rest of the portion of the web contains the information that is not relevant to the user and may swamp desired results. Relevancy of Information − It is considered that a particular person is generally interested in only small portion of the web, while the rest of the portion of the web contains the information that is not relevant to the user and may swamp desired results. The basic structure of the web page is based on the Document Object Model (DOM). The DOM structure refers to a tree like structure where the HTML tag in the page corresponds to a node in the DOM tree. We can segment the web page by using predefined tags in HTML. The HTML syntax is flexible therefore, the web pages does not follow the W3C specifications. Not following the specifications of W3C may cause error in DOM tree structure. The DOM structure was initially introduced for presentation in the browser and not for description of semantic structure of the web page. The DOM structure cannot correctly identify the semantic relationship between the different parts of a web page. The purpose of VIPS is to extract the semantic structure of a web page based on its visual presentation. The purpose of VIPS is to extract the semantic structure of a web page based on its visual presentation. Such a semantic structure corresponds to a tree structure. In this tree each node corresponds to a block. Such a semantic structure corresponds to a tree structure. In this tree each node corresponds to a block. A value is assigned to each node. This value is called the Degree of Coherence. This value is assigned to indicate the coherent content in the block based on visual perception. A value is assigned to each node. This value is called the Degree of Coherence. This value is assigned to indicate the coherent content in the block based on visual perception. The VIPS algorithm first extracts all the suitable blocks from the HTML DOM tree. After that it finds the separators between these blocks. The VIPS algorithm first extracts all the suitable blocks from the HTML DOM tree. After that it finds the separators between these blocks. The separators refer to the horizontal or vertical lines in a web page that visually cross with no blocks. The separators refer to the horizontal or vertical lines in a web page that visually cross with no blocks. The semantics of the web page is constructed on the basis of these blocks. The semantics of the web page is constructed on the basis of these blocks. The following figure shows the procedure of VIPS algorithm − Data mining is widely used in diverse areas. There are a number of commercial data mining system available today and yet there are many challenges in this field. In this tutorial, we will discuss the applications and the trend of data mining. Here is the list of areas where data mining is widely used − Financial Data Analysis Retail Industry Telecommunication Industry Biological Data Analysis Other Scientific Applications Intrusion Detection The financial data in banking and financial industry is generally reliable and of high quality which facilitates systematic data analysis and data mining. Some of the typical cases are as follows − Design and construction of data warehouses for multidimensional data analysis and data mining. Design and construction of data warehouses for multidimensional data analysis and data mining. Loan payment prediction and customer credit policy analysis. Loan payment prediction and customer credit policy analysis. Classification and clustering of customers for targeted marketing. Classification and clustering of customers for targeted marketing. Detection of money laundering and other financial crimes. Detection of money laundering and other financial crimes. Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services. It is natural that the quantity of data collected will continue to expand rapidly because of the increasing ease, availability and popularity of the web. Data mining in retail industry helps in identifying customer buying patterns and trends that lead to improved quality of customer service and good customer retention and satisfaction. Here is the list of examples of data mining in the retail industry − Design and Construction of data warehouses based on the benefits of data mining. Design and Construction of data warehouses based on the benefits of data mining. Multidimensional analysis of sales, customers, products, time and region. Multidimensional analysis of sales, customers, products, time and region. Analysis of effectiveness of sales campaigns. Analysis of effectiveness of sales campaigns. Customer Retention. Customer Retention. Product recommendation and cross-referencing of items. Product recommendation and cross-referencing of items. Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc. Due to the development of new computer and communication technologies, the telecommunication industry is rapidly expanding. This is the reason why data mining is become very important to help and understand the business. Data mining in telecommunication industry helps in identifying the telecommunication patterns, catch fraudulent activities, make better use of resource, and improve quality of service. Here is the list of examples for which data mining improves telecommunication services − Multidimensional Analysis of Telecommunication data. Multidimensional Analysis of Telecommunication data. Fraudulent pattern analysis. Fraudulent pattern analysis. Identification of unusual patterns. Identification of unusual patterns. Multidimensional association and sequential patterns analysis. Multidimensional association and sequential patterns analysis. Mobile Telecommunication services. Mobile Telecommunication services. Use of visualization tools in telecommunication data analysis. Use of visualization tools in telecommunication data analysis. In recent times, we have seen a tremendous growth in the field of biology such as genomics, proteomics, functional Genomics and biomedical research. Biological data mining is a very important part of Bioinformatics. Following are the aspects in which data mining contributes for biological data analysis − Semantic integration of heterogeneous, distributed genomic and proteomic databases. Semantic integration of heterogeneous, distributed genomic and proteomic databases. Alignment, indexing, similarity search and comparative analysis multiple nucleotide sequences. Alignment, indexing, similarity search and comparative analysis multiple nucleotide sequences. Discovery of structural patterns and analysis of genetic networks and protein pathways. Discovery of structural patterns and analysis of genetic networks and protein pathways. Association and path analysis. Association and path analysis. Visualization tools in genetic data analysis. Visualization tools in genetic data analysis. The applications discussed above tend to handle relatively small and homogeneous data sets for which the statistical techniques are appropriate. Huge amount of data have been collected from scientific domains such as geosciences, astronomy, etc. A large amount of data sets is being generated because of the fast numerical simulations in various fields such as climate and ecosystem modeling, chemical engineering, fluid dynamics, etc. Following are the applications of data mining in the field of Scientific Applications − Data Warehouses and data preprocessing. Graph-based mining. Visualization and domain specific knowledge. Intrusion refers to any kind of action that threatens integrity, confidentiality, or the availability of network resources. In this world of connectivity, security has become the major issue. With increased usage of internet and availability of the tools and tricks for intruding and attacking network prompted intrusion detection to become a critical component of network administration. Here is the list of areas in which data mining technology may be applied for intrusion detection − Development of data mining algorithm for intrusion detection. Development of data mining algorithm for intrusion detection. Association and correlation analysis, aggregation to help select and build discriminating attributes. Association and correlation analysis, aggregation to help select and build discriminating attributes. Analysis of Stream data. Analysis of Stream data. Distributed data mining. Distributed data mining. Visualization and query tools. Visualization and query tools. There are many data mining system products and domain specific data mining applications. The new data mining systems and applications are being added to the previous systems. Also, efforts are being made to standardize data mining languages. The selection of a data mining system depends on the following features − Data Types − The data mining system may handle formatted text, record-based data, and relational data. The data could also be in ASCII text, relational database data or data warehouse data. Therefore, we should check what exact format the data mining system can handle. Data Types − The data mining system may handle formatted text, record-based data, and relational data. The data could also be in ASCII text, relational database data or data warehouse data. Therefore, we should check what exact format the data mining system can handle. System Issues − We must consider the compatibility of a data mining system with different operating systems. One data mining system may run on only one operating system or on several. There are also data mining systems that provide web-based user interfaces and allow XML data as input. System Issues − We must consider the compatibility of a data mining system with different operating systems. One data mining system may run on only one operating system or on several. There are also data mining systems that provide web-based user interfaces and allow XML data as input. Data Sources − Data sources refer to the data formats in which data mining system will operate. Some data mining system may work only on ASCII text files while others on multiple relational sources. Data mining system should also support ODBC connections or OLE DB for ODBC connections. Data Sources − Data sources refer to the data formats in which data mining system will operate. Some data mining system may work only on ASCII text files while others on multiple relational sources. Data mining system should also support ODBC connections or OLE DB for ODBC connections. Data Mining functions and methodologies − There are some data mining systems that provide only one data mining function such as classification while some provides multiple data mining functions such as concept description, discovery-driven OLAP analysis, association mining, linkage analysis, statistical analysis, classification, prediction, clustering, outlier analysis, similarity search, etc. Data Mining functions and methodologies − There are some data mining systems that provide only one data mining function such as classification while some provides multiple data mining functions such as concept description, discovery-driven OLAP analysis, association mining, linkage analysis, statistical analysis, classification, prediction, clustering, outlier analysis, similarity search, etc. Coupling data mining with databases or data warehouse systems − Data mining systems need to be coupled with a database or a data warehouse system. The coupled components are integrated into a uniform information processing environment. Here are the types of coupling listed below − No coupling Loose Coupling Semi tight Coupling Tight Coupling Coupling data mining with databases or data warehouse systems − Data mining systems need to be coupled with a database or a data warehouse system. The coupled components are integrated into a uniform information processing environment. Here are the types of coupling listed below − No coupling Loose Coupling Semi tight Coupling Tight Coupling Scalability − There are two scalability issues in data mining − Row (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query. Column (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns. Scalability − There are two scalability issues in data mining − Row (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query. Row (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query. Column (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns. Column (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns. Visualization Tools − Visualization in data mining can be categorized as follows − Data Visualization Mining Results Visualization Mining process visualization Visual data mining Visualization Tools − Visualization in data mining can be categorized as follows − Data Visualization Mining Results Visualization Mining process visualization Visual data mining Data Mining query language and graphical user interface − An easy-to-use graphical user interface is important to promote user-guided, interactive data mining. Unlike relational database systems, data mining systems do not share underlying data mining query language. Data Mining query language and graphical user interface − An easy-to-use graphical user interface is important to promote user-guided, interactive data mining. Unlike relational database systems, data mining systems do not share underlying data mining query language. Data mining concepts are still evolving and here are the latest trends that we get to see in this field − Application Exploration. Application Exploration. Scalable and interactive data mining methods. Scalable and interactive data mining methods. Integration of data mining with database systems, data warehouse systems and web database systems. Integration of data mining with database systems, data warehouse systems and web database systems. SStandardization of data mining query language. SStandardization of data mining query language. Visual data mining. Visual data mining. New methods for mining complex types of data. New methods for mining complex types of data. Biological data mining. Biological data mining. Data mining and software engineering. Data mining and software engineering. Web mining. Web mining. Distributed data mining. Distributed data mining. Real time data mining. Real time data mining. Multi database data mining. Multi database data mining. Privacy protection and information security in data mining. Privacy protection and information security in data mining. The theoretical foundations of data mining includes the following concepts − Data Reduction − The basic idea of this theory is to reduce the data representation which trades accuracy for speed in response to the need to obtain quick approximate answers to queries on very large databases. Some of the data reduction techniques are as follows − Singular value Decomposition Wavelets Regression Log-linear models Histograms Clustering Sampling Construction of Index Trees Data Reduction − The basic idea of this theory is to reduce the data representation which trades accuracy for speed in response to the need to obtain quick approximate answers to queries on very large databases. Some of the data reduction techniques are as follows − Singular value Decomposition Singular value Decomposition Wavelets Wavelets Regression Regression Log-linear models Log-linear models Histograms Histograms Clustering Clustering Sampling Sampling Construction of Index Trees Construction of Index Trees Data Compression − The basic idea of this theory is to compress the given data by encoding in terms of the following − Bits Association Rules Decision Trees Clusters Data Compression − The basic idea of this theory is to compress the given data by encoding in terms of the following − Bits Bits Association Rules Association Rules Decision Trees Decision Trees Clusters Clusters Pattern Discovery − The basic idea of this theory is to discover patterns occurring in a database. Following are the areas that contribute to this theory − Machine Learning Neural Network Association Mining Sequential Pattern Matching Clustering Pattern Discovery − The basic idea of this theory is to discover patterns occurring in a database. Following are the areas that contribute to this theory − Machine Learning Machine Learning Neural Network Neural Network Association Mining Association Mining Sequential Pattern Matching Sequential Pattern Matching Clustering Clustering Probability Theory − This theory is based on statistical theory. The basic idea behind this theory is to discover joint probability distributions of random variables. Probability Theory − This theory is based on statistical theory. The basic idea behind this theory is to discover joint probability distributions of random variables. Probability Theory − According to this theory, data mining finds the patterns that are interesting only to the extent that they can be used in the decision-making process of some enterprise. Probability Theory − According to this theory, data mining finds the patterns that are interesting only to the extent that they can be used in the decision-making process of some enterprise. Microeconomic View − As per this theory, a database schema consists of data and patterns that are stored in a database. Therefore, data mining is the task of performing induction on databases. Microeconomic View − As per this theory, a database schema consists of data and patterns that are stored in a database. Therefore, data mining is the task of performing induction on databases. Inductive databases − Apart from the database-oriented techniques, there are statistical techniques available for data analysis. These techniques can be applied to scientific data and data from economic and social sciences as well. Inductive databases − Apart from the database-oriented techniques, there are statistical techniques available for data analysis. These techniques can be applied to scientific data and data from economic and social sciences as well. Some of the Statistical Data Mining Techniques are as follows − Regression − Regression methods are used to predict the value of the response variable from one or more predictor variables where the variables are numeric. Listed below are the forms of Regression − Linear Multiple Weighted Polynomial Nonparametric Robust Regression − Regression methods are used to predict the value of the response variable from one or more predictor variables where the variables are numeric. Listed below are the forms of Regression − Linear Linear Multiple Multiple Weighted Weighted Polynomial Polynomial Nonparametric Nonparametric Robust Robust Generalized Linear Models − Generalized Linear Model includes − Logistic Regression Poisson Regression The model's generalization allows a categorical response variable to be related to a set of predictor variables in a manner similar to the modelling of numeric response variable using linear regression. Generalized Linear Models − Generalized Linear Model includes − Logistic Regression Logistic Regression Poisson Regression Poisson Regression The model's generalization allows a categorical response variable to be related to a set of predictor variables in a manner similar to the modelling of numeric response variable using linear regression. Analysis of Variance − This technique analyzes − Experimental data for two or more populations described by a numeric response variable. One or more categorical variables (factors). Analysis of Variance − This technique analyzes − Experimental data for two or more populations described by a numeric response variable. Experimental data for two or more populations described by a numeric response variable. One or more categorical variables (factors). One or more categorical variables (factors). Mixed-effect Models − These models are used for analyzing grouped data. These models describe the relationship between a response variable and some co-variates in the data grouped according to one or more factors. Mixed-effect Models − These models are used for analyzing grouped data. These models describe the relationship between a response variable and some co-variates in the data grouped according to one or more factors. Factor Analysis − Factor analysis is used to predict a categorical response variable. This method assumes that independent variables follow a multivariate normal distribution. Factor Analysis − Factor analysis is used to predict a categorical response variable. This method assumes that independent variables follow a multivariate normal distribution. Time Series Analysis − Following are the methods for analyzing time-series data − Auto-regression Methods. Univariate ARIMA (AutoRegressive Integrated Moving Average) Modeling. Long-memory time-series modeling. Time Series Analysis − Following are the methods for analyzing time-series data − Auto-regression Methods. Auto-regression Methods. Univariate ARIMA (AutoRegressive Integrated Moving Average) Modeling. Univariate ARIMA (AutoRegressive Integrated Moving Average) Modeling. Long-memory time-series modeling. Long-memory time-series modeling. Visual Data Mining uses data and/or knowledge visualization techniques to discover implicit knowledge from large data sets. Visual data mining can be viewed as an integration of the following disciplines − Data Visualization Data Visualization Data Mining Data Mining Visual data mining is closely related to the following − Computer Graphics Computer Graphics Multimedia Systems Multimedia Systems Human Computer Interaction Human Computer Interaction Pattern Recognition Pattern Recognition High-performance Computing High-performance Computing Generally data visualization and data mining can be integrated in the following ways − Data Visualization − The data in a database or a data warehouse can be viewed in several visual forms that are listed below − Boxplots 3-D Cubes Data distribution charts Curves Surfaces Link graphs etc. Data Visualization − The data in a database or a data warehouse can be viewed in several visual forms that are listed below − Boxplots Boxplots 3-D Cubes 3-D Cubes Data distribution charts Data distribution charts Curves Curves Surfaces Surfaces Link graphs etc. Link graphs etc. Data Mining Result Visualization − Data Mining Result Visualization is the presentation of the results of data mining in visual forms. These visual forms could be scattered plots, boxplots, etc. Data Mining Result Visualization − Data Mining Result Visualization is the presentation of the results of data mining in visual forms. These visual forms could be scattered plots, boxplots, etc. Data Mining Process Visualization − Data Mining Process Visualization presents the several processes of data mining. It allows the users to see how the data is extracted. It also allows the users to see from which database or data warehouse the data is cleaned, integrated, preprocessed, and mined. Data Mining Process Visualization − Data Mining Process Visualization presents the several processes of data mining. It allows the users to see how the data is extracted. It also allows the users to see from which database or data warehouse the data is cleaned, integrated, preprocessed, and mined. Audio data mining makes use of audio signals to indicate the patterns of data or the features of data mining results. By transforming patterns into sound and musing, we can listen to pitches and tunes, instead of watching pictures, in order to identify anything interesting. Consumers today come across a variety of goods and services while shopping. During live customer transactions, a Recommender System helps the consumer by making product recommendations. The Collaborative Filtering Approach is generally used for recommending products to customers. These recommendations are based on the opinions of other customers. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2342, "s": 2110, "text": "There is a huge amount of data available in the Information Industry. This data is of no use until it is converted into useful information. It is necessary to analyze this huge amount of data and extract useful information from it." }, { "code": null, "e": 2756, "s": 2342, "text": "Extraction of information is not the only process we need to perform; data mining also involves other processes such as Data Cleaning, Data Integration, Data Transformation, Data Mining, Pattern Evaluation and Data Presentation. Once all these processes are over, we would be able to use this information in many applications such as Fraud Detection, Market Analysis, Production Control, Science Exploration, etc." }, { "code": null, "e": 3015, "s": 2756, "text": "Data Mining is defined as extracting information from huge sets of data. In other words, we can say that data mining is the procedure of mining knowledge from data. The information or knowledge extracted so can be used for any of the following applications −" }, { "code": null, "e": 3031, "s": 3015, "text": "Market Analysis" }, { "code": null, "e": 3047, "s": 3031, "text": "Fraud Detection" }, { "code": null, "e": 3066, "s": 3047, "text": "Customer Retention" }, { "code": null, "e": 3085, "s": 3066, "text": "Production Control" }, { "code": null, "e": 3105, "s": 3085, "text": "Science Exploration" }, { "code": null, "e": 3161, "s": 3105, "text": "Data mining is highly useful in the following domains −" }, { "code": null, "e": 3192, "s": 3161, "text": "Market Analysis and Management" }, { "code": null, "e": 3229, "s": 3192, "text": "Corporate Analysis & Risk Management" }, { "code": null, "e": 3245, "s": 3229, "text": "Fraud Detection" }, { "code": null, "e": 3414, "s": 3245, "text": "Apart from these, data mining can also be used in the areas of production control, customer retention, science exploration, sports, astrology, and Internet Web Surf-Aid" }, { "code": null, "e": 3488, "s": 3414, "text": "Listed below are the various fields of market where data mining is used −" }, { "code": null, "e": 3584, "s": 3488, "text": "Customer Profiling − Data mining helps determine what kind of people buy what kind of products." }, { "code": null, "e": 3680, "s": 3584, "text": "Customer Profiling − Data mining helps determine what kind of people buy what kind of products." }, { "code": null, "e": 3863, "s": 3680, "text": "Identifying Customer Requirements − Data mining helps in identifying the best products for different customers. It uses prediction to find the factors that may attract new customers." }, { "code": null, "e": 4046, "s": 3863, "text": "Identifying Customer Requirements − Data mining helps in identifying the best products for different customers. It uses prediction to find the factors that may attract new customers." }, { "code": null, "e": 4139, "s": 4046, "text": "Cross Market Analysis − Data mining performs Association/correlations between product sales." }, { "code": null, "e": 4232, "s": 4139, "text": "Cross Market Analysis − Data mining performs Association/correlations between product sales." }, { "code": null, "e": 4389, "s": 4232, "text": "Target Marketing − Data mining helps to find clusters of model customers who share the same characteristics such as interests, spending habits, income, etc." }, { "code": null, "e": 4546, "s": 4389, "text": "Target Marketing − Data mining helps to find clusters of model customers who share the same characteristics such as interests, spending habits, income, etc." }, { "code": null, "e": 4650, "s": 4546, "text": "Determining Customer purchasing pattern − Data mining helps in determining customer purchasing pattern." }, { "code": null, "e": 4754, "s": 4650, "text": "Determining Customer purchasing pattern − Data mining helps in determining customer purchasing pattern." }, { "code": null, "e": 4852, "s": 4754, "text": "Providing Summary Information − Data mining provides us various multidimensional summary reports." }, { "code": null, "e": 4950, "s": 4852, "text": "Providing Summary Information − Data mining provides us various multidimensional summary reports." }, { "code": null, "e": 5020, "s": 4950, "text": "Data mining is used in the following fields of the Corporate Sector −" }, { "code": null, "e": 5153, "s": 5020, "text": "Finance Planning and Asset Evaluation − It involves cash flow analysis and prediction, contingent claim analysis to evaluate assets." }, { "code": null, "e": 5286, "s": 5153, "text": "Finance Planning and Asset Evaluation − It involves cash flow analysis and prediction, contingent claim analysis to evaluate assets." }, { "code": null, "e": 5372, "s": 5286, "text": "Resource Planning − It involves summarizing and comparing the resources and spending." }, { "code": null, "e": 5458, "s": 5372, "text": "Resource Planning − It involves summarizing and comparing the resources and spending." }, { "code": null, "e": 5530, "s": 5458, "text": "Competition − It involves monitoring competitors and market directions." }, { "code": null, "e": 5602, "s": 5530, "text": "Competition − It involves monitoring competitors and market directions." }, { "code": null, "e": 5893, "s": 5602, "text": "Data mining is also used in the fields of credit card services and telecommunication to detect frauds. In fraud telephone calls, it helps to find the destination of the call, duration of the call, time of the day or week, etc. It also analyzes the patterns that deviate from expected norms." }, { "code": null, "e": 6066, "s": 5893, "text": "Data mining deals with the kind of patterns that can be mined. On the basis of the kind\nof data to be mined, there are two categories of functions involved in Data Mining −" }, { "code": null, "e": 6078, "s": 6066, "text": "Descriptive" }, { "code": null, "e": 6108, "s": 6078, "text": "Classification and Prediction" }, { "code": null, "e": 6236, "s": 6108, "text": "The descriptive function deals with the general properties of data in the database. Here\nis the list of descriptive functions −" }, { "code": null, "e": 6262, "s": 6236, "text": "Class/Concept Description" }, { "code": null, "e": 6290, "s": 6262, "text": "Mining of Frequent Patterns" }, { "code": null, "e": 6313, "s": 6290, "text": "Mining of Associations" }, { "code": null, "e": 6336, "s": 6313, "text": "Mining of Correlations" }, { "code": null, "e": 6355, "s": 6336, "text": "Mining of Clusters" }, { "code": null, "e": 6735, "s": 6355, "text": "Class/Concept refers to the data to be associated with the classes or concepts. For example, in a company, the classes of items for sales include computer and printers, and concepts of customers include big spenders and budget spenders. Such descriptions of a class or a concept are called class/concept descriptions. These descriptions can be derived by the following two ways −" }, { "code": null, "e": 6863, "s": 6735, "text": "Data Characterization − This refers to summarizing data of class under study. This class under study is called as Target Class." }, { "code": null, "e": 6991, "s": 6863, "text": "Data Characterization − This refers to summarizing data of class under study. This class under study is called as Target Class." }, { "code": null, "e": 7104, "s": 6991, "text": "Data Discrimination − It refers to the mapping or classification of a class with some predefined group or class." }, { "code": null, "e": 7217, "s": 7104, "text": "Data Discrimination − It refers to the mapping or classification of a class with some predefined group or class." }, { "code": null, "e": 7347, "s": 7217, "text": "Frequent patterns are those patterns that occur frequently in transactional data. Here is\nthe list of kind of frequent patterns −" }, { "code": null, "e": 7457, "s": 7347, "text": "Frequent Item Set − It refers to a set of items that frequently appear together, for example, milk and bread." }, { "code": null, "e": 7567, "s": 7457, "text": "Frequent Item Set − It refers to a set of items that frequently appear together, for example, milk and bread." }, { "code": null, "e": 7691, "s": 7567, "text": "Frequent Subsequence − A sequence of patterns that occur frequently such as\npurchasing a camera is followed by memory card." }, { "code": null, "e": 7815, "s": 7691, "text": "Frequent Subsequence − A sequence of patterns that occur frequently such as\npurchasing a camera is followed by memory card." }, { "code": null, "e": 7981, "s": 7815, "text": "Frequent Sub Structure − Substructure refers to different structural forms, such as graphs, trees, or lattices, which may be combined with item-sets or subsequences." }, { "code": null, "e": 8147, "s": 7981, "text": "Frequent Sub Structure − Substructure refers to different structural forms, such as graphs, trees, or lattices, which may be combined with item-sets or subsequences." }, { "code": null, "e": 8358, "s": 8147, "text": "Associations are used in retail sales to identify patterns that are frequently purchased\ntogether. This process refers to the process of uncovering the relationship among data and determining association rules." }, { "code": null, "e": 8516, "s": 8358, "text": "For example, a retailer generates an association rule that shows that 70% of time milk is\nsold with bread and only 30% of times biscuits are sold with bread." }, { "code": null, "e": 8752, "s": 8516, "text": "It is a kind of additional analysis performed to uncover interesting statistical correlations\nbetween associated-attribute-value pairs or between two item sets to analyze that if they have positive, negative or no effect on each other." }, { "code": null, "e": 8955, "s": 8752, "text": "Cluster refers to a group of similar kind of objects. Cluster analysis refers to forming\ngroup of objects that are very similar to each other but are highly different from the objects in other clusters." }, { "code": null, "e": 9285, "s": 8955, "text": "Classification is the process of finding a model that describes the data classes or concepts. The purpose is to be able to use this model to predict the class of objects whose class label is unknown. This derived model is based on the analysis of sets of training data. The derived model can be presented in the following forms −" }, { "code": null, "e": 9316, "s": 9285, "text": "Classification (IF-THEN) Rules" }, { "code": null, "e": 9331, "s": 9316, "text": "Decision Trees" }, { "code": null, "e": 9353, "s": 9331, "text": "Mathematical Formulae" }, { "code": null, "e": 9369, "s": 9353, "text": "Neural Networks" }, { "code": null, "e": 9436, "s": 9369, "text": "The list of functions involved in these processes are as follows −" }, { "code": null, "e": 9734, "s": 9436, "text": "Classification − It predicts the class of objects whose class label is unknown. Its objective is to find a derived model that describes and distinguishes data classes\nor concepts. The Derived Model is based on the analysis set of training data i.e. the data object whose class label is well known." }, { "code": null, "e": 10032, "s": 9734, "text": "Classification − It predicts the class of objects whose class label is unknown. Its objective is to find a derived model that describes and distinguishes data classes\nor concepts. The Derived Model is based on the analysis set of training data i.e. the data object whose class label is well known." }, { "code": null, "e": 10287, "s": 10032, "text": "Prediction − It is used to predict missing or unavailable numerical data values rather than class labels. Regression Analysis is generally used for prediction. Prediction can also be used for identification of distribution trends based on available data." }, { "code": null, "e": 10542, "s": 10287, "text": "Prediction − It is used to predict missing or unavailable numerical data values rather than class labels. Regression Analysis is generally used for prediction. Prediction can also be used for identification of distribution trends based on available data." }, { "code": null, "e": 10682, "s": 10542, "text": "Outlier Analysis − Outliers may be defined as the data objects that do not\ncomply with the general behavior or model of the data available." }, { "code": null, "e": 10822, "s": 10682, "text": "Outlier Analysis − Outliers may be defined as the data objects that do not\ncomply with the general behavior or model of the data available." }, { "code": null, "e": 10967, "s": 10822, "text": "Evolution Analysis − Evolution analysis refers to the description and model\nregularities or trends for objects whose behavior changes over time." }, { "code": null, "e": 11112, "s": 10967, "text": "Evolution Analysis − Evolution analysis refers to the description and model\nregularities or trends for objects whose behavior changes over time." }, { "code": null, "e": 11182, "s": 11112, "text": "We can specify a data mining task in the form of a data mining query." }, { "code": null, "e": 11217, "s": 11182, "text": "This query is input to the system." }, { "code": null, "e": 11289, "s": 11217, "text": "A data mining query is defined in terms of data mining task primitives." }, { "code": null, "e": 11441, "s": 11289, "text": "Note − These primitives allow us to communicate in an interactive manner with the data mining system. Here is the list of Data Mining Task Primitives −" }, { "code": null, "e": 11480, "s": 11441, "text": "Set of task relevant data to be mined." }, { "code": null, "e": 11511, "s": 11480, "text": "Kind of knowledge to be mined." }, { "code": null, "e": 11565, "s": 11511, "text": "Background knowledge to be used in discovery process." }, { "code": null, "e": 11629, "s": 11565, "text": "Interestingness measures and thresholds for pattern evaluation." }, { "code": null, "e": 11685, "s": 11629, "text": "Representation for visualizing the discovered patterns." }, { "code": null, "e": 11788, "s": 11685, "text": "This is the portion of database in which the user is interested. This portion includes the\nfollowing −" }, { "code": null, "e": 11808, "s": 11788, "text": "Database Attributes" }, { "code": null, "e": 11846, "s": 11808, "text": "Data Warehouse dimensions of interest" }, { "code": null, "e": 11920, "s": 11846, "text": "It refers to the kind of functions to be performed. These functions are −" }, { "code": null, "e": 11937, "s": 11920, "text": "Characterization" }, { "code": null, "e": 11952, "s": 11937, "text": "Discrimination" }, { "code": null, "e": 11989, "s": 11952, "text": "Association and Correlation Analysis" }, { "code": null, "e": 12004, "s": 11989, "text": "Classification" }, { "code": null, "e": 12015, "s": 12004, "text": "Prediction" }, { "code": null, "e": 12026, "s": 12015, "text": "Clustering" }, { "code": null, "e": 12043, "s": 12026, "text": "Outlier Analysis" }, { "code": null, "e": 12062, "s": 12043, "text": "Evolution Analysis" }, { "code": null, "e": 12283, "s": 12062, "text": "The background knowledge allows data to be mined at multiple levels of abstraction. For\nexample, the Concept hierarchies are one of the background knowledge that allows data to be mined at multiple levels of abstraction." }, { "code": null, "e": 12454, "s": 12283, "text": "This is used to evaluate the patterns that are discovered by the process of knowledge discovery. There are different interesting measures for different kind of knowledge." }, { "code": null, "e": 12579, "s": 12454, "text": "This refers to the form in which discovered patterns are to be displayed. These representations may include the following. −" }, { "code": null, "e": 12585, "s": 12579, "text": "Rules" }, { "code": null, "e": 12592, "s": 12585, "text": "Tables" }, { "code": null, "e": 12599, "s": 12592, "text": "Charts" }, { "code": null, "e": 12606, "s": 12599, "text": "Graphs" }, { "code": null, "e": 12621, "s": 12606, "text": "Decision Trees" }, { "code": null, "e": 12627, "s": 12621, "text": "Cubes" }, { "code": null, "e": 12925, "s": 12627, "text": "Data mining is not an easy task, as the algorithms used can get very complex and data is not always available at one place. It needs to be integrated from various heterogeneous data sources. These factors also create some issues. Here in this tutorial, we will discuss the major issues regarding −" }, { "code": null, "e": 12965, "s": 12925, "text": "Mining Methodology and User Interaction" }, { "code": null, "e": 12984, "s": 12965, "text": "Performance Issues" }, { "code": null, "e": 13010, "s": 12984, "text": "Diverse Data Types Issues" }, { "code": null, "e": 13060, "s": 13010, "text": "The following diagram describes the major issues." }, { "code": null, "e": 13105, "s": 13060, "text": "It refers to the following kinds of issues −" }, { "code": null, "e": 13317, "s": 13105, "text": "Mining different kinds of knowledge in databases − Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery task." }, { "code": null, "e": 13529, "s": 13317, "text": "Mining different kinds of knowledge in databases − Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery task." }, { "code": null, "e": 13778, "s": 13529, "text": "Interactive mining of knowledge at multiple levels of abstraction − The data mining process needs to be interactive because it allows users to focus the search for patterns, providing and refining data mining requests based on the returned results." }, { "code": null, "e": 14027, "s": 13778, "text": "Interactive mining of knowledge at multiple levels of abstraction − The data mining process needs to be interactive because it allows users to focus the search for patterns, providing and refining data mining requests based on the returned results." }, { "code": null, "e": 14305, "s": 14027, "text": "Incorporation of background knowledge − To guide discovery process and to express the discovered patterns, the background knowledge can be used. Background knowledge may be used to express the discovered patterns not only in concise terms but at multiple levels of abstraction." }, { "code": null, "e": 14583, "s": 14305, "text": "Incorporation of background knowledge − To guide discovery process and to express the discovered patterns, the background knowledge can be used. Background knowledge may be used to express the discovered patterns not only in concise terms but at multiple levels of abstraction." }, { "code": null, "e": 14829, "s": 14583, "text": "Data mining query languages and ad hoc data mining − Data Mining Query language that allows the user to describe ad hoc mining tasks, should be integrated with a data warehouse query language and optimized for efficient and flexible data mining." }, { "code": null, "e": 15075, "s": 14829, "text": "Data mining query languages and ad hoc data mining − Data Mining Query language that allows the user to describe ad hoc mining tasks, should be integrated with a data warehouse query language and optimized for efficient and flexible data mining." }, { "code": null, "e": 15297, "s": 15075, "text": "Presentation and visualization of data mining results − Once the patterns are discovered it needs to be expressed in high level languages, and visual representations. These representations should be easily understandable." }, { "code": null, "e": 15519, "s": 15297, "text": "Presentation and visualization of data mining results − Once the patterns are discovered it needs to be expressed in high level languages, and visual representations. These representations should be easily understandable." }, { "code": null, "e": 15775, "s": 15519, "text": "Handling noisy or incomplete data − The data cleaning methods are required to handle the noise and incomplete objects while mining the data regularities. If the data cleaning methods are not there then the accuracy of the discovered patterns will be poor." }, { "code": null, "e": 16031, "s": 15775, "text": "Handling noisy or incomplete data − The data cleaning methods are required to handle the noise and incomplete objects while mining the data regularities. If the data cleaning methods are not there then the accuracy of the discovered patterns will be poor." }, { "code": null, "e": 16162, "s": 16031, "text": "Pattern evaluation − The patterns discovered should be interesting because either they represent common knowledge or lack novelty." }, { "code": null, "e": 16293, "s": 16162, "text": "Pattern evaluation − The patterns discovered should be interesting because either they represent common knowledge or lack novelty." }, { "code": null, "e": 16351, "s": 16293, "text": "There can be performance-related issues such as follows −" }, { "code": null, "e": 16547, "s": 16351, "text": "Efficiency and scalability of data mining algorithms − In order to effectively extract the information from huge amount of data in databases, data mining algorithm must be efficient and scalable." }, { "code": null, "e": 16743, "s": 16547, "text": "Efficiency and scalability of data mining algorithms − In order to effectively extract the information from huge amount of data in databases, data mining algorithm must be efficient and scalable." }, { "code": null, "e": 17224, "s": 16743, "text": "Parallel, distributed, and incremental mining algorithms − The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate the development of parallel and distributed data mining algorithms. These algorithms divide the data into partitions which is further processed in a parallel fashion. Then the results from the partitions is merged. The incremental algorithms, update databases without mining the data again from scratch." }, { "code": null, "e": 17705, "s": 17224, "text": "Parallel, distributed, and incremental mining algorithms − The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate the development of parallel and distributed data mining algorithms. These algorithms divide the data into partitions which is further processed in a parallel fashion. Then the results from the partitions is merged. The incremental algorithms, update databases without mining the data again from scratch." }, { "code": null, "e": 17927, "s": 17705, "text": "Handling of relational and complex types of data − The database may contain complex data objects, multimedia data objects, spatial data, temporal data etc. It is not possible for one system to mine all these kind of data." }, { "code": null, "e": 18149, "s": 17927, "text": "Handling of relational and complex types of data − The database may contain complex data objects, multimedia data objects, spatial data, temporal data etc. It is not possible for one system to mine all these kind of data." }, { "code": null, "e": 18436, "s": 18149, "text": "Mining information from heterogeneous databases and global information systems − The data is available at different data sources on LAN or WAN. These data source may be structured, semi structured or unstructured. Therefore mining the knowledge from them adds challenges to data mining." }, { "code": null, "e": 18723, "s": 18436, "text": "Mining information from heterogeneous databases and global information systems − The data is available at different data sources on LAN or WAN. These data source may be structured, semi structured or unstructured. Therefore mining the knowledge from them adds challenges to data mining." }, { "code": null, "e": 18833, "s": 18723, "text": "A data warehouse exhibits the following characteristics to support the management's decision-making process −" }, { "code": null, "e": 19202, "s": 18833, "text": "Subject Oriented − Data warehouse is subject oriented because it provides us the information around a subject rather than the organization's ongoing operations. These subjects can be product, customers, suppliers, sales, revenue, etc. The data warehouse does not focus on the ongoing operations, rather it focuses on modelling and analysis of data for decision-making." }, { "code": null, "e": 19571, "s": 19202, "text": "Subject Oriented − Data warehouse is subject oriented because it provides us the information around a subject rather than the organization's ongoing operations. These subjects can be product, customers, suppliers, sales, revenue, etc. The data warehouse does not focus on the ongoing operations, rather it focuses on modelling and analysis of data for decision-making." }, { "code": null, "e": 19768, "s": 19571, "text": "Integrated − Data warehouse is constructed by integration of data from heterogeneous sources such as relational databases, flat files etc. This integration enhances the effective analysis of data." }, { "code": null, "e": 19965, "s": 19768, "text": "Integrated − Data warehouse is constructed by integration of data from heterogeneous sources such as relational databases, flat files etc. This integration enhances the effective analysis of data." }, { "code": null, "e": 20147, "s": 19965, "text": "Time Variant − The data collected in a data warehouse is identified with a particular time period. The data in a data warehouse provides information from a historical point of view." }, { "code": null, "e": 20329, "s": 20147, "text": "Time Variant − The data collected in a data warehouse is identified with a particular time period. The data in a data warehouse provides information from a historical point of view." }, { "code": null, "e": 20582, "s": 20329, "text": "Non-volatile − Nonvolatile means the previous data is not removed when new data is added to it. The data warehouse is kept separate from the operational database therefore frequent changes in operational database is not reflected in the data warehouse." }, { "code": null, "e": 20835, "s": 20582, "text": "Non-volatile − Nonvolatile means the previous data is not removed when new data is added to it. The data warehouse is kept separate from the operational database therefore frequent changes in operational database is not reflected in the data warehouse." }, { "code": null, "e": 21095, "s": 20835, "text": "Data warehousing is the process of constructing and using the data warehouse. A data warehouse is constructed by integrating the data from multiple heterogeneous sources. It supports analytical reporting, structured and/or ad hoc queries, and decision making." }, { "code": null, "e": 21256, "s": 21095, "text": "Data warehousing involves data cleaning, data integration, and data consolidations. To integrate heterogeneous databases, we have the following two approaches −" }, { "code": null, "e": 21278, "s": 21256, "text": "Query Driven Approach" }, { "code": null, "e": 21301, "s": 21278, "text": "Update Driven Approach" }, { "code": null, "e": 21519, "s": 21301, "text": "This is the traditional approach to integrate heterogeneous databases. This approach is used to build wrappers and integrators on top of multiple heterogeneous databases. These integrators are also known as mediators." }, { "code": null, "e": 21681, "s": 21519, "text": "When a query is issued to a client side, a metadata dictionary translates the query into the queries, appropriate for the individual heterogeneous site involved." }, { "code": null, "e": 21843, "s": 21681, "text": "When a query is issued to a client side, a metadata dictionary translates the query into the queries, appropriate for the individual heterogeneous site involved." }, { "code": null, "e": 21911, "s": 21843, "text": "Now these queries are mapped and sent to the local query processor." }, { "code": null, "e": 21979, "s": 21911, "text": "Now these queries are mapped and sent to the local query processor." }, { "code": null, "e": 22057, "s": 21979, "text": "The results from heterogeneous sites are integrated into a global answer set." }, { "code": null, "e": 22135, "s": 22057, "text": "The results from heterogeneous sites are integrated into a global answer set." }, { "code": null, "e": 22183, "s": 22135, "text": "This approach has the following disadvantages −" }, { "code": null, "e": 22260, "s": 22183, "text": "The Query Driven Approach needs complex integration and filtering processes." }, { "code": null, "e": 22337, "s": 22260, "text": "The Query Driven Approach needs complex integration and filtering processes." }, { "code": null, "e": 22401, "s": 22337, "text": "It is very inefficient and very expensive for frequent queries." }, { "code": null, "e": 22465, "s": 22401, "text": "It is very inefficient and very expensive for frequent queries." }, { "code": null, "e": 22531, "s": 22465, "text": "This approach is expensive for queries that require aggregations." }, { "code": null, "e": 22597, "s": 22531, "text": "This approach is expensive for queries that require aggregations." }, { "code": null, "e": 22913, "s": 22597, "text": "Today's data warehouse systems follow update-driven approach rather than the traditional approach discussed earlier. In the update-driven approach, the information from multiple heterogeneous sources is integrated in advance and stored in a warehouse. This information is available for direct querying and analysis." }, { "code": null, "e": 22958, "s": 22913, "text": "This approach has the following advantages −" }, { "code": null, "e": 22999, "s": 22958, "text": "This approach provides high performance." }, { "code": null, "e": 23040, "s": 22999, "text": "This approach provides high performance." }, { "code": null, "e": 23165, "s": 23040, "text": "The data can be copied, processed, integrated, annotated, summarized and restructured in the semantic data store in advance." }, { "code": null, "e": 23290, "s": 23165, "text": "The data can be copied, processed, integrated, annotated, summarized and restructured in the semantic data store in advance." }, { "code": null, "e": 23372, "s": 23290, "text": "Query processing does not require interface with the processing at local sources." }, { "code": null, "e": 23582, "s": 23372, "text": "Online Analytical Mining integrates with Online Analytical Processing with data mining and mining knowledge in multidimensional databases. Here is the diagram that shows the integration of both OLAP and OLAM −" }, { "code": null, "e": 23628, "s": 23582, "text": "OLAM is important for the following reasons −" }, { "code": null, "e": 23946, "s": 23628, "text": "High quality of data in data warehouses − The data mining tools are required to work on integrated, consistent, and cleaned data. These steps are very costly in the preprocessing of data. The data warehouses constructed by such preprocessing are valuable sources of high quality data for OLAP and data mining as well." }, { "code": null, "e": 24264, "s": 23946, "text": "High quality of data in data warehouses − The data mining tools are required to work on integrated, consistent, and cleaned data. These steps are very costly in the preprocessing of data. The data warehouses constructed by such preprocessing are valuable sources of high quality data for OLAP and data mining as well." }, { "code": null, "e": 24558, "s": 24264, "text": "Available information processing infrastructure surrounding data warehouses − Information processing infrastructure refers to accessing, integration, consolidation, and transformation of multiple heterogeneous databases, web-accessing and service facilities, reporting and OLAP analysis tools." }, { "code": null, "e": 24852, "s": 24558, "text": "Available information processing infrastructure surrounding data warehouses − Information processing infrastructure refers to accessing, integration, consolidation, and transformation of multiple heterogeneous databases, web-accessing and service facilities, reporting and OLAP analysis tools." }, { "code": null, "e": 25061, "s": 24852, "text": "OLAP−based exploratory data analysis − Exploratory data analysis is required for effective data mining. OLAM provides facility for data mining on various subset of data and at different levels of abstraction." }, { "code": null, "e": 25270, "s": 25061, "text": "OLAP−based exploratory data analysis − Exploratory data analysis is required for effective data mining. OLAM provides facility for data mining on various subset of data and at different levels of abstraction." }, { "code": null, "e": 25511, "s": 25270, "text": "Online selection of data mining functions − Integrating OLAP with multiple data mining functions and online analytical mining provide users with the flexibility to select desired data mining functions and swap data mining tasks dynamically." }, { "code": null, "e": 25752, "s": 25511, "text": "Online selection of data mining functions − Integrating OLAP with multiple data mining functions and online analytical mining provide users with the flexibility to select desired data mining functions and swap data mining tasks dynamically." }, { "code": null, "e": 25977, "s": 25752, "text": "Data mining is defined as extracting the information from a huge set of data. In other words we can say that data mining is mining the knowledge from data. This information can be used for any of the following applications −" }, { "code": null, "e": 25993, "s": 25977, "text": "Market Analysis" }, { "code": null, "e": 26009, "s": 25993, "text": "Fraud Detection" }, { "code": null, "e": 26028, "s": 26009, "text": "Customer Retention" }, { "code": null, "e": 26047, "s": 26028, "text": "Production Control" }, { "code": null, "e": 26067, "s": 26047, "text": "Science Exploration" }, { "code": null, "e": 26213, "s": 26067, "text": "Data mining engine is very essential to the data mining system. It consists of a set of functional modules that perform the following functions −" }, { "code": null, "e": 26230, "s": 26213, "text": "Characterization" }, { "code": null, "e": 26267, "s": 26230, "text": "Association and Correlation Analysis" }, { "code": null, "e": 26282, "s": 26267, "text": "Classification" }, { "code": null, "e": 26293, "s": 26282, "text": "Prediction" }, { "code": null, "e": 26310, "s": 26293, "text": "Cluster analysis" }, { "code": null, "e": 26327, "s": 26310, "text": "Outlier analysis" }, { "code": null, "e": 26346, "s": 26327, "text": "Evolution analysis" }, { "code": null, "e": 26478, "s": 26346, "text": "This is the domain knowledge. This knowledge is used to guide the search or evaluate the interestingness of the resulting patterns." }, { "code": null, "e": 26699, "s": 26478, "text": "Some people treat data mining same as knowledge discovery, while others view data mining as an essential step in the process of knowledge discovery. Here is the list of steps involved in the knowledge discovery process −" }, { "code": null, "e": 26713, "s": 26699, "text": "Data Cleaning" }, { "code": null, "e": 26730, "s": 26713, "text": "Data Integration" }, { "code": null, "e": 26745, "s": 26730, "text": "Data Selection" }, { "code": null, "e": 26765, "s": 26745, "text": "Data Transformation" }, { "code": null, "e": 26777, "s": 26765, "text": "Data Mining" }, { "code": null, "e": 26796, "s": 26777, "text": "Pattern Evaluation" }, { "code": null, "e": 26819, "s": 26796, "text": "Knowledge Presentation" }, { "code": null, "e": 26995, "s": 26819, "text": "User interface is the module of data mining system that helps the communication between users and the data mining system. User Interface allows the following functionalities −" }, { "code": null, "e": 27060, "s": 26995, "text": "Interact with the system by specifying a data mining query task." }, { "code": null, "e": 27108, "s": 27060, "text": "Providing information to help focus the search." }, { "code": null, "e": 27162, "s": 27108, "text": "Mining based on the intermediate data mining results." }, { "code": null, "e": 27225, "s": 27162, "text": "Browse database and data warehouse schemas or data structures." }, { "code": null, "e": 27250, "s": 27225, "text": "Evaluate mined patterns." }, { "code": null, "e": 27293, "s": 27250, "text": "Visualize the patterns in different forms." }, { "code": null, "e": 27516, "s": 27293, "text": "Data Integration is a data preprocessing technique that merges the data from multiple heterogeneous data sources into a coherent data store. Data integration may involve inconsistent data and therefore needs data cleaning." }, { "code": null, "e": 27796, "s": 27516, "text": "Data cleaning is a technique that is applied to remove the noisy data and correct the inconsistencies in data. Data cleaning involves transformations to correct the wrong data. Data cleaning is performed as a data preprocessing step while preparing the data for a data warehouse." }, { "code": null, "e": 27997, "s": 27796, "text": "Data Selection is the process where data relevant to the analysis task are retrieved from the database. Sometimes data transformation and consolidation are performed before the data selection process." }, { "code": null, "e": 28200, "s": 27997, "text": "Cluster refers to a group of similar kind of objects. Cluster analysis refers to forming group of objects that are very similar to each other but are highly different from the objects in other clusters." }, { "code": null, "e": 28334, "s": 28200, "text": "In this step, data is transformed or consolidated into forms appropriate for mining, by performing summary or aggregation operations." }, { "code": null, "e": 28565, "s": 28334, "text": "Some people don’t differentiate data mining from knowledge discovery while others view data mining as an essential step in the process of knowledge discovery. Here is the list of steps involved in the knowledge discovery process −" }, { "code": null, "e": 28639, "s": 28565, "text": "Data Cleaning − In this step, the noise and inconsistent data is removed." }, { "code": null, "e": 28713, "s": 28639, "text": "Data Cleaning − In this step, the noise and inconsistent data is removed." }, { "code": null, "e": 28782, "s": 28713, "text": "Data Integration − In this step, multiple data sources are combined." }, { "code": null, "e": 28851, "s": 28782, "text": "Data Integration − In this step, multiple data sources are combined." }, { "code": null, "e": 28950, "s": 28851, "text": "Data Selection − In this step, data relevant to the analysis task are retrieved from the database." }, { "code": null, "e": 29049, "s": 28950, "text": "Data Selection − In this step, data relevant to the analysis task are retrieved from the database." }, { "code": null, "e": 29204, "s": 29049, "text": "Data Transformation − In this step, data is transformed or consolidated into forms appropriate for mining by performing summary or aggregation operations." }, { "code": null, "e": 29359, "s": 29204, "text": "Data Transformation − In this step, data is transformed or consolidated into forms appropriate for mining by performing summary or aggregation operations." }, { "code": null, "e": 29454, "s": 29359, "text": "Data Mining − In this step, intelligent methods are applied in order to extract data patterns." }, { "code": null, "e": 29549, "s": 29454, "text": "Data Mining − In this step, intelligent methods are applied in order to extract data patterns." }, { "code": null, "e": 29613, "s": 29549, "text": "Pattern Evaluation − In this step, data patterns are evaluated." }, { "code": null, "e": 29677, "s": 29613, "text": "Pattern Evaluation − In this step, data patterns are evaluated." }, { "code": null, "e": 29742, "s": 29677, "text": "Knowledge Presentation − In this step, knowledge is represented." }, { "code": null, "e": 29807, "s": 29742, "text": "Knowledge Presentation − In this step, knowledge is represented." }, { "code": null, "e": 29872, "s": 29807, "text": "The following diagram shows the process of knowledge discovery −" }, { "code": null, "e": 29997, "s": 29872, "text": "There is a large variety of data mining systems available. Data mining systems may integrate techniques from the following −" }, { "code": null, "e": 30019, "s": 29997, "text": "Spatial Data Analysis" }, { "code": null, "e": 30041, "s": 30019, "text": "Information Retrieval" }, { "code": null, "e": 30061, "s": 30041, "text": "Pattern Recognition" }, { "code": null, "e": 30076, "s": 30061, "text": "Image Analysis" }, { "code": null, "e": 30094, "s": 30076, "text": "Signal Processing" }, { "code": null, "e": 30112, "s": 30094, "text": "Computer Graphics" }, { "code": null, "e": 30127, "s": 30112, "text": "Web Technology" }, { "code": null, "e": 30136, "s": 30127, "text": "Business" }, { "code": null, "e": 30151, "s": 30136, "text": "Bioinformatics" }, { "code": null, "e": 30228, "s": 30151, "text": "A data mining system can be classified according to the following criteria −" }, { "code": null, "e": 30248, "s": 30228, "text": "Database Technology" }, { "code": null, "e": 30259, "s": 30248, "text": "Statistics" }, { "code": null, "e": 30276, "s": 30259, "text": "Machine Learning" }, { "code": null, "e": 30296, "s": 30276, "text": "Information Science" }, { "code": null, "e": 30310, "s": 30296, "text": "Visualization" }, { "code": null, "e": 30328, "s": 30310, "text": "Other Disciplines" }, { "code": null, "e": 30508, "s": 30328, "text": "Apart from these, a data mining system can also be classified based on the kind of (a) databases mined, (b) knowledge mined, (c) techniques utilized, and (d) applications adapted." }, { "code": null, "e": 30752, "s": 30508, "text": "We can classify a data mining system according to the kind of databases mined. Database system can be classified according to different criteria such as data models, types of data, etc. And the data mining system can be classified accordingly." }, { "code": null, "e": 30918, "s": 30752, "text": "For example, if we classify a database according to the data model, then we may have a relational, transactional, object-relational, or data warehouse mining system." }, { "code": null, "e": 31085, "s": 30918, "text": "We can classify a data mining system according to the kind of knowledge mined. It means the data mining system is classified on the basis of functionalities such as −" }, { "code": null, "e": 31102, "s": 31085, "text": "Characterization" }, { "code": null, "e": 31117, "s": 31102, "text": "Discrimination" }, { "code": null, "e": 31154, "s": 31117, "text": "Association and Correlation Analysis" }, { "code": null, "e": 31169, "s": 31154, "text": "Classification" }, { "code": null, "e": 31180, "s": 31169, "text": "Prediction" }, { "code": null, "e": 31197, "s": 31180, "text": "Outlier Analysis" }, { "code": null, "e": 31216, "s": 31197, "text": "Evolution Analysis" }, { "code": null, "e": 31418, "s": 31216, "text": "We can classify a data mining system according to the kind of techniques used. We can describe these techniques according to the degree of user interaction involved or the methods of analysis employed." }, { "code": null, "e": 31530, "s": 31418, "text": "We can classify a data mining system according to the applications adapted. These applications are as follows −" }, { "code": null, "e": 31538, "s": 31530, "text": "Finance" }, { "code": null, "e": 31557, "s": 31538, "text": "Telecommunications" }, { "code": null, "e": 31561, "s": 31557, "text": "DNA" }, { "code": null, "e": 31575, "s": 31561, "text": "Stock Markets" }, { "code": null, "e": 31582, "s": 31575, "text": "E-mail" }, { "code": null, "e": 31912, "s": 31582, "text": "If a data mining system is not integrated with a database or a data warehouse system, then there will be no system to communicate with. This scheme is known as the non-coupling scheme. In this scheme, the main focus is on data mining design and on developing efficient and effective algorithms for mining the available data sets." }, { "code": null, "e": 31960, "s": 31912, "text": "The list of Integration Schemes is as follows −" }, { "code": null, "e": 32233, "s": 31960, "text": "No Coupling − In this scheme, the data mining system does not utilize any of the database or data warehouse functions. It fetches the data from a particular source and processes that data using some data mining algorithms. The data mining result is stored in another file." }, { "code": null, "e": 32506, "s": 32233, "text": "No Coupling − In this scheme, the data mining system does not utilize any of the database or data warehouse functions. It fetches the data from a particular source and processes that data using some data mining algorithms. The data mining result is stored in another file." }, { "code": null, "e": 32854, "s": 32506, "text": "Loose Coupling − In this scheme, the data mining system may use some of the functions of database and data warehouse system. It fetches the data from the data respiratory managed by these systems and performs data mining on that data. It then stores the mining result either in a file or in a designated place in a database or in a data warehouse." }, { "code": null, "e": 33202, "s": 32854, "text": "Loose Coupling − In this scheme, the data mining system may use some of the functions of database and data warehouse system. It fetches the data from the data respiratory managed by these systems and performs data mining on that data. It then stores the mining result either in a file or in a designated place in a database or in a data warehouse." }, { "code": null, "e": 33432, "s": 33202, "text": "Semi−tight Coupling − In this scheme, the data mining system is linked with a database or a data warehouse system and in addition to that, efficient implementations of a few data mining primitives can be provided in the database." }, { "code": null, "e": 33662, "s": 33432, "text": "Semi−tight Coupling − In this scheme, the data mining system is linked with a database or a data warehouse system and in addition to that, efficient implementations of a few data mining primitives can be provided in the database." }, { "code": null, "e": 33885, "s": 33662, "text": "Tight coupling − In this coupling scheme, the data mining system is smoothly integrated into the database or data warehouse system. The data mining subsystem is treated as one functional component of an information system." }, { "code": null, "e": 34108, "s": 33885, "text": "Tight coupling − In this coupling scheme, the data mining system is smoothly integrated into the database or data warehouse system. The data mining subsystem is treated as one functional component of an information system." }, { "code": null, "e": 34641, "s": 34108, "text": "The Data Mining Query Language (DMQL) was proposed by Han, Fu, Wang, et al. for the DBMiner data mining system. The Data Mining Query Language is actually based on the Structured Query Language (SQL). Data Mining Query Languages can be designed to support ad hoc and interactive data mining. This DMQL provides commands for specifying primitives. The DMQL can work with databases and data warehouses as well. DMQL can be used to define data mining tasks. Particularly we examine how to define data warehouses and data marts in DMQL." }, { "code": null, "e": 34704, "s": 34641, "text": "Here is the syntax of DMQL for specifying task-relevant data −" }, { "code": null, "e": 34895, "s": 34704, "text": "use database database_name\n\nor \n\nuse data warehouse data_warehouse_name\nin relevance to att_or_dim_list\nfrom relation(s)/cube(s) [where condition]\norder by order_list\ngroup by grouping_list\n" }, { "code": null, "e": 35010, "s": 34895, "text": "Here we will discuss the syntax for Characterization, Discrimination, Association, Classification, and Prediction." }, { "code": null, "e": 35047, "s": 35010, "text": "The syntax for characterization is −" }, { "code": null, "e": 35113, "s": 35047, "text": "mine characteristics [as pattern_name]\n analyze {measure(s) }\n" }, { "code": null, "e": 35194, "s": 35113, "text": "The analyze clause, specifies aggregate measures, such as count, sum, or count%." }, { "code": null, "e": 35208, "s": 35194, "text": "For example −" }, { "code": null, "e": 35318, "s": 35208, "text": "Description describing customer purchasing habits.\nmine characteristics as customerPurchasing\nanalyze count%\n" }, { "code": null, "e": 35353, "s": 35318, "text": "The syntax for Discrimination is −" }, { "code": null, "e": 35523, "s": 35353, "text": "mine comparison [as {pattern_name]}\nFor {target_class } where {t arget_condition } \n{versus {contrast_class_i }\nwhere {contrast_condition_i}} \nanalyze {measure(s) }\n" }, { "code": null, "e": 35840, "s": 35523, "text": "For example, a user may define big spenders as customers who purchase items that cost $100 or more on an average; and budget spenders as customers who purchase items at less than $100 on an average. The mining of discriminant descriptions for customers from each of these categories can be specified in the DMQL as −" }, { "code": null, "e": 35977, "s": 35840, "text": "mine comparison as purchaseGroups\nfor bigSpenders where avg(I.price) ≥$100\nversus budgetSpenders where avg(I.price)< $100\nanalyze count\n" }, { "code": null, "e": 36008, "s": 35977, "text": "The syntax for Association is−" }, { "code": null, "e": 36075, "s": 36008, "text": "mine associations [ as {pattern_name} ]\n{matching {metapattern} }\n" }, { "code": null, "e": 36089, "s": 36075, "text": "For Example −" }, { "code": null, "e": 36170, "s": 36089, "text": "mine associations as buyingHabits\nmatching P(X:customer,W) ^ Q(X,Y) ≥ buys(X,Z)\n" }, { "code": null, "e": 36278, "s": 36170, "text": "where X is key of customer relation; P and Q are predicate variables; and W, Y, and Z are object variables." }, { "code": null, "e": 36313, "s": 36278, "text": "The syntax for Classification is −" }, { "code": null, "e": 36395, "s": 36313, "text": "mine classification [as pattern_name]\nanalyze classifying_attribute_or_dimension\n" }, { "code": null, "e": 36597, "s": 36395, "text": "For example, to mine patterns, classifying customer credit rating where the classes are determined by the attribute credit_rating, and mine classification is determined as classifyCustomerCreditRating." }, { "code": null, "e": 36620, "s": 36597, "text": "analyze credit_rating\n" }, { "code": null, "e": 36651, "s": 36620, "text": "The syntax for prediction is −" }, { "code": null, "e": 36770, "s": 36651, "text": "mine prediction [as pattern_name]\nanalyze prediction_attribute_or_dimension\n{set {attribute_or_dimension_i= value_i}}\n" }, { "code": null, "e": 36829, "s": 36770, "text": "To specify concept hierarchies, use the following syntax −" }, { "code": null, "e": 36885, "s": 36829, "text": "use hierarchy <hierarchy> for <attribute_or_dimension>\n" }, { "code": null, "e": 36961, "s": 36885, "text": "We use different syntaxes to define different types of hierarchies such as−" }, { "code": null, "e": 37778, "s": 36961, "text": "-schema hierarchies\ndefine hierarchy time_hierarchy on date as [date,month quarter,year]\n-\nset-grouping hierarchies\ndefine hierarchy age_hierarchy for age on customer as\nlevel1: {young, middle_aged, senior} < level0: all\nlevel2: {20, ..., 39} < level1: young\nlevel3: {40, ..., 59} < level1: middle_aged\nlevel4: {60, ..., 89} < level1: senior\n\n-operation-derived hierarchies\ndefine hierarchy age_hierarchy for age on customer as\n{age_category(1), ..., age_category(5)} \n:= cluster(default, age, 5) < all(age)\n\n-rule-based hierarchies\ndefine hierarchy profit_margin_hierarchy on item as\nlevel_1: low_profit_margin < level_0: all\n\nif (price - cost)< $50\n level_1: medium-profit_margin < level_0: all\n \nif ((price - cost) > $50) and ((price - cost) ≤ $250)) \n level_1: high_profit_margin < level_0: all\n" }, { "code": null, "e": 37868, "s": 37778, "text": "Interestingness measures and thresholds can be specified by the user with the statement −" }, { "code": null, "e": 37927, "s": 37868, "text": "with <interest_measure_name> threshold = threshold_value\n" }, { "code": null, "e": 37941, "s": 37927, "text": "For Example −" }, { "code": null, "e": 38004, "s": 37941, "text": "with support threshold = 0.05\nwith confidence threshold = 0.7\n" }, { "code": null, "e": 38109, "s": 38004, "text": "We have a syntax, which allows users to specify the display of discovered patterns in one or more forms." }, { "code": null, "e": 38135, "s": 38109, "text": "display as <result_form>\n" }, { "code": null, "e": 38149, "s": 38135, "text": "For Example −" }, { "code": null, "e": 38167, "s": 38149, "text": "display as table\n" }, { "code": null, "e": 38687, "s": 38167, "text": "As a market manager of a company, you would like to characterize the buying habits of customers who can purchase items priced at no less than $100; with respect to the customer's age, type of item purchased, and the place where the item was purchased. You would like to know the percentage of customers having that characteristic. In particular, you are only interested in purchases made in Canada, and paid with an American Express credit card. You would like to view the resulting descriptions in the form of a table." }, { "code": null, "e": 39094, "s": 38687, "text": "use database AllElectronics_db\nuse hierarchy location_hierarchy for B.address\nmine characteristics as customerPurchasing\nanalyze count%\nin relevance to C.age,I.type,I.place_made\nfrom customer C, item I, purchase P, items_sold S, branch B\nwhere I.item_ID = S.item_ID and P.cust_ID = C.cust_ID and\nP.method_paid = \"AmEx\" and B.address = \"Canada\" and I.price ≥ 100\nwith noise threshold = 5%\ndisplay as table\n" }, { "code": null, "e": 39170, "s": 39094, "text": "Standardizing the Data Mining Languages will serve the following purposes −" }, { "code": null, "e": 39225, "s": 39170, "text": "Helps systematic development of data mining solutions." }, { "code": null, "e": 39280, "s": 39225, "text": "Helps systematic development of data mining solutions." }, { "code": null, "e": 39356, "s": 39280, "text": "Improves interoperability among multiple data mining systems and functions." }, { "code": null, "e": 39432, "s": 39356, "text": "Improves interoperability among multiple data mining systems and functions." }, { "code": null, "e": 39471, "s": 39432, "text": "Promotes education and rapid learning." }, { "code": null, "e": 39510, "s": 39471, "text": "Promotes education and rapid learning." }, { "code": null, "e": 39575, "s": 39510, "text": "Promotes the use of data mining systems in industry and society." }, { "code": null, "e": 39640, "s": 39575, "text": "Promotes the use of data mining systems in industry and society." }, { "code": null, "e": 39812, "s": 39640, "text": "There are two forms of data analysis that can be used for extracting models describing important classes or to predict future data trends. These two forms are as follows −" }, { "code": null, "e": 39827, "s": 39812, "text": "Classification" }, { "code": null, "e": 39838, "s": 39827, "text": "Prediction" }, { "code": null, "e": 40205, "s": 39838, "text": "Classification models predict categorical class labels; and prediction models predict continuous valued functions. For example, we can build a classification model to categorize bank loan applications as either safe or risky, or a prediction model to predict the expenditures in dollars of potential customers on computer equipment given their income and occupation." }, { "code": null, "e": 40290, "s": 40205, "text": "Following are the examples of cases where the data analysis task is Classification −" }, { "code": null, "e": 40414, "s": 40290, "text": "A bank loan officer wants to analyze the data in order to know which customer (loan applicant) are risky or which are safe." }, { "code": null, "e": 40538, "s": 40414, "text": "A bank loan officer wants to analyze the data in order to know which customer (loan applicant) are risky or which are safe." }, { "code": null, "e": 40650, "s": 40538, "text": "A marketing manager at a company needs to analyze a customer with a given profile, who will buy a new computer." }, { "code": null, "e": 40762, "s": 40650, "text": "A marketing manager at a company needs to analyze a customer with a given profile, who will buy a new computer." }, { "code": null, "e": 40956, "s": 40762, "text": "In both of the above examples, a model or classifier is constructed to predict the categorical labels. These labels are risky or safe for loan application data and yes or no for marketing data." }, { "code": null, "e": 41037, "s": 40956, "text": "Following are the examples of cases where the data analysis task is Prediction −" }, { "code": null, "e": 41399, "s": 41037, "text": "Suppose the marketing manager needs to predict how much a given customer will spend during a sale at his company. In this example we are bothered to predict a numeric value. Therefore the data analysis task is an example of numeric prediction. In this case, a model or a predictor will be constructed that predicts a continuous-valued-function or ordered value." }, { "code": null, "e": 41503, "s": 41399, "text": "Note − Regression analysis is a statistical methodology that is most often used for numeric prediction." }, { "code": null, "e": 41678, "s": 41503, "text": "With the help of the bank loan application that we have discussed above, let us understand the working of classification. The Data Classification process includes two steps −" }, { "code": null, "e": 41711, "s": 41678, "text": "Building the Classifier or Model" }, { "code": null, "e": 41747, "s": 41711, "text": "Using Classifier for Classification" }, { "code": null, "e": 41801, "s": 41747, "text": "This step is the learning step or the learning phase." }, { "code": null, "e": 41855, "s": 41801, "text": "This step is the learning step or the learning phase." }, { "code": null, "e": 41920, "s": 41855, "text": "In this step the classification algorithms build the classifier." }, { "code": null, "e": 41985, "s": 41920, "text": "In this step the classification algorithms build the classifier." }, { "code": null, "e": 42093, "s": 41985, "text": "The classifier is built from the training set made up of database tuples and their associated class labels." }, { "code": null, "e": 42201, "s": 42093, "text": "The classifier is built from the training set made up of database tuples and their associated class labels." }, { "code": null, "e": 42356, "s": 42201, "text": "Each tuple that constitutes the training set is referred to as a category or class. These tuples can also be referred to as sample, object or data points." }, { "code": null, "e": 42511, "s": 42356, "text": "Each tuple that constitutes the training set is referred to as a category or class. These tuples can also be referred to as sample, object or data points." }, { "code": null, "e": 42750, "s": 42511, "text": "In this step, the classifier is used for classification. Here the test data is used to estimate the accuracy of classification rules. The classification rules can be applied to the new data tuples if the accuracy is considered acceptable." }, { "code": null, "e": 42878, "s": 42750, "text": "The major issue is preparing the data for Classification and Prediction. Preparing the data involves the following activities −" }, { "code": null, "e": 43151, "s": 42878, "text": "Data Cleaning − Data cleaning involves removing the noise and treatment of missing values. The noise is removed by applying smoothing techniques and the problem of missing values is solved by replacing a missing value with most commonly occurring value for that attribute." }, { "code": null, "e": 43424, "s": 43151, "text": "Data Cleaning − Data cleaning involves removing the noise and treatment of missing values. The noise is removed by applying smoothing techniques and the problem of missing values is solved by replacing a missing value with most commonly occurring value for that attribute." }, { "code": null, "e": 43578, "s": 43424, "text": "Relevance Analysis − Database may also have the irrelevant attributes. Correlation analysis is used to know whether any two given attributes are related." }, { "code": null, "e": 43732, "s": 43578, "text": "Relevance Analysis − Database may also have the irrelevant attributes. Correlation analysis is used to know whether any two given attributes are related." }, { "code": null, "e": 44276, "s": 43732, "text": "Data Transformation and reduction − The data can be transformed by any of the following methods.\n\nNormalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used.\nGeneralization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies.\n\n" }, { "code": null, "e": 44373, "s": 44276, "text": "Data Transformation and reduction − The data can be transformed by any of the following methods." }, { "code": null, "e": 44672, "s": 44373, "text": "Normalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used." }, { "code": null, "e": 44971, "s": 44672, "text": "Normalization − The data is transformed using normalization. Normalization involves scaling all values for given attribute in order to make them fall within a small specified range. Normalization is used when in the learning step, the neural networks or the methods involving measurements are used." }, { "code": null, "e": 45116, "s": 44971, "text": "Generalization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies." }, { "code": null, "e": 45261, "s": 45116, "text": "Generalization − The data can also be transformed by generalizing it to the higher concept. For this purpose we can use the concept hierarchies." }, { "code": null, "e": 45392, "s": 45261, "text": "Note − Data can also be reduced by some other methods such as wavelet transformation, binning, histogram analysis, and clustering." }, { "code": null, "e": 45474, "s": 45392, "text": "Here is the criteria for comparing the methods of Classification and Prediction −" }, { "code": null, "e": 45712, "s": 45474, "text": "Accuracy − Accuracy of classifier refers to the ability of classifier. It predict the class label correctly and the accuracy of the predictor refers to how well a given predictor can guess the value of predicted attribute for a new data." }, { "code": null, "e": 45950, "s": 45712, "text": "Accuracy − Accuracy of classifier refers to the ability of classifier. It predict the class label correctly and the accuracy of the predictor refers to how well a given predictor can guess the value of predicted attribute for a new data." }, { "code": null, "e": 46049, "s": 45950, "text": "Speed − This refers to the computational cost in generating and using the classifier or predictor." }, { "code": null, "e": 46148, "s": 46049, "text": "Speed − This refers to the computational cost in generating and using the classifier or predictor." }, { "code": null, "e": 46264, "s": 46148, "text": "Robustness − It refers to the ability of classifier or predictor to make correct predictions from given noisy data." }, { "code": null, "e": 46380, "s": 46264, "text": "Robustness − It refers to the ability of classifier or predictor to make correct predictions from given noisy data." }, { "code": null, "e": 46510, "s": 46380, "text": "Scalability − Scalability refers to the ability to construct the classifier or predictor efficiently; given large amount of data." }, { "code": null, "e": 46640, "s": 46510, "text": "Scalability − Scalability refers to the ability to construct the classifier or predictor efficiently; given large amount of data." }, { "code": null, "e": 46725, "s": 46640, "text": "Interpretability − It refers to what extent the classifier or predictor understands." }, { "code": null, "e": 46810, "s": 46725, "text": "Interpretability − It refers to what extent the classifier or predictor understands." }, { "code": null, "e": 47075, "s": 46810, "text": "A decision tree is a structure that includes a root node, branches, and leaf nodes. Each internal node denotes a test on an attribute, each branch denotes the outcome of a test, and each leaf node holds a class label. The topmost node in the tree is the root node." }, { "code": null, "e": 47307, "s": 47075, "text": "The following decision tree is for the concept buy_computer that indicates whether a customer at a company is likely to buy a computer or not. Each internal node represents a test on an attribute. Each leaf node represents a class." }, { "code": null, "e": 47363, "s": 47307, "text": "The benefits of having a decision tree are as follows −" }, { "code": null, "e": 47405, "s": 47363, "text": "It does not require any domain knowledge." }, { "code": null, "e": 47431, "s": 47405, "text": "It is easy to comprehend." }, { "code": null, "e": 47509, "s": 47431, "text": "The learning and classification steps of a decision tree are simple and fast." }, { "code": null, "e": 47853, "s": 47509, "text": "A machine researcher named J. Ross Quinlan in 1980 developed a decision tree algorithm known as ID3 (Iterative Dichotomiser). Later, he presented C4.5, which was the successor of ID3. ID3 and C4.5 adopt a greedy approach. In this algorithm, there is no backtracking; the trees are constructed in a top-down recursive divide-and-conquer manner." }, { "code": null, "e": 49343, "s": 47853, "text": "Generating a decision tree form training tuples of data partition D\nAlgorithm : Generate_decision_tree\n\nInput:\nData partition, D, which is a set of training tuples \nand their associated class labels.\nattribute_list, the set of candidate attributes.\nAttribute selection method, a procedure to determine the\nsplitting criterion that best partitions that the data \ntuples into individual classes. This criterion includes a \nsplitting_attribute and either a splitting point or splitting subset.\n\nOutput:\n A Decision Tree\n\nMethod\ncreate a node N;\n\nif tuples in D are all of the same class, C then\n return N as leaf node labeled with class C;\n \nif attribute_list is empty then\n return N as leaf node with labeled \n with majority class in D;|| majority voting\n \napply attribute_selection_method(D, attribute_list) \nto find the best splitting_criterion;\nlabel node N with splitting_criterion;\n\nif splitting_attribute is discrete-valued and\n multiway splits allowed then // no restricted to binary trees\n\nattribute_list = splitting attribute; // remove splitting attribute\nfor each outcome j of splitting criterion\n\n // partition the tuples and grow subtrees for each partition\n let Dj be the set of data tuples in D satisfying outcome j; // a partition\n \n if Dj is empty then\n attach a leaf labeled with the majority \n class in D to node N;\n else \n attach the node returned by Generate \n decision tree(Dj, attribute list) to node N;\n end for\nreturn N;\n" }, { "code": null, "e": 49492, "s": 49343, "text": "Tree pruning is performed in order to remove anomalies in the training data due to noise or outliers. The pruned trees are smaller and less complex." }, { "code": null, "e": 49535, "s": 49492, "text": "There are two approaches to prune a tree −" }, { "code": null, "e": 49603, "s": 49535, "text": "Pre-pruning − The tree is pruned by halting its construction early." }, { "code": null, "e": 49671, "s": 49603, "text": "Pre-pruning − The tree is pruned by halting its construction early." }, { "code": null, "e": 49744, "s": 49671, "text": "Post-pruning - This approach removes a sub-tree from a fully grown tree." }, { "code": null, "e": 49817, "s": 49744, "text": "Post-pruning - This approach removes a sub-tree from a fully grown tree." }, { "code": null, "e": 49883, "s": 49817, "text": "The cost complexity is measured by the following two parameters −" }, { "code": null, "e": 49917, "s": 49883, "text": "Number of leaves in the tree, and" }, { "code": null, "e": 49941, "s": 49917, "text": "Error rate of the tree." }, { "code": null, "e": 50185, "s": 49941, "text": "Bayesian classification is based on Bayes' Theorem. Bayesian classifiers are the statistical classifiers. Bayesian classifiers can predict class membership probabilities such as the probability that a given tuple belongs to a particular class." }, { "code": null, "e": 50268, "s": 50185, "text": "Bayes' Theorem is named after Thomas Bayes. There are two types of probabilities −" }, { "code": null, "e": 50299, "s": 50268, "text": "Posterior Probability [P(H/X)]" }, { "code": null, "e": 50324, "s": 50299, "text": "Prior Probability [P(H)]" }, { "code": null, "e": 50372, "s": 50324, "text": "where X is data tuple and H is some hypothesis." }, { "code": null, "e": 50401, "s": 50372, "text": "According to Bayes' Theorem," }, { "code": null, "e": 50565, "s": 50401, "text": "Bayesian Belief Networks specify joint conditional probability distributions. They are also known as Belief Networks, Bayesian Networks, or Probabilistic Networks." }, { "code": null, "e": 50666, "s": 50565, "text": "A Belief Network allows class conditional independencies to be defined between subsets of variables." }, { "code": null, "e": 50767, "s": 50666, "text": "A Belief Network allows class conditional independencies to be defined between subsets of variables." }, { "code": null, "e": 50856, "s": 50767, "text": "It provides a graphical model of causal relationship on which learning can be performed." }, { "code": null, "e": 50945, "s": 50856, "text": "It provides a graphical model of causal relationship on which learning can be performed." }, { "code": null, "e": 51003, "s": 50945, "text": "We can use a trained Bayesian Network for classification." }, { "code": null, "e": 51061, "s": 51003, "text": "We can use a trained Bayesian Network for classification." }, { "code": null, "e": 51126, "s": 51061, "text": "There are two components that define a Bayesian Belief Network −" }, { "code": null, "e": 51149, "s": 51126, "text": "Directed acyclic graph" }, { "code": null, "e": 51189, "s": 51149, "text": "A set of conditional probability tables" }, { "code": null, "e": 51257, "s": 51189, "text": "Each node in a directed acyclic graph represents a random variable." }, { "code": null, "e": 51310, "s": 51257, "text": "These variable may be discrete or continuous valued." }, { "code": null, "e": 51384, "s": 51310, "text": "These variables may correspond to the actual attribute given in the data." }, { "code": null, "e": 51464, "s": 51384, "text": "The following diagram shows a directed acyclic graph for six Boolean variables." }, { "code": null, "e": 51869, "s": 51464, "text": "The arc in the diagram allows representation of causal knowledge. For example, lung cancer is influenced by a person's family history of lung cancer, as well as whether or not the person is a smoker. It is worth noting that the variable PositiveXray is independent of whether the patient has a family history of lung cancer or that the patient is a smoker, given that we know the patient has lung cancer." }, { "code": null, "e": 52070, "s": 51869, "text": "The conditional probability table for the values of the variable LungCancer (LC) showing each possible combination of the values of its parent nodes, FamilyHistory (FH), and Smoker (S) is as follows −" }, { "code": null, "e": 52194, "s": 52070, "text": "Rule-based classifier makes use of a set of IF-THEN rules for classification. We can express a rule in the following from −" }, { "code": null, "e": 52221, "s": 52194, "text": "Let us consider a rule R1," }, { "code": null, "e": 52286, "s": 52221, "text": "R1: IF age = youth AND student = yes \n THEN buy_computer = yes" }, { "code": null, "e": 52307, "s": 52286, "text": "Points to remember −" }, { "code": null, "e": 52374, "s": 52307, "text": "The IF part of the rule is called rule antecedent or precondition." }, { "code": null, "e": 52441, "s": 52374, "text": "The IF part of the rule is called rule antecedent or precondition." }, { "code": null, "e": 52494, "s": 52441, "text": "The THEN part of the rule is called rule consequent." }, { "code": null, "e": 52547, "s": 52494, "text": "The THEN part of the rule is called rule consequent." }, { "code": null, "e": 52657, "s": 52547, "text": "The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed." }, { "code": null, "e": 52767, "s": 52657, "text": "The antecedent part the condition consist of one or more attribute tests and these tests are logically ANDed." }, { "code": null, "e": 52817, "s": 52767, "text": "The consequent part consists of class prediction." }, { "code": null, "e": 52867, "s": 52817, "text": "The consequent part consists of class prediction." }, { "code": null, "e": 52913, "s": 52867, "text": "Note − We can also write rule R1 as follows −" }, { "code": null, "e": 52972, "s": 52913, "text": "R1: (age = youth) ^ (student = yes))(buys computer = yes)\n" }, { "code": null, "e": 53053, "s": 52972, "text": "If the condition holds true for a given tuple, then the antecedent is satisfied." }, { "code": null, "e": 53159, "s": 53053, "text": "Here we will learn how to build a rule-based classifier by extracting IF-THEN rules from a decision tree." }, { "code": null, "e": 53180, "s": 53159, "text": "Points to remember −" }, { "code": null, "e": 53221, "s": 53180, "text": "To extract a rule from a decision tree −" }, { "code": null, "e": 53287, "s": 53221, "text": "One rule is created for each path from the root to the leaf node." }, { "code": null, "e": 53353, "s": 53287, "text": "One rule is created for each path from the root to the leaf node." }, { "code": null, "e": 53425, "s": 53353, "text": "To form a rule antecedent, each splitting criterion is logically ANDed." }, { "code": null, "e": 53497, "s": 53425, "text": "To form a rule antecedent, each splitting criterion is logically ANDed." }, { "code": null, "e": 53568, "s": 53497, "text": "The leaf node holds the class prediction, forming the rule consequent." }, { "code": null, "e": 53639, "s": 53568, "text": "The leaf node holds the class prediction, forming the rule consequent." }, { "code": null, "e": 53871, "s": 53639, "text": "Sequential Covering Algorithm can be used to extract IF-THEN rules form the training data. We do not require to generate a decision tree first. In this algorithm, each rule for a given class covers many of the tuples of that class." }, { "code": null, "e": 54210, "s": 53871, "text": "Some of the sequential Covering Algorithms are AQ, CN2, and RIPPER. As per the general strategy the rules are learned one at a time. For each time rules are learned, a tuple covered by the rule is removed and the process continues for the rest of the tuples. This is because the path to each leaf in a decision tree corresponds to a rule." }, { "code": null, "e": 54306, "s": 54210, "text": "Note − The Decision tree induction can be considered as learning a set of rules simultaneously." }, { "code": null, "e": 54538, "s": 54306, "text": "The Following is the sequential learning Algorithm where rules are learned for one class at a time. When learning a rule from a class Ci, we want the rule to cover all the tuples from class C only and no tuple form any other class." }, { "code": null, "e": 55018, "s": 54538, "text": "Algorithm: Sequential Covering\n\nInput: \nD, a data set class-labeled tuples,\nAtt_vals, the set of all attributes and their possible values.\n\nOutput: A Set of IF-THEN rules.\nMethod:\nRule_set={ }; // initial set of rules learned is empty\n\nfor each class c do\n \n repeat\n Rule = Learn_One_Rule(D, Att_valls, c);\n remove tuples covered by Rule form D;\n until termination condition;\n \n Rule_set=Rule_set+Rule; // add a new rule to rule-set\nend for\nreturn Rule_Set;\n" }, { "code": null, "e": 55070, "s": 55018, "text": "The rule is pruned is due to the following reason −" }, { "code": null, "e": 55260, "s": 55070, "text": "The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required." }, { "code": null, "e": 55450, "s": 55260, "text": "The Assessment of quality is made on the original set of training data. The rule may perform well on training data but less well on subsequent data. That's why the rule pruning is required." }, { "code": null, "e": 55612, "s": 55450, "text": "The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples." }, { "code": null, "e": 55774, "s": 55612, "text": "The rule is pruned by removing conjunct. The rule R is pruned, if pruned version of R has greater quality than what was assessed on an independent set of tuples." }, { "code": null, "e": 55859, "s": 55774, "text": "FOIL is one of the simple and effective method for rule pruning. For a given rule R," }, { "code": null, "e": 55938, "s": 55859, "text": "where pos and neg is the number of positive tuples covered by R, respectively." }, { "code": null, "e": 56100, "s": 55938, "text": "Note − This value will increase with the accuracy of R on the pruning set. Hence, if the FOIL_Prune value is higher for the pruned version of R, then we prune R." }, { "code": null, "e": 56222, "s": 56100, "text": "Here we will discuss other classification methods such as Genetic Algorithms, Rough Set Approach, and Fuzzy Set Approach." }, { "code": null, "e": 56468, "s": 56222, "text": "The idea of genetic algorithm is derived from natural evolution. In genetic algorithm, first of all, the initial population is created. This initial population consists of randomly generated rules. We can represent each rule by a string of bits." }, { "code": null, "e": 56645, "s": 56468, "text": "For example, in a given training set, the samples are described by two Boolean attributes such as A1 and A2. And this given training set contains two classes such as C1 and C2." }, { "code": null, "e": 56815, "s": 56645, "text": "We can encode the rule IF A1 AND NOT A2 THEN C2 into a bit string 100. In this bit representation, the two leftmost bits represent the attribute A1 and A2, respectively." }, { "code": null, "e": 56886, "s": 56815, "text": "Likewise, the rule IF NOT A1 AND NOT A2 THEN C1 can be encoded as 001." }, { "code": null, "e": 57042, "s": 56886, "text": "Note − If the attribute has K values where K>2, then we can use the K bits to encode the attribute values. The classes are also encoded in the same manner." }, { "code": null, "e": 57063, "s": 57042, "text": "Points to remember −" }, { "code": null, "e": 57248, "s": 57063, "text": "Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well." }, { "code": null, "e": 57433, "s": 57248, "text": "Based on the notion of the survival of the fittest, a new population is formed that consists of the fittest rules in the current population and offspring values of these rules as well." }, { "code": null, "e": 57528, "s": 57433, "text": "The fitness of a rule is assessed by its classification accuracy on a set of training samples." }, { "code": null, "e": 57623, "s": 57528, "text": "The fitness of a rule is assessed by its classification accuracy on a set of training samples." }, { "code": null, "e": 57709, "s": 57623, "text": "The genetic operators such as crossover and mutation are applied to create offspring." }, { "code": null, "e": 57795, "s": 57709, "text": "The genetic operators such as crossover and mutation are applied to create offspring." }, { "code": null, "e": 57883, "s": 57795, "text": "In crossover, the substring from pair of rules are swapped to form a new pair of rules." }, { "code": null, "e": 57971, "s": 57883, "text": "In crossover, the substring from pair of rules are swapped to form a new pair of rules." }, { "code": null, "e": 58040, "s": 57971, "text": "In mutation, randomly selected bits in a rule's string are inverted." }, { "code": null, "e": 58109, "s": 58040, "text": "In mutation, randomly selected bits in a rule's string are inverted." }, { "code": null, "e": 58212, "s": 58109, "text": "We can use the rough set approach to discover structural relationship within imprecise and noisy data." }, { "code": null, "e": 58360, "s": 58212, "text": "Note − This approach can only be applied on discrete-valued attributes. Therefore, continuous-valued attributes must be discretized before its use." }, { "code": null, "e": 58616, "s": 58360, "text": "The Rough Set Theory is based on the establishment of equivalence classes within the given training data. The tuples that forms the equivalence class are indiscernible. It means the samples are identical with respect to the attributes describing the data." }, { "code": null, "e": 58791, "s": 58616, "text": "There are some classes in the given real world data, which cannot be distinguished in terms of available attributes. We can use the rough sets to roughly define such classes." }, { "code": null, "e": 58878, "s": 58791, "text": "For a given class C, the rough set definition is approximated by two sets as follows −" }, { "code": null, "e": 59047, "s": 58878, "text": "Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C." }, { "code": null, "e": 59216, "s": 59047, "text": "Lower Approximation of C − The lower approximation of C consists of all the data tuples, that based on the knowledge of the attribute, are certain to belong to class C." }, { "code": null, "e": 59386, "s": 59216, "text": "Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C." }, { "code": null, "e": 59556, "s": 59386, "text": "Upper Approximation of C − The upper approximation of C consists of all the tuples, that based on the knowledge of attributes, cannot be described as not belonging to C." }, { "code": null, "e": 59631, "s": 59556, "text": "The following diagram shows the Upper and Lower Approximation of class C −" }, { "code": null, "e": 59933, "s": 59631, "text": "Fuzzy Set Theory is also called Possibility Theory. This theory was proposed by Lotfi Zadeh in 1965 as an alternative the two-value logic and probability theory. This theory allows us to work at a high level of abstraction. It also provides us the means for dealing with imprecise measurement of data." }, { "code": null, "e": 60297, "s": 59933, "text": "The fuzzy set theory also allows us to deal with vague or inexact facts. For example, being a member of a set of high incomes is in exact (e.g. if $50,000 is high then what about $49,000 and $48,000). Unlike the traditional CRISP set where the element either belong to S or its complement but in fuzzy set theory the element can belong to more than one fuzzy set." }, { "code": null, "e": 60465, "s": 60297, "text": "For example, the income value $49,000 belongs to both the medium and high fuzzy sets but to differing degrees. Fuzzy set notation for this income value is as follows −" }, { "code": null, "e": 60520, "s": 60465, "text": "mmedium_income($49k)=0.15 and mhigh_income($49k)=0.96\n" }, { "code": null, "e": 60693, "s": 60520, "text": "where ‘m’ is the membership function that operates on the fuzzy sets of medium_income and high_income respectively. This notation can be shown diagrammatically as follows −" }, { "code": null, "e": 60869, "s": 60693, "text": "Cluster is a group of objects that belongs to the same class. In other words, similar objects are grouped in one cluster and dissimilar objects are grouped in another cluster." }, { "code": null, "e": 60966, "s": 60869, "text": "Clustering is the process of making a group of abstract objects into classes of similar objects." }, { "code": null, "e": 60985, "s": 60966, "text": "Points to Remember" }, { "code": null, "e": 61040, "s": 60985, "text": "A cluster of data objects can be treated as one group." }, { "code": null, "e": 61095, "s": 61040, "text": "A cluster of data objects can be treated as one group." }, { "code": null, "e": 61239, "s": 61095, "text": "While doing cluster analysis, we first partition the set of data into groups based on data similarity and then assign the labels to the groups." }, { "code": null, "e": 61383, "s": 61239, "text": "While doing cluster analysis, we first partition the set of data into groups based on data similarity and then assign the labels to the groups." }, { "code": null, "e": 61544, "s": 61383, "text": "The main advantage of clustering over classification is that, it is adaptable to changes and helps single out useful features that distinguish different groups." }, { "code": null, "e": 61705, "s": 61544, "text": "The main advantage of clustering over classification is that, it is adaptable to changes and helps single out useful features that distinguish different groups." }, { "code": null, "e": 61845, "s": 61705, "text": "Clustering analysis is broadly used in many applications such as market research, pattern recognition, data analysis, and image processing." }, { "code": null, "e": 61985, "s": 61845, "text": "Clustering analysis is broadly used in many applications such as market research, pattern recognition, data analysis, and image processing." }, { "code": null, "e": 62151, "s": 61985, "text": "Clustering can also help marketers discover distinct groups in their customer base. And they can characterize their customer groups based on the purchasing patterns." }, { "code": null, "e": 62317, "s": 62151, "text": "Clustering can also help marketers discover distinct groups in their customer base. And they can characterize their customer groups based on the purchasing patterns." }, { "code": null, "e": 62500, "s": 62317, "text": "In the field of biology, it can be used to derive plant and animal taxonomies, categorize genes with similar functionalities and gain insight into structures inherent to populations." }, { "code": null, "e": 62683, "s": 62500, "text": "In the field of biology, it can be used to derive plant and animal taxonomies, categorize genes with similar functionalities and gain insight into structures inherent to populations." }, { "code": null, "e": 62909, "s": 62683, "text": "Clustering also helps in identification of areas of similar land use in an earth observation database. It also helps in the identification of groups of houses in a city according to house type, value, and geographic location." }, { "code": null, "e": 63135, "s": 62909, "text": "Clustering also helps in identification of areas of similar land use in an earth observation database. It also helps in the identification of groups of houses in a city according to house type, value, and geographic location." }, { "code": null, "e": 63220, "s": 63135, "text": "Clustering also helps in classifying documents on the web for information discovery." }, { "code": null, "e": 63305, "s": 63220, "text": "Clustering also helps in classifying documents on the web for information discovery." }, { "code": null, "e": 63403, "s": 63305, "text": "Clustering is also used in outlier detection applications such as detection of credit card fraud." }, { "code": null, "e": 63501, "s": 63403, "text": "Clustering is also used in outlier detection applications such as detection of credit card fraud." }, { "code": null, "e": 63652, "s": 63501, "text": "As a data mining function, cluster analysis serves as a tool to gain insight into the distribution of data to observe characteristics of each cluster." }, { "code": null, "e": 63803, "s": 63652, "text": "As a data mining function, cluster analysis serves as a tool to gain insight into the distribution of data to observe characteristics of each cluster." }, { "code": null, "e": 63883, "s": 63803, "text": "The following points throw light on why clustering is required in data mining −" }, { "code": null, "e": 63973, "s": 63883, "text": "Scalability − We need highly scalable clustering algorithms to deal with large databases." }, { "code": null, "e": 64063, "s": 63973, "text": "Scalability − We need highly scalable clustering algorithms to deal with large databases." }, { "code": null, "e": 64250, "s": 64063, "text": "Ability to deal with different kinds of attributes − Algorithms should be capable to be applied on any kind of data such as interval-based (numerical) data, categorical, and binary data." }, { "code": null, "e": 64437, "s": 64250, "text": "Ability to deal with different kinds of attributes − Algorithms should be capable to be applied on any kind of data such as interval-based (numerical) data, categorical, and binary data." }, { "code": null, "e": 64672, "s": 64437, "text": "Discovery of clusters with attribute shape − The clustering algorithm should be capable of detecting clusters of arbitrary shape. They should not be bounded to only distance measures that tend to find spherical cluster of small sizes." }, { "code": null, "e": 64907, "s": 64672, "text": "Discovery of clusters with attribute shape − The clustering algorithm should be capable of detecting clusters of arbitrary shape. They should not be bounded to only distance measures that tend to find spherical cluster of small sizes." }, { "code": null, "e": 65046, "s": 64907, "text": "High dimensionality − The clustering algorithm should not only be able to handle low-dimensional data but also the high dimensional space." }, { "code": null, "e": 65185, "s": 65046, "text": "High dimensionality − The clustering algorithm should not only be able to handle low-dimensional data but also the high dimensional space." }, { "code": null, "e": 65353, "s": 65185, "text": "Ability to deal with noisy data − Databases contain noisy, missing or erroneous data. Some algorithms are sensitive to such data and may lead to poor quality clusters." }, { "code": null, "e": 65521, "s": 65353, "text": "Ability to deal with noisy data − Databases contain noisy, missing or erroneous data. Some algorithms are sensitive to such data and may lead to poor quality clusters." }, { "code": null, "e": 65616, "s": 65521, "text": "Interpretability − The clustering results should be interpretable, comprehensible, and usable." }, { "code": null, "e": 65711, "s": 65616, "text": "Interpretability − The clustering results should be interpretable, comprehensible, and usable." }, { "code": null, "e": 65780, "s": 65711, "text": "Clustering methods can be classified into the following categories −" }, { "code": null, "e": 65800, "s": 65780, "text": "Partitioning Method" }, { "code": null, "e": 65820, "s": 65800, "text": "Hierarchical Method" }, { "code": null, "e": 65841, "s": 65820, "text": "Density-based Method" }, { "code": null, "e": 65859, "s": 65841, "text": "Grid-Based Method" }, { "code": null, "e": 65878, "s": 65859, "text": "Model-Based Method" }, { "code": null, "e": 65902, "s": 65878, "text": "Constraint-based Method" }, { "code": null, "e": 66160, "s": 65902, "text": "Suppose we are given a database of ‘n’ objects and the partitioning method constructs ‘k’ partition of data. Each partition will represent a cluster and k ≤ n. It means that it will classify the data into k groups, which satisfy the following requirements −" }, { "code": null, "e": 66201, "s": 66160, "text": "Each group contains at least one object." }, { "code": null, "e": 66242, "s": 66201, "text": "Each group contains at least one object." }, { "code": null, "e": 66288, "s": 66242, "text": "Each object must belong to exactly one group." }, { "code": null, "e": 66334, "s": 66288, "text": "Each object must belong to exactly one group." }, { "code": null, "e": 66355, "s": 66334, "text": "Points to remember −" }, { "code": null, "e": 66458, "s": 66355, "text": "For a given number of partitions (say k), the partitioning method will create an initial partitioning." }, { "code": null, "e": 66561, "s": 66458, "text": "For a given number of partitions (say k), the partitioning method will create an initial partitioning." }, { "code": null, "e": 66680, "s": 66561, "text": "Then it uses the iterative relocation technique to improve the partitioning by moving objects from one group to other." }, { "code": null, "e": 66799, "s": 66680, "text": "Then it uses the iterative relocation technique to improve the partitioning by moving objects from one group to other." }, { "code": null, "e": 67013, "s": 66799, "text": "This method creates a hierarchical decomposition of the given set of data objects. We can classify hierarchical methods on the basis of how the hierarchical decomposition is formed. There are two approaches here −" }, { "code": null, "e": 67036, "s": 67013, "text": "Agglomerative Approach" }, { "code": null, "e": 67054, "s": 67036, "text": "Divisive Approach" }, { "code": null, "e": 67349, "s": 67054, "text": "This approach is also known as the bottom-up approach. In this, we start with each object forming a separate group. It keeps on merging the objects or groups that are close to one another. It keep on doing so until all of the groups are merged into one or until the termination condition holds." }, { "code": null, "e": 67709, "s": 67349, "text": "This approach is also known as the top-down approach. In this, we start with all of the objects in the same cluster. In the continuous iteration, a cluster is split up into smaller clusters. It is down until each object in one cluster or the termination condition holds. This method is rigid, i.e., once a merging or splitting is done, it can never be undone." }, { "code": null, "e": 67803, "s": 67709, "text": "Here are the two approaches that are used to improve the quality of hierarchical clustering −" }, { "code": null, "e": 67882, "s": 67803, "text": "Perform careful analysis of object linkages at each hierarchical partitioning." }, { "code": null, "e": 67961, "s": 67882, "text": "Perform careful analysis of object linkages at each hierarchical partitioning." }, { "code": null, "e": 68150, "s": 67961, "text": "Integrate hierarchical agglomeration by first using a hierarchical agglomerative algorithm to group objects into micro-clusters, and then performing macro-clustering on the micro-clusters." }, { "code": null, "e": 68339, "s": 68150, "text": "Integrate hierarchical agglomeration by first using a hierarchical agglomerative algorithm to group objects into micro-clusters, and then performing macro-clustering on the micro-clusters." }, { "code": null, "e": 68641, "s": 68339, "text": "This method is based on the notion of density. The basic idea is to continue growing the given cluster as long as the density in the neighborhood exceeds some threshold, i.e., for each data point within a given cluster, the radius of a given cluster has to contain at least a minimum number of points." }, { "code": null, "e": 68770, "s": 68641, "text": "In this, the objects together form a grid. The object space is quantized into finite number of cells that form a grid structure." }, { "code": null, "e": 68781, "s": 68770, "text": "Advantages" }, { "code": null, "e": 68841, "s": 68781, "text": "The major advantage of this method is fast processing time." }, { "code": null, "e": 68901, "s": 68841, "text": "The major advantage of this method is fast processing time." }, { "code": null, "e": 68987, "s": 68901, "text": "It is dependent only on the number of cells in each dimension in the quantized space." }, { "code": null, "e": 69073, "s": 68987, "text": "It is dependent only on the number of cells in each dimension in the quantized space." }, { "code": null, "e": 69300, "s": 69073, "text": "In this method, a model is hypothesized for each cluster to find the best fit of data for a given model. This method locates the clusters by clustering the density function. It reflects spatial distribution of the data points." }, { "code": null, "e": 69497, "s": 69300, "text": "This method also provides a way to automatically determine the number of clusters based on standard statistics, taking outlier or noise into account. It therefore yields robust clustering methods." }, { "code": null, "e": 69866, "s": 69497, "text": "In this method, the clustering is performed by the incorporation of user or application-oriented constraints. A constraint refers to the user expectation or the properties of desired clustering results. Constraints provide us with an interactive way of communication with the clustering process. Constraints can be specified by the user or the application requirement." }, { "code": null, "e": 70202, "s": 69866, "text": "Text databases consist of huge collection of documents. They collect these information from several sources such as news articles, books, digital libraries, e-mail messages, web pages, etc. Due to increase in the amount of information, the text databases are growing rapidly. In many of the text databases, the data is semi-structured." }, { "code": null, "e": 70756, "s": 70202, "text": "For example, a document may contain a few structured fields, such as title, author, publishing_date, etc. But along with the structure data, the document also contains unstructured text components, such as abstract and contents. Without knowing what could be in the documents, it is difficult to formulate effective queries for analyzing and extracting useful information from the data. Users require tools to compare the documents and rank their importance and relevance. Therefore, text mining has become popular and an essential theme in data mining." }, { "code": null, "e": 71045, "s": 70756, "text": "Information retrieval deals with the retrieval of information from a large number of text-based documents. Some of the database systems are not usually present in information retrieval systems because both handle different kinds of data. Examples of information retrieval system include −" }, { "code": null, "e": 71077, "s": 71045, "text": "Online Library catalogue system" }, { "code": null, "e": 71112, "s": 71077, "text": "Online Document Management Systems" }, { "code": null, "e": 71136, "s": 71112, "text": "Web Search Systems etc." }, { "code": null, "e": 71361, "s": 71136, "text": "Note − The main problem in an information retrieval system is to locate relevant documents in a document collection based on a user's query. This kind of user's query consists of some keywords describing an information need." }, { "code": null, "e": 71715, "s": 71361, "text": "In such search problems, the user takes an initiative to pull relevant information out from a collection. This is appropriate when the user has ad-hoc information need, i.e., a short-term need. But if the user has a long-term information need, then the retrieval system can also take an initiative to push any newly arrived information item to the user." }, { "code": null, "e": 71868, "s": 71715, "text": "This kind of access to information is called Information Filtering. And the corresponding systems are known as Filtering Systems or Recommender Systems." }, { "code": null, "e": 72258, "s": 71868, "text": "We need to check the accuracy of a system when it retrieves a number of documents on the basis of user's input. Let the set of documents relevant to a query be denoted as {Relevant} and the set of retrieved document as {Retrieved}. The set of documents that are relevant and retrieved can be denoted as {Relevant} ∩ {Retrieved}. This can be shown in the form of a Venn diagram as follows −" }, { "code": null, "e": 72341, "s": 72258, "text": "There are three fundamental measures for assessing the quality of text retrieval −" }, { "code": null, "e": 72351, "s": 72341, "text": "Precision" }, { "code": null, "e": 72358, "s": 72351, "text": "Recall" }, { "code": null, "e": 72366, "s": 72358, "text": "F-score" }, { "code": null, "e": 72487, "s": 72366, "text": "Precision is the percentage of retrieved documents that are in fact relevant to the query. Precision can be defined as −" }, { "code": null, "e": 72543, "s": 72487, "text": "Precision= |{Relevant} ∩ {Retrieved}| / |{Retrieved}|\n" }, { "code": null, "e": 72663, "s": 72543, "text": "Recall is the percentage of documents that are relevant to the query and were in fact retrieved. Recall is defined as −" }, { "code": null, "e": 72716, "s": 72663, "text": "Recall = |{Relevant} ∩ {Retrieved}| / |{Relevant}|\n" }, { "code": null, "e": 72915, "s": 72716, "text": "F-score is the commonly used trade-off. The information retrieval system often needs to trade-off for precision or vice versa. F-score is defined as harmonic mean of recall or precision as follows −" }, { "code": null, "e": 72972, "s": 72915, "text": "F-score = recall x precision / (recall + precision) / 2\n" }, { "code": null, "e": 73073, "s": 72972, "text": "The World Wide Web contains huge amounts of information that provides a rich source for data mining." }, { "code": null, "e": 73179, "s": 73073, "text": "The web poses great challenges for resource and knowledge discovery based on the following observations −" }, { "code": null, "e": 73332, "s": 73179, "text": "The web is too huge − The size of the web is very huge and rapidly increasing. This seems that the web is too huge for data warehousing and data mining." }, { "code": null, "e": 73485, "s": 73332, "text": "The web is too huge − The size of the web is very huge and rapidly increasing. This seems that the web is too huge for data warehousing and data mining." }, { "code": null, "e": 73758, "s": 73485, "text": "Complexity of Web pages − The web pages do not have unifying structure. They are very complex as compared to traditional text document. There are huge amount of documents in digital library of web. These libraries are not arranged according to any particular sorted order." }, { "code": null, "e": 74031, "s": 73758, "text": "Complexity of Web pages − The web pages do not have unifying structure. They are very complex as compared to traditional text document. There are huge amount of documents in digital library of web. These libraries are not arranged according to any particular sorted order." }, { "code": null, "e": 74208, "s": 74031, "text": "Web is dynamic information source − The information on the web is rapidly updated. The data such as news, stock markets, weather, sports, shopping, etc., are regularly updated." }, { "code": null, "e": 74385, "s": 74208, "text": "Web is dynamic information source − The information on the web is rapidly updated. The data such as news, stock markets, weather, sports, shopping, etc., are regularly updated." }, { "code": null, "e": 74650, "s": 74385, "text": "Diversity of user communities − The user community on the web is rapidly expanding. These users have different backgrounds, interests, and usage purposes. There are more than 100 million workstations that are connected to the Internet and still rapidly increasing." }, { "code": null, "e": 74915, "s": 74650, "text": "Diversity of user communities − The user community on the web is rapidly expanding. These users have different backgrounds, interests, and usage purposes. There are more than 100 million workstations that are connected to the Internet and still rapidly increasing." }, { "code": null, "e": 75172, "s": 74915, "text": "Relevancy of Information − It is considered that a particular person is generally interested in only small portion of the web, while the rest of the portion of the web contains the information that is not relevant to the user and may swamp desired results." }, { "code": null, "e": 75429, "s": 75172, "text": "Relevancy of Information − It is considered that a particular person is generally interested in only small portion of the web, while the rest of the portion of the web contains the information that is not relevant to the user and may swamp desired results." }, { "code": null, "e": 75864, "s": 75429, "text": "The basic structure of the web page is based on the Document Object Model (DOM). The DOM structure refers to a tree like structure where the HTML tag in the page corresponds to a node in the DOM tree. We can segment the web page by using predefined tags in HTML. The HTML syntax is flexible therefore, the web pages does not follow the W3C specifications. Not following the specifications of W3C may cause error in DOM tree structure." }, { "code": null, "e": 76115, "s": 75864, "text": "The DOM structure was initially introduced for presentation in the browser and not for description of semantic structure of the web page. The DOM structure cannot correctly identify the semantic relationship between the different parts of a web page." }, { "code": null, "e": 76220, "s": 76115, "text": "The purpose of VIPS is to extract the semantic structure of a web page based on its visual presentation." }, { "code": null, "e": 76325, "s": 76220, "text": "The purpose of VIPS is to extract the semantic structure of a web page based on its visual presentation." }, { "code": null, "e": 76431, "s": 76325, "text": "Such a semantic structure corresponds to a tree structure. In this tree each node corresponds to a block." }, { "code": null, "e": 76537, "s": 76431, "text": "Such a semantic structure corresponds to a tree structure. In this tree each node corresponds to a block." }, { "code": null, "e": 76714, "s": 76537, "text": "A value is assigned to each node. This value is called the Degree of Coherence. This value is assigned to indicate the coherent content in the block based on visual perception." }, { "code": null, "e": 76891, "s": 76714, "text": "A value is assigned to each node. This value is called the Degree of Coherence. This value is assigned to indicate the coherent content in the block based on visual perception." }, { "code": null, "e": 77030, "s": 76891, "text": "The VIPS algorithm first extracts all the suitable blocks from the HTML DOM tree. After that it finds the separators between these blocks." }, { "code": null, "e": 77169, "s": 77030, "text": "The VIPS algorithm first extracts all the suitable blocks from the HTML DOM tree. After that it finds the separators between these blocks." }, { "code": null, "e": 77276, "s": 77169, "text": "The separators refer to the horizontal or vertical lines in a web page that visually cross with no blocks." }, { "code": null, "e": 77383, "s": 77276, "text": "The separators refer to the horizontal or vertical lines in a web page that visually cross with no blocks." }, { "code": null, "e": 77458, "s": 77383, "text": "The semantics of the web page is constructed on the basis of these blocks." }, { "code": null, "e": 77533, "s": 77458, "text": "The semantics of the web page is constructed on the basis of these blocks." }, { "code": null, "e": 77594, "s": 77533, "text": "The following figure shows the procedure of VIPS algorithm −" }, { "code": null, "e": 77837, "s": 77594, "text": "Data mining is widely used in diverse areas. There are a number of commercial data mining system available today and yet there are many challenges in this field. In this tutorial, we will discuss the applications and the trend of data mining." }, { "code": null, "e": 77898, "s": 77837, "text": "Here is the list of areas where data mining is widely used −" }, { "code": null, "e": 77922, "s": 77898, "text": "Financial Data Analysis" }, { "code": null, "e": 77938, "s": 77922, "text": "Retail Industry" }, { "code": null, "e": 77965, "s": 77938, "text": "Telecommunication Industry" }, { "code": null, "e": 77990, "s": 77965, "text": "Biological Data Analysis" }, { "code": null, "e": 78020, "s": 77990, "text": "Other Scientific Applications" }, { "code": null, "e": 78040, "s": 78020, "text": "Intrusion Detection" }, { "code": null, "e": 78238, "s": 78040, "text": "The financial data in banking and financial industry is generally reliable and of high quality which facilitates systematic data analysis and data mining. Some of the typical cases are as follows −" }, { "code": null, "e": 78333, "s": 78238, "text": "Design and construction of data warehouses for multidimensional data analysis and data mining." }, { "code": null, "e": 78428, "s": 78333, "text": "Design and construction of data warehouses for multidimensional data analysis and data mining." }, { "code": null, "e": 78489, "s": 78428, "text": "Loan payment prediction and customer credit policy analysis." }, { "code": null, "e": 78550, "s": 78489, "text": "Loan payment prediction and customer credit policy analysis." }, { "code": null, "e": 78617, "s": 78550, "text": "Classification and clustering of customers for targeted marketing." }, { "code": null, "e": 78684, "s": 78617, "text": "Classification and clustering of customers for targeted marketing." }, { "code": null, "e": 78742, "s": 78684, "text": "Detection of money laundering and other financial crimes." }, { "code": null, "e": 78800, "s": 78742, "text": "Detection of money laundering and other financial crimes." }, { "code": null, "e": 79144, "s": 78800, "text": "Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services. It is natural that the quantity of data collected will continue to expand rapidly because of the increasing ease, availability and popularity of the web." }, { "code": null, "e": 79397, "s": 79144, "text": "Data mining in retail industry helps in identifying customer buying patterns and trends that lead to improved quality of customer service and good customer retention and satisfaction. Here is the list of examples of data mining in the retail industry −" }, { "code": null, "e": 79478, "s": 79397, "text": "Design and Construction of data warehouses based on the benefits of data mining." }, { "code": null, "e": 79559, "s": 79478, "text": "Design and Construction of data warehouses based on the benefits of data mining." }, { "code": null, "e": 79633, "s": 79559, "text": "Multidimensional analysis of sales, customers, products, time and region." }, { "code": null, "e": 79707, "s": 79633, "text": "Multidimensional analysis of sales, customers, products, time and region." }, { "code": null, "e": 79753, "s": 79707, "text": "Analysis of effectiveness of sales campaigns." }, { "code": null, "e": 79799, "s": 79753, "text": "Analysis of effectiveness of sales campaigns." }, { "code": null, "e": 79819, "s": 79799, "text": "Customer Retention." }, { "code": null, "e": 79839, "s": 79819, "text": "Customer Retention." }, { "code": null, "e": 79894, "s": 79839, "text": "Product recommendation and cross-referencing of items." }, { "code": null, "e": 79949, "s": 79894, "text": "Product recommendation and cross-referencing of items." }, { "code": null, "e": 80373, "s": 79949, "text": "Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc. Due to the development of new computer and communication technologies, the telecommunication industry is rapidly expanding. This is the reason why data mining is become very important to help and understand the business." }, { "code": null, "e": 80647, "s": 80373, "text": "Data mining in telecommunication industry helps in identifying the telecommunication patterns, catch fraudulent activities, make better use of resource, and improve quality of service. Here is the list of examples for which data mining improves telecommunication services −" }, { "code": null, "e": 80700, "s": 80647, "text": "Multidimensional Analysis of Telecommunication data." }, { "code": null, "e": 80753, "s": 80700, "text": "Multidimensional Analysis of Telecommunication data." }, { "code": null, "e": 80782, "s": 80753, "text": "Fraudulent pattern analysis." }, { "code": null, "e": 80811, "s": 80782, "text": "Fraudulent pattern analysis." }, { "code": null, "e": 80847, "s": 80811, "text": "Identification of unusual patterns." }, { "code": null, "e": 80883, "s": 80847, "text": "Identification of unusual patterns." }, { "code": null, "e": 80946, "s": 80883, "text": "Multidimensional association and sequential patterns analysis." }, { "code": null, "e": 81009, "s": 80946, "text": "Multidimensional association and sequential patterns analysis." }, { "code": null, "e": 81044, "s": 81009, "text": "Mobile Telecommunication services." }, { "code": null, "e": 81079, "s": 81044, "text": "Mobile Telecommunication services." }, { "code": null, "e": 81142, "s": 81079, "text": "Use of visualization tools in telecommunication data analysis." }, { "code": null, "e": 81205, "s": 81142, "text": "Use of visualization tools in telecommunication data analysis." }, { "code": null, "e": 81511, "s": 81205, "text": "In recent times, we have seen a tremendous growth in the field of biology such as genomics, proteomics, functional Genomics and biomedical research. Biological data mining is a very important part of Bioinformatics. Following are the aspects in which data mining contributes for biological data analysis −" }, { "code": null, "e": 81595, "s": 81511, "text": "Semantic integration of heterogeneous, distributed genomic and proteomic databases." }, { "code": null, "e": 81679, "s": 81595, "text": "Semantic integration of heterogeneous, distributed genomic and proteomic databases." }, { "code": null, "e": 81774, "s": 81679, "text": "Alignment, indexing, similarity search and comparative analysis multiple nucleotide sequences." }, { "code": null, "e": 81869, "s": 81774, "text": "Alignment, indexing, similarity search and comparative analysis multiple nucleotide sequences." }, { "code": null, "e": 81957, "s": 81869, "text": "Discovery of structural patterns and analysis of genetic networks and protein pathways." }, { "code": null, "e": 82045, "s": 81957, "text": "Discovery of structural patterns and analysis of genetic networks and protein pathways." }, { "code": null, "e": 82076, "s": 82045, "text": "Association and path analysis." }, { "code": null, "e": 82107, "s": 82076, "text": "Association and path analysis." }, { "code": null, "e": 82153, "s": 82107, "text": "Visualization tools in genetic data analysis." }, { "code": null, "e": 82199, "s": 82153, "text": "Visualization tools in genetic data analysis." }, { "code": null, "e": 82723, "s": 82199, "text": "The applications discussed above tend to handle relatively small and homogeneous data sets for which the statistical techniques are appropriate. Huge amount of data have been collected from scientific domains such as geosciences, astronomy, etc. A large amount of data sets is being generated because of the fast numerical simulations in various fields such as climate and ecosystem modeling, chemical engineering, fluid dynamics, etc. Following are the applications of data mining in the field of Scientific Applications −" }, { "code": null, "e": 82763, "s": 82723, "text": "Data Warehouses and data preprocessing." }, { "code": null, "e": 82783, "s": 82763, "text": "Graph-based mining." }, { "code": null, "e": 82828, "s": 82783, "text": "Visualization and domain specific knowledge." }, { "code": null, "e": 83316, "s": 82828, "text": "Intrusion refers to any kind of action that threatens integrity, confidentiality, or the availability of network resources. In this world of connectivity, security has become the major issue. With increased usage of internet and availability of the tools and tricks for intruding and attacking network prompted intrusion detection to become a critical component of network administration. Here is the list of areas in which data mining technology may be applied for intrusion detection −" }, { "code": null, "e": 83378, "s": 83316, "text": "Development of data mining algorithm for intrusion detection." }, { "code": null, "e": 83440, "s": 83378, "text": "Development of data mining algorithm for intrusion detection." }, { "code": null, "e": 83542, "s": 83440, "text": "Association and correlation analysis, aggregation to help select and build discriminating attributes." }, { "code": null, "e": 83644, "s": 83542, "text": "Association and correlation analysis, aggregation to help select and build discriminating attributes." }, { "code": null, "e": 83669, "s": 83644, "text": "Analysis of Stream data." }, { "code": null, "e": 83694, "s": 83669, "text": "Analysis of Stream data." }, { "code": null, "e": 83719, "s": 83694, "text": "Distributed data mining." }, { "code": null, "e": 83744, "s": 83719, "text": "Distributed data mining." }, { "code": null, "e": 83775, "s": 83744, "text": "Visualization and query tools." }, { "code": null, "e": 83806, "s": 83775, "text": "Visualization and query tools." }, { "code": null, "e": 84048, "s": 83806, "text": "There are many data mining system products and domain specific data mining applications. The new data mining systems and applications are being added to the previous systems. Also, efforts are being made to standardize data mining languages." }, { "code": null, "e": 84122, "s": 84048, "text": "The selection of a data mining system depends on the following features −" }, { "code": null, "e": 84392, "s": 84122, "text": "Data Types − The data mining system may handle formatted text, record-based data, and relational data. The data could also be in ASCII text, relational database data or data warehouse data. Therefore, we should check what exact format the data mining system can handle." }, { "code": null, "e": 84662, "s": 84392, "text": "Data Types − The data mining system may handle formatted text, record-based data, and relational data. The data could also be in ASCII text, relational database data or data warehouse data. Therefore, we should check what exact format the data mining system can handle." }, { "code": null, "e": 84949, "s": 84662, "text": "System Issues − We must consider the compatibility of a data mining system with different operating systems. One data mining system may run on only one operating system or on several. There are also data mining systems that provide web-based user interfaces and allow XML data as input." }, { "code": null, "e": 85236, "s": 84949, "text": "System Issues − We must consider the compatibility of a data mining system with different operating systems. One data mining system may run on only one operating system or on several. There are also data mining systems that provide web-based user interfaces and allow XML data as input." }, { "code": null, "e": 85523, "s": 85236, "text": "Data Sources − Data sources refer to the data formats in which data mining system will operate. Some data mining system may work only on ASCII text files while others on multiple relational sources. Data mining system should also support ODBC connections or OLE DB for ODBC connections." }, { "code": null, "e": 85810, "s": 85523, "text": "Data Sources − Data sources refer to the data formats in which data mining system will operate. Some data mining system may work only on ASCII text files while others on multiple relational sources. Data mining system should also support ODBC connections or OLE DB for ODBC connections." }, { "code": null, "e": 86207, "s": 85810, "text": "Data Mining functions and methodologies − There are some data mining systems that provide only one data mining function such as classification while some provides multiple data mining functions such as concept description, discovery-driven OLAP analysis, association mining, linkage analysis, statistical analysis, classification, prediction, clustering, outlier analysis, similarity search, etc." }, { "code": null, "e": 86604, "s": 86207, "text": "Data Mining functions and methodologies − There are some data mining systems that provide only one data mining function such as classification while some provides multiple data mining functions such as concept description, discovery-driven OLAP analysis, association mining, linkage analysis, statistical analysis, classification, prediction, clustering, outlier analysis, similarity search, etc." }, { "code": null, "e": 86951, "s": 86604, "text": "Coupling data mining with databases or data warehouse systems − Data mining systems need to be coupled with a database or a data warehouse system. The coupled components are integrated into a uniform information processing environment. Here are the types of coupling listed below −\n\nNo coupling\nLoose Coupling\nSemi tight Coupling\nTight Coupling\n\n" }, { "code": null, "e": 87233, "s": 86951, "text": "Coupling data mining with databases or data warehouse systems − Data mining systems need to be coupled with a database or a data warehouse system. The coupled components are integrated into a uniform information processing environment. Here are the types of coupling listed below −" }, { "code": null, "e": 87245, "s": 87233, "text": "No coupling" }, { "code": null, "e": 87260, "s": 87245, "text": "Loose Coupling" }, { "code": null, "e": 87280, "s": 87260, "text": "Semi tight Coupling" }, { "code": null, "e": 87295, "s": 87280, "text": "Tight Coupling" }, { "code": null, "e": 87713, "s": 87295, "text": "Scalability − There are two scalability issues in data mining −\n\nRow (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query.\nColumn (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns.\n\n" }, { "code": null, "e": 87777, "s": 87713, "text": "Scalability − There are two scalability issues in data mining −" }, { "code": null, "e": 87960, "s": 87777, "text": "Row (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query." }, { "code": null, "e": 88143, "s": 87960, "text": "Row (Database size) Scalability − A data mining system is considered as row scalable when the number or rows are enlarged 10 times. It takes no more than 10 times to execute a query." }, { "code": null, "e": 88311, "s": 88143, "text": "Column (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns." }, { "code": null, "e": 88479, "s": 88311, "text": "Column (Dimension) Salability − A data mining system is considered as column scalable if the mining query execution time increases linearly with the number of columns." }, { "code": null, "e": 88661, "s": 88479, "text": "Visualization Tools − Visualization in data mining can be categorized as follows −\n\nData Visualization\nMining Results Visualization\nMining process visualization\nVisual data mining\n\n" }, { "code": null, "e": 88744, "s": 88661, "text": "Visualization Tools − Visualization in data mining can be categorized as follows −" }, { "code": null, "e": 88763, "s": 88744, "text": "Data Visualization" }, { "code": null, "e": 88792, "s": 88763, "text": "Mining Results Visualization" }, { "code": null, "e": 88821, "s": 88792, "text": "Mining process visualization" }, { "code": null, "e": 88840, "s": 88821, "text": "Visual data mining" }, { "code": null, "e": 89108, "s": 88840, "text": "Data Mining query language and graphical user interface − An easy-to-use graphical user interface is important to promote user-guided, interactive data mining. Unlike relational database systems, data mining systems do not share underlying data mining query language." }, { "code": null, "e": 89376, "s": 89108, "text": "Data Mining query language and graphical user interface − An easy-to-use graphical user interface is important to promote user-guided, interactive data mining. Unlike relational database systems, data mining systems do not share underlying data mining query language." }, { "code": null, "e": 89482, "s": 89376, "text": "Data mining concepts are still evolving and here are the latest trends that we get to see in this field −" }, { "code": null, "e": 89507, "s": 89482, "text": "Application Exploration." }, { "code": null, "e": 89532, "s": 89507, "text": "Application Exploration." }, { "code": null, "e": 89578, "s": 89532, "text": "Scalable and interactive data mining methods." }, { "code": null, "e": 89624, "s": 89578, "text": "Scalable and interactive data mining methods." }, { "code": null, "e": 89723, "s": 89624, "text": "Integration of data mining with database systems, data warehouse systems and web database systems." }, { "code": null, "e": 89822, "s": 89723, "text": "Integration of data mining with database systems, data warehouse systems and web database systems." }, { "code": null, "e": 89870, "s": 89822, "text": "SStandardization of data mining query language." }, { "code": null, "e": 89918, "s": 89870, "text": "SStandardization of data mining query language." }, { "code": null, "e": 89938, "s": 89918, "text": "Visual data mining." }, { "code": null, "e": 89958, "s": 89938, "text": "Visual data mining." }, { "code": null, "e": 90004, "s": 89958, "text": "New methods for mining complex types of data." }, { "code": null, "e": 90050, "s": 90004, "text": "New methods for mining complex types of data." }, { "code": null, "e": 90074, "s": 90050, "text": "Biological data mining." }, { "code": null, "e": 90098, "s": 90074, "text": "Biological data mining." }, { "code": null, "e": 90136, "s": 90098, "text": "Data mining and software engineering." }, { "code": null, "e": 90174, "s": 90136, "text": "Data mining and software engineering." }, { "code": null, "e": 90186, "s": 90174, "text": "Web mining." }, { "code": null, "e": 90198, "s": 90186, "text": "Web mining." }, { "code": null, "e": 90223, "s": 90198, "text": "Distributed data mining." }, { "code": null, "e": 90248, "s": 90223, "text": "Distributed data mining." }, { "code": null, "e": 90271, "s": 90248, "text": "Real time data mining." }, { "code": null, "e": 90294, "s": 90271, "text": "Real time data mining." }, { "code": null, "e": 90322, "s": 90294, "text": "Multi database data mining." }, { "code": null, "e": 90350, "s": 90322, "text": "Multi database data mining." }, { "code": null, "e": 90410, "s": 90350, "text": "Privacy protection and information security in data mining." }, { "code": null, "e": 90470, "s": 90410, "text": "Privacy protection and information security in data mining." }, { "code": null, "e": 90547, "s": 90470, "text": "The theoretical foundations of data mining includes the following concepts −" }, { "code": null, "e": 90943, "s": 90547, "text": "Data Reduction − The basic idea of this theory is to reduce the data representation which trades accuracy for speed in response to the need to obtain quick approximate answers to queries on very large databases. Some of the data reduction techniques are as follows −\n\nSingular value Decomposition\nWavelets\nRegression\nLog-linear models\nHistograms\nClustering\nSampling\nConstruction of Index Trees\n\n" }, { "code": null, "e": 91210, "s": 90943, "text": "Data Reduction − The basic idea of this theory is to reduce the data representation which trades accuracy for speed in response to the need to obtain quick approximate answers to queries on very large databases. Some of the data reduction techniques are as follows −" }, { "code": null, "e": 91239, "s": 91210, "text": "Singular value Decomposition" }, { "code": null, "e": 91268, "s": 91239, "text": "Singular value Decomposition" }, { "code": null, "e": 91277, "s": 91268, "text": "Wavelets" }, { "code": null, "e": 91286, "s": 91277, "text": "Wavelets" }, { "code": null, "e": 91297, "s": 91286, "text": "Regression" }, { "code": null, "e": 91308, "s": 91297, "text": "Regression" }, { "code": null, "e": 91326, "s": 91308, "text": "Log-linear models" }, { "code": null, "e": 91344, "s": 91326, "text": "Log-linear models" }, { "code": null, "e": 91355, "s": 91344, "text": "Histograms" }, { "code": null, "e": 91366, "s": 91355, "text": "Histograms" }, { "code": null, "e": 91377, "s": 91366, "text": "Clustering" }, { "code": null, "e": 91388, "s": 91377, "text": "Clustering" }, { "code": null, "e": 91397, "s": 91388, "text": "Sampling" }, { "code": null, "e": 91406, "s": 91397, "text": "Sampling" }, { "code": null, "e": 91434, "s": 91406, "text": "Construction of Index Trees" }, { "code": null, "e": 91462, "s": 91434, "text": "Construction of Index Trees" }, { "code": null, "e": 91631, "s": 91462, "text": "Data Compression − The basic idea of this theory is to compress the given data by encoding in terms of the following −\n\nBits\nAssociation Rules\nDecision Trees\nClusters\n\n" }, { "code": null, "e": 91750, "s": 91631, "text": "Data Compression − The basic idea of this theory is to compress the given data by encoding in terms of the following −" }, { "code": null, "e": 91755, "s": 91750, "text": "Bits" }, { "code": null, "e": 91760, "s": 91755, "text": "Bits" }, { "code": null, "e": 91778, "s": 91760, "text": "Association Rules" }, { "code": null, "e": 91796, "s": 91778, "text": "Association Rules" }, { "code": null, "e": 91811, "s": 91796, "text": "Decision Trees" }, { "code": null, "e": 91826, "s": 91811, "text": "Decision Trees" }, { "code": null, "e": 91835, "s": 91826, "text": "Clusters" }, { "code": null, "e": 91844, "s": 91835, "text": "Clusters" }, { "code": null, "e": 92093, "s": 91844, "text": "Pattern Discovery − The basic idea of this theory is to discover patterns occurring in a database. Following are the areas that contribute to this theory −\n\nMachine Learning\nNeural Network\nAssociation Mining\nSequential Pattern Matching\nClustering\n\n" }, { "code": null, "e": 92249, "s": 92093, "text": "Pattern Discovery − The basic idea of this theory is to discover patterns occurring in a database. Following are the areas that contribute to this theory −" }, { "code": null, "e": 92266, "s": 92249, "text": "Machine Learning" }, { "code": null, "e": 92283, "s": 92266, "text": "Machine Learning" }, { "code": null, "e": 92298, "s": 92283, "text": "Neural Network" }, { "code": null, "e": 92313, "s": 92298, "text": "Neural Network" }, { "code": null, "e": 92332, "s": 92313, "text": "Association Mining" }, { "code": null, "e": 92351, "s": 92332, "text": "Association Mining" }, { "code": null, "e": 92379, "s": 92351, "text": "Sequential Pattern Matching" }, { "code": null, "e": 92407, "s": 92379, "text": "Sequential Pattern Matching" }, { "code": null, "e": 92418, "s": 92407, "text": "Clustering" }, { "code": null, "e": 92429, "s": 92418, "text": "Clustering" }, { "code": null, "e": 92596, "s": 92429, "text": "Probability Theory − This theory is based on statistical theory. The basic idea behind this theory is to discover joint probability distributions of random variables." }, { "code": null, "e": 92763, "s": 92596, "text": "Probability Theory − This theory is based on statistical theory. The basic idea behind this theory is to discover joint probability distributions of random variables." }, { "code": null, "e": 92954, "s": 92763, "text": "Probability Theory − According to this theory, data mining finds the patterns that are interesting only to the extent that they can be used in the decision-making process of some enterprise." }, { "code": null, "e": 93145, "s": 92954, "text": "Probability Theory − According to this theory, data mining finds the patterns that are interesting only to the extent that they can be used in the decision-making process of some enterprise." }, { "code": null, "e": 93338, "s": 93145, "text": "Microeconomic View − As per this theory, a database schema consists of data and patterns that are stored in a database. Therefore, data mining is the task of performing induction on databases." }, { "code": null, "e": 93531, "s": 93338, "text": "Microeconomic View − As per this theory, a database schema consists of data and patterns that are stored in a database. Therefore, data mining is the task of performing induction on databases." }, { "code": null, "e": 93763, "s": 93531, "text": "Inductive databases − Apart from the database-oriented techniques, there are statistical techniques available for data analysis. These techniques can be applied to scientific data and data from economic and social sciences as well." }, { "code": null, "e": 93995, "s": 93763, "text": "Inductive databases − Apart from the database-oriented techniques, there are statistical techniques available for data analysis. These techniques can be applied to scientific data and data from economic and social sciences as well." }, { "code": null, "e": 94059, "s": 93995, "text": "Some of the Statistical Data Mining Techniques are as follows −" }, { "code": null, "e": 94319, "s": 94059, "text": "Regression − Regression methods are used to predict the value of the response variable from one or more predictor variables where the variables are numeric. Listed below are the forms of Regression −\n\nLinear\nMultiple\nWeighted\nPolynomial\nNonparametric\nRobust\n\n" }, { "code": null, "e": 94519, "s": 94319, "text": "Regression − Regression methods are used to predict the value of the response variable from one or more predictor variables where the variables are numeric. Listed below are the forms of Regression −" }, { "code": null, "e": 94526, "s": 94519, "text": "Linear" }, { "code": null, "e": 94533, "s": 94526, "text": "Linear" }, { "code": null, "e": 94542, "s": 94533, "text": "Multiple" }, { "code": null, "e": 94551, "s": 94542, "text": "Multiple" }, { "code": null, "e": 94560, "s": 94551, "text": "Weighted" }, { "code": null, "e": 94569, "s": 94560, "text": "Weighted" }, { "code": null, "e": 94580, "s": 94569, "text": "Polynomial" }, { "code": null, "e": 94591, "s": 94580, "text": "Polynomial" }, { "code": null, "e": 94605, "s": 94591, "text": "Nonparametric" }, { "code": null, "e": 94619, "s": 94605, "text": "Nonparametric" }, { "code": null, "e": 94626, "s": 94619, "text": "Robust" }, { "code": null, "e": 94633, "s": 94626, "text": "Robust" }, { "code": null, "e": 94941, "s": 94633, "text": "Generalized Linear Models − Generalized Linear Model includes −\n\nLogistic Regression\nPoisson Regression\n\nThe model's generalization allows a categorical response variable to be related to a set of predictor variables in a manner similar to the modelling of numeric response variable using linear regression." }, { "code": null, "e": 95005, "s": 94941, "text": "Generalized Linear Models − Generalized Linear Model includes −" }, { "code": null, "e": 95025, "s": 95005, "text": "Logistic Regression" }, { "code": null, "e": 95045, "s": 95025, "text": "Logistic Regression" }, { "code": null, "e": 95064, "s": 95045, "text": "Poisson Regression" }, { "code": null, "e": 95083, "s": 95064, "text": "Poisson Regression" }, { "code": null, "e": 95286, "s": 95083, "text": "The model's generalization allows a categorical response variable to be related to a set of predictor variables in a manner similar to the modelling of numeric response variable using linear regression." }, { "code": null, "e": 95471, "s": 95286, "text": "Analysis of Variance − This technique analyzes −\n\nExperimental data for two or more populations described by a numeric response variable.\nOne or more categorical variables (factors).\n\n" }, { "code": null, "e": 95520, "s": 95471, "text": "Analysis of Variance − This technique analyzes −" }, { "code": null, "e": 95608, "s": 95520, "text": "Experimental data for two or more populations described by a numeric response variable." }, { "code": null, "e": 95696, "s": 95608, "text": "Experimental data for two or more populations described by a numeric response variable." }, { "code": null, "e": 95741, "s": 95696, "text": "One or more categorical variables (factors)." }, { "code": null, "e": 95786, "s": 95741, "text": "One or more categorical variables (factors)." }, { "code": null, "e": 96000, "s": 95786, "text": "Mixed-effect Models − These models are used for analyzing grouped data. These models describe the relationship between a response variable and some co-variates in the data grouped according to one or more factors." }, { "code": null, "e": 96214, "s": 96000, "text": "Mixed-effect Models − These models are used for analyzing grouped data. These models describe the relationship between a response variable and some co-variates in the data grouped according to one or more factors." }, { "code": null, "e": 96390, "s": 96214, "text": "Factor Analysis − Factor analysis is used to predict a categorical response variable. This method assumes that independent variables follow a multivariate normal distribution." }, { "code": null, "e": 96566, "s": 96390, "text": "Factor Analysis − Factor analysis is used to predict a categorical response variable. This method assumes that independent variables follow a multivariate normal distribution." }, { "code": null, "e": 96780, "s": 96566, "text": "Time Series Analysis − Following are the methods for analyzing time-series data −\n\nAuto-regression Methods.\nUnivariate ARIMA (AutoRegressive Integrated Moving Average) Modeling.\nLong-memory time-series modeling.\n\n" }, { "code": null, "e": 96862, "s": 96780, "text": "Time Series Analysis − Following are the methods for analyzing time-series data −" }, { "code": null, "e": 96887, "s": 96862, "text": "Auto-regression Methods." }, { "code": null, "e": 96912, "s": 96887, "text": "Auto-regression Methods." }, { "code": null, "e": 96982, "s": 96912, "text": "Univariate ARIMA (AutoRegressive Integrated Moving Average) Modeling." }, { "code": null, "e": 97052, "s": 96982, "text": "Univariate ARIMA (AutoRegressive Integrated Moving Average) Modeling." }, { "code": null, "e": 97086, "s": 97052, "text": "Long-memory time-series modeling." }, { "code": null, "e": 97120, "s": 97086, "text": "Long-memory time-series modeling." }, { "code": null, "e": 97326, "s": 97120, "text": "Visual Data Mining uses data and/or knowledge visualization techniques to discover implicit knowledge from large data sets. Visual data mining can be viewed as an integration of the following disciplines −" }, { "code": null, "e": 97345, "s": 97326, "text": "Data Visualization" }, { "code": null, "e": 97364, "s": 97345, "text": "Data Visualization" }, { "code": null, "e": 97376, "s": 97364, "text": "Data Mining" }, { "code": null, "e": 97388, "s": 97376, "text": "Data Mining" }, { "code": null, "e": 97445, "s": 97388, "text": "Visual data mining is closely related to the following −" }, { "code": null, "e": 97463, "s": 97445, "text": "Computer Graphics" }, { "code": null, "e": 97481, "s": 97463, "text": "Computer Graphics" }, { "code": null, "e": 97500, "s": 97481, "text": "Multimedia Systems" }, { "code": null, "e": 97519, "s": 97500, "text": "Multimedia Systems" }, { "code": null, "e": 97546, "s": 97519, "text": "Human Computer Interaction" }, { "code": null, "e": 97573, "s": 97546, "text": "Human Computer Interaction" }, { "code": null, "e": 97593, "s": 97573, "text": "Pattern Recognition" }, { "code": null, "e": 97613, "s": 97593, "text": "Pattern Recognition" }, { "code": null, "e": 97640, "s": 97613, "text": "High-performance Computing" }, { "code": null, "e": 97667, "s": 97640, "text": "High-performance Computing" }, { "code": null, "e": 97754, "s": 97667, "text": "Generally data visualization and data mining can be integrated in the following ways −" }, { "code": null, "e": 97960, "s": 97754, "text": "Data Visualization − The data in a database or a data warehouse can be viewed in several visual forms that are listed below −\n\nBoxplots\n3-D Cubes\nData distribution charts\nCurves\nSurfaces\nLink graphs etc.\n\n" }, { "code": null, "e": 98086, "s": 97960, "text": "Data Visualization − The data in a database or a data warehouse can be viewed in several visual forms that are listed below −" }, { "code": null, "e": 98095, "s": 98086, "text": "Boxplots" }, { "code": null, "e": 98104, "s": 98095, "text": "Boxplots" }, { "code": null, "e": 98114, "s": 98104, "text": "3-D Cubes" }, { "code": null, "e": 98124, "s": 98114, "text": "3-D Cubes" }, { "code": null, "e": 98149, "s": 98124, "text": "Data distribution charts" }, { "code": null, "e": 98174, "s": 98149, "text": "Data distribution charts" }, { "code": null, "e": 98181, "s": 98174, "text": "Curves" }, { "code": null, "e": 98188, "s": 98181, "text": "Curves" }, { "code": null, "e": 98197, "s": 98188, "text": "Surfaces" }, { "code": null, "e": 98206, "s": 98197, "text": "Surfaces" }, { "code": null, "e": 98223, "s": 98206, "text": "Link graphs etc." }, { "code": null, "e": 98240, "s": 98223, "text": "Link graphs etc." }, { "code": null, "e": 98435, "s": 98240, "text": "Data Mining Result Visualization − Data Mining Result Visualization is the presentation of the results of data mining in visual forms. These visual forms could be scattered plots, boxplots, etc." }, { "code": null, "e": 98630, "s": 98435, "text": "Data Mining Result Visualization − Data Mining Result Visualization is the presentation of the results of data mining in visual forms. These visual forms could be scattered plots, boxplots, etc." }, { "code": null, "e": 98929, "s": 98630, "text": "Data Mining Process Visualization − Data Mining Process Visualization presents the several processes of data mining. It allows the users to see how the data is extracted. It also allows the users to see from which database or data warehouse the data is cleaned, integrated, preprocessed, and mined." }, { "code": null, "e": 99228, "s": 98929, "text": "Data Mining Process Visualization − Data Mining Process Visualization presents the several processes of data mining. It allows the users to see how the data is extracted. It also allows the users to see from which database or data warehouse the data is cleaned, integrated, preprocessed, and mined." }, { "code": null, "e": 99503, "s": 99228, "text": "Audio data mining makes use of audio signals to indicate the patterns of data or the features of data mining results. By transforming patterns into sound and musing, we can listen to pitches and tunes, instead of watching pictures, in order to identify anything interesting." }, { "code": null, "e": 99852, "s": 99503, "text": "Consumers today come across a variety of goods and services while shopping. During live customer transactions, a Recommender System helps the consumer by making product recommendations. The Collaborative Filtering Approach is generally used for recommending products to customers. These recommendations are based on the opinions of other customers." }, { "code": null, "e": 99887, "s": 99852, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 99899, "s": 99887, "text": " Ravi Kiran" }, { "code": null, "e": 99934, "s": 99899, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 99953, "s": 99934, "text": " Arnab Chakraborty" }, { "code": null, "e": 99988, "s": 99953, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 100003, "s": 99988, "text": " Parth Panjabi" }, { "code": null, "e": 100036, "s": 100003, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 100055, "s": 100036, "text": " Arnab Chakraborty" }, { "code": null, "e": 100089, "s": 100055, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 100117, "s": 100089, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 100153, "s": 100117, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 100181, "s": 100153, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 100188, "s": 100181, "text": " Print" }, { "code": null, "e": 100199, "s": 100188, "text": " Add Notes" } ]
Python | Convert String to bytes - GeeksforGeeks
22 May, 2019 Inter conversions are as usual quite popular, but conversion between a string to bytes is more common these days due to the fact that for handling files or Machine Learning ( Pickle File ), we extensively require the strings to be converted to bytes. Let’s discuss certain ways in which this can be performed. Method #1 : Using bytes(str, enc) String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to specified encoding. # Python code to demonstrate# convert string to byte # Using bytes(str, enc) # initializing string test_string = "GFG is best" # printing original string print("The original string : " + str(test_string)) # Using bytes(str, enc)# convert string to byte res = bytes(test_string, 'utf-8') # print resultprint("The byte converted string is : " + str(res) + ", type : " + str(type(res))) The original string : GFG is best The byte converted string is : b'GFG is best', type : <class 'bytes'> Method #2 : Using encode(enc) The most recommended method to perform this particular task, using the encode function to get the conversion done, as it reduces one extra linking to a particular library, this function directly calls it. # Python code to demonstrate# convert string to byte # Using encode(enc) # initializing string test_string = "GFG is best" # printing original string print("The original string : " + str(test_string)) # Using encode(enc)# convert string to byte res = test_string.encode('utf-8') # print resultprint("The byte converted string is : " + str(res) + ", type : " + str(type(res))) The original string : GFG is best The byte converted string is : b'GFG is best', type : <class 'bytes'> Python string-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not
[ { "code": null, "e": 24317, "s": 24289, "text": "\n22 May, 2019" }, { "code": null, "e": 24627, "s": 24317, "text": "Inter conversions are as usual quite popular, but conversion between a string to bytes is more common these days due to the fact that for handling files or Machine Learning ( Pickle File ), we extensively require the strings to be converted to bytes. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 24661, "s": 24627, "text": "Method #1 : Using bytes(str, enc)" }, { "code": null, "e": 24871, "s": 24661, "text": "String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to specified encoding." }, { "code": "# Python code to demonstrate# convert string to byte # Using bytes(str, enc) # initializing string test_string = \"GFG is best\" # printing original string print(\"The original string : \" + str(test_string)) # Using bytes(str, enc)# convert string to byte res = bytes(test_string, 'utf-8') # print resultprint(\"The byte converted string is : \" + str(res) + \", type : \" + str(type(res)))", "e": 25260, "s": 24871, "text": null }, { "code": null, "e": 25366, "s": 25260, "text": "The original string : GFG is best\nThe byte converted string is : b'GFG is best', type : <class 'bytes'>\n" }, { "code": null, "e": 25398, "s": 25368, "text": "Method #2 : Using encode(enc)" }, { "code": null, "e": 25603, "s": 25398, "text": "The most recommended method to perform this particular task, using the encode function to get the conversion done, as it reduces one extra linking to a particular library, this function directly calls it." }, { "code": "# Python code to demonstrate# convert string to byte # Using encode(enc) # initializing string test_string = \"GFG is best\" # printing original string print(\"The original string : \" + str(test_string)) # Using encode(enc)# convert string to byte res = test_string.encode('utf-8') # print resultprint(\"The byte converted string is : \" + str(res) + \", type : \" + str(type(res)))", "e": 25984, "s": 25603, "text": null }, { "code": null, "e": 26090, "s": 25984, "text": "The original string : GFG is best\nThe byte converted string is : b'GFG is best', type : <class 'bytes'>\n" }, { "code": null, "e": 26113, "s": 26090, "text": "Python string-programs" }, { "code": null, "e": 26120, "s": 26113, "text": "Python" }, { "code": null, "e": 26136, "s": 26120, "text": "Python Programs" }, { "code": null, "e": 26234, "s": 26136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26243, "s": 26234, "text": "Comments" }, { "code": null, "e": 26256, "s": 26243, "text": "Old Comments" }, { "code": null, "e": 26274, "s": 26256, "text": "Python Dictionary" }, { "code": null, "e": 26309, "s": 26274, "text": "Read a file line by line in Python" }, { "code": null, "e": 26331, "s": 26309, "text": "Enumerate() in Python" }, { "code": null, "e": 26363, "s": 26331, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26393, "s": 26363, "text": "Iterate over a list in Python" }, { "code": null, "e": 26436, "s": 26393, "text": "Python program to convert a list to string" }, { "code": null, "e": 26458, "s": 26436, "text": "Defaultdict in Python" }, { "code": null, "e": 26497, "s": 26458, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26543, "s": 26497, "text": "Python | Split string into list of characters" } ]
Git Setup for Mac Users. Mac users, let’s setup Git the right... | by Joseph Robinson, PhD | Towards Data Science
I stumbled upon Medium a few months ago — initially, I found the content broad in scope and material keen on quality — already there have been significant improvements found in blogs and overall interface. With that, and as I configure a new iMac for the lab (i.e., SMILE Lab — more on this later), I figured I would record the process followed to install and configure Git. I intend to make this my first of many blogs; nonetheless, I figured this simple tutorial serves as an excellent way to “break the ice”. I hope you enjoy it! Let’s now move on to some good old fashion Git for Mac — We will get your Mac machine set up properly. Install Git Initial Setup Git Styles in Terminal Git Autocomplete Git Ignore Git Aliases Git Authentication Desktop (GUI) Applications The first thing is first — installation. This is quite simple. It can be done a couple of different ways. For the sake of having the brew package manager installed, I recommend using Homebrew. Open the terminal and install Homebrew by running the following command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" Then install git brew install git — or — The easiest way to install Git on a Mac is via the stand-alone installer: Download the latest Git for Mac installer.Follow the prompts to install Git. Download the latest Git for Mac installer. Follow the prompts to install Git. Open a terminal and verify the installation was successful by typing and running the following in the terminal Open a terminal and verify the installation was successful by typing and running the following in the terminal git --version 2. Configure your Git username and email using the following commands, replacing Ava’s name with your own. These details associated with any commits that you create: git config --global user.name "Ava Paris"git config --global user.email "[email protected]" 3. (Optional) To remember your Git username and password when working with HTTPS repositories, configure the git-credential-osxkeychain helper. There are many styles for display. Regardless, let’s keep it simple and neat — setup a Git color scheme and branch information displayed in the terminal. Colors: Unless you are reading this from a monochrome display, let’s take advantage of some of the color features for git. Most definitely, specific components of Git are best displayed in color, making it easier to identifier different components and, thus, more comfortable to read. From the terminal run the following set of commands (i.e., from any folder): git config --global color.status autogit config --global color.branch autogit config --global color.interactive autogit config --global color.diff auto Mac terminals can be configured to use colors to improve the display. For this, copy and paste the following into file ~/.gitconfig. [color] branch = auto diff = auto status = auto[color "branch"] current = yellow reverse local = yellow remote = green[color "diff"] meta = yellow bold frag = magenta bold old = red bold new = green bold[color "status"] added = yellow changed = green untracked = cyan Repo and branch listing: One of the best customization for Git, in my opinion, is displaying branch information in the terminal. For this, simply add the following lines of text to ~/.bash_profile file: parse_git_branch() {git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'}export PS1="$NO_COLOUR[\t] $BLUE\u$SSH_FLAG:$YELLOW\w$NO_COLOUR: \n$GREEN\$(parse_git_branch) $BLUE\\$ $NO_COLOUR" Now, in the current repo, the prompt would look like the following: [jrobinso@blackhawk matlab (master)]$ Autocomplete via tab key can be a handy feature to have. However, autocompletion is not set up automatically on MacOS. Fortunately, setting this takes only a couple of easy steps. First, install the required brew package as follows: brew install bash-completion Next, add the following snippet of code to ~/.bash_profile file. source /usr/local/etc/bash_completion.d/git-completion.bash Either open a new terminal or run source ~/.bash_profile and enjoy! Some files or file-types are typically not added to the repo. Thus, the ‘status’ display printout would be cleaner if these files were omitted. All that needs to be done for this is to create ~/.gitignore and add. For starters, let’s create a file with the following contents: .DS_Store Note, ~/.gitexcludes also work per project, in which case the file exists in the root directory of the repo. Nonetheless, .DS_Store should be ignored globally per the instructions above were followed. Aliases, especially for Git, are typically worthwhile! If there is nothing else, at least add this feature to your global Git configurations. Notice I referred to the configurations as being ‘global’ — ~/.gitconfig are configurations applied system-wide, and project-specific configurations get handled in .gitconfiglocated in the root of a repository (i.e., <repo>/.gitconfig). For aliases, typically makes the most sense to add to global configurations. If needed later, then add unique alias to a specific project. Perhaps worth noting that alias, or all Git configurations for that matter, are first set using local configurations, and then globally if not specified in locally. In other words, let’s say you have the same alias defined in local and global configurations, then the local definition would be used in for that specific repo. Regardless of local or global, but with global is recommended, add the following [alias] block to .gitconfig: [alias] st = status -uno ci = commit br = branch co = checkout df = diff lg = log -p lgg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative f = fetch Now try + add additional aliases whenever seen fit... it’s as easy as that. [jrobinso@blackhawk matlab (feature_branch)]$ git co master Switched to branch 'master'[jrobinso@blackhawk matlab (master)]$ git st # On branch master nothing to commit (use -u to show untracked files)[jrobinso@blackhawk matlab (master)]$ git f # <fetch output> Often an SSH key is needed for authentication purposes. For this, generate a key from the terminal: [jrobinso@blackhawk ~]$ ssh-keygen Hit return a couple of times (i.e., leave passcode blank). Next, copy SSH key to clipboard via [jrobinso@blackhawk ~]$ cat ~/.ssh/id_rsa.pub | pbcopy Finally, paste the key into settings page on repository host(s). Considering Git does have a tad bit of a learning curve, even though the best way to overcome this is to get comfortable with it at its core (i.e., from the terminal), perhaps a GUI would be preferred by some. With that, I figured it was worth mentioning GUI-based Git repo tools. For this, two options stand out: SourceTree and Github Desktop App. SourceTree has the advantage of working with repositories from various hosts (e.g., Github, Bitbucket, etc.), while Github Desktop App is Github specific. Properly setting up a development environment and first-and-foremost in most projects. By taking a few minutes to complete this tutorial, Git version control is now correctly set up on your machine to enhance and optimize your throughput. For those new to git or not comfortable in the terminal, perhaps a desktop application would suit you best (e.g., SourceTree or GitHub Desktop App). These provide many features, tools, and visualizations in a GUI. Regardless, the terminal is a must in some situations. Plus, a better understanding of Git and version control would be acquired if one faced the learning curve that comes with using it from a terminal. In any case, whether an expert or beginner, your system should now be ready to use Git. I hope you enjoy it! If something is missing or could be improved, please share below — whether a Git alias you could not live without, a neat feature, or an aspect that could be improved or is outdated. Of course, all questions are also welcome! Thank you for reading my first blog — hope it was enjoyed, feel free to provide feedback on how future blogs could be improved. Checkout version for macOS Catalina 10.15.3 [ blog ].
[ { "code": null, "e": 705, "s": 172, "text": "I stumbled upon Medium a few months ago — initially, I found the content broad in scope and material keen on quality — already there have been significant improvements found in blogs and overall interface. With that, and as I configure a new iMac for the lab (i.e., SMILE Lab — more on this later), I figured I would record the process followed to install and configure Git. I intend to make this my first of many blogs; nonetheless, I figured this simple tutorial serves as an excellent way to “break the ice”. I hope you enjoy it!" }, { "code": null, "e": 808, "s": 705, "text": "Let’s now move on to some good old fashion Git for Mac — We will get your Mac machine set up properly." }, { "code": null, "e": 820, "s": 808, "text": "Install Git" }, { "code": null, "e": 834, "s": 820, "text": "Initial Setup" }, { "code": null, "e": 857, "s": 834, "text": "Git Styles in Terminal" }, { "code": null, "e": 874, "s": 857, "text": "Git Autocomplete" }, { "code": null, "e": 885, "s": 874, "text": "Git Ignore" }, { "code": null, "e": 897, "s": 885, "text": "Git Aliases" }, { "code": null, "e": 916, "s": 897, "text": "Git Authentication" }, { "code": null, "e": 943, "s": 916, "text": "Desktop (GUI) Applications" }, { "code": null, "e": 1136, "s": 943, "text": "The first thing is first — installation. This is quite simple. It can be done a couple of different ways. For the sake of having the brew package manager installed, I recommend using Homebrew." }, { "code": null, "e": 1209, "s": 1136, "text": "Open the terminal and install Homebrew by running the following command:" }, { "code": null, "e": 1308, "s": 1209, "text": "/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"" }, { "code": null, "e": 1325, "s": 1308, "text": "Then install git" }, { "code": null, "e": 1342, "s": 1325, "text": "brew install git" }, { "code": null, "e": 1349, "s": 1342, "text": "— or —" }, { "code": null, "e": 1423, "s": 1349, "text": "The easiest way to install Git on a Mac is via the stand-alone installer:" }, { "code": null, "e": 1500, "s": 1423, "text": "Download the latest Git for Mac installer.Follow the prompts to install Git." }, { "code": null, "e": 1543, "s": 1500, "text": "Download the latest Git for Mac installer." }, { "code": null, "e": 1578, "s": 1543, "text": "Follow the prompts to install Git." }, { "code": null, "e": 1689, "s": 1578, "text": "Open a terminal and verify the installation was successful by typing and running the following in the terminal" }, { "code": null, "e": 1800, "s": 1689, "text": "Open a terminal and verify the installation was successful by typing and running the following in the terminal" }, { "code": null, "e": 1814, "s": 1800, "text": "git --version" }, { "code": null, "e": 1980, "s": 1814, "text": "2. Configure your Git username and email using the following commands, replacing Ava’s name with your own. These details associated with any commits that you create:" }, { "code": null, "e": 2072, "s": 1980, "text": "git config --global user.name \"Ava Paris\"git config --global user.email \"[email protected]\"" }, { "code": null, "e": 2216, "s": 2072, "text": "3. (Optional) To remember your Git username and password when working with HTTPS repositories, configure the git-credential-osxkeychain helper." }, { "code": null, "e": 2370, "s": 2216, "text": "There are many styles for display. Regardless, let’s keep it simple and neat — setup a Git color scheme and branch information displayed in the terminal." }, { "code": null, "e": 2378, "s": 2370, "text": "Colors:" }, { "code": null, "e": 2655, "s": 2378, "text": "Unless you are reading this from a monochrome display, let’s take advantage of some of the color features for git. Most definitely, specific components of Git are best displayed in color, making it easier to identifier different components and, thus, more comfortable to read." }, { "code": null, "e": 2732, "s": 2655, "text": "From the terminal run the following set of commands (i.e., from any folder):" }, { "code": null, "e": 2884, "s": 2732, "text": "git config --global color.status autogit config --global color.branch autogit config --global color.interactive autogit config --global color.diff auto" }, { "code": null, "e": 3017, "s": 2884, "text": "Mac terminals can be configured to use colors to improve the display. For this, copy and paste the following into file ~/.gitconfig." }, { "code": null, "e": 3285, "s": 3017, "text": "[color]\tbranch = auto\tdiff = auto\tstatus = auto[color \"branch\"]\tcurrent = yellow reverse\tlocal = yellow\tremote = green[color \"diff\"]\tmeta = yellow bold\tfrag = magenta bold\told = red bold\tnew = green bold[color \"status\"]\tadded = yellow\tchanged = green\tuntracked = cyan" }, { "code": null, "e": 3310, "s": 3285, "text": "Repo and branch listing:" }, { "code": null, "e": 3414, "s": 3310, "text": "One of the best customization for Git, in my opinion, is displaying branch information in the terminal." }, { "code": null, "e": 3488, "s": 3414, "text": "For this, simply add the following lines of text to ~/.bash_profile file:" }, { "code": null, "e": 3690, "s": 3488, "text": "parse_git_branch() {git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \\(.*\\)/ (\\1)/'}export PS1=\"$NO_COLOUR[\\t] $BLUE\\u$SSH_FLAG:$YELLOW\\w$NO_COLOUR: \\n$GREEN\\$(parse_git_branch) $BLUE\\\\$ $NO_COLOUR\"" }, { "code": null, "e": 3758, "s": 3690, "text": "Now, in the current repo, the prompt would look like the following:" }, { "code": null, "e": 3796, "s": 3758, "text": "[jrobinso@blackhawk matlab (master)]$" }, { "code": null, "e": 3976, "s": 3796, "text": "Autocomplete via tab key can be a handy feature to have. However, autocompletion is not set up automatically on MacOS. Fortunately, setting this takes only a couple of easy steps." }, { "code": null, "e": 4029, "s": 3976, "text": "First, install the required brew package as follows:" }, { "code": null, "e": 4058, "s": 4029, "text": "brew install bash-completion" }, { "code": null, "e": 4123, "s": 4058, "text": "Next, add the following snippet of code to ~/.bash_profile file." }, { "code": null, "e": 4183, "s": 4123, "text": "source /usr/local/etc/bash_completion.d/git-completion.bash" }, { "code": null, "e": 4251, "s": 4183, "text": "Either open a new terminal or run source ~/.bash_profile and enjoy!" }, { "code": null, "e": 4528, "s": 4251, "text": "Some files or file-types are typically not added to the repo. Thus, the ‘status’ display printout would be cleaner if these files were omitted. All that needs to be done for this is to create ~/.gitignore and add. For starters, let’s create a file with the following contents:" }, { "code": null, "e": 4538, "s": 4528, "text": ".DS_Store" }, { "code": null, "e": 4739, "s": 4538, "text": "Note, ~/.gitexcludes also work per project, in which case the file exists in the root directory of the repo. Nonetheless, .DS_Store should be ignored globally per the instructions above were followed." }, { "code": null, "e": 5118, "s": 4739, "text": "Aliases, especially for Git, are typically worthwhile! If there is nothing else, at least add this feature to your global Git configurations. Notice I referred to the configurations as being ‘global’ — ~/.gitconfig are configurations applied system-wide, and project-specific configurations get handled in .gitconfiglocated in the root of a repository (i.e., <repo>/.gitconfig)." }, { "code": null, "e": 5583, "s": 5118, "text": "For aliases, typically makes the most sense to add to global configurations. If needed later, then add unique alias to a specific project. Perhaps worth noting that alias, or all Git configurations for that matter, are first set using local configurations, and then globally if not specified in locally. In other words, let’s say you have the same alias defined in local and global configurations, then the local definition would be used in for that specific repo." }, { "code": null, "e": 5693, "s": 5583, "text": "Regardless of local or global, but with global is recommended, add the following [alias] block to .gitconfig:" }, { "code": null, "e": 5942, "s": 5693, "text": "[alias] st = status -uno ci = commit br = branch co = checkout df = diff lg = log -p lgg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative f = fetch" }, { "code": null, "e": 6018, "s": 5942, "text": "Now try + add additional aliases whenever seen fit... it’s as easy as that." }, { "code": null, "e": 6281, "s": 6018, "text": "[jrobinso@blackhawk matlab (feature_branch)]$ git co master Switched to branch 'master'[jrobinso@blackhawk matlab (master)]$ git st # On branch master nothing to commit (use -u to show untracked files)[jrobinso@blackhawk matlab (master)]$ git f # <fetch output>" }, { "code": null, "e": 6337, "s": 6281, "text": "Often an SSH key is needed for authentication purposes." }, { "code": null, "e": 6381, "s": 6337, "text": "For this, generate a key from the terminal:" }, { "code": null, "e": 6416, "s": 6381, "text": "[jrobinso@blackhawk ~]$ ssh-keygen" }, { "code": null, "e": 6475, "s": 6416, "text": "Hit return a couple of times (i.e., leave passcode blank)." }, { "code": null, "e": 6511, "s": 6475, "text": "Next, copy SSH key to clipboard via" }, { "code": null, "e": 6566, "s": 6511, "text": "[jrobinso@blackhawk ~]$ cat ~/.ssh/id_rsa.pub | pbcopy" }, { "code": null, "e": 6631, "s": 6566, "text": "Finally, paste the key into settings page on repository host(s)." }, { "code": null, "e": 6980, "s": 6631, "text": "Considering Git does have a tad bit of a learning curve, even though the best way to overcome this is to get comfortable with it at its core (i.e., from the terminal), perhaps a GUI would be preferred by some. With that, I figured it was worth mentioning GUI-based Git repo tools. For this, two options stand out: SourceTree and Github Desktop App." }, { "code": null, "e": 7135, "s": 6980, "text": "SourceTree has the advantage of working with repositories from various hosts (e.g., Github, Bitbucket, etc.), while Github Desktop App is Github specific." }, { "code": null, "e": 7374, "s": 7135, "text": "Properly setting up a development environment and first-and-foremost in most projects. By taking a few minutes to complete this tutorial, Git version control is now correctly set up on your machine to enhance and optimize your throughput." }, { "code": null, "e": 7791, "s": 7374, "text": "For those new to git or not comfortable in the terminal, perhaps a desktop application would suit you best (e.g., SourceTree or GitHub Desktop App). These provide many features, tools, and visualizations in a GUI. Regardless, the terminal is a must in some situations. Plus, a better understanding of Git and version control would be acquired if one faced the learning curve that comes with using it from a terminal." }, { "code": null, "e": 7900, "s": 7791, "text": "In any case, whether an expert or beginner, your system should now be ready to use Git. I hope you enjoy it!" }, { "code": null, "e": 8126, "s": 7900, "text": "If something is missing or could be improved, please share below — whether a Git alias you could not live without, a neat feature, or an aspect that could be improved or is outdated. Of course, all questions are also welcome!" }, { "code": null, "e": 8254, "s": 8126, "text": "Thank you for reading my first blog — hope it was enjoyed, feel free to provide feedback on how future blogs could be improved." } ]
Cutting edge semantic search and sentence similarity | by Daulet Nurmanbetov | Towards Data Science
We commonly spend a lot of time looking for a specific piece of information in a large document. And we commonly find if using CTRL + F. The proverbial Google-fu, the art of effectively searching for information on google is a valuable skill in a 21st-century workplace. All of humanity’s knowledge is available to us, it is a matter of asking the right question, and knowing how to skim through results to find the relevant answer. Our brains perform a semantic search, where we review the results and find sentences that are similar to our search query. This is especially true in finance and legal professions as documents get lengthy and we have to resort to searching many keywords to find the right sentence or a passage. To this day, the cumulative human effort spent on discovery is staggering. Machine learning has been trying to solve this problem of semantic search since the dawn of NLP. A whole area of study -Semantic Search has emerged. And recently thanks to advancements in Deep Learning computers are able to accurately surface relevant information to us with minimal human involvement. Natural Language Processing (NLP) field has a term for this, when a word is mentioned we call it a “surface form” take for example the word “president” by itself this means the head of the country. But depending on context and time it could mean Trump or Obama. Advancements in NLP allow us to effectively map these surface forms and capture the context in those words into something called “embeddings” Embeddings are commonly a vector of numbers which have certain peculiar characteristics. Two words with similar meaning would have similar vectors allowing us to compute vector similarities. Extending this idea, in the vector space, we should be able to compute the similarity between any two sentences. And this is what sentence embedding models achieve. These models convert any given sentences into a vector to be able to quickly compute the similarity or dissimilarity of any pair of sentences. The idea is not new, The paper that started it all — word2vec proposed representing individual words with vectors back in 2013. However, we came a long way since then with BERT and other Transformer-based models which allow us to capture the context of those words much more effectively. Here how we stack up on recent embedding models compared to word2vec or GloVe of the past. These modified and fine-tuned BERT NLP models are quite good at identifying similar sentences, much better than older predecessors. Let's take a look at what this means in a practical sense. I have several article headlines from April 2020, And I wish to find the most similar sentences to a set of search terms. Here are my search terms — 1. The economy is more resilient and improving.2. The economy is in a lot of trouble.3. Trump is hurting his own reelection chances. And the article headlines I have are the following — Coronavirus:White House organizing program to slash development time for coronavirus vaccine by as much as eight months (Bloomberg)Trump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ)AstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg)Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill)Reopening:Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico)White House risks backlash with coronavirus optimism if cases flare up again (The Hill)Florida plans to start reopening on Monday with restaurants and retail in most areas allowed to resume business in most areas (Bloomberg)California Governor Newsom plans to order closure of all state beaches and parks starting Friday due to concerns about overcrowding (CNN)Japan preparing to extend coronavirus state of emergency, which is scheduled to end 6-May, by about another month (Reuters)Policy/Stimulus:Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico)Global economy:China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg)China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg)Japan's March factory output fell at the fastest pace in five months, while retail sales also dropped (Reuters)Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT)US-China:Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters)Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ)Oil:Trump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg)Munchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times)Norway, Europe's biggest oil producer, joins international efforts to cut supply for first time in almost two decades (Bloomberg)IEA says coronavirus could drive 6% decline in global energy demand in 2020 (FT)Corporate:Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ)Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg)Tesla posts third straight quarterly profit while Musk rants on call about need for lockdowns to be lifted (Bloomberg)eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ)Royal Dutch Shell cuts dividend for first time since World War II and also suspends next tranche of buyback program (Reuters)Chesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters)Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) After running the similarity of each query to each embedding, here are the top 5 similar sentences for each of my search terms: ======================Query: The economy is more resilient and improving.Top 5 most similar sentences in corpus:Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ) (Score: 0.5362)Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg) (Score: 0.4632)Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ) (Score: 0.3558)Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico) (Score: 0.3052)White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.2885)======================Query: The economy is in a lot of trouble.Top 5 most similar sentences in corpus:Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.4667)eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ) (Score: 0.4338)China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg) (Score: 0.4283)Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT) (Score: 0.4252)China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg) (Score: 0.4052)======================Query: Trump is hurting his own reelection chances.Top 5 most similar sentences in corpus:Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill) (Score: 0.7472)Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) (Score: 0.7408)Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters) (Score: 0.7111)Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.6213)White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.6181) You can see how uncannily accurate the model is able to pick out the most similar sentences. The code I used can be found below — !git clone [email protected]:huggingface/transformers.git !cd transformers !pip install . import scipy from sentence_transformers import SentenceTransformer model = SentenceTransformer('bert-base-nli-mean-tokens') # Get a sample corpus to search over _c=""" Coronavirus: White House organizing program to slash development time for coronavirus vaccine by as much as eight months (Bloomberg) Trump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ) AstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg) Reopening: Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) White House risks backlash with coronavirus optimism if cases flare up again (The Hill) Florida plans to start reopening on Monday with restaurants and retail in most areas allowed to resume business in most areas (Bloomberg) California Governor Newsom plans to order closure of all state beaches and parks starting Friday due to concerns about overcrowding (CNN) Japan preparing to extend coronavirus state of emergency, which is scheduled to end 6-May, by about another month (Reuters) Policy/Stimulus: Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico) Global economy: China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg) China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg) Japan's March factory output fell at the fastest pace in five months, while retail sales also dropped (Reuters) Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT) US-China: Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters) Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ) Oil: Trump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg) Munchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times) Norway, Europe's biggest oil producer, joins international efforts to cut supply for first time in almost two decades (Bloomberg) IEA says coronavirus could drive 6% decline in global energy demand in 2020 (FT) Corporate: Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ) Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg) Tesla posts third straight quarterly profit while Musk rants on call about need for lockdowns to be lifted (Bloomberg) eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ) Royal Dutch Shell cuts dividend for first time since World War II and also suspends next tranche of buyback program (Reuters) Chesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters) Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) Trump contradicts US intel, says Covid-19 started in Wuhan lab. """ # Convert the corpus into a list of headlines corpus=[i for i in _c.split('\n')if i != ''and len(i.split(' '))>=4] # Get a vector for each headline (sentence) in the corpus corpus_embeddings = model.encode(corpus) # Define search queries and embed them to vectors as well queries = [ 'The economy is more resilient and improving.', 'The economy is in a lot of trouble.', 'Trump is hurting his own reelection chances.'] query_embeddings = model.encode(queries) # For each search term return 5 closest sentences closest_n = 5 for query, query_embedding in zip(queries, query_embeddings): distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, "cosine")[0] results = zip(range(len(distances)), distances) results = sorted(results, key=lambda x: x[1]) print("\n\n======================\n\n") print("Query:", query) print("\nTop 5 most similar sentences in corpus:") for idx, distance in results[0:closest_n]: print(corpus[idx].strip(), "(Score: %.4f)" % (1-distance)) ====================== Query: The economy is more resilient and improving. Top 5 most similar sentences in corpus: Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ) (Score: 0.5362) Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg) (Score: 0.4632) Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ) (Score: 0.3558) Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico) (Score: 0.3052) White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.2885) ====================== Query: The economy is in a lot of trouble. Top 5 most similar sentences in corpus: Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.4667) eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ) (Score: 0.4338) China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg) (Score: 0.4283) Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT) (Score: 0.4252) China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg) (Score: 0.4052) ====================== Query: Trump is hurting his own reelection chances. Top 5 most similar sentences in corpus: Trump contradicts US intel, says Covid-19 started in Wuhan lab. (Score: 0.7472) Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) (Score: 0.7408) Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters) (Score: 0.7111) Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.6213) White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.6181) The example above is simple, but illustrates an important point of semantic search. It would take a human couple of minutes to find the most-similar sentences. It gives us the ability to find specific information in a text without human involvement, this means we can search phrases we care about in thousands of documents at computer speed. This technology is already being leveraged to find similar sentences between two documents. Or a key piece of information in a quarterly earnings report. With this semantic search, for example, we can easily find daily active users for all social companies like Twitter, Facebook, Snapchat, and others. Even though they define and call the metic differently — Daily Active Users (DAU) or Monthly Active Users (MAU) or Monetizable Active Users (mMAU). Semantic search powered by BERT can find that all these surface forms mean the same thing semantically — a measure of performance and it’s able to pluck the sentence of interest for us from the reports. It is not a far fetch idea that hedge funds are leveraging semantic search to parse through and surface metrics within Quarterly reports (10-Q/10-K) and have them available as a quantitative trade signal in an instant once they are published. The experiment above shows how effective semantic search has gotten in the last year. Another major way one can use these vector embeddings of sentences is for clustering. We can quickly cluster sentences in a single document or multiple documents into similar groups. Using the above code one can take advantage of a simple k-means from sklearn— from sklearn.cluster import KMeansimport numpy as npnum_clusters = 10clustering_model = KMeans(n_clusters=num_clusters)clustering_model.fit(corpus_embeddings)cluster_assignment = clustering_model.labels_for i in range(10): print() print(f'Cluster {i + 1} contains:') clust_sent = np.where(cluster_assignment == i) for k in clust_sent[0]: print(f'- {corpus[k]}') And again, results are spot-on for a machine. Here is a couple of clusters — Cluster 2 contains:- AstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg)- Trump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ)Cluster 3 contains:- Chesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters)- Trump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg)- Munchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times)Cluster 4 contains:- Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters)- Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ)- Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill) Interestingly, ElasticSeach now has a dense vector field and others in the industry operationalizing the ability to quickly compare two vectors such as Facebook’s faiss. This technology is cutting-edge but is quite operational and can be rolled out in a matter of weeks. Cutting edge AI is at the fingertips of anyone knowing what to look for. If you are interested to learn more feel free to reach out, I am always available for an e-coffee. Stay safe out there. Thanks to Nils Reimers’ informative post on huggingface discussion the led me to write this.
[ { "code": null, "e": 604, "s": 171, "text": "We commonly spend a lot of time looking for a specific piece of information in a large document. And we commonly find if using CTRL + F. The proverbial Google-fu, the art of effectively searching for information on google is a valuable skill in a 21st-century workplace. All of humanity’s knowledge is available to us, it is a matter of asking the right question, and knowing how to skim through results to find the relevant answer." }, { "code": null, "e": 974, "s": 604, "text": "Our brains perform a semantic search, where we review the results and find sentences that are similar to our search query. This is especially true in finance and legal professions as documents get lengthy and we have to resort to searching many keywords to find the right sentence or a passage. To this day, the cumulative human effort spent on discovery is staggering." }, { "code": null, "e": 1276, "s": 974, "text": "Machine learning has been trying to solve this problem of semantic search since the dawn of NLP. A whole area of study -Semantic Search has emerged. And recently thanks to advancements in Deep Learning computers are able to accurately surface relevant information to us with minimal human involvement." }, { "code": null, "e": 1538, "s": 1276, "text": "Natural Language Processing (NLP) field has a term for this, when a word is mentioned we call it a “surface form” take for example the word “president” by itself this means the head of the country. But depending on context and time it could mean Trump or Obama." }, { "code": null, "e": 1871, "s": 1538, "text": "Advancements in NLP allow us to effectively map these surface forms and capture the context in those words into something called “embeddings” Embeddings are commonly a vector of numbers which have certain peculiar characteristics. Two words with similar meaning would have similar vectors allowing us to compute vector similarities." }, { "code": null, "e": 2179, "s": 1871, "text": "Extending this idea, in the vector space, we should be able to compute the similarity between any two sentences. And this is what sentence embedding models achieve. These models convert any given sentences into a vector to be able to quickly compute the similarity or dissimilarity of any pair of sentences." }, { "code": null, "e": 2467, "s": 2179, "text": "The idea is not new, The paper that started it all — word2vec proposed representing individual words with vectors back in 2013. However, we came a long way since then with BERT and other Transformer-based models which allow us to capture the context of those words much more effectively." }, { "code": null, "e": 2558, "s": 2467, "text": "Here how we stack up on recent embedding models compared to word2vec or GloVe of the past." }, { "code": null, "e": 2749, "s": 2558, "text": "These modified and fine-tuned BERT NLP models are quite good at identifying similar sentences, much better than older predecessors. Let's take a look at what this means in a practical sense." }, { "code": null, "e": 2871, "s": 2749, "text": "I have several article headlines from April 2020, And I wish to find the most similar sentences to a set of search terms." }, { "code": null, "e": 2898, "s": 2871, "text": "Here are my search terms —" }, { "code": null, "e": 3031, "s": 2898, "text": "1. The economy is more resilient and improving.2. The economy is in a lot of trouble.3. Trump is hurting his own reelection chances." }, { "code": null, "e": 3084, "s": 3031, "text": "And the article headlines I have are the following —" }, { "code": null, "e": 6455, "s": 3084, "text": "Coronavirus:White House organizing program to slash development time for coronavirus vaccine by as much as eight months (Bloomberg)Trump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ)AstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg)Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill)Reopening:Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico)White House risks backlash with coronavirus optimism if cases flare up again (The Hill)Florida plans to start reopening on Monday with restaurants and retail in most areas allowed to resume business in most areas (Bloomberg)California Governor Newsom plans to order closure of all state beaches and parks starting Friday due to concerns about overcrowding (CNN)Japan preparing to extend coronavirus state of emergency, which is scheduled to end 6-May, by about another month (Reuters)Policy/Stimulus:Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico)Global economy:China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg)China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg)Japan's March factory output fell at the fastest pace in five months, while retail sales also dropped (Reuters)Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT)US-China:Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters)Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ)Oil:Trump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg)Munchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times)Norway, Europe's biggest oil producer, joins international efforts to cut supply for first time in almost two decades (Bloomberg)IEA says coronavirus could drive 6% decline in global energy demand in 2020 (FT)Corporate:Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ)Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg)Tesla posts third straight quarterly profit while Musk rants on call about need for lockdowns to be lifted (Bloomberg)eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ)Royal Dutch Shell cuts dividend for first time since World War II and also suspends next tranche of buyback program (Reuters)Chesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters)Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ)" }, { "code": null, "e": 6583, "s": 6455, "text": "After running the similarity of each query to each embedding, here are the top 5 similar sentences for each of my search terms:" }, { "code": null, "e": 9031, "s": 6583, "text": "======================Query: The economy is more resilient and improving.Top 5 most similar sentences in corpus:Microsoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ) (Score: 0.5362)Facebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg) (Score: 0.4632)Senior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ) (Score: 0.3558)Economists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico) (Score: 0.3052)White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.2885)======================Query: The economy is in a lot of trouble.Top 5 most similar sentences in corpus:Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.4667)eBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ) (Score: 0.4338)China's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg) (Score: 0.4283)Eurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT) (Score: 0.4252)China's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg) (Score: 0.4052)======================Query: Trump is hurting his own reelection chances.Top 5 most similar sentences in corpus:Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill) (Score: 0.7472)Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) (Score: 0.7408)Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters) (Score: 0.7111)Inconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.6213)White House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.6181)" }, { "code": null, "e": 9124, "s": 9031, "text": "You can see how uncannily accurate the model is able to pick out the most similar sentences." }, { "code": null, "e": 9161, "s": 9124, "text": "The code I used can be found below —" }, { "code": null, "e": 9249, "s": 9161, "text": "!git clone [email protected]:huggingface/transformers.git\n!cd transformers\n!pip install .\n" }, { "code": null, "e": 9374, "s": 9249, "text": "import scipy\nfrom sentence_transformers import SentenceTransformer\nmodel = SentenceTransformer('bert-base-nli-mean-tokens')\n" }, { "code": null, "e": 12816, "s": 9374, "text": "# Get a sample corpus to search over\n_c=\"\"\"\nCoronavirus:\nWhite House organizing program to slash development time for coronavirus vaccine by as much as eight months (Bloomberg)\nTrump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ)\nAstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg)\nReopening:\nInconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico)\nWhite House risks backlash with coronavirus optimism if cases flare up again (The Hill)\nFlorida plans to start reopening on Monday with restaurants and retail in most areas allowed to resume business in most areas (Bloomberg)\nCalifornia Governor Newsom plans to order closure of all state beaches and parks starting Friday due to concerns about overcrowding (CNN)\nJapan preparing to extend coronavirus state of emergency, which is scheduled to end 6-May, by about another month (Reuters)\nPolicy/Stimulus:\nEconomists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico)\nGlobal economy:\nChina's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg)\nChina's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg)\nJapan's March factory output fell at the fastest pace in five months, while retail sales also dropped (Reuters)\nEurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT)\nUS-China:\nTrump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters)\nSenior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ)\nOil:\nTrump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg)\nMunchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times)\nNorway, Europe's biggest oil producer, joins international efforts to cut supply for first time in almost two decades (Bloomberg)\nIEA says coronavirus could drive 6% decline in global energy demand in 2020 (FT)\nCorporate:\nMicrosoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ)\nFacebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg)\nTesla posts third straight quarterly profit while Musk rants on call about need for lockdowns to be lifted (Bloomberg)\neBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ)\nRoyal Dutch Shell cuts dividend for first time since World War II and also suspends next tranche of buyback program (Reuters)\nChesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters)\nAmazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ)\nTrump contradicts US intel, says Covid-19 started in Wuhan lab.\n\"\"\"\n" }, { "code": null, "e": 12932, "s": 12816, "text": "# Convert the corpus into a list of headlines\ncorpus=[i for i in _c.split('\\n')if i != ''and len(i.split(' '))>=4]\n" }, { "code": null, "e": 13032, "s": 12932, "text": "# Get a vector for each headline (sentence) in the corpus\ncorpus_embeddings = model.encode(corpus)\n" }, { "code": null, "e": 13283, "s": 13032, "text": "# Define search queries and embed them to vectors as well\nqueries = [\n 'The economy is more resilient and improving.', 'The economy is in a lot of trouble.', 'Trump is hurting his own reelection chances.']\nquery_embeddings = model.encode(queries)\n" }, { "code": null, "e": 13851, "s": 13283, "text": "# For each search term return 5 closest sentences\nclosest_n = 5\nfor query, query_embedding in zip(queries, query_embeddings):\n distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, \"cosine\")[0]\n\n results = zip(range(len(distances)), distances)\n results = sorted(results, key=lambda x: x[1])\n\n print(\"\\n\\n======================\\n\\n\")\n print(\"Query:\", query)\n print(\"\\nTop 5 most similar sentences in corpus:\")\n\n for idx, distance in results[0:closest_n]:\n print(corpus[idx].strip(), \"(Score: %.4f)\" % (1-distance))\n" }, { "code": null, "e": 16325, "s": 13851, "text": "======================\n\n\nQuery: The economy is more resilient and improving.\n\nTop 5 most similar sentences in corpus:\nMicrosoft reports strong results as shift to more activities online drives growth in areas from cloud-computing to video gams (WSJ) (Score: 0.5362)\nFacebook revenue beats expectations and while ad revenue fell sharply in March there have been recent signs of stability (Bloomberg) (Score: 0.4632)\nSenior White House official confident China will meet obligations under trad deal despite fallout from coronavirus pandemic (WSJ) (Score: 0.3558)\nEconomists from a broad range of ideological backgrounds encouraging Congress to keep spending to combat the coronavirus fallout and don't believe now is time to worry about deficit (Politico) (Score: 0.3052)\nWhite House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.2885)\n\n\n======================\n\n\nQuery: The economy is in a lot of trouble.\n\nTop 5 most similar sentences in corpus:\nInconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.4667)\neBay helped by online shopping surge though classifieds business hurt by closure of car dealerships and lower traffic (WSJ) (Score: 0.4338)\nChina's Beige Book shows employment situation in Chinese factories worsened in April from end of March, suggesting economy on less solid ground than government data (Bloomberg) (Score: 0.4283)\nEurozone economy contracts by 3.8% in Q1, the fastest decline on record (FT) (Score: 0.4252)\nChina's official PMIs mixed with beat from services and miss from manufacturing (Bloomberg) (Score: 0.4052)\n\n\n======================\n\n\nQuery: Trump is hurting his own reelection chances.\n\nTop 5 most similar sentences in corpus:\nTrump contradicts US intel, says Covid-19 started in Wuhan lab. (Score: 0.7472)\nAmazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ) (Score: 0.7408)\nTrump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters) (Score: 0.7111)\nInconsistent patchwork of state, local and business decision-making on reopening raising concerns about a second wave of the coronavirus (Politico) (Score: 0.6213)\nWhite House risks backlash with coronavirus optimism if cases flare up again (The Hill) (Score: 0.6181)\n" }, { "code": null, "e": 16667, "s": 16325, "text": "The example above is simple, but illustrates an important point of semantic search. It would take a human couple of minutes to find the most-similar sentences. It gives us the ability to find specific information in a text without human involvement, this means we can search phrases we care about in thousands of documents at computer speed." }, { "code": null, "e": 17321, "s": 16667, "text": "This technology is already being leveraged to find similar sentences between two documents. Or a key piece of information in a quarterly earnings report. With this semantic search, for example, we can easily find daily active users for all social companies like Twitter, Facebook, Snapchat, and others. Even though they define and call the metic differently — Daily Active Users (DAU) or Monthly Active Users (MAU) or Monetizable Active Users (mMAU). Semantic search powered by BERT can find that all these surface forms mean the same thing semantically — a measure of performance and it’s able to pluck the sentence of interest for us from the reports." }, { "code": null, "e": 17564, "s": 17321, "text": "It is not a far fetch idea that hedge funds are leveraging semantic search to parse through and surface metrics within Quarterly reports (10-Q/10-K) and have them available as a quantitative trade signal in an instant once they are published." }, { "code": null, "e": 17650, "s": 17564, "text": "The experiment above shows how effective semantic search has gotten in the last year." }, { "code": null, "e": 17833, "s": 17650, "text": "Another major way one can use these vector embeddings of sentences is for clustering. We can quickly cluster sentences in a single document or multiple documents into similar groups." }, { "code": null, "e": 17911, "s": 17833, "text": "Using the above code one can take advantage of a simple k-means from sklearn—" }, { "code": null, "e": 18292, "s": 17911, "text": "from sklearn.cluster import KMeansimport numpy as npnum_clusters = 10clustering_model = KMeans(n_clusters=num_clusters)clustering_model.fit(corpus_embeddings)cluster_assignment = clustering_model.labels_for i in range(10): print() print(f'Cluster {i + 1} contains:') clust_sent = np.where(cluster_assignment == i) for k in clust_sent[0]: print(f'- {corpus[k]}')" }, { "code": null, "e": 18369, "s": 18292, "text": "And again, results are spot-on for a machine. Here is a couple of clusters —" }, { "code": null, "e": 19374, "s": 18369, "text": "Cluster 2 contains:- AstraZeneca to make an experimental coronavirus vaccine developed by Oxford University (Bloomberg)- Trump says he is pushing FDA to approve emergency-use authorization for Gilead's remdesivir (WSJ)Cluster 3 contains:- Chesapeake Energy preparing bankruptcy filing and has held discussions with lenders about a ~$1B loan (Reuters)- Trump administration may announce plans as soon as today to offer loans to oil companies, possibly in exchange for a financial stake (Bloomberg)- Munchin says Trump administration could allow oil companies to store another several hundred million barrels (NY Times)Cluster 4 contains:- Trump says China wants to him to lose his bid for re-election and notes he is looking at different options in terms of consequences for Beijing over the virus (Reuters)- Amazon accused by Trump administration of tolerating counterfeit sales, but company says hit politically motivated (WSJ)- Trump contradicts US intel, says Covid-19 started in Wuhan lab. (The Hill)" }, { "code": null, "e": 19718, "s": 19374, "text": "Interestingly, ElasticSeach now has a dense vector field and others in the industry operationalizing the ability to quickly compare two vectors such as Facebook’s faiss. This technology is cutting-edge but is quite operational and can be rolled out in a matter of weeks. Cutting edge AI is at the fingertips of anyone knowing what to look for." }, { "code": null, "e": 19838, "s": 19718, "text": "If you are interested to learn more feel free to reach out, I am always available for an e-coffee. Stay safe out there." } ]
Django – Handling multiple forms in single view
We sometimes need to handle multiple forms in a single function or view. In this article, we will see how to write a function which will handle two forms at the same time and in same view. It is handy in many cases; we will handle more than two forms too. Create a Django project and an app, I named the project "multipleFormHandle" and the app as "formhandlingapp". Do some basic stuff like including app in settings.py INSTALLED_APPS and include app's url in project's url. Now create forms.py in app and a "templates" folder in the app directory. Add home.html in templates. Install the multi-form_view library − pip install multi_form_view Now in urls.py of app − from django.urls import path,include from . import views urlpatterns = [ path('',views.SchoolData.as_view(),name='home'), ] Here, we setup views and use our viewset as view. We are going to use viewset here. In models.py − from django.db import models # Create your models here. class StudentData(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100) class TeachertData(models.Model): name=models.CharField(max_length=100) ClassTeacherOF=models.CharField(max_length=100) Salary=models.CharField(max_length=100) We created two models because we are going to save forms data in models. In forms.py − from django import forms from .models import TeachertData,StudentData class StudentForm(forms.ModelForm): class Meta: model=StudentData fields="__all__" class TeacherForm(forms.ModelForm): class Meta: model=TeachertData fields="__all__" Here, we created model forms which we will render on the frontend from our view. In home.html − <!DOCTYPE html> <html> <head> <title>tut</title> </head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label><h3>Teacher</h3></label> //accessing form 1 from view {{ forms.teacher_form.as_p }} <label><h3>Student</h3></label> //accessing form 2 from view {{ forms.student_form.as_p }} <input type="submit" value="submit"/> </form> </body> </html> It is our frontend where we render two Django forms under a single form element and with a single submit button. I will not add style, because here we are learning the concept and the way to do that. In views.py − from django.shortcuts import render from .forms import StudentForm,TeacherForm from django.views.generic.list import ListView from django.urls import reverse from multi_form_view import MultiModelFormView # Create your views here. class SchoolData(MultiModelFormView): form_classes = { 'student_form' : StudentForm, 'teacher_form' : TeacherForm, } template_name = 'home.html' def get_success_url(self): return reverse('home') def forms_valid(self, forms): student = forms['student_form'].save(commit=False) teacher=forms['teacher_form'].save(commit=False) return super(SchoolData, self).forms_valid(forms) Here we created a viewset, we define two forms to render one is student form and the other is teacher form. We defined the HTML which we have to render. We define what to do when a form is submitted under get_success_url. In form_valid, we save the form data and verify if both the forms are right or not.
[ { "code": null, "e": 1318, "s": 1062, "text": "We sometimes need to handle multiple forms in a single function or view. In this article, we will see how to write a function which will handle two forms at the same time and in same view. It is handy in many cases; we will handle more than two forms too." }, { "code": null, "e": 1429, "s": 1318, "text": "Create a Django project and an app, I named the project \"multipleFormHandle\" and the app as \"formhandlingapp\"." }, { "code": null, "e": 1538, "s": 1429, "text": "Do some basic stuff like including app in settings.py INSTALLED_APPS and include app's url in project's url." }, { "code": null, "e": 1640, "s": 1538, "text": "Now create forms.py in app and a \"templates\" folder in the app directory. Add home.html in templates." }, { "code": null, "e": 1678, "s": 1640, "text": "Install the multi-form_view library −" }, { "code": null, "e": 1706, "s": 1678, "text": "pip install multi_form_view" }, { "code": null, "e": 1730, "s": 1706, "text": "Now in urls.py of app −" }, { "code": null, "e": 1857, "s": 1730, "text": "from django.urls import path,include\nfrom . import views\nurlpatterns = [\n path('',views.SchoolData.as_view(),name='home'),\n]" }, { "code": null, "e": 1941, "s": 1857, "text": "Here, we setup views and use our viewset as view. We are going to use viewset here." }, { "code": null, "e": 1956, "s": 1941, "text": "In models.py −" }, { "code": null, "e": 2347, "s": 1956, "text": "from django.db import models\n\n# Create your models here.\n\nclass StudentData(models.Model):\n name=models.CharField(max_length=100)\n standard=models.CharField(max_length=100)\n section=models.CharField(max_length=100)\n\nclass TeachertData(models.Model):\n name=models.CharField(max_length=100)\n ClassTeacherOF=models.CharField(max_length=100)\n Salary=models.CharField(max_length=100)" }, { "code": null, "e": 2420, "s": 2347, "text": "We created two models because we are going to save forms data in models." }, { "code": null, "e": 2434, "s": 2420, "text": "In forms.py −" }, { "code": null, "e": 2703, "s": 2434, "text": "from django import forms\nfrom .models import TeachertData,StudentData\n\nclass StudentForm(forms.ModelForm):\n class Meta:\n model=StudentData\n fields=\"__all__\"\n\nclass TeacherForm(forms.ModelForm):\n class Meta:\n model=TeachertData\n fields=\"__all__\"" }, { "code": null, "e": 2784, "s": 2703, "text": "Here, we created model forms which we will render on the frontend from our view." }, { "code": null, "e": 2799, "s": 2784, "text": "In home.html −" }, { "code": null, "e": 3278, "s": 2799, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>tut</title>\n </head>\n <body>\n <form method=\"post\" enctype=\"multipart/form-data\">\n {% csrf_token %}\n\n <label><h3>Teacher</h3></label>\n //accessing form 1 from view\n {{ forms.teacher_form.as_p }}\n <label><h3>Student</h3></label>\n //accessing form 2 from view\n {{ forms.student_form.as_p }}\n <input type=\"submit\" value=\"submit\"/>\n </form>\n </body>\n</html>" }, { "code": null, "e": 3391, "s": 3278, "text": "It is our frontend where we render two Django forms under a single form element and with a single submit button." }, { "code": null, "e": 3478, "s": 3391, "text": "I will not add style, because here we are learning the concept and the way to do that." }, { "code": null, "e": 3492, "s": 3478, "text": "In views.py −" }, { "code": null, "e": 4150, "s": 3492, "text": "from django.shortcuts import render\nfrom .forms import StudentForm,TeacherForm\nfrom django.views.generic.list import ListView\nfrom django.urls import reverse\n\nfrom multi_form_view import MultiModelFormView\n# Create your views here.\nclass SchoolData(MultiModelFormView):\n form_classes = {\n 'student_form' : StudentForm,\n 'teacher_form' : TeacherForm,\n }\n template_name = 'home.html'\n def get_success_url(self):\n return reverse('home')\n def forms_valid(self, forms):\n student = forms['student_form'].save(commit=False)\n teacher=forms['teacher_form'].save(commit=False)\n return super(SchoolData, self).forms_valid(forms)" }, { "code": null, "e": 4456, "s": 4150, "text": "Here we created a viewset, we define two forms to render one is student form and the other is teacher form. We defined the HTML which we have to render. We define what to do when a form is submitted under get_success_url. In form_valid, we save the form data and verify if both the forms are right or not." } ]
Check if a prime number can be expressed as sum of two Prime Numbers in Python
Suppose we have a prime number n. we have to check whether we can express n as x + y where x and y are also two prime numbers. So, if the input is like n = 19, then the output will be True as we can express it like 19 = 17 + 2 To solve this, we will follow these steps − Define a function isPrime() . This will take number if number <= 1, thenreturn False return False if number is same as 2, thenreturn True return True if number is even, thenreturn False return False for i in range 3 to integer part of ((square root of number) + 1), increase by 2, doif number is divisible by i, thenreturn False if number is divisible by i, thenreturn False return False return True From the main method do the following − if isPrime(number) and isPrime(number - 2) both are true, thenreturn True return True otherwise,return False return False Let us see the following implementation to get better understanding − Live Demo from math import sqrt def isPrime(number): if number <= 1: return False if number == 2: return True if number % 2 == 0: return False for i in range(3, int(sqrt(number))+1, 2): if number%i == 0: return False return True def solve(number): if isPrime(number) and isPrime(number - 2): return True else: return False n = 19 print(solve(n)) 19 True
[ { "code": null, "e": 1189, "s": 1062, "text": "Suppose we have a prime number n. we have to check whether we can express n as x + y where x and y are also two prime numbers." }, { "code": null, "e": 1289, "s": 1189, "text": "So, if the input is like n = 19, then the output will be True as we can express it like 19 = 17 + 2" }, { "code": null, "e": 1333, "s": 1289, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1385, "s": 1333, "text": "Define a function isPrime() . This will take number" }, { "code": null, "e": 1418, "s": 1385, "text": "if number <= 1, thenreturn False" }, { "code": null, "e": 1431, "s": 1418, "text": "return False" }, { "code": null, "e": 1471, "s": 1431, "text": "if number is same as 2, thenreturn True" }, { "code": null, "e": 1483, "s": 1471, "text": "return True" }, { "code": null, "e": 1519, "s": 1483, "text": "if number is even, thenreturn False" }, { "code": null, "e": 1532, "s": 1519, "text": "return False" }, { "code": null, "e": 1662, "s": 1532, "text": "for i in range 3 to integer part of ((square root of number) + 1), increase by 2, doif number is divisible by i, thenreturn False" }, { "code": null, "e": 1708, "s": 1662, "text": "if number is divisible by i, thenreturn False" }, { "code": null, "e": 1721, "s": 1708, "text": "return False" }, { "code": null, "e": 1733, "s": 1721, "text": "return True" }, { "code": null, "e": 1773, "s": 1733, "text": "From the main method do the following −" }, { "code": null, "e": 1847, "s": 1773, "text": "if isPrime(number) and isPrime(number - 2) both are true, thenreturn True" }, { "code": null, "e": 1859, "s": 1847, "text": "return True" }, { "code": null, "e": 1882, "s": 1859, "text": "otherwise,return False" }, { "code": null, "e": 1895, "s": 1882, "text": "return False" }, { "code": null, "e": 1965, "s": 1895, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1976, "s": 1965, "text": " Live Demo" }, { "code": null, "e": 2378, "s": 1976, "text": "from math import sqrt\ndef isPrime(number):\n if number <= 1:\n return False\n if number == 2:\n return True\n if number % 2 == 0:\n return False\n for i in range(3, int(sqrt(number))+1, 2):\n if number%i == 0:\n return False\n return True\ndef solve(number):\n if isPrime(number) and isPrime(number - 2):\n return True\n else:\n return False\nn = 19\nprint(solve(n))" }, { "code": null, "e": 2381, "s": 2378, "text": "19" }, { "code": null, "e": 2386, "s": 2381, "text": "True" } ]
Grant MySQL table and column permissions using Python - GeeksforGeeks
20 May, 2021 MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such as PyMySQL, mysql.connector, etc. In this article, we are going to grant permissions to a user in accessing a database and its MySQL tables. The CREATE USER statement creates a user account with no privileges. The statement for creating a user in MySQL is given below. CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'password'; The above user can log in into MySQL Server, but cannot do anything such as querying data and selecting a database from tables. In our case, user_name is geeksforgeeks and password for login is 1234. To change the user in MySQL client, use the below command: SYSTEM MYSQL -u geeksforgeeks -p1234; To check the current user, one can use the below command: SELECT user(); The above statement could be used to know the permissions of the user. SHOW GRANTS FOR user_name@localhost; See the below example: Default Privileges Note: To grant permissions to the user geeksforgeesks you must be logged into root account. Users can’t grant permissions to themselves. Below is the python program to add table and column permissions to the user geeksforgeeks: Python3 # import required moduleimport pymysql # establish connection to MySQLconnection = pymysql.connect( # specify host host='localhost', # specify root account user='root', # specify password for root account password='1234', # default port number is 3306 fro MySQL port=3306) # make a cursor to run sql queriesmycursor = connection.cursor() # granting all permissions on all databases and their# tables of geeksforgeeks user permission also includes# table and column grantsmycursor.execute("Grant all on *.* to geeksforgeeks@localhost") # print all privileges of geeksforgeeks usermycursor.execute("Show grants for geeksforgeeks@localhost")result = mycursor.fetchall()print(result) # commit privilegesmycursor.execute("Flush Privileges") # close connection to MySQLconnection.close() Output Python Output MySQL Terminal MySQL output We could see that permissions to CREATE and ALTER MySQL tables have been provided to user geeksforgeeks. akshaysingh98088 Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 May, 2021" }, { "code": null, "e": 24676, "s": 24292, "text": "MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such as PyMySQL, mysql.connector, etc. " }, { "code": null, "e": 24911, "s": 24676, "text": "In this article, we are going to grant permissions to a user in accessing a database and its MySQL tables. The CREATE USER statement creates a user account with no privileges. The statement for creating a user in MySQL is given below." }, { "code": null, "e": 24973, "s": 24911, "text": "CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'password';" }, { "code": null, "e": 25175, "s": 24973, "text": "The above user can log in into MySQL Server, but cannot do anything such as querying data and selecting a database from tables. In our case, user_name is geeksforgeeks and password for login is 1234. " }, { "code": null, "e": 25234, "s": 25175, "text": "To change the user in MySQL client, use the below command:" }, { "code": null, "e": 25272, "s": 25234, "text": "SYSTEM MYSQL -u geeksforgeeks -p1234;" }, { "code": null, "e": 25330, "s": 25272, "text": "To check the current user, one can use the below command:" }, { "code": null, "e": 25345, "s": 25330, "text": "SELECT user();" }, { "code": null, "e": 25417, "s": 25345, "text": "The above statement could be used to know the permissions of the user. " }, { "code": null, "e": 25454, "s": 25417, "text": "SHOW GRANTS FOR user_name@localhost;" }, { "code": null, "e": 25477, "s": 25454, "text": "See the below example:" }, { "code": null, "e": 25496, "s": 25477, "text": "Default Privileges" }, { "code": null, "e": 25634, "s": 25496, "text": "Note: To grant permissions to the user geeksforgeesks you must be logged into root account. Users can’t grant permissions to themselves. " }, { "code": null, "e": 25725, "s": 25634, "text": "Below is the python program to add table and column permissions to the user geeksforgeeks:" }, { "code": null, "e": 25733, "s": 25725, "text": "Python3" }, { "code": "# import required moduleimport pymysql # establish connection to MySQLconnection = pymysql.connect( # specify host host='localhost', # specify root account user='root', # specify password for root account password='1234', # default port number is 3306 fro MySQL port=3306) # make a cursor to run sql queriesmycursor = connection.cursor() # granting all permissions on all databases and their# tables of geeksforgeeks user permission also includes# table and column grantsmycursor.execute(\"Grant all on *.* to geeksforgeeks@localhost\") # print all privileges of geeksforgeeks usermycursor.execute(\"Show grants for geeksforgeeks@localhost\")result = mycursor.fetchall()print(result) # commit privilegesmycursor.execute(\"Flush Privileges\") # close connection to MySQLconnection.close()", "e": 26557, "s": 25733, "text": null }, { "code": null, "e": 26564, "s": 26557, "text": "Output" }, { "code": null, "e": 26578, "s": 26564, "text": "Python Output" }, { "code": null, "e": 26593, "s": 26578, "text": "MySQL Terminal" }, { "code": null, "e": 26606, "s": 26593, "text": "MySQL output" }, { "code": null, "e": 26711, "s": 26606, "text": "We could see that permissions to CREATE and ALTER MySQL tables have been provided to user geeksforgeeks." }, { "code": null, "e": 26728, "s": 26711, "text": "akshaysingh98088" }, { "code": null, "e": 26741, "s": 26728, "text": "Python-mySQL" }, { "code": null, "e": 26748, "s": 26741, "text": "Python" }, { "code": null, "e": 26846, "s": 26748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26855, "s": 26846, "text": "Comments" }, { "code": null, "e": 26868, "s": 26855, "text": "Old Comments" }, { "code": null, "e": 26900, "s": 26868, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26956, "s": 26900, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27011, "s": 26956, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27053, "s": 27011, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27095, "s": 27053, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27126, "s": 27095, "text": "Python | os.path.join() method" }, { "code": null, "e": 27165, "s": 27126, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27187, "s": 27165, "text": "Defaultdict in Python" }, { "code": null, "e": 27216, "s": 27187, "text": "Create a directory in Python" } ]
Program for power of a complex number in O(log n) in C++
Given a complex number in the form of x+yi and an integer n; the task is calculate and print the value of the complex number if we power the complex number by n. What is a complex number? A complex number is number which can be written in the form of a + bi, where a and b are the real numbers and i is the solution of the equation or we can say an imaginary number. So, simply putting it we can say that complex number is a combination of Real number and imaginary number. Raising power of a complex number To raise the power of a complex number we use the below formula − (a+bi) (c+di)=( ac−bd )+(ad+bc )i Like we have a complex number 2+3i and raising its power by 5 then we will get − (2+3 i)5=(2+3 i)(2+3i)(2+3 i)(2+3 i)(2+3i) Using the above formula we will get answer − Input: x[0] = 10, x[1] = 11 /*Where x[0] is the first real number and 11 is the second real number*/ n = 4 Output: -47959 + i(9240) Input: x[0] = 2, x[1] =3 n = 5 Output: 122 + i(597) Approach we are using to solve the above problem − So, the problem can be solved using iterative method easily but the complexity will be O(n), but we have to solve the problem in O(log n) time. For that we can − First take the input in form of an array. In function Power the x^nCheck if n is 1, then return xRecursively call power pass x and n/2 and store its result in a variable sq.Check if dividing n by 2 leaves a remainder 0; if so then return the results obtained from cmul(sq, sq)Check if dividing n by 2 does not leaves a remainder 0; if so then return the results obtained from cmul(x, cmul(sq, sq)). Check if n is 1, then return x Recursively call power pass x and n/2 and store its result in a variable sq. Check if dividing n by 2 leaves a remainder 0; if so then return the results obtained from cmul(sq, sq) Check if dividing n by 2 does not leaves a remainder 0; if so then return the results obtained from cmul(x, cmul(sq, sq)). In function cmul().Check if x1 = a+bi and x2 = x+di, then x1 * x2 = (a*c–b*d)+(b*c+d*a)i. Check if x1 = a+bi and x2 = x+di, then x1 * x2 = (a*c–b*d)+(b*c+d*a)i. Return and printthe results obtained. Start Step 1-> declare function to calculate the product of two complex numbers long long* complex(long long* part1, long long* part2) Declare long long* ans = new long long[2] Set ans[0] = (part1[0] * part2[0]) - (part1[1] * part2[1]) Se ans[1] = (part1[1] * part2[0]) + part1[0] * part2[1] return ans Step 2-> declare function to return the complex number raised to the power n long long* power(long long* x, long long n) Declare long long* temp = new long long[2] IF n = 0 Set temp[0] = 0 Set temp[1] = 0 return temp End IF n = 1 return x End Declare long long* part = power(x, n / 2) IF n % 2 = 0 return complex(part, part) End return complex(x, complex(part, part)) Step 3 -> In main() Declare int n Declare and set long long* x = new long long[2] Set x[0] = 10 Set x[1] = -11 Set n = 4 Call long long* a = power(x, n) Stop Live Demo #include <bits/stdc++.h> using namespace std; //calculate product of two complex numbers long long* complex(long long* part1, long long* part2) { long long* ans = new long long[2]; ans[0] = (part1[0] * part2[0]) - (part1[1] * part2[1]); ans[1] = (part1[1] * part2[0]) + part1[0] * part2[1]; return ans; } // Function to return the complex number raised to the power n long long* power(long long* x, long long n) { long long* temp = new long long[2]; if (n == 0) { temp[0] = 0; temp[1] = 0; return temp; } if (n == 1) return x; long long* part = power(x, n / 2); if (n % 2 == 0) return complex(part, part); return complex(x, complex(part, part)); } int main() { int n; long long* x = new long long[2]; x[0] = 10; x[1] = -11; n = 4; long long* a = power(x, n); cout << a[0] << " + i ( " << a[1] << " )" << endl; return 0; } power of complex number in O(Log n) : -47959 + i ( 9240 )
[ { "code": null, "e": 1224, "s": 1062, "text": "Given a complex number in the form of x+yi and an integer n; the task is calculate and print the value of the complex number if we power the complex number by n." }, { "code": null, "e": 1250, "s": 1224, "text": "What is a complex number?" }, { "code": null, "e": 1536, "s": 1250, "text": "A complex number is number which can be written in the form of a + bi, where a and b are the real numbers and i is the solution of the equation or we can say an imaginary number. So, simply putting it we can say that complex number is a combination of Real number and imaginary number." }, { "code": null, "e": 1570, "s": 1536, "text": "Raising power of a complex number" }, { "code": null, "e": 1636, "s": 1570, "text": "To raise the power of a complex number we use the below formula −" }, { "code": null, "e": 1670, "s": 1636, "text": "(a+bi) (c+di)=( ac−bd )+(ad+bc )i" }, { "code": null, "e": 1700, "s": 1670, "text": "Like we have a complex number" }, { "code": null, "e": 1751, "s": 1700, "text": "2+3i and raising its power by 5 then we will get −" }, { "code": null, "e": 1794, "s": 1751, "text": "(2+3 i)5=(2+3 i)(2+3i)(2+3 i)(2+3 i)(2+3i)" }, { "code": null, "e": 1839, "s": 1794, "text": "Using the above formula we will get answer −" }, { "code": null, "e": 2023, "s": 1839, "text": "Input: x[0] = 10, x[1] = 11 /*Where x[0] is the first real number and 11 is the\nsecond real number*/\nn = 4\nOutput: -47959 + i(9240)\nInput: x[0] = 2, x[1] =3\nn = 5\nOutput: 122 + i(597)" }, { "code": null, "e": 2074, "s": 2023, "text": "Approach we are using to solve the above problem −" }, { "code": null, "e": 2236, "s": 2074, "text": "So, the problem can be solved using iterative method easily but the complexity will be O(n), but we have to solve the problem in O(log n) time. For that we can −" }, { "code": null, "e": 2278, "s": 2236, "text": "First take the input in form of an array." }, { "code": null, "e": 2635, "s": 2278, "text": "In function Power the x^nCheck if n is 1, then return xRecursively call power pass x and n/2 and store its result in a variable sq.Check if dividing n by 2 leaves a remainder 0; if so then return the results obtained from cmul(sq, sq)Check if dividing n by 2 does not leaves a remainder 0; if so then return the results obtained from cmul(x, cmul(sq, sq))." }, { "code": null, "e": 2666, "s": 2635, "text": "Check if n is 1, then return x" }, { "code": null, "e": 2743, "s": 2666, "text": "Recursively call power pass x and n/2 and store its result in a variable sq." }, { "code": null, "e": 2847, "s": 2743, "text": "Check if dividing n by 2 leaves a remainder 0; if so then return the results obtained from cmul(sq, sq)" }, { "code": null, "e": 2970, "s": 2847, "text": "Check if dividing n by 2 does not leaves a remainder 0; if so then return the results obtained from cmul(x, cmul(sq, sq))." }, { "code": null, "e": 3060, "s": 2970, "text": "In function cmul().Check if x1 = a+bi and x2 = x+di, then x1 * x2 = (a*c–b*d)+(b*c+d*a)i." }, { "code": null, "e": 3131, "s": 3060, "text": "Check if x1 = a+bi and x2 = x+di, then x1 * x2 = (a*c–b*d)+(b*c+d*a)i." }, { "code": null, "e": 3169, "s": 3131, "text": "Return and printthe results obtained." }, { "code": null, "e": 4091, "s": 3169, "text": "Start\nStep 1-> declare function to calculate the product of two complex numbers\n long long* complex(long long* part1, long long* part2)\n Declare long long* ans = new long long[2]\n Set ans[0] = (part1[0] * part2[0]) - (part1[1] * part2[1])\n Se ans[1] = (part1[1] * part2[0]) + part1[0] * part2[1]\n return ans\nStep 2-> declare function to return the complex number raised to the power n\n long long* power(long long* x, long long n)\n Declare long long* temp = new long long[2]\n IF n = 0\n Set temp[0] = 0\n Set temp[1] = 0\n return temp\n End\n IF n = 1\n return x\n End\n Declare long long* part = power(x, n / 2)\n IF n % 2 = 0\n return complex(part, part)\n End\n return complex(x, complex(part, part))\nStep 3 -> In main()\n Declare int n\n Declare and set long long* x = new long long[2]\n Set x[0] = 10\n Set x[1] = -11\n Set n = 4\n Call long long* a = power(x, n)\nStop" }, { "code": null, "e": 4102, "s": 4091, "text": " Live Demo" }, { "code": null, "e": 5026, "s": 4102, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//calculate product of two complex numbers\nlong long* complex(long long* part1, long long* part2) {\n long long* ans = new long long[2];\n ans[0] = (part1[0] * part2[0]) - (part1[1] * part2[1]);\n ans[1] = (part1[1] * part2[0]) + part1[0] * part2[1];\n return ans;\n}\n// Function to return the complex number raised to the power n\nlong long* power(long long* x, long long n) {\n long long* temp = new long long[2];\n if (n == 0) {\n temp[0] = 0;\n temp[1] = 0;\n return temp;\n }\n if (n == 1)\n return x;\n long long* part = power(x, n / 2);\n if (n % 2 == 0)\n return complex(part, part);\n return complex(x, complex(part, part));\n}\nint main() {\n int n;\n long long* x = new long long[2];\n x[0] = 10;\n x[1] = -11;\n n = 4;\n long long* a = power(x, n);\n cout << a[0] << \" + i ( \" << a[1] << \" )\" << endl;\n return 0;\n}" }, { "code": null, "e": 5084, "s": 5026, "text": "power of complex number in O(Log n) : -47959 + i ( 9240 )" } ]
Interchanging first and second halves of strings - GeeksforGeeks
06 Aug, 2021 Given two strings and . Create two new strings by exchanging the first half and second half of one of the strings with the first half and second half of the other string respectively. Examples: Input : fighter warrior Output :warhter figrior Input :remuneration day Output :dration remuneay In the first example, fighter is made up of two parts fig and hter. Similarly, warrior is also made up of two parts war and rior. Interchange the first part of both the strings to create two new strings warhter and figrior. Similarly, in the second example first part of remuneration which is remune is exchanged with the first part of day to create dration and remuneay. C++ Java Python3 C# PHP Javascript // CPP code to create two new strings// by swapping first and second halves#include<bits/stdc++.h>using namespace std; // Function to concatenate two// different halves of given stringsvoid swapTwoHalves(string a , string b){ int la = a.length(); int lb = b.length(); // Creating new strings by // exchanging the first half // of a and b. Please refer below for // details of substr. // https://www.geeksforgeeks.org/stdsubstr-in-ccpp/ string c = a.substr(0, la/2) + b.substr(lb/2, lb); string d = b.substr(0, lb/2) + a.substr(la/2, la); cout << c << endl << d << endl;} // Driver functionint main(){ string a = "remuneration"; string b = "day"; swapTwoHalves(a, b); return 0;} // Java code to create two new strings// by swapping first and second halvesimport java.io.*;class ns{ // Function to concatenate two // different halves of given strings public static void swapTwoHalves(String a, String b) { int la = a.length(); int lb = b.length(); // Creating new strings by // exchanging the first half // of a and b. Please refer below // for details of substring. // https://www.geeksforgeeks.org/java-lang-string-substring-java/ String c = a.substring(0,la/2) + b.substring(lb/2,lb); String d = b.substring(0,lb/2) + a.substring(la/2,la); System.out.println(c + "\n" + d); } public static void main (String args[]) { // Given strings String a = "remuneration"; String b = "day"; // Calling function swapTwoHalves(a, b); }} # Python 3 code to create two new strings# by swapping first and second halves # Function to concatenate two# different halves of given stringsdef swapTwoHalves( a ,b) : la = len(a) lb = len(b) # Creating new strings by # exchanging the first half # of a and b. Please refer below for # details of substr. # https://www.geeksforgeeks.org/stdsubstr-in-ccpp/ c = a[0:la//2] + b[lb//2: lb] d = b[0: lb//2] + a[la//2: la] print( c, "\n" , d ) # Driver functiona = "remuneration"b = "day"swapTwoHalves(a, b) # This code is contributed by Nikita Tiwari // C# code to create two// new strings by swapping// first and second halvesusing System; class GFG{ // Function to concatenate // two different halves // of given strings static void swapTwoHalves(string a , string b) { int la = a.Length; int lb = b.Length; // Creating new strings // by exchanging the // first half of a and b. string c = a.Substring(0, la / 2) + b.Substring(lb / 2, lb / 2 + 1); string d = b.Substring(0, lb / 2) + a.Substring(la / 2, la / 2); Console.Write (c + "\n" + d + "\n"); } // Driver Code static void Main() { string a = "remuneration"; string b = "day"; swapTwoHalves(a, b); }} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP code to create two// new strings by swapping// first and second halves // Function to concatenate // two different halves of// given stringsfunction swapTwoHalves($a , $b){ $la = strlen($a); $lb = strlen($b); // Creating new strings // by exchanging the first // half of a and b. $c = substr($a, 0, intval($la / 2)) . substr($b, intval($lb / 2), $lb); $d = substr($b, 0, intval($lb / 2)) . substr($a, intval($la / 2), $la); echo ($c . "\n" . $d . "\n");} // Driver Code$a = "remuneration";$b = "day"; swapTwoHalves($a, $b); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript code to create two new strings// by swapping first and second halves// Function to concatenate two// different halves of given stringsfunction swapTwoHalves(a, b) { var la = a.length; var lb = b.length; // Creating new strings by // exchanging the first half // of a and b. Please refer below // for details of substring. // https://www.geeksforgeeks.org/java-lang-string-substring-java/ var c = a.substring(0,la/2) + b.substring(lb/2,lb); var d = b.substring(0,lb/2) + a.substring(la/2,la); document.write(c +"<br>" + "\n" + d); } // Given strings var a = "remuneration"; var b = "day"; // Calling function swapTwoHalves(a, b); // This code is contributed by shivanisinghss2110</script> Output: remuneay dration YouTubeGeeksforGeeks502K subscribersInterchanging first and second halves of stings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Qo0zMKGEr18" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> manishshaw1 kk9826225 shivanisinghss2110 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters
[ { "code": null, "e": 24634, "s": 24606, "text": "\n06 Aug, 2021" }, { "code": null, "e": 24818, "s": 24634, "text": "Given two strings and . Create two new strings by exchanging the first half and second half of one of the strings with the first half and second half of the other string respectively." }, { "code": null, "e": 24829, "s": 24818, "text": "Examples: " }, { "code": null, "e": 24958, "s": 24829, "text": "Input : fighter\n warrior\nOutput :warhter\n figrior\n\nInput :remuneration\n day\nOutput :dration\n remuneay" }, { "code": null, "e": 25330, "s": 24958, "text": "In the first example, fighter is made up of two parts fig and hter. Similarly, warrior is also made up of two parts war and rior. Interchange the first part of both the strings to create two new strings warhter and figrior. Similarly, in the second example first part of remuneration which is remune is exchanged with the first part of day to create dration and remuneay." }, { "code": null, "e": 25334, "s": 25330, "text": "C++" }, { "code": null, "e": 25339, "s": 25334, "text": "Java" }, { "code": null, "e": 25347, "s": 25339, "text": "Python3" }, { "code": null, "e": 25350, "s": 25347, "text": "C#" }, { "code": null, "e": 25354, "s": 25350, "text": "PHP" }, { "code": null, "e": 25365, "s": 25354, "text": "Javascript" }, { "code": "// CPP code to create two new strings// by swapping first and second halves#include<bits/stdc++.h>using namespace std; // Function to concatenate two// different halves of given stringsvoid swapTwoHalves(string a , string b){ int la = a.length(); int lb = b.length(); // Creating new strings by // exchanging the first half // of a and b. Please refer below for // details of substr. // https://www.geeksforgeeks.org/stdsubstr-in-ccpp/ string c = a.substr(0, la/2) + b.substr(lb/2, lb); string d = b.substr(0, lb/2) + a.substr(la/2, la); cout << c << endl << d << endl;} // Driver functionint main(){ string a = \"remuneration\"; string b = \"day\"; swapTwoHalves(a, b); return 0;}", "e": 26130, "s": 25365, "text": null }, { "code": "// Java code to create two new strings// by swapping first and second halvesimport java.io.*;class ns{ // Function to concatenate two // different halves of given strings public static void swapTwoHalves(String a, String b) { int la = a.length(); int lb = b.length(); // Creating new strings by // exchanging the first half // of a and b. Please refer below // for details of substring. // https://www.geeksforgeeks.org/java-lang-string-substring-java/ String c = a.substring(0,la/2) + b.substring(lb/2,lb); String d = b.substring(0,lb/2) + a.substring(la/2,la); System.out.println(c + \"\\n\" + d); } public static void main (String args[]) { // Given strings String a = \"remuneration\"; String b = \"day\"; // Calling function swapTwoHalves(a, b); }}", "e": 27112, "s": 26130, "text": null }, { "code": "# Python 3 code to create two new strings# by swapping first and second halves # Function to concatenate two# different halves of given stringsdef swapTwoHalves( a ,b) : la = len(a) lb = len(b) # Creating new strings by # exchanging the first half # of a and b. Please refer below for # details of substr. # https://www.geeksforgeeks.org/stdsubstr-in-ccpp/ c = a[0:la//2] + b[lb//2: lb] d = b[0: lb//2] + a[la//2: la] print( c, \"\\n\" , d ) # Driver functiona = \"remuneration\"b = \"day\"swapTwoHalves(a, b) # This code is contributed by Nikita Tiwari", "e": 27708, "s": 27112, "text": null }, { "code": "// C# code to create two// new strings by swapping// first and second halvesusing System; class GFG{ // Function to concatenate // two different halves // of given strings static void swapTwoHalves(string a , string b) { int la = a.Length; int lb = b.Length; // Creating new strings // by exchanging the // first half of a and b. string c = a.Substring(0, la / 2) + b.Substring(lb / 2, lb / 2 + 1); string d = b.Substring(0, lb / 2) + a.Substring(la / 2, la / 2); Console.Write (c + \"\\n\" + d + \"\\n\"); } // Driver Code static void Main() { string a = \"remuneration\"; string b = \"day\"; swapTwoHalves(a, b); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 28659, "s": 27708, "text": null }, { "code": "<?php// PHP code to create two// new strings by swapping// first and second halves // Function to concatenate // two different halves of// given stringsfunction swapTwoHalves($a , $b){ $la = strlen($a); $lb = strlen($b); // Creating new strings // by exchanging the first // half of a and b. $c = substr($a, 0, intval($la / 2)) . substr($b, intval($lb / 2), $lb); $d = substr($b, 0, intval($lb / 2)) . substr($a, intval($la / 2), $la); echo ($c . \"\\n\" . $d . \"\\n\");} // Driver Code$a = \"remuneration\";$b = \"day\"; swapTwoHalves($a, $b); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 29318, "s": 28659, "text": null }, { "code": "<script> // JavaScript code to create two new strings// by swapping first and second halves// Function to concatenate two// different halves of given stringsfunction swapTwoHalves(a, b) { var la = a.length; var lb = b.length; // Creating new strings by // exchanging the first half // of a and b. Please refer below // for details of substring. // https://www.geeksforgeeks.org/java-lang-string-substring-java/ var c = a.substring(0,la/2) + b.substring(lb/2,lb); var d = b.substring(0,lb/2) + a.substring(la/2,la); document.write(c +\"<br>\" + \"\\n\" + d); } // Given strings var a = \"remuneration\"; var b = \"day\"; // Calling function swapTwoHalves(a, b); // This code is contributed by shivanisinghss2110</script>", "e": 30218, "s": 29318, "text": null }, { "code": null, "e": 30227, "s": 30218, "text": "Output: " }, { "code": null, "e": 30245, "s": 30227, "text": "remuneay\ndration " }, { "code": null, "e": 31091, "s": 30245, "text": "YouTubeGeeksforGeeks502K subscribersInterchanging first and second halves of stings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Qo0zMKGEr18\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 31105, "s": 31093, "text": "manishshaw1" }, { "code": null, "e": 31115, "s": 31105, "text": "kk9826225" }, { "code": null, "e": 31134, "s": 31115, "text": "shivanisinghss2110" }, { "code": null, "e": 31142, "s": 31134, "text": "Strings" }, { "code": null, "e": 31150, "s": 31142, "text": "Strings" }, { "code": null, "e": 31248, "s": 31150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31323, "s": 31248, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 31380, "s": 31323, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31416, "s": 31380, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 31452, "s": 31416, "text": "Convert string to char array in C++" }, { "code": null, "e": 31490, "s": 31452, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 31543, "s": 31490, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31573, "s": 31543, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 31625, "s": 31573, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 31670, "s": 31625, "text": "Top 50 String Coding Problems for Interviews" } ]
Bulma | Box - GeeksforGeeks
18 Jun, 2020 Bulma is a free, and open source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The box element is simply a container with a shadow, a border, a radius, and some padding. We can use this in many places in our project design. It gives an interactive look to our project. Example 1: This example creating a box container using Bulma. <!DOCTYPE html><html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class='box'> <h1 class='title' style='color:green'> Geek for Geeks </h1> <p class='is-family-monospace'> 'GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> <div class='buttons'> <button class='button is-fullwidth'> Know more about GfG </button> </div> </div> </div> </div> </div></body> </html> Output: Example 2: This example creating an input box using Bulma. <!DOCTYPE html><html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 12px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="box"> <div> <h1 class='title has-text-centered'> Login </h1> </div> <form action='#' method='post'> <div class='field'> <label class='label' id='username'>Username</label> <div class='control has-icons-left'> <input class='input' type='text' for='username' placeholder='Username'> <span class="icon is-small is-left"> <i class="fas fa-user"></i> </span> </div> </div> <div class='field'> <label class='label' id='password'> Password </label> <div class='control has-icons-left'> <input class='input' type='password' for='password' placeholder='Password'> <span class="icon is-small is-left"> <i class="fas fa-lock"></i> </span> </div> <div class='buttons'> <button class='button is-link'> Login </button> </div> </div> </form> </div> </div> </div> </div></body> </html> Output: Example 3: This example creating a message box using Bulma. <html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="box"> <article class="media"> <div class="media-left"> <figure class="image is-64x64"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png"> </figure> </div> <div class="media-content"> <div class="content"> <p> <strong>GeeksforGeeks</strong> <small>@geeks</small> <br> Welcome to GeeksforGeeks </br> 'GeeksforGeeks' is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> <nav class="level is-mobile"> <div class="level-left"> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-reply"></i> </span> </a> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-retweet"></i> </span> </a> <a class="level-item"> <span class="icon is-small"> <i class="fas fa-heart"></i> </span> </a> </div> </nav> </div> </article> </div> </div> </div> </div></body> </html> Output: Note: Here in all the above examples, we use some extra Bulma classes like container, column, title, button, media, image, input, label, etc to design our content well. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bulma CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 26108, "s": 26080, "text": "\n18 Jun, 2020" }, { "code": null, "e": 26493, "s": 26108, "text": "Bulma is a free, and open source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.The box element is simply a container with a shadow, a border, a radius, and some padding. We can use this in many places in our project design. It gives an interactive look to our project." }, { "code": null, "e": 26555, "s": 26493, "text": "Example 1: This example creating a box container using Bulma." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class='box'> <h1 class='title' style='color:green'> Geek for Geeks </h1> <p class='is-family-monospace'> 'GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> <div class='buttons'> <button class='button is-fullwidth'> Know more about GfG </button> </div> </div> </div> </div> </div></body> </html>", "e": 28178, "s": 26555, "text": null }, { "code": null, "e": 28186, "s": 28178, "text": "Output:" }, { "code": null, "e": 28245, "s": 28186, "text": "Example 2: This example creating an input box using Bulma." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 12px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"box\"> <div> <h1 class='title has-text-centered'> Login </h1> </div> <form action='#' method='post'> <div class='field'> <label class='label' id='username'>Username</label> <div class='control has-icons-left'> <input class='input' type='text' for='username' placeholder='Username'> <span class=\"icon is-small is-left\"> <i class=\"fas fa-user\"></i> </span> </div> </div> <div class='field'> <label class='label' id='password'> Password </label> <div class='control has-icons-left'> <input class='input' type='password' for='password' placeholder='Password'> <span class=\"icon is-small is-left\"> <i class=\"fas fa-lock\"></i> </span> </div> <div class='buttons'> <button class='button is-link'> Login </button> </div> </div> </form> </div> </div> </div> </div></body> </html>", "e": 30751, "s": 28245, "text": null }, { "code": null, "e": 30759, "s": 30751, "text": "Output:" }, { "code": null, "e": 30819, "s": 30759, "text": "Example 3: This example creating a message box using Bulma." }, { "code": "<html> <head> <title>Bulma Box</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } .buttons { margin-top: 15px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"box\"> <article class=\"media\"> <div class=\"media-left\"> <figure class=\"image is-64x64\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png\"> </figure> </div> <div class=\"media-content\"> <div class=\"content\"> <p> <strong>GeeksforGeeks</strong> <small>@geeks</small> <br> Welcome to GeeksforGeeks </br> 'GeeksforGeeks' is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> <nav class=\"level is-mobile\"> <div class=\"level-left\"> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-reply\"></i> </span> </a> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-retweet\"></i> </span> </a> <a class=\"level-item\"> <span class=\"icon is-small\"> <i class=\"fas fa-heart\"></i> </span> </a> </div> </nav> </div> </article> </div> </div> </div> </div></body> </html>", "e": 34190, "s": 30819, "text": null }, { "code": null, "e": 34198, "s": 34190, "text": "Output:" }, { "code": null, "e": 34367, "s": 34198, "text": "Note: Here in all the above examples, we use some extra Bulma classes like container, column, title, button, media, image, input, label, etc to design our content well." }, { "code": null, "e": 34504, "s": 34367, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34510, "s": 34504, "text": "Bulma" }, { "code": null, "e": 34514, "s": 34510, "text": "CSS" }, { "code": null, "e": 34519, "s": 34514, "text": "HTML" }, { "code": null, "e": 34536, "s": 34519, "text": "Web Technologies" }, { "code": null, "e": 34541, "s": 34536, "text": "HTML" }, { "code": null, "e": 34639, "s": 34541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34648, "s": 34639, "text": "Comments" }, { "code": null, "e": 34661, "s": 34648, "text": "Old Comments" }, { "code": null, "e": 34723, "s": 34661, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34773, "s": 34723, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34821, "s": 34773, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34879, "s": 34821, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34929, "s": 34879, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 34991, "s": 34929, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35041, "s": 34991, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35089, "s": 35041, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35149, "s": 35089, "text": "How to set the default value for an HTML <select> element ?" } ]
PyCaret and Streamlit: How to Create and Deploy Data Science Web App | by Ruben Winastwan | Towards Data Science
Building and deploying a machine learning model have never been easier. Right now, we have a lot of frameworks and libraries that enable us to build machine learning models with just a few lines of code. Among all of them, PyCaret is one of the best. To create and deploy a web app for our data science project, Streamlit has become very popular lately. In this article, we will use these two libraries to create a data science web app. We’re going to use PyCaret to build a wine quality classifier. Next, we’re going to use Streamlit to create and deploy this wine classifier. You’ll be surprised of how easy and quick it is to build the classifier and deploy the web app with these two libraries. So, let’s get started! The data that we will use in this article is the Wine Quality dataset, which you can download for free here. This dataset consists of 1599 instances with 12 features. Let’s load the dataset with Pandas. import pandas as pd import numpy as np wine_df = pd.read_csv('D:/Dataset/Wine Quality/wine_qual.csv') wine_df.head() As you can see above, we have different features such as fixed acidity, citric acid, pH, and so on. The task of our classifier is to predict whether the wine quality is good or bad. However, the values for quality feature is not what we would’ve expected. We need to transform the value in this feature to be either ‘good’ or ‘bad’. To do this, we need to set certain rules. If the wine quality is equal or greater than 6, then we can classify the quality of the wine as good, otherwise the quality is bad. wine_df.quality = np.where(wine_df.quality >= 6,'Good', 'Bad') wine_df.head() Now we have the data that we’re looking for! Note that you can also check that there are 855 wines classified as ‘good’ and 744 wines classified as ‘bad’. This proportion seems pretty balanced and safe to say that we don’t have an imbalanced dataset issue. The dataset is also clean, which means that there is no missing value, no duplicate value, and the data types are all correct. Next, let’s build our classifier model using PyCaret. PyCaret is a low-code machine learning library that automates all of the machine learning workflows. What it does is that it provides a wrapper for popular machine learning libraries such as scikit-learn, XGBoost, LightGBM, CatBoost, and many more. With PyCaret, we can basically build our machine learning model for classification, regression, clustering, anomaly detection, or NLP problems in just a few lines of code. If you haven’t installed PyCaret, you can easily do so by typing the following pip command. pip install pycaret Since we’re going to solve a classification problem, then we need to use pycaret.classification module. If you solve different problems, then you need to use other modules, which you can find out more in PyCaret official documentation page. First things first, we need to setup our PyCaret environment with setup() function. This function needs to be called first before we call other functions in PyCaret. from pycaret.classification import *exp_clf01 = setup(data = wine_df, target = 'quality', session_id = 123) As you can see, we passed two parameters as the argument for setup() function: data — Our input data. target — The name of the feature that we want to predict (dependent variable). session_id — The identifier for our setup environment. If you run the code snippet above, you’ll get the following outputs: From the output above, you can see that the setup() function will automatically split our data into train set and test set. Also, it will automatically infer the data types of your features: whether your feature is a numerical feature or a categorical feature. You need to take a look at the output carefully because there are times when the function infers the data types incorrectly. If you find that one of the feature is inferred incorrectly, you can correct it by doing the following: exp_clf01 = setup(data = wine_df, target = 'quality', session_id = 123, categorical_features = ['feature1', 'feature2'], numerical_features = ['feature3', 'feature4']) You can use categorical_features or numerical_features parameter to change the data types that are incorrectly inferred by setup() function. You need to pass a list of string of the name of the features that you want to change. Next, let’s build our classifier model. When we want to build a machine learning model, most of the times we don’t know in advance which models that will give us the best performance according to our metrics. With PyCaret, you’re able to compare the performance of different kinds of classification models with literally single line of code. best = compare_models() As you can see, it turns out that Random Forest classifier gives us the best performance in 5 out of 7 metrics. Let’s say we want to use F1 score metrics for our wine classifier, then of course Random Forest classifier will give us the best performance. Before we go further, let’s see whether we can improve the performance of the models by tuning our setup() function. exp_clf102 = setup(data = train_data, target = 'quality', session_id=123, normalize = True, transformation = True) As you can see, we passed several additional parameters there to tune our setup: normalize — To transform our features by scaling them to a given range. transformation — To transform our features such that our data can be represented by normal distribution. This can be helpful for models like Logistic Regression, LDA, or Gaussian Native Bayes. There are a lot of tuning options that you can do inside this setup() function. You can learn more about it here. Also note that we use the same session_id as our previous setup() function. This is to make sure that all of the future improvements on the model are solely due to the change that we’ve implemented in this setup() function. Let’s compare the models once again with our new setup. As you can see, most of the metrics are slightly improved after we tuned the setup. Before we tuned the setup, the F1 score of Extra Tree classifier is 0.8306. After we tuned the setup, the F1 score becomes 0.8375. Based on this result, let’s build our Extra Tree classifier. We can do this with a single line of code. et_model = create_model('et') Next, you can evaluate your model by looking at the visualization of the ROC curve, feature importance, or confusion matrix of your model with also a single line of code. evaluate_model(et_model) As a final check, we can use our Extra Tree classifier to predict the test data that has been generated by PyCaret. As mentioned earlier, soon after we executed the setup() function at the very first step, PyCaret will automatically split our data into training data and test data. All of the model performance and evaluation metrics that we’ve seen above are solely based on the training data. To use the model to predict the test data, we can use the predict_model function. predict_model(et_model) Finally, let’s save our Extra Tree classifier model. save_model(et_model, model_name = 'extra_tree_model') And that’s it for model building with PyCaret. After this you should have a pickle file called ‘extra_tree_model’ in your working directory. We will use this saved model to build a wine classifier web app with Streamlit. Now it’s time for us to build our wine classifier web app. In this post, we’re going to use Streamlit to build the web app as it is more beginner friendly than Flask. Plus, you don’t need to have any prior experience with HTML and CSS to use Streamlit. If you haven’t installed Streamlit yet, you can do so by typing the following pip command: pip install streamlit The first thing that we need to do is importing all of the relevant libraries. Note that we’re going to use the Extra Tree classifier model that we’ve saved before using PyCaret. To load the model and to make a prediction using the saved model, we can use load_model and predict_model functions from PyCaret. In the code above, we import the libraries, create a function to make a prediction, load the saved model, and create the title and text of our web app. Next, we need to let the user to specify the value of our features. Since our features are all numeric features, it will be best to represent them with a slider widget. To create a slider widget, we can use slider() function from Streamlit. Note that we passed several parameters to slider() function: label — The label of the feature that will be displayed in the web app. min_value — Minimum value of the slider. max_value — Maximum value of the slider. value — Default value of the slider when you open your web app. step — The amount of increment and decrement when you move the slider. Next we need to convert all of those user input values into a dataframe. Then, we can use the dataframe as the input of our model’s prediction. And that’s it basically! Now your web app is done. To check your web app, you need to open your prompt, then go to the working directory of your Python file. In the working directory of your Python file, type the following: streamlit run your_python_file.py Next, a browser window will pop-up to show you the UI of your web app like the following: However, there is still one small problem to solve. Your web app now can only be accessed in your local computer. That means that other people can’t see and use your web app. If you want other people to use your web app, you need to deploy your web app. In this post, I’m going to show you how to deploy your Streamlit web app with Streamlit sharing. There are two easy options if you want to deploy your web app: either using Heroku or Streamlit sharing. The problem with Heroku is that if you only have free tier access, they will limit your slug size to around 500MB. Meanwhile, PyCaret itself has a lot of dependencies, which means that the size of your web app will exceed the slug size limit of Heroku. Because of that, let’s use Streamlit sharing to deploy the wine classier web app. It’s really easy to deploy your Streamlit web app with Streamlit sharing. Below is the step-by-step on how you can deploy your web app: The first thing that you need to do is requesting an invite to Streamlit sharing. You can do so by accessing this page. All you need to do is to enter your name and the email that you use for your GitHub account. If you don’t remember your email, you can do so by logging in into your GitHub account, then go to Settings. In the Settings, select Emails and you’ll see your email address. Next, create a repo in your GitHub that contains three files: the Python file for creating the web app, the pickle file of classifier model that we’ve built using PyCaret, and a text file called requirements.txt. This text file should contain all of the dependencies that we need to create our web app. For our wine classifier, the content should look like this: pycaretstreamlitpandasnumpy After you’ve requested an invite, you should wait a little bit until you get an invitation from Streamlit via your Email. Next, go to this page and sign in with your GitHub account. Now you should see the following page after you’ve signed in. Next, click on ‘New app’ button and you’ll see the following page. In the Repository field, enter the path to your GitHub repo which contains the Python file to create the web app. In the Main file path, enter the name of your Python file. Finally, click Deploy! Now wait a little bit until your web app is deployed. Note that after your web app has been successfully deployed, you’ll see the URL to access your web app with the format as follows: https://share.streamlit.io/[user name]/[repo name]/[branch name]/[app path] You can share this URL to other people so that they can use and play around with your web app. You can check the deployed version of wine classifier covered in this article here. Also, you can check the complete Notebook and Python file to build the wine classifier web app here. And that’s it! Hopefully, this article is somewhat helpful for you. I’ve always thought that Heroku would be the easiest available option to deploy your data science web app. However, if you build your web app with Streamlit, then Streamlit sharing would be the easiest and the most convenient way to deploy your web app.
[ { "code": null, "e": 526, "s": 172, "text": "Building and deploying a machine learning model have never been easier. Right now, we have a lot of frameworks and libraries that enable us to build machine learning models with just a few lines of code. Among all of them, PyCaret is one of the best. To create and deploy a web app for our data science project, Streamlit has become very popular lately." }, { "code": null, "e": 894, "s": 526, "text": "In this article, we will use these two libraries to create a data science web app. We’re going to use PyCaret to build a wine quality classifier. Next, we’re going to use Streamlit to create and deploy this wine classifier. You’ll be surprised of how easy and quick it is to build the classifier and deploy the web app with these two libraries. So, let’s get started!" }, { "code": null, "e": 1097, "s": 894, "text": "The data that we will use in this article is the Wine Quality dataset, which you can download for free here. This dataset consists of 1599 instances with 12 features. Let’s load the dataset with Pandas." }, { "code": null, "e": 1137, "s": 1097, "text": "import pandas as pd\nimport numpy as np\n" }, { "code": null, "e": 1201, "s": 1137, "text": "wine_df = pd.read_csv('D:/Dataset/Wine Quality/wine_qual.csv')\n" }, { "code": null, "e": 1217, "s": 1201, "text": "wine_df.head()\n" }, { "code": null, "e": 1553, "s": 1220, "text": "As you can see above, we have different features such as fixed acidity, citric acid, pH, and so on. The task of our classifier is to predict whether the wine quality is good or bad. However, the values for quality feature is not what we would’ve expected. We need to transform the value in this feature to be either ‘good’ or ‘bad’." }, { "code": null, "e": 1727, "s": 1553, "text": "To do this, we need to set certain rules. If the wine quality is equal or greater than 6, then we can classify the quality of the wine as good, otherwise the quality is bad." }, { "code": null, "e": 1791, "s": 1727, "text": "wine_df.quality = np.where(wine_df.quality >= 6,'Good', 'Bad')\n" }, { "code": null, "e": 1807, "s": 1791, "text": "wine_df.head()\n" }, { "code": null, "e": 2067, "s": 1810, "text": "Now we have the data that we’re looking for! Note that you can also check that there are 855 wines classified as ‘good’ and 744 wines classified as ‘bad’. This proportion seems pretty balanced and safe to say that we don’t have an imbalanced dataset issue." }, { "code": null, "e": 2194, "s": 2067, "text": "The dataset is also clean, which means that there is no missing value, no duplicate value, and the data types are all correct." }, { "code": null, "e": 2248, "s": 2194, "text": "Next, let’s build our classifier model using PyCaret." }, { "code": null, "e": 2497, "s": 2248, "text": "PyCaret is a low-code machine learning library that automates all of the machine learning workflows. What it does is that it provides a wrapper for popular machine learning libraries such as scikit-learn, XGBoost, LightGBM, CatBoost, and many more." }, { "code": null, "e": 2669, "s": 2497, "text": "With PyCaret, we can basically build our machine learning model for classification, regression, clustering, anomaly detection, or NLP problems in just a few lines of code." }, { "code": null, "e": 2761, "s": 2669, "text": "If you haven’t installed PyCaret, you can easily do so by typing the following pip command." }, { "code": null, "e": 2781, "s": 2761, "text": "pip install pycaret" }, { "code": null, "e": 3022, "s": 2781, "text": "Since we’re going to solve a classification problem, then we need to use pycaret.classification module. If you solve different problems, then you need to use other modules, which you can find out more in PyCaret official documentation page." }, { "code": null, "e": 3188, "s": 3022, "text": "First things first, we need to setup our PyCaret environment with setup() function. This function needs to be called first before we call other functions in PyCaret." }, { "code": null, "e": 3296, "s": 3188, "text": "from pycaret.classification import *exp_clf01 = setup(data = wine_df, target = 'quality', session_id = 123)" }, { "code": null, "e": 3375, "s": 3296, "text": "As you can see, we passed two parameters as the argument for setup() function:" }, { "code": null, "e": 3398, "s": 3375, "text": "data — Our input data." }, { "code": null, "e": 3477, "s": 3398, "text": "target — The name of the feature that we want to predict (dependent variable)." }, { "code": null, "e": 3532, "s": 3477, "text": "session_id — The identifier for our setup environment." }, { "code": null, "e": 3601, "s": 3532, "text": "If you run the code snippet above, you’ll get the following outputs:" }, { "code": null, "e": 3725, "s": 3601, "text": "From the output above, you can see that the setup() function will automatically split our data into train set and test set." }, { "code": null, "e": 4091, "s": 3725, "text": "Also, it will automatically infer the data types of your features: whether your feature is a numerical feature or a categorical feature. You need to take a look at the output carefully because there are times when the function infers the data types incorrectly. If you find that one of the feature is inferred incorrectly, you can correct it by doing the following:" }, { "code": null, "e": 4259, "s": 4091, "text": "exp_clf01 = setup(data = wine_df, target = 'quality', session_id = 123, categorical_features = ['feature1', 'feature2'], numerical_features = ['feature3', 'feature4'])" }, { "code": null, "e": 4487, "s": 4259, "text": "You can use categorical_features or numerical_features parameter to change the data types that are incorrectly inferred by setup() function. You need to pass a list of string of the name of the features that you want to change." }, { "code": null, "e": 4527, "s": 4487, "text": "Next, let’s build our classifier model." }, { "code": null, "e": 4829, "s": 4527, "text": "When we want to build a machine learning model, most of the times we don’t know in advance which models that will give us the best performance according to our metrics. With PyCaret, you’re able to compare the performance of different kinds of classification models with literally single line of code." }, { "code": null, "e": 4853, "s": 4829, "text": "best = compare_models()" }, { "code": null, "e": 5107, "s": 4853, "text": "As you can see, it turns out that Random Forest classifier gives us the best performance in 5 out of 7 metrics. Let’s say we want to use F1 score metrics for our wine classifier, then of course Random Forest classifier will give us the best performance." }, { "code": null, "e": 5224, "s": 5107, "text": "Before we go further, let’s see whether we can improve the performance of the models by tuning our setup() function." }, { "code": null, "e": 5588, "s": 5224, "text": "exp_clf102 = setup(data = train_data, target = 'quality', session_id=123, normalize = True, transformation = True)" }, { "code": null, "e": 5669, "s": 5588, "text": "As you can see, we passed several additional parameters there to tune our setup:" }, { "code": null, "e": 5741, "s": 5669, "text": "normalize — To transform our features by scaling them to a given range." }, { "code": null, "e": 5934, "s": 5741, "text": "transformation — To transform our features such that our data can be represented by normal distribution. This can be helpful for models like Logistic Regression, LDA, or Gaussian Native Bayes." }, { "code": null, "e": 6048, "s": 5934, "text": "There are a lot of tuning options that you can do inside this setup() function. You can learn more about it here." }, { "code": null, "e": 6272, "s": 6048, "text": "Also note that we use the same session_id as our previous setup() function. This is to make sure that all of the future improvements on the model are solely due to the change that we’ve implemented in this setup() function." }, { "code": null, "e": 6328, "s": 6272, "text": "Let’s compare the models once again with our new setup." }, { "code": null, "e": 6543, "s": 6328, "text": "As you can see, most of the metrics are slightly improved after we tuned the setup. Before we tuned the setup, the F1 score of Extra Tree classifier is 0.8306. After we tuned the setup, the F1 score becomes 0.8375." }, { "code": null, "e": 6647, "s": 6543, "text": "Based on this result, let’s build our Extra Tree classifier. We can do this with a single line of code." }, { "code": null, "e": 6677, "s": 6647, "text": "et_model = create_model('et')" }, { "code": null, "e": 6848, "s": 6677, "text": "Next, you can evaluate your model by looking at the visualization of the ROC curve, feature importance, or confusion matrix of your model with also a single line of code." }, { "code": null, "e": 6873, "s": 6848, "text": "evaluate_model(et_model)" }, { "code": null, "e": 7268, "s": 6873, "text": "As a final check, we can use our Extra Tree classifier to predict the test data that has been generated by PyCaret. As mentioned earlier, soon after we executed the setup() function at the very first step, PyCaret will automatically split our data into training data and test data. All of the model performance and evaluation metrics that we’ve seen above are solely based on the training data." }, { "code": null, "e": 7350, "s": 7268, "text": "To use the model to predict the test data, we can use the predict_model function." }, { "code": null, "e": 7374, "s": 7350, "text": "predict_model(et_model)" }, { "code": null, "e": 7427, "s": 7374, "text": "Finally, let’s save our Extra Tree classifier model." }, { "code": null, "e": 7481, "s": 7427, "text": "save_model(et_model, model_name = 'extra_tree_model')" }, { "code": null, "e": 7702, "s": 7481, "text": "And that’s it for model building with PyCaret. After this you should have a pickle file called ‘extra_tree_model’ in your working directory. We will use this saved model to build a wine classifier web app with Streamlit." }, { "code": null, "e": 7955, "s": 7702, "text": "Now it’s time for us to build our wine classifier web app. In this post, we’re going to use Streamlit to build the web app as it is more beginner friendly than Flask. Plus, you don’t need to have any prior experience with HTML and CSS to use Streamlit." }, { "code": null, "e": 8046, "s": 7955, "text": "If you haven’t installed Streamlit yet, you can do so by typing the following pip command:" }, { "code": null, "e": 8068, "s": 8046, "text": "pip install streamlit" }, { "code": null, "e": 8377, "s": 8068, "text": "The first thing that we need to do is importing all of the relevant libraries. Note that we’re going to use the Extra Tree classifier model that we’ve saved before using PyCaret. To load the model and to make a prediction using the saved model, we can use load_model and predict_model functions from PyCaret." }, { "code": null, "e": 8529, "s": 8377, "text": "In the code above, we import the libraries, create a function to make a prediction, load the saved model, and create the title and text of our web app." }, { "code": null, "e": 8770, "s": 8529, "text": "Next, we need to let the user to specify the value of our features. Since our features are all numeric features, it will be best to represent them with a slider widget. To create a slider widget, we can use slider() function from Streamlit." }, { "code": null, "e": 8831, "s": 8770, "text": "Note that we passed several parameters to slider() function:" }, { "code": null, "e": 8903, "s": 8831, "text": "label — The label of the feature that will be displayed in the web app." }, { "code": null, "e": 8944, "s": 8903, "text": "min_value — Minimum value of the slider." }, { "code": null, "e": 8985, "s": 8944, "text": "max_value — Maximum value of the slider." }, { "code": null, "e": 9049, "s": 8985, "text": "value — Default value of the slider when you open your web app." }, { "code": null, "e": 9120, "s": 9049, "text": "step — The amount of increment and decrement when you move the slider." }, { "code": null, "e": 9264, "s": 9120, "text": "Next we need to convert all of those user input values into a dataframe. Then, we can use the dataframe as the input of our model’s prediction." }, { "code": null, "e": 9315, "s": 9264, "text": "And that’s it basically! Now your web app is done." }, { "code": null, "e": 9422, "s": 9315, "text": "To check your web app, you need to open your prompt, then go to the working directory of your Python file." }, { "code": null, "e": 9488, "s": 9422, "text": "In the working directory of your Python file, type the following:" }, { "code": null, "e": 9522, "s": 9488, "text": "streamlit run your_python_file.py" }, { "code": null, "e": 9612, "s": 9522, "text": "Next, a browser window will pop-up to show you the UI of your web app like the following:" }, { "code": null, "e": 9963, "s": 9612, "text": "However, there is still one small problem to solve. Your web app now can only be accessed in your local computer. That means that other people can’t see and use your web app. If you want other people to use your web app, you need to deploy your web app. In this post, I’m going to show you how to deploy your Streamlit web app with Streamlit sharing." }, { "code": null, "e": 10321, "s": 9963, "text": "There are two easy options if you want to deploy your web app: either using Heroku or Streamlit sharing. The problem with Heroku is that if you only have free tier access, they will limit your slug size to around 500MB. Meanwhile, PyCaret itself has a lot of dependencies, which means that the size of your web app will exceed the slug size limit of Heroku." }, { "code": null, "e": 10539, "s": 10321, "text": "Because of that, let’s use Streamlit sharing to deploy the wine classier web app. It’s really easy to deploy your Streamlit web app with Streamlit sharing. Below is the step-by-step on how you can deploy your web app:" }, { "code": null, "e": 10927, "s": 10539, "text": "The first thing that you need to do is requesting an invite to Streamlit sharing. You can do so by accessing this page. All you need to do is to enter your name and the email that you use for your GitHub account. If you don’t remember your email, you can do so by logging in into your GitHub account, then go to Settings. In the Settings, select Emails and you’ll see your email address." }, { "code": null, "e": 11290, "s": 10927, "text": "Next, create a repo in your GitHub that contains three files: the Python file for creating the web app, the pickle file of classifier model that we’ve built using PyCaret, and a text file called requirements.txt. This text file should contain all of the dependencies that we need to create our web app. For our wine classifier, the content should look like this:" }, { "code": null, "e": 11318, "s": 11290, "text": "pycaretstreamlitpandasnumpy" }, { "code": null, "e": 11440, "s": 11318, "text": "After you’ve requested an invite, you should wait a little bit until you get an invitation from Streamlit via your Email." }, { "code": null, "e": 11500, "s": 11440, "text": "Next, go to this page and sign in with your GitHub account." }, { "code": null, "e": 11562, "s": 11500, "text": "Now you should see the following page after you’ve signed in." }, { "code": null, "e": 11629, "s": 11562, "text": "Next, click on ‘New app’ button and you’ll see the following page." }, { "code": null, "e": 11825, "s": 11629, "text": "In the Repository field, enter the path to your GitHub repo which contains the Python file to create the web app. In the Main file path, enter the name of your Python file. Finally, click Deploy!" }, { "code": null, "e": 11879, "s": 11825, "text": "Now wait a little bit until your web app is deployed." }, { "code": null, "e": 12010, "s": 11879, "text": "Note that after your web app has been successfully deployed, you’ll see the URL to access your web app with the format as follows:" }, { "code": null, "e": 12086, "s": 12010, "text": "https://share.streamlit.io/[user name]/[repo name]/[branch name]/[app path]" }, { "code": null, "e": 12181, "s": 12086, "text": "You can share this URL to other people so that they can use and play around with your web app." }, { "code": null, "e": 12265, "s": 12181, "text": "You can check the deployed version of wine classifier covered in this article here." }, { "code": null, "e": 12366, "s": 12265, "text": "Also, you can check the complete Notebook and Python file to build the wine classifier web app here." }, { "code": null, "e": 12434, "s": 12366, "text": "And that’s it! Hopefully, this article is somewhat helpful for you." } ]
Python - Visualizing image in different color spaces
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. OpenCV-Python makes use of Numpy, which is a highly optimized library for numerical operations with a MATLAB-style syntax. All the OpenCV array structures are converted to and from Numpy arrays. # read image as RGB # Importing cv2 and matplotlib module import cv2 import matplotlib.pyplot as plt # reads image as RGB img = cv2.imread('download.png') # shows the image plt.imshow(img) # read image as GrayScale # Importing cv2 module import cv2 # Reads image as gray scale img = cv2.imread('download.png', 0) # We can alternatively convert # image by using cv2color img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shows the image cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() # read image as YCrCb color space # Import cv2 module import cv2 # Reads the image img = cv2.imread('download.png') # Convert to YCrCb color space img = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) # Shows the image cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() # read image as HSV color space # Importing cv2 module import cv2 # Reads the image img = cv2.imread('download.png') # Converts to HSV color space img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Shows the image cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() # Heat map of image # Importing matplotlib and cv2 import matplotlib.pyplot as plt import cv2 # reads the image img = cv2.imread('download.png') # plot heat map image plt.imshow(img, cmap ='hot') # Spectral map of image # Importing matplotlib and cv2 import matplotlib.pyplot as plt import cv2 img = cv2.imread('download.png') plt.imshow(img, cmap ='nipy_spectral')
[ { "code": null, "e": 1347, "s": 1062, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. OpenCV-Python makes use of Numpy, which is a highly optimized library for numerical operations with a MATLAB-style syntax. All the OpenCV array structures are converted to and from Numpy arrays." }, { "code": null, "e": 2755, "s": 1347, "text": "# read image as RGB\n# Importing cv2 and matplotlib module\nimport cv2\nimport matplotlib.pyplot as plt\n# reads image as RGB\nimg = cv2.imread('download.png')\n# shows the image\nplt.imshow(img)\n# read image as GrayScale\n# Importing cv2 module\nimport cv2\n# Reads image as gray scale\nimg = cv2.imread('download.png', 0)\n# We can alternatively convert\n# image by using cv2color\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# Shows the image\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n# read image as YCrCb color space\n# Import cv2 module\nimport cv2\n# Reads the image\nimg = cv2.imread('download.png')\n# Convert to YCrCb color space\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n# Shows the image\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n# read image as HSV color space\n# Importing cv2 module\nimport cv2\n# Reads the image\nimg = cv2.imread('download.png')\n# Converts to HSV color space\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n# Shows the image\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n# Heat map of image\n# Importing matplotlib and cv2\nimport matplotlib.pyplot as plt\nimport cv2\n# reads the image\nimg = cv2.imread('download.png')\n# plot heat map image\nplt.imshow(img, cmap ='hot')\n# Spectral map of image\n# Importing matplotlib and cv2\nimport matplotlib.pyplot as plt\nimport cv2\nimg = cv2.imread('download.png')\nplt.imshow(img, cmap ='nipy_spectral')" } ]
How to switch to new window in Selenium for Python?
Selenium can switch to new windows when there are multiple windows opened. There may be scenarios when filling a date field in a form opens to a new window or clicking a link, button or an advertisement opens a new tab. Selenium uses the current_window_handle and window_handles methods to work with new windows. The window_handles method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String]. The current_window_handle method is used to store the window handle id of the present active window. Finally to switch to a particular window, switch_to_window() method is used. The handle id of the window where we want to switch is passed as an argument to that method. The steps to be followed to implement the above concept − After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method. After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method. We shall iterate through all the window handle ids till we get our desired window handle id. We shall iterate through all the window handle ids till we get our desired window handle id. Let us then grab the current window handle id with the help of current_window_handle method. Let us then grab the current window handle id with the help of current_window_handle method. Then switch to that window with switch_to_window() method. Then switch to that window with switch_to_window() method. Code Implementation. from selenium import webdriver import time driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.get("https://accounts.google.com/signup") driver.find_element_by_link_text("Help").click() #prints parent window title print("Parent window title: " + driver.title) #get current window handle p = driver.current_window_handle #get first child window chwnd = driver.window_handles for w in chwnd: #switch focus to child window if(w!=p): driver.switch_to.window(w) break time.sleep(0.9) print("Child window title: " + driver.title) driver.quit()
[ { "code": null, "e": 1282, "s": 1062, "text": "Selenium can switch to new windows when there are multiple windows opened. There may be scenarios when filling a date field in a form opens to a new window or clicking a link, button or an advertisement opens a new tab." }, { "code": null, "e": 1558, "s": 1282, "text": "Selenium uses the current_window_handle and window_handles methods to work with new windows. The window_handles method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String]." }, { "code": null, "e": 1829, "s": 1558, "text": "The current_window_handle method is used to store the window handle id of the present active window. Finally to switch to a particular window, switch_to_window() method is used. The handle id of the window where we want to switch is passed as an argument to that method." }, { "code": null, "e": 1887, "s": 1829, "text": "The steps to be followed to implement the above concept −" }, { "code": null, "e": 2031, "s": 1887, "text": "After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method." }, { "code": null, "e": 2175, "s": 2031, "text": "After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method." }, { "code": null, "e": 2268, "s": 2175, "text": "We shall iterate through all the window handle ids till we get our desired window handle id." }, { "code": null, "e": 2361, "s": 2268, "text": "We shall iterate through all the window handle ids till we get our desired window handle id." }, { "code": null, "e": 2454, "s": 2361, "text": "Let us then grab the current window handle id with the help of current_window_handle method." }, { "code": null, "e": 2547, "s": 2454, "text": "Let us then grab the current window handle id with the help of current_window_handle method." }, { "code": null, "e": 2606, "s": 2547, "text": "Then switch to that window with switch_to_window() method." }, { "code": null, "e": 2665, "s": 2606, "text": "Then switch to that window with switch_to_window() method." }, { "code": null, "e": 2686, "s": 2665, "text": "Code Implementation." }, { "code": null, "e": 3257, "s": 2686, "text": "from selenium import webdriver\nimport time\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.get(\"https://accounts.google.com/signup\")\ndriver.find_element_by_link_text(\"Help\").click()\n#prints parent window title\nprint(\"Parent window title: \" + driver.title)\n#get current window handle\np = driver.current_window_handle\n#get first child window\nchwnd = driver.window_handles\nfor w in chwnd:\n #switch focus to child window\n if(w!=p):\n driver.switch_to.window(w)\n break\ntime.sleep(0.9)\nprint(\"Child window title: \" + driver.title)\ndriver.quit()" } ]
Get data inside a button tag using BeautifulSoup - GeeksforGeeks
26 Mar, 2021 Sometimes while working with BeautifulSoup, are you stuck at the point where you have to get data inside a button tag? Don’t worry. Just read the article and get to know how you can do the same. For instance, consider this simple page source having a button tag. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Apple</title></head><body> <button id="enjoy" onclick="gfg.html"> Click Me! </button></body></html> Once you have created the button in the HTML code, you can get the text inside a button tag using: btn_text=btn.text print(btn_text) Also, you can find the onclick link of the button inside a button tag using: btn_onclick=btn['onclick'] print(btn_onclick) Step 1: First, import the libraries Beautiful Soup and os. from bs4 import BeautifulSoup as bs import os Step 2: Now, remove the last segment of the path by entering the name of the Python file in which you are currently working. base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working)) Step 3: Then, open the HTML file from which you want to read the value. html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’)) Step 4: Moreover, parse the HTML file in Beautiful Soup soup=bs(html, 'html.parser') Step 5: Next, find the button for which you want to obtain the data. btn=soup.find("button", {"id":"#Id name of the button"}) Step 6: Now, for obtaining the text stored inside the button tag in the HTML, use: btn_text=btn.text Step 7: Further, for finding the onclick link inside the button tag, you can write the code as follows: btn_onclick=btn['onclick'] Step 8: Finally, printing the text and onclick link of the button tag obtained in steps 6 and 7. print(btn_text) print(btn_onclick) Python # Python program to get data inside# a button tag using BeautifulSoup # Import the libraries BeautifulSoup # and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to make# changeshtml = open(os.path.join(base, 'run.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Finding the location of buttonbtn = soup.find("button", {"id": "enjoy"}) # Obtaining the text stored inside button tagbtn_text = btn.text # Obtaining the onclick link of button tagbtn_onclick = btn['onclick'] # Printing the valuesprint(btn_text)print(btn_onclick) Output: Picked Python BeautifulSoup Python bs4-Exercises Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24487, "s": 24292, "text": "Sometimes while working with BeautifulSoup, are you stuck at the point where you have to get data inside a button tag? Don’t worry. Just read the article and get to know how you can do the same." }, { "code": null, "e": 24555, "s": 24487, "text": "For instance, consider this simple page source having a button tag." }, { "code": null, "e": 24560, "s": 24555, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Apple</title></head><body> <button id=\"enjoy\" onclick=\"gfg.html\"> Click Me! </button></body></html>", "e": 24741, "s": 24560, "text": null }, { "code": null, "e": 24840, "s": 24741, "text": "Once you have created the button in the HTML code, you can get the text inside a button tag using:" }, { "code": null, "e": 24874, "s": 24840, "text": "btn_text=btn.text\nprint(btn_text)" }, { "code": null, "e": 24951, "s": 24874, "text": "Also, you can find the onclick link of the button inside a button tag using:" }, { "code": null, "e": 24997, "s": 24951, "text": "btn_onclick=btn['onclick']\nprint(btn_onclick)" }, { "code": null, "e": 25056, "s": 24997, "text": "Step 1: First, import the libraries Beautiful Soup and os." }, { "code": null, "e": 25102, "s": 25056, "text": "from bs4 import BeautifulSoup as bs\nimport os" }, { "code": null, "e": 25227, "s": 25102, "text": "Step 2: Now, remove the last segment of the path by entering the name of the Python file in which you are currently working." }, { "code": null, "e": 25323, "s": 25227, "text": "base=os.path.dirname(os.path.abspath(‘#Name of Python file in which you are currently working))" }, { "code": null, "e": 25395, "s": 25323, "text": "Step 3: Then, open the HTML file from which you want to read the value." }, { "code": null, "e": 25481, "s": 25395, "text": "html=open(os.path.join(base, ‘#Name of HTML file from which you wish to read value’))" }, { "code": null, "e": 25537, "s": 25481, "text": "Step 4: Moreover, parse the HTML file in Beautiful Soup" }, { "code": null, "e": 25566, "s": 25537, "text": "soup=bs(html, 'html.parser')" }, { "code": null, "e": 25635, "s": 25566, "text": "Step 5: Next, find the button for which you want to obtain the data." }, { "code": null, "e": 25692, "s": 25635, "text": "btn=soup.find(\"button\", {\"id\":\"#Id name of the button\"})" }, { "code": null, "e": 25775, "s": 25692, "text": "Step 6: Now, for obtaining the text stored inside the button tag in the HTML, use:" }, { "code": null, "e": 25793, "s": 25775, "text": "btn_text=btn.text" }, { "code": null, "e": 25897, "s": 25793, "text": "Step 7: Further, for finding the onclick link inside the button tag, you can write the code as follows:" }, { "code": null, "e": 25924, "s": 25897, "text": "btn_onclick=btn['onclick']" }, { "code": null, "e": 26021, "s": 25924, "text": "Step 8: Finally, printing the text and onclick link of the button tag obtained in steps 6 and 7." }, { "code": null, "e": 26056, "s": 26021, "text": "print(btn_text)\nprint(btn_onclick)" }, { "code": null, "e": 26063, "s": 26056, "text": "Python" }, { "code": "# Python program to get data inside# a button tag using BeautifulSoup # Import the libraries BeautifulSoup # and osfrom bs4 import BeautifulSoup as bsimport os # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to make# changeshtml = open(os.path.join(base, 'run.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Finding the location of buttonbtn = soup.find(\"button\", {\"id\": \"enjoy\"}) # Obtaining the text stored inside button tagbtn_text = btn.text # Obtaining the onclick link of button tagbtn_onclick = btn['onclick'] # Printing the valuesprint(btn_text)print(btn_onclick)", "e": 26744, "s": 26063, "text": null }, { "code": null, "e": 26752, "s": 26744, "text": "Output:" }, { "code": null, "e": 26759, "s": 26752, "text": "Picked" }, { "code": null, "e": 26780, "s": 26759, "text": "Python BeautifulSoup" }, { "code": null, "e": 26801, "s": 26780, "text": "Python bs4-Exercises" }, { "code": null, "e": 26808, "s": 26801, "text": "Python" }, { "code": null, "e": 26906, "s": 26808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26938, "s": 26906, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26980, "s": 26938, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27036, "s": 26980, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27078, "s": 27036, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27109, "s": 27078, "text": "Python | os.path.join() method" }, { "code": null, "e": 27164, "s": 27109, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27186, "s": 27164, "text": "Defaultdict in Python" }, { "code": null, "e": 27225, "s": 27186, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27254, "s": 27225, "text": "Create a directory in Python" } ]
Initialize HashMap in Java - GeeksforGeeks
11 Dec, 2018 HashMap is a part of java.util package.HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface. It stores the data in (Key, Value) pairs.We can initialize HashMap using the constructor in four different ways :1.HashMap()It is the default constructor with initial capacity 16 and load factor 0.75.HashMap hs=new HashMap(); // Java program to demonstrate simple initialization // of HashMapimport java.util.*;public class GFG { public static void main(String args[]) { HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, "Ram"); hm.put(2, "Shyam"); hm.put(3, "Sita"); System.out.println("Values " + hm); }} Values {1=Ram, 2=Shyam, 3=Sita} 2.HashMap(int initialCapacity)It is used to create an empty HashMap object with specified initial capacity under default load factor 0.75.HashMap hs=new HashMap(10); // Java program to demonstrate initialization // of HashMap with given capacity.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(3); hm.put(1, "C"); hm.put(2, "C++"); hm.put(3, "Java"); System.out.println("Values of hm" + hm); }} Values of hm{1=C, 2=C++, 3=Java} 3.HashMap(int initial capacity, float loadFactor)It is used to create an empty HashMap object with specified initial capacity as well as load factor.HashMap hs=new HashMap(10, 0.5); // Java program to demonstrate initialization // of HashMap with given capacity and load factor.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(3, 0.5f); hm.put(1, "C"); hm.put(2, "C++"); hm.put(3, "Java"); System.out.println("Values of hm" + hm); }} Values of hm{1=C, 2=C++, 3=Java} 4.HashMap(Map map)It is used to initializes the hash map by using the elements of the given Map object map.HashMap hs=new HashMap(map); // Java program to demonstrate initialization // of HashMap from another HashMap.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, "C"); hm.put(2, "C++"); hm.put(3, "Java"); System.out.println("Values of hm" + hm); // Creating a new map from above map HashMap<Integer, String> language = new HashMap<Integer, String>(hm); System.out.println("Values of language " + language); }} Values of hm{1=C, 2=C++, 3=Java} Values of language {1=C, 2=C++, 3=Java} Initializing Immutable HashMapPlease see Immutable Map in Java Java-Collections Java-HashMap java-map Java-Map-Programs Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java Collections in Java Overriding in Java Queue Interface In Java
[ { "code": null, "e": 24001, "s": 23973, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24379, "s": 24001, "text": "HashMap is a part of java.util package.HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface. It stores the data in (Key, Value) pairs.We can initialize HashMap using the constructor in four different ways :1.HashMap()It is the default constructor with initial capacity 16 and load factor 0.75.HashMap hs=new HashMap();" }, { "code": "// Java program to demonstrate simple initialization // of HashMapimport java.util.*;public class GFG { public static void main(String args[]) { HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, \"Ram\"); hm.put(2, \"Shyam\"); hm.put(3, \"Sita\"); System.out.println(\"Values \" + hm); }}", "e": 24726, "s": 24379, "text": null }, { "code": null, "e": 24759, "s": 24726, "text": "Values {1=Ram, 2=Shyam, 3=Sita}\n" }, { "code": null, "e": 24925, "s": 24759, "text": "2.HashMap(int initialCapacity)It is used to create an empty HashMap object with specified initial capacity under default load factor 0.75.HashMap hs=new HashMap(10);" }, { "code": "// Java program to demonstrate initialization // of HashMap with given capacity.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(3); hm.put(1, \"C\"); hm.put(2, \"C++\"); hm.put(3, \"Java\"); System.out.println(\"Values of hm\" + hm); }}", "e": 25288, "s": 24925, "text": null }, { "code": null, "e": 25322, "s": 25288, "text": "Values of hm{1=C, 2=C++, 3=Java}\n" }, { "code": null, "e": 25504, "s": 25322, "text": "3.HashMap(int initial capacity, float loadFactor)It is used to create an empty HashMap object with specified initial capacity as well as load factor.HashMap hs=new HashMap(10, 0.5);" }, { "code": "// Java program to demonstrate initialization // of HashMap with given capacity and load factor.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(3, 0.5f); hm.put(1, \"C\"); hm.put(2, \"C++\"); hm.put(3, \"Java\"); System.out.println(\"Values of hm\" + hm); }}", "e": 25903, "s": 25504, "text": null }, { "code": null, "e": 25937, "s": 25903, "text": "Values of hm{1=C, 2=C++, 3=Java}\n" }, { "code": null, "e": 26073, "s": 25937, "text": "4.HashMap(Map map)It is used to initializes the hash map by using the elements of the given Map object map.HashMap hs=new HashMap(map);" }, { "code": "// Java program to demonstrate initialization // of HashMap from another HashMap.import java.util.*;public class GFG { public static void main(String[] args) { HashMap<Integer, String> hm = new HashMap<Integer, String>(); hm.put(1, \"C\"); hm.put(2, \"C++\"); hm.put(3, \"Java\"); System.out.println(\"Values of hm\" + hm); // Creating a new map from above map HashMap<Integer, String> language = new HashMap<Integer, String>(hm); System.out.println(\"Values of language \" + language); }}", "e": 26622, "s": 26073, "text": null }, { "code": null, "e": 26696, "s": 26622, "text": "Values of hm{1=C, 2=C++, 3=Java}\nValues of language {1=C, 2=C++, 3=Java}\n" }, { "code": null, "e": 26759, "s": 26696, "text": "Initializing Immutable HashMapPlease see Immutable Map in Java" }, { "code": null, "e": 26776, "s": 26759, "text": "Java-Collections" }, { "code": null, "e": 26789, "s": 26776, "text": "Java-HashMap" }, { "code": null, "e": 26798, "s": 26789, "text": "java-map" }, { "code": null, "e": 26816, "s": 26798, "text": "Java-Map-Programs" }, { "code": null, "e": 26823, "s": 26816, "text": "Picked" }, { "code": null, "e": 26828, "s": 26823, "text": "Java" }, { "code": null, "e": 26833, "s": 26828, "text": "Java" }, { "code": null, "e": 26850, "s": 26833, "text": "Java-Collections" }, { "code": null, "e": 26948, "s": 26850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26957, "s": 26948, "text": "Comments" }, { "code": null, "e": 26970, "s": 26957, "text": "Old Comments" }, { "code": null, "e": 26989, "s": 26970, "text": "Interfaces in Java" }, { "code": null, "e": 27021, "s": 26989, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27039, "s": 27021, "text": "ArrayList in Java" }, { "code": null, "e": 27059, "s": 27039, "text": "Stack Class in Java" }, { "code": null, "e": 27091, "s": 27059, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27115, "s": 27091, "text": "Singleton Class in Java" }, { "code": null, "e": 27134, "s": 27115, "text": "LinkedList in Java" }, { "code": null, "e": 27154, "s": 27134, "text": "Collections in Java" }, { "code": null, "e": 27173, "s": 27154, "text": "Overriding in Java" } ]
Python read data from MySQL Database - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we’ll show how to read data from MySQL DB Python step by step. To set up the environment, we need to connect MySQL with Python, go through this tutorial to see how to connect MySQL using mysql connector. If you follow along with the tutorial link, we have connected everything and have code below in our IDE. # Importing the MySQL-Python-connector import mysql.connector as mysqlConnector # Creating connection with the MySQL Server Running conn = mysqlConnector.connect(host='localhost',user='root',passwd='root') # Checking if connection is made or not if conn: print("Connection Successful :)") else: print("Connection Failed :(") # Creating a cursor object to traverse the resultset cur = conn.cursor() cur.execute("SHOW DATABASES") for row in cur: print(row) # Closing the connection conn.close() Output: Connection Successful (‘information_schema’,) (‘mysql’,) (‘performance_schema’,) (‘sys’,) We can access the data using the SQL Select query which will return the result set according to the conditions specified. Let us access data from our table. import mysql.connector as mysqlConnector conn = mysqlConnector.connect(host='localhost',user='root',passwd='root',database='cse') if conn:print("Connection Successful :)") else:print("Connection Failed :(") cur = conn.cursor() try: cur.execute("select * from students") print("Query Executed Successfully !!!") for row in cur: print(row) except Exception as e: print("Invalid Query") print(e) conn.close() Output: Connection Successful :) Query Executed Successfully !!! (13, 'Kunal', 91001, 'a') (1, 'rahul', 91567, 'b') (10, 'shivam', 91223, 'a') (31, 'shivam', 91085, 'c') import mysql.connector as mysqlConnector conn = mysqlConnector.connect(host='localhost',user='root',passwd='root',database='cse') if conn:print("Connection Successful :)") else:print("Connection Failed :(") cur = conn.cursor() try: cur.execute("select * from students where name='shivam'") print("Query Executed Successfully !!!") for row in cur: print(row) except Exception as e: print("Invalid Query") print(e) conn.close() Output: Connection Successful :) Query Executed Successfully !!! (10, 'shivam', 91223, 'a') (31, 'shivam', 91085, 'c') Now that we have successfully learned how to retrieve the data from the tables. Python MySQL connector Python MySQL PIP Happy Learning 🙂 Python Insert data into MySQL Database Python MySQL create database and table Read an Image in JDBC Example How to Remove Spaces from String in Python How to Read CSV File in Python How to connect MySQL DB with Python Python How to read input from keyboard How to read a text file in Python ? How to read JSON file in Python ? Python raw_input read input from keyboard What are different Python Data Types Python List Data Structure In Depth Python Tuple Data Structure in Depth How to connect MySQL Database in Eclipse Spring Boot Security MySQL Database Integration Example Python Insert data into MySQL Database Python MySQL create database and table Read an Image in JDBC Example How to Remove Spaces from String in Python How to Read CSV File in Python How to connect MySQL DB with Python Python How to read input from keyboard How to read a text file in Python ? How to read JSON file in Python ? Python raw_input read input from keyboard What are different Python Data Types Python List Data Structure In Depth Python Tuple Data Structure in Depth How to connect MySQL Database in Eclipse Spring Boot Security MySQL Database Integration Example Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 479, "s": 398, "text": "In this tutorial, we’ll show how to read data from MySQL DB Python step by step." }, { "code": null, "e": 620, "s": 479, "text": "To set up the environment, we need to connect MySQL with Python, go through this tutorial to see how to connect MySQL using mysql connector." }, { "code": null, "e": 725, "s": 620, "text": "If you follow along with the tutorial link, we have connected everything and have code below in our IDE." }, { "code": null, "e": 1231, "s": 725, "text": "# Importing the MySQL-Python-connector\nimport mysql.connector as mysqlConnector\n# Creating connection with the MySQL Server Running \nconn = mysqlConnector.connect(host='localhost',user='root',passwd='root')\n# Checking if connection is made or not\nif conn:\n print(\"Connection Successful :)\")\nelse:\n print(\"Connection Failed :(\")\n# Creating a cursor object to traverse the resultset\ncur = conn.cursor()\ncur.execute(\"SHOW DATABASES\")\nfor row in cur:\n print(row)\n# Closing the connection\nconn.close()" }, { "code": null, "e": 1239, "s": 1231, "text": "Output:" }, { "code": null, "e": 1330, "s": 1239, "text": "Connection Successful \n(‘information_schema’,)\n(‘mysql’,)\n(‘performance_schema’,)\n(‘sys’,)" }, { "code": null, "e": 1487, "s": 1330, "text": "We can access the data using the SQL Select query which will return the result set according to the conditions specified. Let us access data from our table." }, { "code": null, "e": 1921, "s": 1487, "text": "import mysql.connector as mysqlConnector\nconn = mysqlConnector.connect(host='localhost',user='root',passwd='root',database='cse')\nif conn:print(\"Connection Successful :)\")\nelse:print(\"Connection Failed :(\")\ncur = conn.cursor()\ntry:\n cur.execute(\"select * from students\")\n print(\"Query Executed Successfully !!!\")\n for row in cur:\n print(row)\nexcept Exception as e:\n print(\"Invalid Query\")\n print(e)\nconn.close()" }, { "code": null, "e": 1929, "s": 1921, "text": "Output:" }, { "code": null, "e": 2091, "s": 1929, "text": "Connection Successful :)\nQuery Executed Successfully !!!\n(13, 'Kunal', 91001, 'a')\n(1, 'rahul', 91567, 'b')\n(10, 'shivam', 91223, 'a')\n(31, 'shivam', 91085, 'c')" }, { "code": null, "e": 2545, "s": 2091, "text": "import mysql.connector as mysqlConnector\nconn = mysqlConnector.connect(host='localhost',user='root',passwd='root',database='cse')\nif conn:print(\"Connection Successful :)\")\nelse:print(\"Connection Failed :(\")\ncur = conn.cursor()\ntry:\n cur.execute(\"select * from students where name='shivam'\")\n print(\"Query Executed Successfully !!!\")\n for row in cur:\n print(row)\nexcept Exception as e:\n print(\"Invalid Query\")\n print(e)\nconn.close()" }, { "code": null, "e": 2553, "s": 2545, "text": "Output:" }, { "code": null, "e": 2664, "s": 2553, "text": "Connection Successful :)\nQuery Executed Successfully !!!\n(10, 'shivam', 91223, 'a')\n(31, 'shivam', 91085, 'c')" }, { "code": null, "e": 2744, "s": 2664, "text": "Now that we have successfully learned how to retrieve the data from the tables." }, { "code": null, "e": 2767, "s": 2744, "text": "Python MySQL connector" }, { "code": null, "e": 2784, "s": 2767, "text": "Python MySQL PIP" }, { "code": null, "e": 2801, "s": 2784, "text": "Happy Learning 🙂" }, { "code": null, "e": 3379, "s": 2801, "text": "\nPython Insert data into MySQL Database\nPython MySQL create database and table\nRead an Image in JDBC Example\nHow to Remove Spaces from String in Python\nHow to Read CSV File in Python\nHow to connect MySQL DB with Python\nPython How to read input from keyboard\nHow to read a text file in Python ?\nHow to read JSON file in Python ?\nPython raw_input read input from keyboard\nWhat are different Python Data Types\nPython List Data Structure In Depth\nPython Tuple Data Structure in Depth\nHow to connect MySQL Database in Eclipse\nSpring Boot Security MySQL Database Integration Example\n" }, { "code": null, "e": 3418, "s": 3379, "text": "Python Insert data into MySQL Database" }, { "code": null, "e": 3457, "s": 3418, "text": "Python MySQL create database and table" }, { "code": null, "e": 3487, "s": 3457, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 3530, "s": 3487, "text": "How to Remove Spaces from String in Python" }, { "code": null, "e": 3561, "s": 3530, "text": "How to Read CSV File in Python" }, { "code": null, "e": 3597, "s": 3561, "text": "How to connect MySQL DB with Python" }, { "code": null, "e": 3636, "s": 3597, "text": "Python How to read input from keyboard" }, { "code": null, "e": 3672, "s": 3636, "text": "How to read a text file in Python ?" }, { "code": null, "e": 3706, "s": 3672, "text": "How to read JSON file in Python ?" }, { "code": null, "e": 3748, "s": 3706, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 3785, "s": 3748, "text": "What are different Python Data Types" }, { "code": null, "e": 3821, "s": 3785, "text": "Python List Data Structure In Depth" }, { "code": null, "e": 3858, "s": 3821, "text": "Python Tuple Data Structure in Depth" }, { "code": null, "e": 3899, "s": 3858, "text": "How to connect MySQL Database in Eclipse" }, { "code": null, "e": 3955, "s": 3899, "text": "Spring Boot Security MySQL Database Integration Example" }, { "code": null, "e": 3961, "s": 3959, "text": "Δ" }, { "code": null, "e": 3984, "s": 3961, "text": " Python – Introduction" }, { "code": null, "e": 4003, "s": 3984, "text": " Python – Features" }, { "code": null, "e": 4032, "s": 4003, "text": " Python – Install on Windows" }, { "code": null, "e": 4059, "s": 4032, "text": " Python – Modes of Program" }, { "code": null, "e": 4083, "s": 4059, "text": " Python – Number System" }, { "code": null, "e": 4105, "s": 4083, "text": " Python – Identifiers" }, { "code": null, "e": 4125, "s": 4105, "text": " Python – Operators" }, { "code": null, "e": 4152, "s": 4125, "text": " Python – Ternary Operator" }, { "code": null, "e": 4185, "s": 4152, "text": " Python – Command Line Arguments" }, { "code": null, "e": 4204, "s": 4185, "text": " Python – Keywords" }, { "code": null, "e": 4225, "s": 4204, "text": " Python – Data Types" }, { "code": null, "e": 4254, "s": 4225, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 4284, "s": 4254, "text": " Python – Virtual Environment" }, { "code": null, "e": 4307, "s": 4284, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4331, "s": 4307, "text": " Python – String to Int" }, { "code": null, "e": 4364, "s": 4331, "text": " Python – Conditional Statements" }, { "code": null, "e": 4387, "s": 4364, "text": " Python – if statement" }, { "code": null, "e": 4416, "s": 4387, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4442, "s": 4416, "text": " Python – Date Formatting" }, { "code": null, "e": 4477, "s": 4442, "text": " Python – Read input from keyboard" }, { "code": null, "e": 4497, "s": 4477, "text": " Python – raw_input" }, { "code": null, "e": 4521, "s": 4497, "text": " Python – List In Depth" }, { "code": null, "e": 4550, "s": 4521, "text": " Python – List Comprehension" }, { "code": null, "e": 4573, "s": 4550, "text": " Python – Set in Depth" }, { "code": null, "e": 4603, "s": 4573, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 4628, "s": 4603, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4658, "s": 4628, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4688, "s": 4658, "text": " Python – Classes and Objects" }, { "code": null, "e": 4711, "s": 4688, "text": " Python – Constructors" }, { "code": null, "e": 4742, "s": 4711, "text": " Python – Object Introspection" }, { "code": null, "e": 4764, "s": 4742, "text": " Python – Inheritance" }, { "code": null, "e": 4785, "s": 4764, "text": " Python – Decorators" }, { "code": null, "e": 4821, "s": 4785, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4851, "s": 4821, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4885, "s": 4851, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4911, "s": 4885, "text": " Python – Multiprocessing" }, { "code": null, "e": 4949, "s": 4911, "text": " Python – Default function parameters" }, { "code": null, "e": 4977, "s": 4949, "text": " Python – Lambdas Functions" }, { "code": null, "e": 5001, "s": 4977, "text": " Python – NumPy Library" }, { "code": null, "e": 5027, "s": 5001, "text": " Python – MySQL Connector" }, { "code": null, "e": 5059, "s": 5027, "text": " Python – MySQL Create Database" }, { "code": null, "e": 5085, "s": 5059, "text": " Python – MySQL Read Data" }, { "code": null, "e": 5113, "s": 5085, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 5144, "s": 5113, "text": " Python – MySQL Update Records" }, { "code": null, "e": 5175, "s": 5144, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 5208, "s": 5175, "text": " Python – String Case Conversion" }, { "code": null, "e": 5243, "s": 5208, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 5280, "s": 5243, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5318, "s": 5280, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5344, "s": 5318, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5369, "s": 5344, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5409, "s": 5369, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5444, "s": 5409, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5479, "s": 5444, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 5508, "s": 5479, "text": " Howto – Read Env variables" }, { "code": null, "e": 5534, "s": 5508, "text": " Howto – Read a text File" }, { "code": null, "e": 5560, "s": 5534, "text": " Howto – Read a JSON File" }, { "code": null, "e": 5592, "s": 5560, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 5620, "s": 5592, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5660, "s": 5620, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5694, "s": 5660, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5719, "s": 5694, "text": " Howto – create Zip File" }, { "code": null, "e": 5740, "s": 5719, "text": " Howto – Get OS info" }, { "code": null, "e": 5771, "s": 5740, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5808, "s": 5771, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5845, "s": 5808, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5867, "s": 5845, "text": " Howto – Sort Objects" }, { "code": null, "e": 5905, "s": 5867, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5928, "s": 5905, "text": " Howto – Read CSV File" }, { "code": null, "e": 5966, "s": 5928, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5997, "s": 5966, "text": " Howto – Access for loop index" }, { "code": null, "e": 6035, "s": 5997, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 6075, "s": 6035, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 6122, "s": 6075, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 6154, "s": 6122, "text": " Howto – Sort dictionary by key" } ]
Create a table inside a MySQL stored procedure and insert a record on calling the procedure
Create a table inside the stored procedure and use INSERT as well − mysql> DELIMITER // mysql> CREATE PROCEDURE create_TableDemo(id int,name varchar(100),age int) BEGIN CREATE TABLE DemoTable ( ClientId int NOT NULL, ClientName varchar(30), ClientAge int, PRIMARY KEY(ClientId) ); INSERT INTO DemoTable VALUES(id,name,age); SELECT *FROM DemoTable; END // Query OK, 0 rows affected (0.17 sec) mysql> DELIMITER ; Call the stored procedure using CALL command − mysql> CALL create_TableDemo(100,'Robert',28); This will produce the following output − +----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 100 | Robert | 28 | +----------+------------+-----------+ 1 row in set (0.76 sec) Query OK, 0 rows affected (0.78 sec)
[ { "code": null, "e": 1130, "s": 1062, "text": "Create a table inside the stored procedure and use INSERT as well −" }, { "code": null, "e": 1518, "s": 1130, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE create_TableDemo(id int,name varchar(100),age int)\n BEGIN\n CREATE TABLE DemoTable\n (\n ClientId int NOT NULL,\n ClientName varchar(30),\n ClientAge int,\n PRIMARY KEY(ClientId)\n );\n INSERT INTO DemoTable VALUES(id,name,age);\n SELECT *FROM DemoTable;\n END\n//\nQuery OK, 0 rows affected (0.17 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1565, "s": 1518, "text": "Call the stored procedure using CALL command −" }, { "code": null, "e": 1612, "s": 1565, "text": "mysql> CALL create_TableDemo(100,'Robert',28);" }, { "code": null, "e": 1653, "s": 1612, "text": "This will produce the following output −" }, { "code": null, "e": 1904, "s": 1653, "text": "+----------+------------+-----------+\n| ClientId | ClientName | ClientAge |\n+----------+------------+-----------+\n| 100 | Robert | 28 |\n+----------+------------+-----------+\n1 row in set (0.76 sec)\nQuery OK, 0 rows affected (0.78 sec)" } ]
File Permissions in Java - GeeksforGeeks
22 Apr, 2022 Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file. For example, file permission can be changed from write to read-only because the user no longer wants to edit the file. A file can be in any combination of the following permissible permissions depicted by methods below in tabular format/ Implementation: A file can be readable and writable but not executable. Here’s a Java program to get the current permissions associated with a file. Example: Java // Java Program to Check the Current File Permissions // Importing required classesimport java.io.*; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating a file by // creating object of File class File file = new File("C:\\Users\\Mayank\\Desktop\\1.txt"); // Checking if the file exists // using exists() method of File class boolean exists = file.exists(); if (exists == true) { // Printing the permissions associated // with the file System.out.println("Executable: " + file.canExecute()); System.out.println("Readable: " + file.canRead()); System.out.println("Writable: " + file.canWrite()); } // If we enter else it means // file does not exists else { System.out.println("File not found."); } }} Output: A file in Java can have any combination of the following permissions: Executable Readable Writable Here are methods to change the permissions associated with a file as depicted in a tabular format below as follows: Note: setReadable() Operation will fail if the user does not have permission to change the access permissions of this abstract path name. If readable is false and the underlying file system does not implement a read permission, then the operation will fail. setWritable() Operation will fail if the user does not have permission to change the access permissions of this abstract pathname. Example: Java // Java Program to Change File Permissions // Importing required classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a new file by // creating object of File class where // local directory is passed as in argument File file = new File("C:\\Users\\Mayank\\Desktop\\1.txt"); // Checking if file exists boolean exists = file.exists(); if (exists == true) { // Changing the file permissions file.setExecutable(true); file.setReadable(true); file.setWritable(false); System.out.println("File permissions changed."); // Printing the permissions associated with the // file currently System.out.println("Executable: " + file.canExecute()); System.out.println("Readable: " + file.canRead()); System.out.println("Writable: " + file.canWrite()); } // If we reach here, file is not found else { System.out.println("File not found"); } }} Output: This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi solankimayank simmytarika5 surinderdawra388 java-file-handling Java-I/O Java-Library Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 27876, "s": 27848, "text": "\n22 Apr, 2022" }, { "code": null, "e": 28265, "s": 27876, "text": "Java provides a number of method calls to check and change the permission of a file, such as a read-only file can be changed to have permissions to write. File permissions are required to be changed when the user wants to restrict the operations permissible on a file. For example, file permission can be changed from write to read-only because the user no longer wants to edit the file. " }, { "code": null, "e": 28384, "s": 28265, "text": "A file can be in any combination of the following permissible permissions depicted by methods below in tabular format/" }, { "code": null, "e": 28533, "s": 28384, "text": "Implementation: A file can be readable and writable but not executable. Here’s a Java program to get the current permissions associated with a file." }, { "code": null, "e": 28542, "s": 28533, "text": "Example:" }, { "code": null, "e": 28547, "s": 28542, "text": "Java" }, { "code": "// Java Program to Check the Current File Permissions // Importing required classesimport java.io.*; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating a file by // creating object of File class File file = new File(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\1.txt\"); // Checking if the file exists // using exists() method of File class boolean exists = file.exists(); if (exists == true) { // Printing the permissions associated // with the file System.out.println(\"Executable: \" + file.canExecute()); System.out.println(\"Readable: \" + file.canRead()); System.out.println(\"Writable: \" + file.canWrite()); } // If we enter else it means // file does not exists else { System.out.println(\"File not found.\"); } }}", "e": 29571, "s": 28547, "text": null }, { "code": null, "e": 29579, "s": 29571, "text": "Output:" }, { "code": null, "e": 29650, "s": 29579, "text": "A file in Java can have any combination of the following permissions: " }, { "code": null, "e": 29661, "s": 29650, "text": "Executable" }, { "code": null, "e": 29670, "s": 29661, "text": "Readable" }, { "code": null, "e": 29679, "s": 29670, "text": "Writable" }, { "code": null, "e": 29795, "s": 29679, "text": "Here are methods to change the permissions associated with a file as depicted in a tabular format below as follows:" }, { "code": null, "e": 29801, "s": 29795, "text": "Note:" }, { "code": null, "e": 30053, "s": 29801, "text": "setReadable() Operation will fail if the user does not have permission to change the access permissions of this abstract path name. If readable is false and the underlying file system does not implement a read permission, then the operation will fail." }, { "code": null, "e": 30184, "s": 30053, "text": "setWritable() Operation will fail if the user does not have permission to change the access permissions of this abstract pathname." }, { "code": null, "e": 30194, "s": 30184, "text": " Example:" }, { "code": null, "e": 30199, "s": 30194, "text": "Java" }, { "code": "// Java Program to Change File Permissions // Importing required classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a new file by // creating object of File class where // local directory is passed as in argument File file = new File(\"C:\\\\Users\\\\Mayank\\\\Desktop\\\\1.txt\"); // Checking if file exists boolean exists = file.exists(); if (exists == true) { // Changing the file permissions file.setExecutable(true); file.setReadable(true); file.setWritable(false); System.out.println(\"File permissions changed.\"); // Printing the permissions associated with the // file currently System.out.println(\"Executable: \" + file.canExecute()); System.out.println(\"Readable: \" + file.canRead()); System.out.println(\"Writable: \" + file.canWrite()); } // If we reach here, file is not found else { System.out.println(\"File not found\"); } }}", "e": 31422, "s": 30199, "text": null }, { "code": null, "e": 31430, "s": 31422, "text": "Output:" }, { "code": null, "e": 31851, "s": 31430, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31867, "s": 31851, "text": "nishkarshgandhi" }, { "code": null, "e": 31881, "s": 31867, "text": "solankimayank" }, { "code": null, "e": 31894, "s": 31881, "text": "simmytarika5" }, { "code": null, "e": 31911, "s": 31894, "text": "surinderdawra388" }, { "code": null, "e": 31930, "s": 31911, "text": "java-file-handling" }, { "code": null, "e": 31939, "s": 31930, "text": "Java-I/O" }, { "code": null, "e": 31952, "s": 31939, "text": "Java-Library" }, { "code": null, "e": 31957, "s": 31952, "text": "Java" }, { "code": null, "e": 31976, "s": 31957, "text": "School Programming" }, { "code": null, "e": 31981, "s": 31976, "text": "Java" }, { "code": null, "e": 32079, "s": 31981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32123, "s": 32079, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32159, "s": 32123, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32184, "s": 32159, "text": "Reverse a string in Java" }, { "code": null, "e": 32216, "s": 32184, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32267, "s": 32216, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32285, "s": 32267, "text": "Python Dictionary" }, { "code": null, "e": 32301, "s": 32285, "text": "Arrays in C/C++" }, { "code": null, "e": 32320, "s": 32301, "text": "Inheritance in C++" }, { "code": null, "e": 32345, "s": 32320, "text": "Reverse a string in Java" } ]
k size subsets with maximum difference d between max and min - GeeksforGeeks
25 Aug, 2021 C++ // C++ code to find no. of subsets with// maximum difference d between max and#include <bits/stdc++.h>using namespace std; // function to calculate factorial of a numbint fact(int i){ if (i == 0) return 1; return i * fact(i - 1);} int ans(int a[], int n, int k, int x){ if (k > n || n < 1) return 0; sort(a, a + n); int count = 0; int j = 1; int i = 0; int kfactorial = fact(k); while (j <= n) { while (j < n && a[j] - a[i] <= x) { j++; } if ((j - i) >= k) { count = count + fact(j - i) / (kfactorial * fact(j - i - k)); } else { i++; j++; continue; } if (j == n) break; while (i < j && a[j] - a[i] > x) { i++; } if ((j - i) >= k) { count = count - fact(j - i) / (kfactorial * fact(j - i - k)); } } return count;} // driver program to test the above// functionint main(){ int arr[] = { 1, 12, 9, 2, 4, 2, 5, 8, 4, 6 }, k = 3,x = 5; int n = sizeof(arr) / sizeof(arr[0]); cout << ans(arr, n, k, x); return 0;}// This code is contributed by Vishakha Chauhan 52 Given an array and two integers k and d, find the number of subsets of this array of size k, where difference between the maximum and minimum number of the subset is atmost d.Examples: Input : a[] = [5, 4, 2, 1, 3], k = 3, d = 5 Output : 10 Explanation: {1,2,3}, {1,2,4}, {1,2,5}, {1,3,4}, {1,3,5}, {1,4,5}, {2,3,4}, {2,3,5}, {2,4,5}, {3,4,5}. We can see each subset has atmost difference d=5 between the minimum and maximum element of each subset. No of such subsets = 10 Input : a[] = [1, 2, 3, 4, 5, 6], k = 3, d = 5 Output : 20 Naive approach: Finding all the subsets of size k and for each subset find the difference between maximum and minimum element. If the difference is less than or equal to d, count them. Efficient approach : 1) Sorting: First sort the array in increasing order. Now, assume we want to find out for each ith element, the number of required subsets in which integer a[i] is present as the minimum element of that subset. The maximum in such a subset will never exceed a[i] + d . 2) Find maximum index j : We can apply binary search over this array for each i, to find the maximum index j, such that a[j] <= a[i]+d . Now any subset that includes a[i] and any other elements from the range i+1...j will be a required subset as because element a[i] is the minimum of that subset, and the difference between any other element and a[i] is always less than equal to d. 3) Apply basic combinatorics formula : Now we want to find the number of required subsets of size k. This will be by using the basic formula of combination when you have to select r items from given n numbers. In the same way we need to choose (k-1) numbers from (j-i) elements already including a[i] which is the minimum number in each subset. The sum of this procedure for each ith element will be the final answer. Here I have used a simple recursive way to find factorial of a number one can use dynamic programming as well to find it. Illustration : Input : a = [5, 4, 2, 1, 3], k = 3, d = 5 Output : 10 Explanation: Sorted array in ascending order : [1, 2, 3, 4, 5]For a[0] = 1 as minimum element No. of subset will be 6 which are {1, 2, 3}, {1, 2, 4}, {1, 2, 5}, {1, 3, 4}, {1, 3, 5}, {1, 4, 5}.For a[1] = 2 as minimum element No. of subset will be 3 which are {2, 3, 4}, {2, 3, 5}, {2, 4, 5}For a[2] = 3 as minimum element No. of subset will be 1 which is {3, 4, 5} No other subset of size k = 3 will be formed by taking a[3] = 4 or a[4] = 5 as minimum element C++ Java Python C# PHP Javascript // C++ code to find no. of subsets with// maximum difference d between max and// min of all K-size subsets function to// calculate factorial of a number#include <bits/stdc++.h>using namespace std; int fact (int n){ if (n==0) return 1; else return n * fact(n-1);} // function to count ways to select r// numbers from n given numbersint findcombination (int n,int r){ return( fact(n) / (fact(n - r) * fact(r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kint find(int arr[], int n, int d, int k){ sort(arr,arr+n); int ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the position // which will be stored in start start = i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid + 1; } if (start != n and arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' // is greater or equal to the given // size k, then only subsets of // required size k can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above// functionint main(){ int arr[] = {1, 2, 3, 4, 5, 6}, k = 3, d = 5; int n = sizeof(arr) / sizeof(arr[0]); cout << find(arr, n,d,k); return 0;}// This code is contributed by Prerna Saini // Java code to find no. of subsets// with maximum difference d between// max and min of all K-size subsetsimport java.util.*; class GFG { // function to calculate factorial// of a numberstatic int fact (int n){ if (n==0) return 1; else return n * fact(n-1);} // function to count ways to select r// numbers from n given numbersstatic int findcombination(int n, int r){ return( fact(n) / (fact(n - r) * fact(r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kstatic int find(int arr[], int n, int d, int k){ Arrays.sort(arr); int ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the position // which will be stored in start start=i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above functionpublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5, 6}, k = 3, d = 5; int n = arr.length; System.out.println(find(arr, n,d,k));}}// This code is contributed by Prerna Saini # Python code to find no. of subsets with maximum# difference d between max and min of all K-size# subsets function to calculate factorial of a# numberdef fact (n): if (n==0): return (1) else: return n * fact(n-1) # function to count ways to select r numbers# from n given numbersdef findcombination (n,r): return( fact(n)//(fact(n-r)*fact(r))) # function to return the total number of required# subsets :# n is the number of elements in list l[0..n-1]# d is the maximum difference between minimum and# maximum element in each subset of size k def find (a, n, d, k): # sort the list first in ascending order a.sort() (start, end, co) = (0, n, 0) for i in range(0, n): val = a[i]+ d # binary search to get the position # which will be stored in start # such that a[start] <= a[i]+d start = i while (start< end-1): mid = (start+end)//2 # if mid value greater than a[i]+d # do search in l[start:mid] if (a[mid] > val): end = mid # if mid value less or equal to a[i]+d # do search in a[mid+1:end] else: start = mid+1 if (start!=n and a[start]<=val): start += 1 # count the numbers of elements that fall # in range i to start c = start-i # if the numbers of elements 'c' is greater # or equal to the given size k, then only # subsets of required size k can be formed if (c >= k): co += findcombination(c-1,k-1) return co # Driver coden = 6 # Number of elementsd = 5 # maximum diffk = 3 # Size of subsetsprint(find([1, 2, 3, 4, 5, 6], n, d, k)) // C# code to find no. of subsets// with maximum difference d between// max and min of all K-size subsetsusing System; class GFG { // function to calculate factorial // of a number static int fact (int n) { if (n == 0) return 1; else return n * fact(n - 1); } // function to count ways to select r // numbers from n given numbers static int findcombination(int n, int r) { return( fact(n) / (fact(n - r) * fact(r))); } // function to return the total number // of required subsets : // n is the number of elements in array // d is the maximum difference between // minimum and maximum element in each // subset of size k static int find(int []arr, int n, int d, int k) { Array.Sort(arr); //int ans = 0, int end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the // position which will be // stored in start start = i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k) co += findcombination(c - 1, k - 1); } return co; } // driver program to test the above function public static void Main() { int []arr = {1, 2, 3, 4, 5, 6}; int k = 3; int d = 5; int n = arr.Length; Console.WriteLine(find(arr, n, d, k)); }} // This code is contributed by anuj_67. <?php // Php code to find no. of subsets with// maximum difference d between max and// min of all K-size subsets function to// calculate factorial of a number function fact ($n){ if ($n==0) return 1; else return $n * fact($n-1);} // function to count ways to select r// numbers from n given numbersfunction findcombination ($n,$r){ return( fact($n) / (fact($n - $r) * fact($r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kfunction find(&$arr, $n, $d, $k){ sort($arr); $ans = 0; $end = $n; $co = 0; $start = 0; // loop to traverse from 0-n for ($i = 0; $i < $n; $i++) { $val = $arr[$i] + $d; // binary search to get the position // which will be stored in start $start = $i; while ($start < $end - 1){ $mid = intval (($start + $end) / 2); // if mid value greater than // arr[i]+d do search in // arr[start:mid] if ($arr[$mid] > $val) $end = $mid; else $start = $mid + 1; } if ($start != $n && $arr[$start] <= $val) $start += 1; $c = $start-$i; // if the numbers of elements 'c' // is greater or equal to the given // size k, then only subsets of // required size k can be formed if ($c >= $k){ $co += findcombination($c - 1, $k - 1);} } return $co;} // driver program to test the above// function $arr = array(1, 2, 3, 4, 5, 6); $k = 3; $d = 5; $n = sizeof($arr) / sizeof($arr[0]); echo find($arr, $n,$d,$k); return 0;?> <script>// Javascript code to find no. of subsets// with maximum difference d between// max and min of all K-size subsets // function to calculate factorial // of a number function fact(n) { let answer=1; if (n == 0 || n == 1) { return answer;} else { for(var i = n; i >= 1; i--){ answer = answer * i; } return answer; } } // function to count ways to select r// numbers from n given numbersfunction findcombination(n,r){ return( Math.floor(fact(n) / (fact(n - r) * fact(r))));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kfunction find(arr, n, d, k){ arr.sort(function(a, b){return a-b;}); let ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (let i = 0; i < n; i++) { let val = arr[i] + d; // binary search to get the position // which will be stored in start start=i; while (start < end - 1){ let mid = Math.floor((start + end) / 2); // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; let c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above functionlet arr = [1, 2, 3, 4, 5, 6];let k = 3, d = 5;let n = arr.length;document.write(find(arr, n, d, k)); // This code is contributed by rag2127.</script> 20 Output: 20 This article is contributed by Sruti Rai . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m ukasp Akanksha_Rai rag2127 vishakhachauhan58 subset Arrays Arrays subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Find subarray with given sum | Set 1 (Nonnegative Numbers) Building Heap from Array Remove duplicates from sorted array Sliding Window Maximum (Maximum of all subarrays of size k) Move all negative numbers to beginning and positive to end with constant extra space
[ { "code": null, "e": 24431, "s": 24403, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24435, "s": 24431, "text": "C++" }, { "code": "// C++ code to find no. of subsets with// maximum difference d between max and#include <bits/stdc++.h>using namespace std; // function to calculate factorial of a numbint fact(int i){ if (i == 0) return 1; return i * fact(i - 1);} int ans(int a[], int n, int k, int x){ if (k > n || n < 1) return 0; sort(a, a + n); int count = 0; int j = 1; int i = 0; int kfactorial = fact(k); while (j <= n) { while (j < n && a[j] - a[i] <= x) { j++; } if ((j - i) >= k) { count = count + fact(j - i) / (kfactorial * fact(j - i - k)); } else { i++; j++; continue; } if (j == n) break; while (i < j && a[j] - a[i] > x) { i++; } if ((j - i) >= k) { count = count - fact(j - i) / (kfactorial * fact(j - i - k)); } } return count;} // driver program to test the above// functionint main(){ int arr[] = { 1, 12, 9, 2, 4, 2, 5, 8, 4, 6 }, k = 3,x = 5; int n = sizeof(arr) / sizeof(arr[0]); cout << ans(arr, n, k, x); return 0;}// This code is contributed by Vishakha Chauhan", "e": 25708, "s": 24435, "text": null }, { "code": null, "e": 25711, "s": 25708, "text": "52" }, { "code": null, "e": 25898, "s": 25711, "text": "Given an array and two integers k and d, find the number of subsets of this array of size k, where difference between the maximum and minimum number of the subset is atmost d.Examples: " }, { "code": null, "e": 26267, "s": 25898, "text": "Input : a[] = [5, 4, 2, 1, 3],\n k = 3, d = 5 \nOutput : 10\nExplanation:\n{1,2,3}, {1,2,4}, {1,2,5}, {1,3,4}, {1,3,5}, \n{1,4,5}, {2,3,4}, {2,3,5}, {2,4,5}, {3,4,5}.\nWe can see each subset has atmost \ndifference d=5 between the minimum\nand maximum element of each subset.\nNo of such subsets = 10 \n\nInput : a[] = [1, 2, 3, 4, 5, 6],\n k = 3, d = 5 \nOutput : 20" }, { "code": null, "e": 27669, "s": 26269, "text": "Naive approach: Finding all the subsets of size k and for each subset find the difference between maximum and minimum element. If the difference is less than or equal to d, count them. Efficient approach : 1) Sorting: First sort the array in increasing order. Now, assume we want to find out for each ith element, the number of required subsets in which integer a[i] is present as the minimum element of that subset. The maximum in such a subset will never exceed a[i] + d . 2) Find maximum index j : We can apply binary search over this array for each i, to find the maximum index j, such that a[j] <= a[i]+d . Now any subset that includes a[i] and any other elements from the range i+1...j will be a required subset as because element a[i] is the minimum of that subset, and the difference between any other element and a[i] is always less than equal to d. 3) Apply basic combinatorics formula : Now we want to find the number of required subsets of size k. This will be by using the basic formula of combination when you have to select r items from given n numbers. In the same way we need to choose (k-1) numbers from (j-i) elements already including a[i] which is the minimum number in each subset. The sum of this procedure for each ith element will be the final answer. Here I have used a simple recursive way to find factorial of a number one can use dynamic programming as well to find it. " }, { "code": null, "e": 28198, "s": 27669, "text": "Illustration : Input : a = [5, 4, 2, 1, 3], k = 3, d = 5 Output : 10 Explanation: Sorted array in ascending order : [1, 2, 3, 4, 5]For a[0] = 1 as minimum element No. of subset will be 6 which are {1, 2, 3}, {1, 2, 4}, {1, 2, 5}, {1, 3, 4}, {1, 3, 5}, {1, 4, 5}.For a[1] = 2 as minimum element No. of subset will be 3 which are {2, 3, 4}, {2, 3, 5}, {2, 4, 5}For a[2] = 3 as minimum element No. of subset will be 1 which is {3, 4, 5} No other subset of size k = 3 will be formed by taking a[3] = 4 or a[4] = 5 as minimum element" }, { "code": null, "e": 28204, "s": 28200, "text": "C++" }, { "code": null, "e": 28209, "s": 28204, "text": "Java" }, { "code": null, "e": 28216, "s": 28209, "text": "Python" }, { "code": null, "e": 28219, "s": 28216, "text": "C#" }, { "code": null, "e": 28223, "s": 28219, "text": "PHP" }, { "code": null, "e": 28234, "s": 28223, "text": "Javascript" }, { "code": "// C++ code to find no. of subsets with// maximum difference d between max and// min of all K-size subsets function to// calculate factorial of a number#include <bits/stdc++.h>using namespace std; int fact (int n){ if (n==0) return 1; else return n * fact(n-1);} // function to count ways to select r// numbers from n given numbersint findcombination (int n,int r){ return( fact(n) / (fact(n - r) * fact(r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kint find(int arr[], int n, int d, int k){ sort(arr,arr+n); int ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the position // which will be stored in start start = i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid + 1; } if (start != n and arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' // is greater or equal to the given // size k, then only subsets of // required size k can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above// functionint main(){ int arr[] = {1, 2, 3, 4, 5, 6}, k = 3, d = 5; int n = sizeof(arr) / sizeof(arr[0]); cout << find(arr, n,d,k); return 0;}// This code is contributed by Prerna Saini", "e": 30027, "s": 28234, "text": null }, { "code": "// Java code to find no. of subsets// with maximum difference d between// max and min of all K-size subsetsimport java.util.*; class GFG { // function to calculate factorial// of a numberstatic int fact (int n){ if (n==0) return 1; else return n * fact(n-1);} // function to count ways to select r// numbers from n given numbersstatic int findcombination(int n, int r){ return( fact(n) / (fact(n - r) * fact(r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kstatic int find(int arr[], int n, int d, int k){ Arrays.sort(arr); int ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the position // which will be stored in start start=i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above functionpublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5, 6}, k = 3, d = 5; int n = arr.length; System.out.println(find(arr, n,d,k));}}// This code is contributed by Prerna Saini", "e": 31853, "s": 30027, "text": null }, { "code": "# Python code to find no. of subsets with maximum# difference d between max and min of all K-size# subsets function to calculate factorial of a# numberdef fact (n): if (n==0): return (1) else: return n * fact(n-1) # function to count ways to select r numbers# from n given numbersdef findcombination (n,r): return( fact(n)//(fact(n-r)*fact(r))) # function to return the total number of required# subsets :# n is the number of elements in list l[0..n-1]# d is the maximum difference between minimum and# maximum element in each subset of size k def find (a, n, d, k): # sort the list first in ascending order a.sort() (start, end, co) = (0, n, 0) for i in range(0, n): val = a[i]+ d # binary search to get the position # which will be stored in start # such that a[start] <= a[i]+d start = i while (start< end-1): mid = (start+end)//2 # if mid value greater than a[i]+d # do search in l[start:mid] if (a[mid] > val): end = mid # if mid value less or equal to a[i]+d # do search in a[mid+1:end] else: start = mid+1 if (start!=n and a[start]<=val): start += 1 # count the numbers of elements that fall # in range i to start c = start-i # if the numbers of elements 'c' is greater # or equal to the given size k, then only # subsets of required size k can be formed if (c >= k): co += findcombination(c-1,k-1) return co # Driver coden = 6 # Number of elementsd = 5 # maximum diffk = 3 # Size of subsetsprint(find([1, 2, 3, 4, 5, 6], n, d, k)) ", "e": 33575, "s": 31853, "text": null }, { "code": "// C# code to find no. of subsets// with maximum difference d between// max and min of all K-size subsetsusing System; class GFG { // function to calculate factorial // of a number static int fact (int n) { if (n == 0) return 1; else return n * fact(n - 1); } // function to count ways to select r // numbers from n given numbers static int findcombination(int n, int r) { return( fact(n) / (fact(n - r) * fact(r))); } // function to return the total number // of required subsets : // n is the number of elements in array // d is the maximum difference between // minimum and maximum element in each // subset of size k static int find(int []arr, int n, int d, int k) { Array.Sort(arr); //int ans = 0, int end = n, co = 0, start = 0; // loop to traverse from 0-n for (int i = 0; i < n; i++) { int val = arr[i] + d; // binary search to get the // position which will be // stored in start start = i; while (start < end - 1){ int mid = (start + end) / 2; // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; int c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k) co += findcombination(c - 1, k - 1); } return co; } // driver program to test the above function public static void Main() { int []arr = {1, 2, 3, 4, 5, 6}; int k = 3; int d = 5; int n = arr.Length; Console.WriteLine(find(arr, n, d, k)); }} // This code is contributed by anuj_67.", "e": 35848, "s": 33575, "text": null }, { "code": "<?php // Php code to find no. of subsets with// maximum difference d between max and// min of all K-size subsets function to// calculate factorial of a number function fact ($n){ if ($n==0) return 1; else return $n * fact($n-1);} // function to count ways to select r// numbers from n given numbersfunction findcombination ($n,$r){ return( fact($n) / (fact($n - $r) * fact($r)));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kfunction find(&$arr, $n, $d, $k){ sort($arr); $ans = 0; $end = $n; $co = 0; $start = 0; // loop to traverse from 0-n for ($i = 0; $i < $n; $i++) { $val = $arr[$i] + $d; // binary search to get the position // which will be stored in start $start = $i; while ($start < $end - 1){ $mid = intval (($start + $end) / 2); // if mid value greater than // arr[i]+d do search in // arr[start:mid] if ($arr[$mid] > $val) $end = $mid; else $start = $mid + 1; } if ($start != $n && $arr[$start] <= $val) $start += 1; $c = $start-$i; // if the numbers of elements 'c' // is greater or equal to the given // size k, then only subsets of // required size k can be formed if ($c >= $k){ $co += findcombination($c - 1, $k - 1);} } return $co;} // driver program to test the above// function $arr = array(1, 2, 3, 4, 5, 6); $k = 3; $d = 5; $n = sizeof($arr) / sizeof($arr[0]); echo find($arr, $n,$d,$k); return 0;?>", "e": 37592, "s": 35848, "text": null }, { "code": "<script>// Javascript code to find no. of subsets// with maximum difference d between// max and min of all K-size subsets // function to calculate factorial // of a number function fact(n) { let answer=1; if (n == 0 || n == 1) { return answer;} else { for(var i = n; i >= 1; i--){ answer = answer * i; } return answer; } } // function to count ways to select r// numbers from n given numbersfunction findcombination(n,r){ return( Math.floor(fact(n) / (fact(n - r) * fact(r))));} // function to return the total number// of required subsets :// n is the number of elements in array// d is the maximum difference between// minimum and maximum element in each// subset of size kfunction find(arr, n, d, k){ arr.sort(function(a, b){return a-b;}); let ans = 0, end = n, co = 0, start = 0; // loop to traverse from 0-n for (let i = 0; i < n; i++) { let val = arr[i] + d; // binary search to get the position // which will be stored in start start=i; while (start < end - 1){ let mid = Math.floor((start + end) / 2); // if mid value greater than // arr[i]+d do search in // arr[start:mid] if (arr[mid] > val) end = mid; else start = mid+1; } if (start !=n && arr[start] <= val) start += 1; let c = start-i; // if the numbers of elements 'c' is // greater or equal to the given size k, // then only subsets of required size k // can be formed if (c >= k){ co += findcombination(c - 1, k - 1);} } return co;} // driver program to test the above functionlet arr = [1, 2, 3, 4, 5, 6];let k = 3, d = 5;let n = arr.length;document.write(find(arr, n, d, k)); // This code is contributed by rag2127.</script>", "e": 39531, "s": 37592, "text": null }, { "code": null, "e": 39534, "s": 39531, "text": "20" }, { "code": null, "e": 39544, "s": 39534, "text": "Output: " }, { "code": null, "e": 39547, "s": 39544, "text": "20" }, { "code": null, "e": 39966, "s": 39547, "text": "This article is contributed by Sruti Rai . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39971, "s": 39966, "text": "vt_m" }, { "code": null, "e": 39977, "s": 39971, "text": "ukasp" }, { "code": null, "e": 39990, "s": 39977, "text": "Akanksha_Rai" }, { "code": null, "e": 39998, "s": 39990, "text": "rag2127" }, { "code": null, "e": 40016, "s": 39998, "text": "vishakhachauhan58" }, { "code": null, "e": 40023, "s": 40016, "text": "subset" }, { "code": null, "e": 40030, "s": 40023, "text": "Arrays" }, { "code": null, "e": 40037, "s": 40030, "text": "Arrays" }, { "code": null, "e": 40044, "s": 40037, "text": "subset" }, { "code": null, "e": 40142, "s": 40044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40151, "s": 40142, "text": "Comments" }, { "code": null, "e": 40164, "s": 40151, "text": "Old Comments" }, { "code": null, "e": 40185, "s": 40164, "text": "Next Greater Element" }, { "code": null, "e": 40210, "s": 40185, "text": "Window Sliding Technique" }, { "code": null, "e": 40237, "s": 40210, "text": "Count pairs with given sum" }, { "code": null, "e": 40286, "s": 40237, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 40324, "s": 40286, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 40383, "s": 40324, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 40408, "s": 40383, "text": "Building Heap from Array" }, { "code": null, "e": 40444, "s": 40408, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 40504, "s": 40444, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" } ]
Python | Convert String ranges to list - GeeksforGeeks
26 Nov, 2019 Sometimes, while working in applications we can have a problem in which we are given a naive string which provides ranges separated by a hyphen and other numbers separated by commas. This problem can occur across many places. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using sum() + split() + list comprehension + enumerate()The combination of above functions can be used to perform these tasks. In this, the split is performed on hyphen and comma and accordingly range, numbers are extracted and compiled into a list. # Python3 code to demonstrate working of# Convert String ranges to list# Using sum() + list comprehension + enumerate() + split() # initializing string test_str = "1, 4-6, 8-10, 11" # printing original string print("The original string is : " + test_str) # Convert String ranges to list# Using sum() + list comprehension + enumerate() + split()res = sum(((list(range(*[int(b) + c for c, b in enumerate(a.split('-'))])) if '-' in a else [int(a)]) for a in test_str.split(', ')), []) # printing resultprint("List after conversion from string : " + str(res)) The original string is : 1, 4-6, 8-10, 11 List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11] Method #2 : Using map() + split() + lambdaThis task can also be performed using above functions. Similar to method above. The only difference is that we use map() and lambda function to reduce complex readability. Works only with Python2. # Python2 code to demonstrate working of# Convert String ranges to list# Using map() + lambda + split() # initializing string test_str = "1, 4-6, 8-10, 11" # printing original string print("The original string is : " + test_str) # Convert String ranges to list# Using map() + lambda + split()temp = [(lambda sub: range(sub[0], sub[-1] + 1))(map(int, ele.split('-')))\ for ele in test_str.split(', ')] res = [b for a in temp for b in a] # printing resultprint("List after conversion from string : " + str(res)) The original string is : 1, 4-6, 8-10, 11 List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 23901, "s": 23873, "text": "\n26 Nov, 2019" }, { "code": null, "e": 24191, "s": 23901, "text": "Sometimes, while working in applications we can have a problem in which we are given a naive string which provides ranges separated by a hyphen and other numbers separated by commas. This problem can occur across many places. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 24453, "s": 24191, "text": "Method #1 : Using sum() + split() + list comprehension + enumerate()The combination of above functions can be used to perform these tasks. In this, the split is performed on hyphen and comma and accordingly range, numbers are extracted and compiled into a list." }, { "code": "# Python3 code to demonstrate working of# Convert String ranges to list# Using sum() + list comprehension + enumerate() + split() # initializing string test_str = \"1, 4-6, 8-10, 11\" # printing original string print(\"The original string is : \" + test_str) # Convert String ranges to list# Using sum() + list comprehension + enumerate() + split()res = sum(((list(range(*[int(b) + c for c, b in enumerate(a.split('-'))])) if '-' in a else [int(a)]) for a in test_str.split(', ')), []) # printing resultprint(\"List after conversion from string : \" + str(res))", "e": 25034, "s": 24453, "text": null }, { "code": null, "e": 25140, "s": 25034, "text": "The original string is : 1, 4-6, 8-10, 11\nList after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]\n" }, { "code": null, "e": 25381, "s": 25142, "text": "Method #2 : Using map() + split() + lambdaThis task can also be performed using above functions. Similar to method above. The only difference is that we use map() and lambda function to reduce complex readability. Works only with Python2." }, { "code": "# Python2 code to demonstrate working of# Convert String ranges to list# Using map() + lambda + split() # initializing string test_str = \"1, 4-6, 8-10, 11\" # printing original string print(\"The original string is : \" + test_str) # Convert String ranges to list# Using map() + lambda + split()temp = [(lambda sub: range(sub[0], sub[-1] + 1))(map(int, ele.split('-')))\\ for ele in test_str.split(', ')] res = [b for a in temp for b in a] # printing resultprint(\"List after conversion from string : \" + str(res))", "e": 25903, "s": 25381, "text": null }, { "code": null, "e": 26009, "s": 25903, "text": "The original string is : 1, 4-6, 8-10, 11\nList after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]\n" }, { "code": null, "e": 26032, "s": 26009, "text": "Python string-programs" }, { "code": null, "e": 26039, "s": 26032, "text": "Python" }, { "code": null, "e": 26055, "s": 26039, "text": "Python Programs" }, { "code": null, "e": 26153, "s": 26055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26162, "s": 26153, "text": "Comments" }, { "code": null, "e": 26175, "s": 26162, "text": "Old Comments" }, { "code": null, "e": 26207, "s": 26175, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26263, "s": 26207, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26305, "s": 26263, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26347, "s": 26305, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26383, "s": 26347, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26405, "s": 26383, "text": "Defaultdict in Python" }, { "code": null, "e": 26444, "s": 26405, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26490, "s": 26444, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26547, "s": 26490, "text": "Python program to check whether a number is Prime or not" } ]
Put your Data Analysis in an R Package — Even if You Don’t Publish it | by Denis Gontcharov | Towards Data Science
A data analysis project consists of many different files: raw data, R scripts, R Markdown reports and Shiny apps. We need a sensible project folder structure to stay organized. Why not take advantage of R’s established package development workflow? Working on our analysis inside an R package offers four benefits: R packages provide a standardized folder structure to organize your filesR packages provide functionality to document data and functionsR packages provide a framework to test your codeputting effort into points 1–3 enables you to reuse and share your code R packages provide a standardized folder structure to organize your files R packages provide functionality to document data and functions R packages provide a framework to test your code putting effort into points 1–3 enables you to reuse and share your code In this article we will work out a data analysis example inside an R package step-by-step. We will see that these benefits require nearly no overhead. For the data analysis example we will: download and save data fileswrite a script and an R-function to process datacreate a minimal exploratory data analysis reportdevelop a minimal interactive R flexdashboard with Shiny download and save data files write a script and an R-function to process data create a minimal exploratory data analysis report develop a minimal interactive R flexdashboard with Shiny The final result can be found on GitHub. I assume you use RStudio. Experience with R package development is recommended but not required. We’ll need the following R packages: R package development: devtools, usethis, roxygen2 R code testing: assertive, testthat Data analysis: ggplot2, dplyr R Markdown and Shiny: knitr, rmarkdown, flexdashboard, Shiny In RStudio navigate to a folder on your computer where you want to create the package. The following command will open a new RStudio session and create a bare-bone package named “WineReviews”. devtools::create("WineReviews") Notice how an additional tab Build becomes available. If you have version control configured in RStudio navigate to Tools, Version control, Project setup and select your version control software from the drop-down menu. We will select Git which initializes a local Git repository with a .gitignore file. We will use the R package roxygen2 to automatically generate documentation for our functions and data. Navigate to Tools, Project Options, Build Tools and tick the checkbox before “Generate documentation with Roxygen”. We will use the following configuration: In the DESCRIPTION file we write basic information about the project: Package: WineReviewsTitle: Your data analysis project belongs in an R packageVersion: 0.1.0Authors@R: person("Denis", "Gontcharov", role = c("aut", "cre"), email = "[email protected]")Description: Demonstrates how to leverage the R package workflow to organize a data science project.License: CC0Encoding: UTF-8LazyData: true Our initial package structure looks like this: .├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── NAMESPACE├── R└── WineReviews.Rproj Let’s run a check on our package build to see if everything is okay. We will do this regularly to ensure the project integrity throughout our work. devtools::check() In this example we use two csv files from the Wine Reviews dataset on Kaggle. We create a folder inst/ with a sub folder extdata/ in which we save the two csv files. (Subfolders of inst/ are installed when the package is built.) .├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── inst│ └── extdata│ ├── winemag-data-130k-v2.csv│ └── winemag-data_first150k.csv├── NAMESPACE├── R└── WineReviews.Rproj To make these files available we have to clean and rebuild the package. This will install the R package on your computer. To retrieve the path to a file in inst/ we use system.file() as follows: system.file( "extdata", "winemag-data-130k-v2.csv", package = "WineReviews") We will now process this raw data into a useful form. The wine reviews are split over the two csv files. Let’s assume that we want to merge these two files into one data frame with four variables: “country”, “points”, “price” and “winery". Let’s call this data frame “wine_data”. The code below creates the data_raw/ folder with a script wine_data.R usethis::use_data_raw(name = "wine_data") The code below creates our desired data frame. Let’s add it to the wine_data.R script and run it. ## code to prepare `wine_data` dataset goes here# retrieve paths to datafilesfirst.file <- system.file( "extdata", "winemag-data-130k-v2.csv", package = "WineReviews")second.file <- system.file( "extdata", "winemag-data_first150k.csv", package = "WineReviews")# read the two .csv filesdata.part.one <- read.csv( first.file, stringsAsFactors = FALSE, encoding = "UTF-8")data.part.two <- read.csv( second.file, stringsAsFactors = FALSE, encoding = "UTF-8")# select 4 variables and merge the two fileswine.variables <- c("country", "points", "price", "winery")data.part.one <- data.part.one[, wine.variables]data.part.two <- data.part.two[, wine.variables]wine_data <- rbind(data.part.one, data.part.two)# save the wine_data dataframe as an .rda file in WineReviews/data/usethis::use_data(wine_data, overwrite = TRUE) The final line creates the data/ folder with the data frame stored as wine_data.rda. After we Clean and Rebuild again this data can be loaded into the global environment like any other R data: data(“wine_data”, package = "WineReviews") It’s good practice to document your created data. All documentation for data should be stored in a a single R script saved in the R/ folder. Let’s create this script with the following content and name it data.R: #' Wine reviews for 51 countries.#'#' A dataset containing wine reviews.#'#' @format A data frame with 280901 rows and 4 variables:#' \describe{#' \item{country}{The country that the wine is from.}#' \item{points}{The number of points rated by WineEnthusiast#' on a scale of 1–100.}#' \item{price}{The cost for a bottle of the wine.}#' \item{winery}{The winery that made the wine.}#' }#' @source \url{https://www.kaggle.com/zynicide/wine-reviews}"wine_data" To create documentation based on this script we run: devtools::document() Roxygen transforms the code above into a a wine_data.Rd file and adds it to the man/ folder. We can view this documentation in the help pane by typing?winedata in the R console. Our package structure now looks like this: .├── .gitignore├── .Rbuildignore├── .Rhistory├── data│ └── wine_data.rda├── data-raw│ └── wine_data.R├── DESCRIPTION├── inst│ └── extdata│ ├── winemag-data-130k-v2.csv│ └── winemag-data_first150k.csv├── man│ └── wine_data.Rd├── NAMESPACE├── R│ └── data.R└── WineReviews.Rproj It’s good practice to regularly check the integrity of our package by running: devtools::check() We get one warning and one note. The warning about R version dependence is introduced after calling usethis::use_data(wine_data, overwrite = TRUE) and is resolved by adding Depends: R (>= 2.10) to the DESCRIPTION file. The note warns us about the package size because the data in inst/extdata exceeds 1 MB. We don’t want to publish this R package on CRAN so we can ignore this. However, we will resolve this note by adding the inst/extdata/ folder to .Rbuildignore. ^WineReviews\.Rproj$^\.Rproj\.user$^data-raw$^inst/extdata$ Now devtools::check() shows everything is fine: Now we can explore the processed data. I like to write reports in R package vignettes because they have a clean layout with whom R users are familiar. If you prefer not to use vignettes you can do the steps in a standard R Markdown document instead of a vignette, as shown in chapter 7. The function below creates a vignettes/ folder with a wine_eda.Rmd vignette that we will use for our exploratory data analysis. usethis::use_vignette(name = “wine_eda”, title = “Wine Reviews EDA”) We will use the popular dplyr R package to manipulate data. It’s important to declare each R package we use in the DESCRIPTION file. Don’t worry: if you forget this devtools::check() will throw a note. Declare the package with: usethis::use_package(“dplyr”) Let’s add some code to the vignette to load the data and show a summary: ---title: “Wine Reviews EDA”output: rmarkdown::html_vignettevignette: > %\VignetteIndexEntry{Wine Reviews EDA} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8}---```{r, include = FALSE}knitr::opts_chunk$set( collapse = TRUE, comment = “#>”)``````{r setup}library(WineReviews)``````{r}# load the previously created wine_data data framedata(wine_data)``````{r}summary(wine_data)``` There are 22691 missing values for the wine price. Let’s transform our data to fill these missing values. R is a functional programming language: we should transform our data by applying functions. “To understand computations in R, two slogans are helpful: Everything that exists is an object. Everything that happens is a function call.” — John Chambers This is the part where our decision to put our analysis in an R package will pay its dividends: package development makes the process of writing, documenting and testing functions incredibly smooth. Let’s replace a missing price with the mean price of that country’s wines. This is not necessarily a good idea statistically speaking, but it will serve to drive the point home. The replacement will be done by a function called “fill_na_mean”. We create a new R script variable_calculation.R and save it in the R/ folder. Notice how we can conveniently write the function’s documentation above its code. (Leave the @export tag otherwise the @examples won’t work.) #' Replace missing values with the mean#'#' @param numeric.vector A vector with at least one numeric value.#'#' @return The input whose NAs are replaced by the input's mean.#'#' @export#'#' @examples fill_na_mean(c(1, 2, 3, NA, 5, 3, NA, 6))fill_na_mean <- function(numeric.vector) { ifelse( is.na(numeric.vector), mean(numeric.vector, na.rm = TRUE), numeric.vector )} To create the documentation we again run: devtools::document() As was the case with documenting data, Roxygen will transform this documentation in a file fill_na_mean.Rd and save it in the man/ folder. We can view this documentation in the help pane by typing?fill_na_mean in the R console. If you wish to resume work after closing or restarting your R session, run the following command to load your functions as well as the packages declared in the DESCIPTION file: devtools::load_all() Next we will write two tests for our newly created function: A run-time test that runs every time the function is called to warn the user for faulty input.A development-time test that runs on command to warn the developer for bugs while writing or modifying the function. A run-time test that runs every time the function is called to warn the user for faulty input. A development-time test that runs on command to warn the developer for bugs while writing or modifying the function. The R package assertive offers functions for run-time testing. usethis::use_package(“assertive”) Our simple test consisting of one line checks if the input is a numeric vector and throw an error when it’s not. Note that run-time tests don’t rely on our package development environment because they are a part of the function. fill_na_mean <- function(numeric.vector) { assertive::assert_is_numeric(numeric.vector) # -> the run-time test ifelse( is.na(numeric.vector), mean(numeric.vector, na.rm = TRUE), numeric.vector )} Contrary to run-time testing, development-time testing with the testthat R package requires an active package development environment. Let’s write a unit test for our function that tests if fill_na_mean(c(2, 2, NA, 5, 3, NA)) returns the vector c(2, 2, 3, 5, 3, 3). First we set up the testthat framework: usethis::use_testthat() The following command creates the script test-variable_calculations.R that contains the unit tests for the functions defined in variable_calculations.R: usethis::use_test("variable_calculations") We modify the code in test-variable_calculations.R to represent our test: context(“Unit tests for fill_na_mean”)test_that(“fill_na_mean fills the NA with 3”, { actual <- fill_na_mean(c(2, 2, NA, 5, 3, NA)) expected <- c(2, 2, 3, 5, 3, 3) expect_equal(actual, expected)}) The following command runs all your tests and returns a pretty report: devtools::test() Now we can fill the missing values in our data analysis wine_eda.Rmd. But what if we wanted to do the same thing in other reports or applications? Should we repeat this procedure in each file? In fact, this function deals with data processing rather than exploratory analysis. It therefore belongs in the winedata.R file that generates the wine_data.rda. Putting this code in winedata.R instead of wine_eda.Rmd has the two advantages: Our code becomes modular: code for data processing is clearly separated from our data analysis report.There is only one script that generates the processed data that is used by all other files. Our code becomes modular: code for data processing is clearly separated from our data analysis report. There is only one script that generates the processed data that is used by all other files. After filling the missing values six observations still have no wine price so we choose to remove them. This is what the final script looks like: ## code to prepare `wine_data` dataset goes here# retrieve paths to datafilesfirst.file <- system.file( "extdata", "winemag-data-130k-v2.csv", package = "WineReviews")second.file <- system.file( "extdata", "winemag-data_first150k.csv", package = "WineReviews")# read the two .csv filesdata.part.one <- read.csv( first.file, stringsAsFactors = FALSE, encoding = "UTF-8")data.part.two <- read.csv( second.file, stringsAsFactors = FALSE, encoding = "UTF-8")# select 4 variables and merge the two fileswine.variables <- c("country", "points", "price", "winery")data.part.one <- data.part.one[, wine.variables]data.part.two <- data.part.two[, wine.variables]wine_data <- rbind(data.part.one, data.part.two)# fill missing prices with the mean price per countrywine_data <- wine_data %>% dplyr::group_by(country) %>% dplyr::mutate(price = fill_na_mean(price))# some countries don't have any non-missing price# we omit these observations from the datawine_data <- wine_data %>% dplyr::filter(!is.na(price))# save the wine_data dataframe as an .rda file in WineReviews/data/usethis::use_data(wine_data, overwrite = TRUE) Because we changed how the raw data is processed we have to document these changes in the data.R file in the data-raw/ folder: #’ Wine reviews for 49 countries.#’#’ A dataset containing processed data of wine reviews.#’ Missing price values have been filled with the mean price for #’ that country#’ six observations coming from countries with no wine price were #’ deleted.#’#’ @format A data frame with 280895 rows and 4 variables:#’ \describe{#’ \item{country}{The country that the wine is from.}#’ \item{points}{The number of points WineEnthusiast#’ rated the wine on a scale of 1–100}#’ \item{price}{The cost for a bottle of the wine}#’ \item{winery}{The winery that made the wine}#’ }#’ @source \url{https://www.kaggle.com/zynicide/wine-reviews}“wine_data” And update the documentation: devtools::document() Let’s knit our vignette. Notice that there are no more missing values even though we didn’t changed the code in the vignette. The missing values are removed in the wine_data.R script. In the vignette we just load the processed wine_data.rda. We can add any R Markdown file to our package. Analogously to raw data, we create a sub folder rmd/ in the inst/ folder. Let’s create a simple dashboard to view the wine price distribution per country. We create an R Markdown file wine_dashboard.Rmd in rmd/ with the following content: ---title: "Wine dashboard"output: flexdashboard::flex_dashboard: orientation: columnsruntime: shiny---```{r setup, include=FALSE}library(flexdashboard)library(ggplot2)``````{r}data(wine_data, package = "WineReviews")```Inputs {.sidebar data-width=150}-------------------------------------```{r}shiny::selectInput( "country", label = "select country", choices = sort(unique(wine_data$country)))```Column-------------------------------------### Wine points versus price ```{r}shiny::renderPlot( ggplot(wine_data[wine_data$country == input$country, ], aes(points, log10(price), group = points)) + geom_boxplot() + labs(x = "points scored by the wine on a 100 scale", y = "Base-10 logarithm of the wine price") + theme_bw())```Column-------------------------------------### Wine price distribution ```{r}shiny::renderPlot( ggplot(wine_data[wine_data$country == input$country, ], aes(price)) + geom_density() + labs(y = "Price density function") + theme_bw())``` Let’s view the dashboard with Run Document: Our data analysis example is now finished. This is what our final project structure looks like: .├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── data│ └── wine_data.rda├── data-raw│ └── wine_data.R├── inst│ ├── extdata│ │ ├── winemag-data-130k-v2.csv│ │ └── winemag-data_first150k.csv│ └── rmd│ └── wine_dashboard.Rmd├── man│ ├── fill_na_mean.Rd│ └── wine_data.Rd├── NAMESPACE├── R│ ├── data.R│ └── variable_calculation.R├── tests│ ├── testthat│ │ └── test-variable_calculations.R│ └── testthat.R├── vignettes│ └── wine_eda.Rmd└── WineReviews.Rproj This structure is suitable version control. Files with code are tracked whereas raw data in inst/extdata and processed data in data/ are not tracked. We can generate the processed data from the (re)downloaded raw data using the R scripts in data-raw/. I recommend adding the following entries to .gitignore: .Rproj.user.Rhistorydata/inst/extdata/inst/doc Here is how we made use of the R package components: DESCRIPTION: gives an overview of the project and its dependencies R/: contains R scripts with functions used throughout the package tests/: contains development-time tests for our functions inst/extdata/: contains our raw data files data-raw/: contains R scripts that process the raw data into tidy data data/: contains tidy data stored as .rda files man/: contains documentation for our objects and functions vignettes/: contains data analysis reports as package vignettes inst/rmd: contains R Markdown files for reports or applications I hope you have enjoyed the article. Would you consider using R packages to store your work? How do you like to organize your projects? Let me know in the comments!
[ { "code": null, "e": 421, "s": 172, "text": "A data analysis project consists of many different files: raw data, R scripts, R Markdown reports and Shiny apps. We need a sensible project folder structure to stay organized. Why not take advantage of R’s established package development workflow?" }, { "code": null, "e": 487, "s": 421, "text": "Working on our analysis inside an R package offers four benefits:" }, { "code": null, "e": 743, "s": 487, "text": "R packages provide a standardized folder structure to organize your filesR packages provide functionality to document data and functionsR packages provide a framework to test your codeputting effort into points 1–3 enables you to reuse and share your code" }, { "code": null, "e": 817, "s": 743, "text": "R packages provide a standardized folder structure to organize your files" }, { "code": null, "e": 881, "s": 817, "text": "R packages provide functionality to document data and functions" }, { "code": null, "e": 930, "s": 881, "text": "R packages provide a framework to test your code" }, { "code": null, "e": 1002, "s": 930, "text": "putting effort into points 1–3 enables you to reuse and share your code" }, { "code": null, "e": 1153, "s": 1002, "text": "In this article we will work out a data analysis example inside an R package step-by-step. We will see that these benefits require nearly no overhead." }, { "code": null, "e": 1192, "s": 1153, "text": "For the data analysis example we will:" }, { "code": null, "e": 1374, "s": 1192, "text": "download and save data fileswrite a script and an R-function to process datacreate a minimal exploratory data analysis reportdevelop a minimal interactive R flexdashboard with Shiny" }, { "code": null, "e": 1403, "s": 1374, "text": "download and save data files" }, { "code": null, "e": 1452, "s": 1403, "text": "write a script and an R-function to process data" }, { "code": null, "e": 1502, "s": 1452, "text": "create a minimal exploratory data analysis report" }, { "code": null, "e": 1559, "s": 1502, "text": "develop a minimal interactive R flexdashboard with Shiny" }, { "code": null, "e": 1600, "s": 1559, "text": "The final result can be found on GitHub." }, { "code": null, "e": 1734, "s": 1600, "text": "I assume you use RStudio. Experience with R package development is recommended but not required. We’ll need the following R packages:" }, { "code": null, "e": 1785, "s": 1734, "text": "R package development: devtools, usethis, roxygen2" }, { "code": null, "e": 1821, "s": 1785, "text": "R code testing: assertive, testthat" }, { "code": null, "e": 1851, "s": 1821, "text": "Data analysis: ggplot2, dplyr" }, { "code": null, "e": 1912, "s": 1851, "text": "R Markdown and Shiny: knitr, rmarkdown, flexdashboard, Shiny" }, { "code": null, "e": 2105, "s": 1912, "text": "In RStudio navigate to a folder on your computer where you want to create the package. The following command will open a new RStudio session and create a bare-bone package named “WineReviews”." }, { "code": null, "e": 2137, "s": 2105, "text": "devtools::create(\"WineReviews\")" }, { "code": null, "e": 2191, "s": 2137, "text": "Notice how an additional tab Build becomes available." }, { "code": null, "e": 2441, "s": 2191, "text": "If you have version control configured in RStudio navigate to Tools, Version control, Project setup and select your version control software from the drop-down menu. We will select Git which initializes a local Git repository with a .gitignore file." }, { "code": null, "e": 2701, "s": 2441, "text": "We will use the R package roxygen2 to automatically generate documentation for our functions and data. Navigate to Tools, Project Options, Build Tools and tick the checkbox before “Generate documentation with Roxygen”. We will use the following configuration:" }, { "code": null, "e": 2771, "s": 2701, "text": "In the DESCRIPTION file we write basic information about the project:" }, { "code": null, "e": 3120, "s": 2771, "text": "Package: WineReviewsTitle: Your data analysis project belongs in an R packageVersion: 0.1.0Authors@R: person(\"Denis\", \"Gontcharov\", role = c(\"aut\", \"cre\"), email = \"[email protected]\")Description: Demonstrates how to leverage the R package workflow to organize a data science project.License: CC0Encoding: UTF-8LazyData: true" }, { "code": null, "e": 3167, "s": 3120, "text": "Our initial package structure looks like this:" }, { "code": null, "e": 3267, "s": 3167, "text": ".├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── NAMESPACE├── R└── WineReviews.Rproj" }, { "code": null, "e": 3415, "s": 3267, "text": "Let’s run a check on our package build to see if everything is okay. We will do this regularly to ensure the project integrity throughout our work." }, { "code": null, "e": 3433, "s": 3415, "text": "devtools::check()" }, { "code": null, "e": 3662, "s": 3433, "text": "In this example we use two csv files from the Wine Reviews dataset on Kaggle. We create a folder inst/ with a sub folder extdata/ in which we save the two csv files. (Subfolders of inst/ are installed when the package is built.)" }, { "code": null, "e": 3859, "s": 3662, "text": ".├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── inst│ └── extdata│ ├── winemag-data-130k-v2.csv│ └── winemag-data_first150k.csv├── NAMESPACE├── R└── WineReviews.Rproj" }, { "code": null, "e": 3981, "s": 3859, "text": "To make these files available we have to clean and rebuild the package. This will install the R package on your computer." }, { "code": null, "e": 4054, "s": 3981, "text": "To retrieve the path to a file in inst/ we use system.file() as follows:" }, { "code": null, "e": 4134, "s": 4054, "text": "system.file( \"extdata\", \"winemag-data-130k-v2.csv\", package = \"WineReviews\")" }, { "code": null, "e": 4414, "s": 4134, "text": "We will now process this raw data into a useful form. The wine reviews are split over the two csv files. Let’s assume that we want to merge these two files into one data frame with four variables: “country”, “points”, “price” and “winery\". Let’s call this data frame “wine_data”." }, { "code": null, "e": 4484, "s": 4414, "text": "The code below creates the data_raw/ folder with a script wine_data.R" }, { "code": null, "e": 4526, "s": 4484, "text": "usethis::use_data_raw(name = \"wine_data\")" }, { "code": null, "e": 4624, "s": 4526, "text": "The code below creates our desired data frame. Let’s add it to the wine_data.R script and run it." }, { "code": null, "e": 5451, "s": 4624, "text": "## code to prepare `wine_data` dataset goes here# retrieve paths to datafilesfirst.file <- system.file( \"extdata\", \"winemag-data-130k-v2.csv\", package = \"WineReviews\")second.file <- system.file( \"extdata\", \"winemag-data_first150k.csv\", package = \"WineReviews\")# read the two .csv filesdata.part.one <- read.csv( first.file, stringsAsFactors = FALSE, encoding = \"UTF-8\")data.part.two <- read.csv( second.file, stringsAsFactors = FALSE, encoding = \"UTF-8\")# select 4 variables and merge the two fileswine.variables <- c(\"country\", \"points\", \"price\", \"winery\")data.part.one <- data.part.one[, wine.variables]data.part.two <- data.part.two[, wine.variables]wine_data <- rbind(data.part.one, data.part.two)# save the wine_data dataframe as an .rda file in WineReviews/data/usethis::use_data(wine_data, overwrite = TRUE)" }, { "code": null, "e": 5644, "s": 5451, "text": "The final line creates the data/ folder with the data frame stored as wine_data.rda. After we Clean and Rebuild again this data can be loaded into the global environment like any other R data:" }, { "code": null, "e": 5687, "s": 5644, "text": "data(“wine_data”, package = \"WineReviews\")" }, { "code": null, "e": 5900, "s": 5687, "text": "It’s good practice to document your created data. All documentation for data should be stored in a a single R script saved in the R/ folder. Let’s create this script with the following content and name it data.R:" }, { "code": null, "e": 6358, "s": 5900, "text": "#' Wine reviews for 51 countries.#'#' A dataset containing wine reviews.#'#' @format A data frame with 280901 rows and 4 variables:#' \\describe{#' \\item{country}{The country that the wine is from.}#' \\item{points}{The number of points rated by WineEnthusiast#' on a scale of 1–100.}#' \\item{price}{The cost for a bottle of the wine.}#' \\item{winery}{The winery that made the wine.}#' }#' @source \\url{https://www.kaggle.com/zynicide/wine-reviews}\"wine_data\"" }, { "code": null, "e": 6411, "s": 6358, "text": "To create documentation based on this script we run:" }, { "code": null, "e": 6432, "s": 6411, "text": "devtools::document()" }, { "code": null, "e": 6610, "s": 6432, "text": "Roxygen transforms the code above into a a wine_data.Rd file and adds it to the man/ folder. We can view this documentation in the help pane by typing?winedata in the R console." }, { "code": null, "e": 6653, "s": 6610, "text": "Our package structure now looks like this:" }, { "code": null, "e": 6951, "s": 6653, "text": ".├── .gitignore├── .Rbuildignore├── .Rhistory├── data│ └── wine_data.rda├── data-raw│ └── wine_data.R├── DESCRIPTION├── inst│ └── extdata│ ├── winemag-data-130k-v2.csv│ └── winemag-data_first150k.csv├── man│ └── wine_data.Rd├── NAMESPACE├── R│ └── data.R└── WineReviews.Rproj" }, { "code": null, "e": 7030, "s": 6951, "text": "It’s good practice to regularly check the integrity of our package by running:" }, { "code": null, "e": 7048, "s": 7030, "text": "devtools::check()" }, { "code": null, "e": 7081, "s": 7048, "text": "We get one warning and one note." }, { "code": null, "e": 7267, "s": 7081, "text": "The warning about R version dependence is introduced after calling usethis::use_data(wine_data, overwrite = TRUE) and is resolved by adding Depends: R (>= 2.10) to the DESCRIPTION file." }, { "code": null, "e": 7514, "s": 7267, "text": "The note warns us about the package size because the data in inst/extdata exceeds 1 MB. We don’t want to publish this R package on CRAN so we can ignore this. However, we will resolve this note by adding the inst/extdata/ folder to .Rbuildignore." }, { "code": null, "e": 7574, "s": 7514, "text": "^WineReviews\\.Rproj$^\\.Rproj\\.user$^data-raw$^inst/extdata$" }, { "code": null, "e": 7622, "s": 7574, "text": "Now devtools::check() shows everything is fine:" }, { "code": null, "e": 7909, "s": 7622, "text": "Now we can explore the processed data. I like to write reports in R package vignettes because they have a clean layout with whom R users are familiar. If you prefer not to use vignettes you can do the steps in a standard R Markdown document instead of a vignette, as shown in chapter 7." }, { "code": null, "e": 8037, "s": 7909, "text": "The function below creates a vignettes/ folder with a wine_eda.Rmd vignette that we will use for our exploratory data analysis." }, { "code": null, "e": 8106, "s": 8037, "text": "usethis::use_vignette(name = “wine_eda”, title = “Wine Reviews EDA”)" }, { "code": null, "e": 8334, "s": 8106, "text": "We will use the popular dplyr R package to manipulate data. It’s important to declare each R package we use in the DESCRIPTION file. Don’t worry: if you forget this devtools::check() will throw a note. Declare the package with:" }, { "code": null, "e": 8364, "s": 8334, "text": "usethis::use_package(“dplyr”)" }, { "code": null, "e": 8437, "s": 8364, "text": "Let’s add some code to the vignette to load the data and show a summary:" }, { "code": null, "e": 8829, "s": 8437, "text": "---title: “Wine Reviews EDA”output: rmarkdown::html_vignettevignette: > %\\VignetteIndexEntry{Wine Reviews EDA} %\\VignetteEngine{knitr::rmarkdown} %\\VignetteEncoding{UTF-8}---```{r, include = FALSE}knitr::opts_chunk$set( collapse = TRUE, comment = “#>”)``````{r setup}library(WineReviews)``````{r}# load the previously created wine_data data framedata(wine_data)``````{r}summary(wine_data)```" }, { "code": null, "e": 9027, "s": 8829, "text": "There are 22691 missing values for the wine price. Let’s transform our data to fill these missing values. R is a functional programming language: we should transform our data by applying functions." }, { "code": null, "e": 9168, "s": 9027, "text": "“To understand computations in R, two slogans are helpful: Everything that exists is an object. Everything that happens is a function call.”" }, { "code": null, "e": 9184, "s": 9168, "text": "— John Chambers" }, { "code": null, "e": 9383, "s": 9184, "text": "This is the part where our decision to put our analysis in an R package will pay its dividends: package development makes the process of writing, documenting and testing functions incredibly smooth." }, { "code": null, "e": 9561, "s": 9383, "text": "Let’s replace a missing price with the mean price of that country’s wines. This is not necessarily a good idea statistically speaking, but it will serve to drive the point home." }, { "code": null, "e": 9847, "s": 9561, "text": "The replacement will be done by a function called “fill_na_mean”. We create a new R script variable_calculation.R and save it in the R/ folder. Notice how we can conveniently write the function’s documentation above its code. (Leave the @export tag otherwise the @examples won’t work.)" }, { "code": null, "e": 10227, "s": 9847, "text": "#' Replace missing values with the mean#'#' @param numeric.vector A vector with at least one numeric value.#'#' @return The input whose NAs are replaced by the input's mean.#'#' @export#'#' @examples fill_na_mean(c(1, 2, 3, NA, 5, 3, NA, 6))fill_na_mean <- function(numeric.vector) { ifelse( is.na(numeric.vector), mean(numeric.vector, na.rm = TRUE), numeric.vector )}" }, { "code": null, "e": 10269, "s": 10227, "text": "To create the documentation we again run:" }, { "code": null, "e": 10290, "s": 10269, "text": "devtools::document()" }, { "code": null, "e": 10518, "s": 10290, "text": "As was the case with documenting data, Roxygen will transform this documentation in a file fill_na_mean.Rd and save it in the man/ folder. We can view this documentation in the help pane by typing?fill_na_mean in the R console." }, { "code": null, "e": 10695, "s": 10518, "text": "If you wish to resume work after closing or restarting your R session, run the following command to load your functions as well as the packages declared in the DESCIPTION file:" }, { "code": null, "e": 10717, "s": 10695, "text": "devtools::load_all() " }, { "code": null, "e": 10778, "s": 10717, "text": "Next we will write two tests for our newly created function:" }, { "code": null, "e": 10989, "s": 10778, "text": "A run-time test that runs every time the function is called to warn the user for faulty input.A development-time test that runs on command to warn the developer for bugs while writing or modifying the function." }, { "code": null, "e": 11084, "s": 10989, "text": "A run-time test that runs every time the function is called to warn the user for faulty input." }, { "code": null, "e": 11201, "s": 11084, "text": "A development-time test that runs on command to warn the developer for bugs while writing or modifying the function." }, { "code": null, "e": 11264, "s": 11201, "text": "The R package assertive offers functions for run-time testing." }, { "code": null, "e": 11298, "s": 11264, "text": "usethis::use_package(“assertive”)" }, { "code": null, "e": 11527, "s": 11298, "text": "Our simple test consisting of one line checks if the input is a numeric vector and throw an error when it’s not. Note that run-time tests don’t rely on our package development environment because they are a part of the function." }, { "code": null, "e": 11729, "s": 11527, "text": "fill_na_mean <- function(numeric.vector) { assertive::assert_is_numeric(numeric.vector) # -> the run-time test ifelse( is.na(numeric.vector), mean(numeric.vector, na.rm = TRUE), numeric.vector )}" }, { "code": null, "e": 11995, "s": 11729, "text": "Contrary to run-time testing, development-time testing with the testthat R package requires an active package development environment. Let’s write a unit test for our function that tests if fill_na_mean(c(2, 2, NA, 5, 3, NA)) returns the vector c(2, 2, 3, 5, 3, 3)." }, { "code": null, "e": 12035, "s": 11995, "text": "First we set up the testthat framework:" }, { "code": null, "e": 12060, "s": 12035, "text": "usethis::use_testthat() " }, { "code": null, "e": 12213, "s": 12060, "text": "The following command creates the script test-variable_calculations.R that contains the unit tests for the functions defined in variable_calculations.R:" }, { "code": null, "e": 12256, "s": 12213, "text": "usethis::use_test(\"variable_calculations\")" }, { "code": null, "e": 12330, "s": 12256, "text": "We modify the code in test-variable_calculations.R to represent our test:" }, { "code": null, "e": 12527, "s": 12330, "text": "context(“Unit tests for fill_na_mean”)test_that(“fill_na_mean fills the NA with 3”, { actual <- fill_na_mean(c(2, 2, NA, 5, 3, NA)) expected <- c(2, 2, 3, 5, 3, 3) expect_equal(actual, expected)})" }, { "code": null, "e": 12598, "s": 12527, "text": "The following command runs all your tests and returns a pretty report:" }, { "code": null, "e": 12616, "s": 12598, "text": "devtools::test() " }, { "code": null, "e": 12809, "s": 12616, "text": "Now we can fill the missing values in our data analysis wine_eda.Rmd. But what if we wanted to do the same thing in other reports or applications? Should we repeat this procedure in each file?" }, { "code": null, "e": 13051, "s": 12809, "text": "In fact, this function deals with data processing rather than exploratory analysis. It therefore belongs in the winedata.R file that generates the wine_data.rda. Putting this code in winedata.R instead of wine_eda.Rmd has the two advantages:" }, { "code": null, "e": 13245, "s": 13051, "text": "Our code becomes modular: code for data processing is clearly separated from our data analysis report.There is only one script that generates the processed data that is used by all other files." }, { "code": null, "e": 13348, "s": 13245, "text": "Our code becomes modular: code for data processing is clearly separated from our data analysis report." }, { "code": null, "e": 13440, "s": 13348, "text": "There is only one script that generates the processed data that is used by all other files." }, { "code": null, "e": 13586, "s": 13440, "text": "After filling the missing values six observations still have no wine price so we choose to remove them. This is what the final script looks like:" }, { "code": null, "e": 14713, "s": 13586, "text": "## code to prepare `wine_data` dataset goes here# retrieve paths to datafilesfirst.file <- system.file( \"extdata\", \"winemag-data-130k-v2.csv\", package = \"WineReviews\")second.file <- system.file( \"extdata\", \"winemag-data_first150k.csv\", package = \"WineReviews\")# read the two .csv filesdata.part.one <- read.csv( first.file, stringsAsFactors = FALSE, encoding = \"UTF-8\")data.part.two <- read.csv( second.file, stringsAsFactors = FALSE, encoding = \"UTF-8\")# select 4 variables and merge the two fileswine.variables <- c(\"country\", \"points\", \"price\", \"winery\")data.part.one <- data.part.one[, wine.variables]data.part.two <- data.part.two[, wine.variables]wine_data <- rbind(data.part.one, data.part.two)# fill missing prices with the mean price per countrywine_data <- wine_data %>% dplyr::group_by(country) %>% dplyr::mutate(price = fill_na_mean(price))# some countries don't have any non-missing price# we omit these observations from the datawine_data <- wine_data %>% dplyr::filter(!is.na(price))# save the wine_data dataframe as an .rda file in WineReviews/data/usethis::use_data(wine_data, overwrite = TRUE)" }, { "code": null, "e": 14840, "s": 14713, "text": "Because we changed how the raw data is processed we have to document these changes in the data.R file in the data-raw/ folder:" }, { "code": null, "e": 15476, "s": 14840, "text": "#’ Wine reviews for 49 countries.#’#’ A dataset containing processed data of wine reviews.#’ Missing price values have been filled with the mean price for #’ that country#’ six observations coming from countries with no wine price were #’ deleted.#’#’ @format A data frame with 280895 rows and 4 variables:#’ \\describe{#’ \\item{country}{The country that the wine is from.}#’ \\item{points}{The number of points WineEnthusiast#’ rated the wine on a scale of 1–100}#’ \\item{price}{The cost for a bottle of the wine}#’ \\item{winery}{The winery that made the wine}#’ }#’ @source \\url{https://www.kaggle.com/zynicide/wine-reviews}“wine_data”" }, { "code": null, "e": 15506, "s": 15476, "text": "And update the documentation:" }, { "code": null, "e": 15527, "s": 15506, "text": "devtools::document()" }, { "code": null, "e": 15769, "s": 15527, "text": "Let’s knit our vignette. Notice that there are no more missing values even though we didn’t changed the code in the vignette. The missing values are removed in the wine_data.R script. In the vignette we just load the processed wine_data.rda." }, { "code": null, "e": 16055, "s": 15769, "text": "We can add any R Markdown file to our package. Analogously to raw data, we create a sub folder rmd/ in the inst/ folder. Let’s create a simple dashboard to view the wine price distribution per country. We create an R Markdown file wine_dashboard.Rmd in rmd/ with the following content:" }, { "code": null, "e": 17014, "s": 16055, "text": "---title: \"Wine dashboard\"output: flexdashboard::flex_dashboard: orientation: columnsruntime: shiny---```{r setup, include=FALSE}library(flexdashboard)library(ggplot2)``````{r}data(wine_data, package = \"WineReviews\")```Inputs {.sidebar data-width=150}-------------------------------------```{r}shiny::selectInput( \"country\", label = \"select country\", choices = sort(unique(wine_data$country)))```Column-------------------------------------### Wine points versus price ```{r}shiny::renderPlot( ggplot(wine_data[wine_data$country == input$country, ], aes(points, log10(price), group = points)) + geom_boxplot() + labs(x = \"points scored by the wine on a 100 scale\", y = \"Base-10 logarithm of the wine price\") + theme_bw())```Column-------------------------------------### Wine price distribution ```{r}shiny::renderPlot( ggplot(wine_data[wine_data$country == input$country, ], aes(price)) + geom_density() + labs(y = \"Price density function\") + theme_bw())```" }, { "code": null, "e": 17058, "s": 17014, "text": "Let’s view the dashboard with Run Document:" }, { "code": null, "e": 17154, "s": 17058, "text": "Our data analysis example is now finished. This is what our final project structure looks like:" }, { "code": null, "e": 17662, "s": 17154, "text": ".├── .gitignore├── .Rbuildignore├── .Rhistory├── DESCRIPTION├── data│ └── wine_data.rda├── data-raw│ └── wine_data.R├── inst│ ├── extdata│ │ ├── winemag-data-130k-v2.csv│ │ └── winemag-data_first150k.csv│ └── rmd│ └── wine_dashboard.Rmd├── man│ ├── fill_na_mean.Rd│ └── wine_data.Rd├── NAMESPACE├── R│ ├── data.R│ └── variable_calculation.R├── tests│ ├── testthat│ │ └── test-variable_calculations.R│ └── testthat.R├── vignettes│ └── wine_eda.Rmd└── WineReviews.Rproj" }, { "code": null, "e": 17970, "s": 17662, "text": "This structure is suitable version control. Files with code are tracked whereas raw data in inst/extdata and processed data in data/ are not tracked. We can generate the processed data from the (re)downloaded raw data using the R scripts in data-raw/. I recommend adding the following entries to .gitignore:" }, { "code": null, "e": 18017, "s": 17970, "text": ".Rproj.user.Rhistorydata/inst/extdata/inst/doc" }, { "code": null, "e": 18070, "s": 18017, "text": "Here is how we made use of the R package components:" }, { "code": null, "e": 18137, "s": 18070, "text": "DESCRIPTION: gives an overview of the project and its dependencies" }, { "code": null, "e": 18203, "s": 18137, "text": "R/: contains R scripts with functions used throughout the package" }, { "code": null, "e": 18261, "s": 18203, "text": "tests/: contains development-time tests for our functions" }, { "code": null, "e": 18304, "s": 18261, "text": "inst/extdata/: contains our raw data files" }, { "code": null, "e": 18375, "s": 18304, "text": "data-raw/: contains R scripts that process the raw data into tidy data" }, { "code": null, "e": 18422, "s": 18375, "text": "data/: contains tidy data stored as .rda files" }, { "code": null, "e": 18481, "s": 18422, "text": "man/: contains documentation for our objects and functions" }, { "code": null, "e": 18545, "s": 18481, "text": "vignettes/: contains data analysis reports as package vignettes" }, { "code": null, "e": 18609, "s": 18545, "text": "inst/rmd: contains R Markdown files for reports or applications" } ]
SysIdentPy: A Python package for modeling nonlinear dynamical data | by Wilson Rocha | Towards Data Science
Mathematical models plays a key role and science and engineering. We see researchers and data-driven professionals using many different models to analyse and predict load demand, cash demand, stock exchange data, biomedical data, chemical process and many more. When the data is a result of a dynamical system, autoregressive models are frequently a safe choice for further tests. In this respect, ARMAX (Autoregressive models with Moving Average and Exogenous Input) models and its variants (ARX, ARMA, ARIMA, etc.) are one of the most used model class. However, the aforementioned models works well for linear data because they are linear models. And this is where SysIdentPy comes in: a python package for nonlinear dynamical systems. Systems are inherently nonlinear. One can argue that in most cases a linear approximation works great and you don’t need a nonlinear model... and I couldn’t agree more. However, what if you want to obtain a dynamic nonlinear model? Well, you can use SysIdentPy for that! SysIdentPy is an open source package for System Identification using NARMAX models (Nonlinear Autoregressive models with Moving Average and Exogenous Input) developed by me with the collaboration of my friends Luan Pascoal, Samuel Oliveira, and Samir Martins. NARMAX models are a generalization of ARMAX family. However, NARMAX model are not a simple extension of ARMAX models and are capable to describe many different and complex nonlinear systems. SysIdentPy aims to be a friendly user and powerful tool. With a few lines of code you can build a NARMAX model. The code below shows a simple example of how to use the library: loading sample data, setting the model parameters, fitting and predicting the model, show model details and plot the results with two residues tests. Pretty straightforward, right? from sysidentpy.polynomial_basis import PolynomialNarmaxfrom sysidentpy.metrics import root_relative_squared_errorfrom sysidentpy.utils.generate_data import get_miso_data, get_siso_datax_train, x_valid, y_train, y_valid = get_siso_data(n=1000, colored_noise=False, sigma=0.001, train_percentage=90)model = PolynomialNarmax(non_degree=2, order_selection=True, n_info_values=10, extended_least_squares=False, ylag=2, xlag=2, info_criteria='aic', estimator='least_squares', )model.fit(x_train, y_train)yhat = model.predict(x_valid, y_valid)rrse = root_relative_squared_error(y_valid, yhat)print(rrse)results = pd.DataFrame(model.results(err_precision=8, dtype='dec'), columns=['Regressors', 'Parameters', 'ERR'])print(results)ee, ex, extras, lam = model.residuals(x_valid, y_valid, yhat)model.plot_result(y_valid, yhat, ee, ex) You can install SysIdentPy using pip install sysidentpy So far we have implemented several tradicional algorithms concerning NARMAX models. Some of those methods are listed here: Forward Regression Orthogonal Least Squares (FROLS) Error Reduction Ratio Householder reflection Extended Least Squares FROLS Ordinary Least Squares Total Least Squares Recursive Least Squares Least Mean Squares (and many variants) Akaike Information Criteria Bayesian Information Criteria Final Prediction Error and more The reader is referred to official documentation and repository for further details: wilsonrljr.github.io github.com Many additional features are already in progress. It will be a pleasure to have the collaboration of all of you to make the library more and more complete. Feel free to contact me on Linkedin or Discord (wilsonrljr#3777). Also, we have a Discord server to talk about SysIdentpy (questions, contributions and so on). You can join us on Discord here.
[ { "code": null, "e": 434, "s": 172, "text": "Mathematical models plays a key role and science and engineering. We see researchers and data-driven professionals using many different models to analyse and predict load demand, cash demand, stock exchange data, biomedical data, chemical process and many more." }, { "code": null, "e": 910, "s": 434, "text": "When the data is a result of a dynamical system, autoregressive models are frequently a safe choice for further tests. In this respect, ARMAX (Autoregressive models with Moving Average and Exogenous Input) models and its variants (ARX, ARMA, ARIMA, etc.) are one of the most used model class. However, the aforementioned models works well for linear data because they are linear models. And this is where SysIdentPy comes in: a python package for nonlinear dynamical systems." }, { "code": null, "e": 1181, "s": 910, "text": "Systems are inherently nonlinear. One can argue that in most cases a linear approximation works great and you don’t need a nonlinear model... and I couldn’t agree more. However, what if you want to obtain a dynamic nonlinear model? Well, you can use SysIdentPy for that!" }, { "code": null, "e": 1441, "s": 1181, "text": "SysIdentPy is an open source package for System Identification using NARMAX models (Nonlinear Autoregressive models with Moving Average and Exogenous Input) developed by me with the collaboration of my friends Luan Pascoal, Samuel Oliveira, and Samir Martins." }, { "code": null, "e": 1632, "s": 1441, "text": "NARMAX models are a generalization of ARMAX family. However, NARMAX model are not a simple extension of ARMAX models and are capable to describe many different and complex nonlinear systems." }, { "code": null, "e": 1990, "s": 1632, "text": "SysIdentPy aims to be a friendly user and powerful tool. With a few lines of code you can build a NARMAX model. The code below shows a simple example of how to use the library: loading sample data, setting the model parameters, fitting and predicting the model, show model details and plot the results with two residues tests. Pretty straightforward, right?" }, { "code": null, "e": 3191, "s": 1990, "text": "from sysidentpy.polynomial_basis import PolynomialNarmaxfrom sysidentpy.metrics import root_relative_squared_errorfrom sysidentpy.utils.generate_data import get_miso_data, get_siso_datax_train, x_valid, y_train, y_valid = get_siso_data(n=1000, colored_noise=False, sigma=0.001, train_percentage=90)model = PolynomialNarmax(non_degree=2, order_selection=True, n_info_values=10, extended_least_squares=False, ylag=2, xlag=2, info_criteria='aic', estimator='least_squares', )model.fit(x_train, y_train)yhat = model.predict(x_valid, y_valid)rrse = root_relative_squared_error(y_valid, yhat)print(rrse)results = pd.DataFrame(model.results(err_precision=8, dtype='dec'), columns=['Regressors', 'Parameters', 'ERR'])print(results)ee, ex, extras, lam = model.residuals(x_valid, y_valid, yhat)model.plot_result(y_valid, yhat, ee, ex)" }, { "code": null, "e": 3224, "s": 3191, "text": "You can install SysIdentPy using" }, { "code": null, "e": 3247, "s": 3224, "text": "pip install sysidentpy" }, { "code": null, "e": 3370, "s": 3247, "text": "So far we have implemented several tradicional algorithms concerning NARMAX models. Some of those methods are listed here:" }, { "code": null, "e": 3422, "s": 3370, "text": "Forward Regression Orthogonal Least Squares (FROLS)" }, { "code": null, "e": 3444, "s": 3422, "text": "Error Reduction Ratio" }, { "code": null, "e": 3467, "s": 3444, "text": "Householder reflection" }, { "code": null, "e": 3496, "s": 3467, "text": "Extended Least Squares FROLS" }, { "code": null, "e": 3519, "s": 3496, "text": "Ordinary Least Squares" }, { "code": null, "e": 3539, "s": 3519, "text": "Total Least Squares" }, { "code": null, "e": 3563, "s": 3539, "text": "Recursive Least Squares" }, { "code": null, "e": 3602, "s": 3563, "text": "Least Mean Squares (and many variants)" }, { "code": null, "e": 3630, "s": 3602, "text": "Akaike Information Criteria" }, { "code": null, "e": 3660, "s": 3630, "text": "Bayesian Information Criteria" }, { "code": null, "e": 3683, "s": 3660, "text": "Final Prediction Error" }, { "code": null, "e": 3692, "s": 3683, "text": "and more" }, { "code": null, "e": 3777, "s": 3692, "text": "The reader is referred to official documentation and repository for further details:" }, { "code": null, "e": 3798, "s": 3777, "text": "wilsonrljr.github.io" }, { "code": null, "e": 3809, "s": 3798, "text": "github.com" }, { "code": null, "e": 3965, "s": 3809, "text": "Many additional features are already in progress. It will be a pleasure to have the collaboration of all of you to make the library more and more complete." } ]
Minimum Number of Platforms Required for a Railway Station using C++.
Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays that represent arrival and departure times of trains that stop. For below input, we need at least 3 platforms − 1. Sort arrival and departure time arrays in ascending order 2. Trace the number of trains at any time keeping track of trains that haves arrived, but not departed #include <iostream> #include <algorithm> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; int getPlatformCount(int *arrival, int *departure, int n){ sort(arrival, arrival + n); sort(departure, departure + n); int platformCnt = 1; int result = 1; int i = 1; int j = 0; while (i < n && j < n) { if (arrival[i] <= departure[j]) { ++platformCnt; ++i; if (platformCnt > result) { result = platformCnt; } } else { --platformCnt; ++j; } } return result; } int main() { int arrival[] = {900, 935, 940, 1100, 1430, 1800}; int departure[] = {915, 1145, 1105, 1200, 1815, 1900}; cout << "Minimum required platforms = " << getPlatformCount(arrival, departure, SIZE(arrival)) << endl; return 0; } When you compile and execute the above program. It generates the following output − Minimum required platforms = 3
[ { "code": null, "e": 1249, "s": 1062, "text": "Given arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits." }, { "code": null, "e": 1337, "s": 1249, "text": "We are given two arrays that represent arrival and departure times of trains that stop." }, { "code": null, "e": 1385, "s": 1337, "text": "For below input, we need at least 3 platforms −" }, { "code": null, "e": 1549, "s": 1385, "text": "1. Sort arrival and departure time arrays in ascending order\n2. Trace the number of trains at any time keeping track of trains that haves arrived, but not departed" }, { "code": null, "e": 2380, "s": 1549, "text": "#include <iostream>\n#include <algorithm>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nint getPlatformCount(int *arrival, int *departure, int n){\n sort(arrival, arrival + n);\n sort(departure, departure + n);\n int platformCnt = 1;\n int result = 1;\n int i = 1;\n int j = 0;\n while (i < n && j < n) {\n if (arrival[i] <= departure[j]) {\n ++platformCnt;\n ++i;\n if (platformCnt > result) {\n result = platformCnt;\n }\n } else {\n --platformCnt;\n ++j;\n }\n }\n return result;\n}\nint main()\n{\n int arrival[] = {900, 935, 940, 1100, 1430, 1800};\n int departure[] = {915, 1145, 1105, 1200, 1815, 1900};\n cout << \"Minimum required platforms = \" <<\n getPlatformCount(arrival, departure, SIZE(arrival)) << endl;\n return 0;\n}" }, { "code": null, "e": 2464, "s": 2380, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 2495, "s": 2464, "text": "Minimum required platforms = 3" } ]
GET and POST requests using Python - GeeksforGeeks
12 May, 2022 This post discusses two HTTP (Hypertext Transfer Protocol) request methods GET and POST requests in Python and their implementation in python. What is HTTP?HTTP is a set of protocols designed to enable communication between clients and servers. It works as a request-response protocol between a client and server.A web browser may be the client, and an application on a computer that hosts a website may be the server. So, to request a response from the server, there are mainly two methods: GET : to request data from the server.POST : to submit data to be processed to the server. GET : to request data from the server. POST : to submit data to be processed to the server. Here is a simple diagram which explains the basic concept of GET and POST methods.Now, to make HTTP requests in python, we can use several HTTP libraries like: httplib urllib requests The most elegant and simplest of above listed libraries is Requests. We will be using requests library in this article. To download and install Requests library, use following command: pip install requests OR, download it from here and install manually. Making a Get request # importing the requests libraryimport requests # api-endpointURL = "http://maps.googleapis.com/maps/api/geocode/json" # location given herelocation = "delhi technological university" # defining a params dict for the parameters to be sent to the APIPARAMS = {'address':location} # sending get request and saving the response as response objectr = requests.get(url = URL, params = PARAMS) # extracting data in json formatdata = r.json() # extracting latitude, longitude and formatted address # of the first matching locationlatitude = data['results'][0]['geometry']['location']['lat']longitude = data['results'][0]['geometry']['location']['lng']formatted_address = data['results'][0]['formatted_address'] # printing the outputprint("Latitude:%s\nLongitude:%s\nFormatted Address:%s" %(latitude, longitude,formatted_address)) Output: The above example finds latitude, longitude, and formatted address of a given location by sending a GET request to the Google Maps API. An API (Application Programming Interface) enables you to access the internal features of a program in a limited fashion. And in most cases, the data provided is in JSON(JavaScript Object Notation) format (which is implemented as dictionary objects in Python!).Important points to infer : PARAMS = {'address':location}The URL for a GET request generally carries some parameters with it. For requests library, parameters can be defined as a dictionary. These parameters are later parsed down and added to the base url or the api-endpoint.To understand the parameters role, try to print r.url after the response object is created. You will see something like this:http://maps.googleapis.com/maps/api/geocode/json?address=delhi+technological+universityThis is the actual URL on which GET request is made PARAMS = {'address':location} The URL for a GET request generally carries some parameters with it. For requests library, parameters can be defined as a dictionary. These parameters are later parsed down and added to the base url or the api-endpoint.To understand the parameters role, try to print r.url after the response object is created. You will see something like this: http://maps.googleapis.com/maps/api/geocode/json?address=delhi+technological+university This is the actual URL on which GET request is made r = requests.get(url = URL, params = PARAMS)Here we create a response object ‘r’ which will store the request-response. We use requests.get() method since we are sending a GET request. The two arguments we pass are url and the parameters dictionary. r = requests.get(url = URL, params = PARAMS) Here we create a response object ‘r’ which will store the request-response. We use requests.get() method since we are sending a GET request. The two arguments we pass are url and the parameters dictionary. data = r.json()Now, in order to retrieve the data from the response object, we need to convert the raw response content into a JSON type data structure. This is achieved by using json() method. Finally, we extract the required information by parsing down the JSON type object. data = r.json() Now, in order to retrieve the data from the response object, we need to convert the raw response content into a JSON type data structure. This is achieved by using json() method. Finally, we extract the required information by parsing down the JSON type object. Making a POST request # importing the requests libraryimport requests # defining the api-endpoint API_ENDPOINT = "http://pastebin.com/api/api_post.php" # your API key hereAPI_KEY = "XXXXXXXXXXXXXXXXX" # your source code heresource_code = '''print("Hello, world!")a = 1b = 2print(a + b)''' # data to be sent to apidata = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'} # sending post request and saving response as response objectr = requests.post(url = API_ENDPOINT, data = data) # extracting response text pastebin_url = r.textprint("The pastebin URL is:%s"%pastebin_url) This example explains how to paste your source_code to pastebin.com by sending POST request to the PASTEBIN API.First of all, you will need to generate an API key by signing up here and then access your API key here. Important features of this code: data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'}Here again, we will need to pass some data to API server. We store this data as a dictionary. data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'} Here again, we will need to pass some data to API server. We store this data as a dictionary. r = requests.post(url = API_ENDPOINT, data = data)Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary. r = requests.post(url = API_ENDPOINT, data = data) Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary. pastebin_url = r.textIn response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text . pastebin_url = r.text In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text . requests.post method could be used for many other tasks as well like filling and submitting the web forms, posting on your FB timeline using the Facebook Graph API, etc. Here are some important points to ponder upon: When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request. In GET method, the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K.No such problem in POST method since we send data in message body of the HTTP request, not the URL. Only ASCII characters are allowed for data to be sent in GET method.There is no such restriction in POST method. GET is less secure compared to POST because data sent is part of the URL. So, GET method should not be used when sending passwords or other sensitive information. This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. puja84375 Python-requests GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Supervised and Unsupervised learning Introduction to Recurrent Neural Network 12 pip Commands For Python Developers 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": 25879, "s": 25851, "text": "\n12 May, 2022" }, { "code": null, "e": 26023, "s": 25879, "text": "This post discusses two HTTP (Hypertext Transfer Protocol) request methods GET and POST requests in Python and their implementation in python." }, { "code": null, "e": 26299, "s": 26023, "text": "What is HTTP?HTTP is a set of protocols designed to enable communication between clients and servers. It works as a request-response protocol between a client and server.A web browser may be the client, and an application on a computer that hosts a website may be the server." }, { "code": null, "e": 26372, "s": 26299, "text": "So, to request a response from the server, there are mainly two methods:" }, { "code": null, "e": 26463, "s": 26372, "text": "GET : to request data from the server.POST : to submit data to be processed to the server." }, { "code": null, "e": 26502, "s": 26463, "text": "GET : to request data from the server." }, { "code": null, "e": 26555, "s": 26502, "text": "POST : to submit data to be processed to the server." }, { "code": null, "e": 26715, "s": 26555, "text": "Here is a simple diagram which explains the basic concept of GET and POST methods.Now, to make HTTP requests in python, we can use several HTTP libraries like:" }, { "code": null, "e": 26723, "s": 26715, "text": "httplib" }, { "code": null, "e": 26730, "s": 26723, "text": "urllib" }, { "code": null, "e": 26739, "s": 26730, "text": "requests" }, { "code": null, "e": 26924, "s": 26739, "text": "The most elegant and simplest of above listed libraries is Requests. We will be using requests library in this article. To download and install Requests library, use following command:" }, { "code": null, "e": 26945, "s": 26924, "text": "pip install requests" }, { "code": null, "e": 26993, "s": 26945, "text": "OR, download it from here and install manually." }, { "code": null, "e": 27014, "s": 26993, "text": "Making a Get request" }, { "code": "# importing the requests libraryimport requests # api-endpointURL = \"http://maps.googleapis.com/maps/api/geocode/json\" # location given herelocation = \"delhi technological university\" # defining a params dict for the parameters to be sent to the APIPARAMS = {'address':location} # sending get request and saving the response as response objectr = requests.get(url = URL, params = PARAMS) # extracting data in json formatdata = r.json() # extracting latitude, longitude and formatted address # of the first matching locationlatitude = data['results'][0]['geometry']['location']['lat']longitude = data['results'][0]['geometry']['location']['lng']formatted_address = data['results'][0]['formatted_address'] # printing the outputprint(\"Latitude:%s\\nLongitude:%s\\nFormatted Address:%s\" %(latitude, longitude,formatted_address))", "e": 27851, "s": 27014, "text": null }, { "code": null, "e": 27859, "s": 27851, "text": "Output:" }, { "code": null, "e": 28284, "s": 27859, "text": "The above example finds latitude, longitude, and formatted address of a given location by sending a GET request to the Google Maps API. An API (Application Programming Interface) enables you to access the internal features of a program in a limited fashion. And in most cases, the data provided is in JSON(JavaScript Object Notation) format (which is implemented as dictionary objects in Python!).Important points to infer :" }, { "code": null, "e": 28796, "s": 28284, "text": "PARAMS = {'address':location}The URL for a GET request generally carries some parameters with it. For requests library, parameters can be defined as a dictionary. These parameters are later parsed down and added to the base url or the api-endpoint.To understand the parameters role, try to print r.url after the response object is created. You will see something like this:http://maps.googleapis.com/maps/api/geocode/json?address=delhi+technological+universityThis is the actual URL on which GET request is made" }, { "code": null, "e": 28826, "s": 28796, "text": "PARAMS = {'address':location}" }, { "code": null, "e": 29171, "s": 28826, "text": "The URL for a GET request generally carries some parameters with it. For requests library, parameters can be defined as a dictionary. These parameters are later parsed down and added to the base url or the api-endpoint.To understand the parameters role, try to print r.url after the response object is created. You will see something like this:" }, { "code": null, "e": 29259, "s": 29171, "text": "http://maps.googleapis.com/maps/api/geocode/json?address=delhi+technological+university" }, { "code": null, "e": 29311, "s": 29259, "text": "This is the actual URL on which GET request is made" }, { "code": null, "e": 29561, "s": 29311, "text": "r = requests.get(url = URL, params = PARAMS)Here we create a response object ‘r’ which will store the request-response. We use requests.get() method since we are sending a GET request. The two arguments we pass are url and the parameters dictionary." }, { "code": null, "e": 29606, "s": 29561, "text": "r = requests.get(url = URL, params = PARAMS)" }, { "code": null, "e": 29812, "s": 29606, "text": "Here we create a response object ‘r’ which will store the request-response. We use requests.get() method since we are sending a GET request. The two arguments we pass are url and the parameters dictionary." }, { "code": null, "e": 30089, "s": 29812, "text": "data = r.json()Now, in order to retrieve the data from the response object, we need to convert the raw response content into a JSON type data structure. This is achieved by using json() method. Finally, we extract the required information by parsing down the JSON type object." }, { "code": null, "e": 30105, "s": 30089, "text": "data = r.json()" }, { "code": null, "e": 30367, "s": 30105, "text": "Now, in order to retrieve the data from the response object, we need to convert the raw response content into a JSON type data structure. This is achieved by using json() method. Finally, we extract the required information by parsing down the JSON type object." }, { "code": null, "e": 30389, "s": 30367, "text": "Making a POST request" }, { "code": "# importing the requests libraryimport requests # defining the api-endpoint API_ENDPOINT = \"http://pastebin.com/api/api_post.php\" # your API key hereAPI_KEY = \"XXXXXXXXXXXXXXXXX\" # your source code heresource_code = '''print(\"Hello, world!\")a = 1b = 2print(a + b)''' # data to be sent to apidata = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'} # sending post request and saving response as response objectr = requests.post(url = API_ENDPOINT, data = data) # extracting response text pastebin_url = r.textprint(\"The pastebin URL is:%s\"%pastebin_url)", "e": 31024, "s": 30389, "text": null }, { "code": null, "e": 31241, "s": 31024, "text": "This example explains how to paste your source_code to pastebin.com by sending POST request to the PASTEBIN API.First of all, you will need to generate an API key by signing up here and then access your API key here." }, { "code": null, "e": 31274, "s": 31241, "text": "Important features of this code:" }, { "code": null, "e": 31503, "s": 31274, "text": "data = {'api_dev_key':API_KEY,\n 'api_option':'paste',\n 'api_paste_code':source_code,\n 'api_paste_format':'python'}Here again, we will need to pass some data to API server. We store this data as a dictionary." }, { "code": null, "e": 31639, "s": 31503, "text": "data = {'api_dev_key':API_KEY,\n 'api_option':'paste',\n 'api_paste_code':source_code,\n 'api_paste_format':'python'}" }, { "code": null, "e": 31733, "s": 31639, "text": "Here again, we will need to pass some data to API server. We store this data as a dictionary." }, { "code": null, "e": 31985, "s": 31733, "text": "r = requests.post(url = API_ENDPOINT, data = data)Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary." }, { "code": null, "e": 32036, "s": 31985, "text": "r = requests.post(url = API_ENDPOINT, data = data)" }, { "code": null, "e": 32238, "s": 32036, "text": "Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary." }, { "code": null, "e": 32401, "s": 32238, "text": "pastebin_url = r.textIn response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text ." }, { "code": null, "e": 32423, "s": 32401, "text": "pastebin_url = r.text" }, { "code": null, "e": 32565, "s": 32423, "text": "In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text ." }, { "code": null, "e": 32735, "s": 32565, "text": "requests.post method could be used for many other tasks as well like filling and submitting the web forms, posting on your FB timeline using the Facebook Graph API, etc." }, { "code": null, "e": 32782, "s": 32735, "text": "Here are some important points to ponder upon:" }, { "code": null, "e": 32974, "s": 32782, "text": "When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters. With POST, form data appears within the message body of the HTTP request." }, { "code": null, "e": 33241, "s": 32974, "text": "In GET method, the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64K.No such problem in POST method since we send data in message body of the HTTP request, not the URL." }, { "code": null, "e": 33354, "s": 33241, "text": "Only ASCII characters are allowed for data to be sent in GET method.There is no such restriction in POST method." }, { "code": null, "e": 33517, "s": 33354, "text": "GET is less secure compared to POST because data sent is part of the URL. So, GET method should not be used when sending passwords or other sensitive information." }, { "code": null, "e": 33810, "s": 33517, "text": "This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33935, "s": 33810, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33945, "s": 33935, "text": "puja84375" }, { "code": null, "e": 33961, "s": 33945, "text": "Python-requests" }, { "code": null, "e": 33967, "s": 33961, "text": "GBlog" }, { "code": null, "e": 33974, "s": 33967, "text": "Python" }, { "code": null, "e": 34072, "s": 33974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34097, "s": 34072, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 34124, "s": 34097, "text": "How to Start Learning DSA?" }, { "code": null, "e": 34161, "s": 34124, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 34202, "s": 34161, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 34240, "s": 34202, "text": "12 pip Commands For Python Developers" }, { "code": null, "e": 34268, "s": 34240, "text": "Read JSON file using Python" }, { "code": null, "e": 34318, "s": 34268, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34340, "s": 34318, "text": "Python map() function" } ]
Delete the last leaf node in a Binary Tree - GeeksforGeeks
17 Jan, 2022 Given a Binary Tree, the task is to find and DELETE the last leaf node.The leaf node is a node with no children. The last leaf node would be the node that is traversed last in sequence during Level Order Traversal. The problem statement is to identify this last visited node and delete this particular node. Examples: Input: Given Tree is: 6 / \ 5 4 / \ \ 1 2 5 Level Order Traversal is: 6 5 4 1 2 5 Output: After deleting the last node (5), the tree would look like as follows. 6 / \ 5 4 / \ 1 2 Level Order Traversal is: 6 5 4 1 2 Input: Given tree is: 1 / \ 3 10 / \ / \ 2 15 4 5 / 1 Level Order Traversal is: 1 3 10 2 15 4 5 1 Output: After deleting the last node (1), the tree would look like as follows. 1 / \ 3 10 / \ / \ 2 15 4 5 Level Order Traversal is: 1 3 10 2 15 4 5 This problem is slightly different from Delete leaf node with value as X wherein we are right away given the value of last leaf node (X) to be deleted, based on which we perform checks and mark the parent node as null to delete it. This approach would identify the last present leaf node on last level of the tree and would delete it.Approach 1: Traversing last level nodes and keeping track of Parent and traversed node. This approach would traverse each node until we reach the last level of the given binary tree. While traversing, we keep track of the last traversed node and its Parent.Once done with traversal, Check if the parent has Right Child, if yes, set it to NULL. If no, set the left pointer to NULLBelow is the implementation of the approach: C++ Java C# Javascript // CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Tree Nodeclass Node{public: int data; Node *left, *right; Node(int data) : data(data) {}}; // Method to perform inorder traversalvoid inorder(Node *root){ if (root == NULL) return; inorder(root->left); cout << root->data << " "; inorder(root->right);} // To keep track of last processed// nodes parent and node itself.Node *lastNode, *parentOfLastNode; // Method to get the height of the treeint height(Node *root){ if (root == NULL) return 0; int lheight = height(root->left) + 1; int rheight = height(root->right) + 1; return max(lheight, rheight);} // Method to keep track of parents// of every nodevoid getLastNodeAndItsParent(Node *root, int level, Node *parent){ if (root == NULL) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root->left, level - 1, root); getLastNodeAndItsParent(root->right, level - 1, root);} // Method to delete last leaf nodevoid deleteLastNode(Node *root){ int levelOfLastNode = height(root); getLastNodeAndItsParent(root, levelOfLastNode, NULL); if (lastNode and parentOfLastNode) { if (parentOfLastNode->right) parentOfLastNode->right = NULL; else parentOfLastNode->left = NULL; } else cout << "Empty Tree\n";} // Driver Codeint main(){ Node *root = new Node(6); root->left = new Node(5); root->right = new Node(4); root->left->left = new Node(1); root->left->right = new Node(2); root->right->right = new Node(5); cout << "Inorder traversal before deletion of last node :\n"; inorder(root); deleteLastNode(root); cout << "\nInorder traversal after deletion of last node :\n"; inorder(root); return 0;} // This code is contributed by// sanjeev2552 // Java Implementation of the approachpublic class DeleteLastNode { // Tree Node static class Node { Node left, right; int data; Node(int data) { this.data = data; } } // Method to perform inorder traversal public void inorder(Node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } // To keep track of last processed // nodes parent and node itself. public static Node lastNode; public static Node parentOfLastNode; // Method to get the height of the tree public int height(Node root) { if (root == null) return 0; int lheight = height(root.left) + 1; int rheight = height(root.right) + 1; return Math.max(lheight, rheight); } // Method to delete last leaf node public void deleteLastNode(Node root) { int levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else System.out.println("Empty Tree"); } // Method to keep track of parents // of every node public void getLastNodeAndItsParent(Node root, int level, Node parent) { if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root); } // Driver Code public static void main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); System.out.println("Inorder traversal " + "before deletion " + "of last node : "); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); System.out.println("\nInorder traversal " + "after deletion of " + "last node : "); deleteLastNode.inorder(root); }} // C# implementation of the above approachusing System; class GFG{ // Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; } } // Method to perform inorder traversal public void inorder(Node root) { if (root == null) return; inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } // To keep track of last processed // nodes parent and node itself. public static Node lastNode; public static Node parentOfLastNode; // Method to get the height of the tree public int height(Node root) { if (root == null) return 0; int lheight = height(root.left) + 1; int rheight = height(root.right) + 1; return Math.Max(lheight, rheight); } // Method to delete last leaf node public void deleteLastNode(Node root) { int levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine("Empty Tree"); } // Method to keep track of parents // of every node public void getLastNodeAndItsParent(Node root, int level, Node parent) { if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root); } // Driver Code public static void Main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); GFG deleteLastNode = new GFG(); Console.WriteLine("Inorder traversal " + "before deletion " + "of last node : "); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); Console.WriteLine("\nInorder traversal " + "after deletion of " + "last node : "); deleteLastNode.inorder(root); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the above approach // Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Method to perform inorder traversalfunction inorder(root){ if (root == null) return; inorder(root.left); document.write(root.data + " "); inorder(root.right);}// To keep track of last processed// nodes parent and node itself.var lastNode = null;var parentOfLastNode = null;// Method to get the height of the treefunction height(root){ if (root == null) return 0; var lheight = height(root.left) + 1; var rheight = height(root.right) + 1; return Math.max(lheight, rheight);} // Method to delete last leaf nodefunction deleteLastNode(root){ var levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine("Empty Tree");}// Method to keep track of parents// of every nodefunction getLastNodeAndItsParent(root, level, parent){ if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root);} // Driver Codevar root = new Node(6);root.left = new Node(5);root.right = new Node(4);root.left.left = new Node(1);root.left.right = new Node(2);root.right.right = new Node(5);document.write("Inorder traversal " + "before deletion " + "of last node :<br>");inorder(root);deleteLastNode(root);document.write("<br>Inorder traversal " + "after deletion of " + "last node :<br>");inorder(root); // This code is contributed by rrrtnx.</script> Inorder traversal before deletion of last node : 1 5 2 6 4 5 Inorder traversal after deletion of last node : 1 5 2 6 4 Time Complexity: Since each node would be traversed once, the time taken would be linear to the number of nodes in a given tree.Approach 2: Performing Level Order Traversal on given Binary Tree using Queue and tracking Parent and last traversed node.This is a Non-Recursive way of achieving above Approach 1. We perform the Level Order Traversal using Queue and keeping track of every visited node and its parent. The last visited node would be the last node that is to be deleted.Below is the implementation of the approach: Java C# // Java implementationimport java.util.LinkedList;import java.util.Queue; public class DeleteLastNode { // Tree Node static class Node { Node left, right; int data; Node(int data) { this.data = data; } } // Function to perform the inorder traversal of the tree public void inorder(Node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } // To keep track of last // processed nodes parent // and node itself. public static Node lastLevelLevelOrder; public static Node parentOfLastNode; // Method to delete the last node // from the tree public void deleteLastNode(Node root) { // If tree is empty, it // would return without // any deletion if (root == null) return; // The queue would be needed // to maintain the level order // traversal of nodes Queue<Node> queue = new LinkedList<>(); queue.offer(root); // The traversing would // continue until all // nodes are traversed once while (!queue.isEmpty()) { Node temp = queue.poll(); // If there is left child if (temp.left != null) { queue.offer(temp.left); // For every traversed node, // we would check if it is a // leaf node by checking if // current node has children to it if (temp.left.left == null && temp.left.right == null) { // For every leaf node // encountered, we would // keep not of it as // "Previously Visided Leaf node. lastLevelLevelOrder = temp.left; parentOfLastNode = temp; } } if (temp.right != null) { queue.offer(temp.right); if (temp.right.left == null && temp.right.right == null) { // For every leaf node // encountered, we would // keep not of it as // "Previously Visided Leaf node. lastLevelLevelOrder = temp.right; parentOfLastNode = temp; } } } // Once out of above loop. // we would certainly have // last visited node, which // is to be deleted and its // parent node. if (lastLevelLevelOrder != null && parentOfLastNode != null) { // If last node is right child // of parent, make right node // of its parent as NULL or // make left node as NULL if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else System.out.println("Empty Tree"); } // Driver Code public static void main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); System.out.println("Inorder traversal " + "before deletion of " + "last node : "); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); System.out.println("\nInorder traversal " + "after deletion " + "of last node : "); deleteLastNode.inorder(root); }} // C# implementation of the approachusing System;using System.Collections.Generic;public class DeleteLastNode { // Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; } } // Function to perform the inorder traversal of the tree public void inorder(Node root) { if (root == null) return; inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } // To keep track of last // processed nodes parent // and node itself. public static Node lastLevelLevelOrder; public static Node parentOfLastNode; // Method to delete the last node // from the tree public void deleteLastNode(Node root) { // If tree is empty, it // would return without // any deletion if (root == null) return; // The queue would be needed // to maintain the level order // traversal of nodes Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); // The traversing would // continue until all // nodes are traversed once while (queue.Count!=0) { Node temp = queue.Dequeue(); // If there is left child if (temp.left != null) { queue.Enqueue(temp.left); // For every traversed node, // we would check if it is a // leaf node by checking if // current node has children to it if (temp.left.left == null && temp.left.right == null) { // For every leaf node // encountered, we would // keep not of it as // "Previously Visided Leaf node. lastLevelLevelOrder = temp.left; parentOfLastNode = temp; } } if (temp.right != null) { queue.Enqueue(temp.right); if (temp.right.left == null && temp.right.right == null) { // For every leaf node // encountered, we would // keep not of it as // "Previously Visided Leaf node. lastLevelLevelOrder = temp.right; parentOfLastNode = temp; } } } // Once out of above loop. // we would certainly have // last visited node, which // is to be deleted and its // parent node. if (lastLevelLevelOrder != null && parentOfLastNode != null) { // If last node is right child // of parent, make right node // of its parent as NULL or // make left node as NULL if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine("Empty Tree"); } // Driver Code public static void Main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); Console.WriteLine("Inorder traversal " + "before deletion of " + "last node : "); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); Console.WriteLine("\nInorder traversal " + "after deletion " + "of last node : "); deleteLastNode.inorder(root); }} // This code contributed by Rajput-Ji Inorder traversal before deletion of last node : 1 5 2 6 4 5 Inorder traversal after deletion of last node : 1 5 2 6 4 Time Complexity: Since every node would be visited once, the time taken would be linear to the number of nodes present in the tree. Auxiliary Space: Since we would be maintaining a queue to do the level order traversal, the space consumed would be . 29AjayKumar Rajput-Ji sanjeev2552 nidhi_biet rrrtnx gabaa406 ruhelaa48 adnanirshad158 Binary Tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Print Binary Tree in 2-Dimensions Real-time application of Data Structures Iterative Postorder Traversal | Set 2 (Using One Stack) Find maximum (or minimum) in Binary Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Min Heap and Max Heap
[ { "code": null, "e": 26185, "s": 26157, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26505, "s": 26185, "text": "Given a Binary Tree, the task is to find and DELETE the last leaf node.The leaf node is a node with no children. The last leaf node would be the node that is traversed last in sequence during Level Order Traversal. The problem statement is to identify this last visited node and delete this particular node. Examples: " }, { "code": null, "e": 27298, "s": 26505, "text": " \nInput: \nGiven Tree is: \n 6\n / \\\n 5 4\n / \\ \\\n 1 2 5 \n\nLevel Order Traversal is: 6 5 4 1 2 5\nOutput: \nAfter deleting the last node (5),\nthe tree would look like as follows. \n\n 6\n / \\\n 5 4\n / \\ \n 1 2 \nLevel Order Traversal is: 6 5 4 1 2\n\nInput: \nGiven tree is: \n 1\n / \\\n 3 10\n / \\ / \\\n 2 15 4 5 \n / \n 1 \nLevel Order Traversal is: 1 3 10 2 15 4 5 1\nOutput: \nAfter deleting the last node (1),\nthe tree would look like as follows.\n\n 1\n / \\\n 3 10\n / \\ / \\\n 2 15 4 5 \n\nLevel Order Traversal is: 1 3 10 2 15 4 5" }, { "code": null, "e": 28060, "s": 27300, "text": "This problem is slightly different from Delete leaf node with value as X wherein we are right away given the value of last leaf node (X) to be deleted, based on which we perform checks and mark the parent node as null to delete it. This approach would identify the last present leaf node on last level of the tree and would delete it.Approach 1: Traversing last level nodes and keeping track of Parent and traversed node. This approach would traverse each node until we reach the last level of the given binary tree. While traversing, we keep track of the last traversed node and its Parent.Once done with traversal, Check if the parent has Right Child, if yes, set it to NULL. If no, set the left pointer to NULLBelow is the implementation of the approach: " }, { "code": null, "e": 28064, "s": 28060, "text": "C++" }, { "code": null, "e": 28069, "s": 28064, "text": "Java" }, { "code": null, "e": 28072, "s": 28069, "text": "C#" }, { "code": null, "e": 28083, "s": 28072, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Tree Nodeclass Node{public: int data; Node *left, *right; Node(int data) : data(data) {}}; // Method to perform inorder traversalvoid inorder(Node *root){ if (root == NULL) return; inorder(root->left); cout << root->data << \" \"; inorder(root->right);} // To keep track of last processed// nodes parent and node itself.Node *lastNode, *parentOfLastNode; // Method to get the height of the treeint height(Node *root){ if (root == NULL) return 0; int lheight = height(root->left) + 1; int rheight = height(root->right) + 1; return max(lheight, rheight);} // Method to keep track of parents// of every nodevoid getLastNodeAndItsParent(Node *root, int level, Node *parent){ if (root == NULL) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root->left, level - 1, root); getLastNodeAndItsParent(root->right, level - 1, root);} // Method to delete last leaf nodevoid deleteLastNode(Node *root){ int levelOfLastNode = height(root); getLastNodeAndItsParent(root, levelOfLastNode, NULL); if (lastNode and parentOfLastNode) { if (parentOfLastNode->right) parentOfLastNode->right = NULL; else parentOfLastNode->left = NULL; } else cout << \"Empty Tree\\n\";} // Driver Codeint main(){ Node *root = new Node(6); root->left = new Node(5); root->right = new Node(4); root->left->left = new Node(1); root->left->right = new Node(2); root->right->right = new Node(5); cout << \"Inorder traversal before deletion of last node :\\n\"; inorder(root); deleteLastNode(root); cout << \"\\nInorder traversal after deletion of last node :\\n\"; inorder(root); return 0;} // This code is contributed by// sanjeev2552", "e": 30159, "s": 28083, "text": null }, { "code": "// Java Implementation of the approachpublic class DeleteLastNode { // Tree Node static class Node { Node left, right; int data; Node(int data) { this.data = data; } } // Method to perform inorder traversal public void inorder(Node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } // To keep track of last processed // nodes parent and node itself. public static Node lastNode; public static Node parentOfLastNode; // Method to get the height of the tree public int height(Node root) { if (root == null) return 0; int lheight = height(root.left) + 1; int rheight = height(root.right) + 1; return Math.max(lheight, rheight); } // Method to delete last leaf node public void deleteLastNode(Node root) { int levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else System.out.println(\"Empty Tree\"); } // Method to keep track of parents // of every node public void getLastNodeAndItsParent(Node root, int level, Node parent) { if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root); } // Driver Code public static void main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); System.out.println(\"Inorder traversal \" + \"before deletion \" + \"of last node : \"); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); System.out.println(\"\\nInorder traversal \" + \"after deletion of \" + \"last node : \"); deleteLastNode.inorder(root); }}", "e": 33169, "s": 30159, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; } } // Method to perform inorder traversal public void inorder(Node root) { if (root == null) return; inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); } // To keep track of last processed // nodes parent and node itself. public static Node lastNode; public static Node parentOfLastNode; // Method to get the height of the tree public int height(Node root) { if (root == null) return 0; int lheight = height(root.left) + 1; int rheight = height(root.right) + 1; return Math.Max(lheight, rheight); } // Method to delete last leaf node public void deleteLastNode(Node root) { int levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine(\"Empty Tree\"); } // Method to keep track of parents // of every node public void getLastNodeAndItsParent(Node root, int level, Node parent) { if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root); } // Driver Code public static void Main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); GFG deleteLastNode = new GFG(); Console.WriteLine(\"Inorder traversal \" + \"before deletion \" + \"of last node : \"); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); Console.WriteLine(\"\\nInorder traversal \" + \"after deletion of \" + \"last node : \"); deleteLastNode.inorder(root); }} // This code is contributed by 29AjayKumar", "e": 36240, "s": 33169, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // Method to perform inorder traversalfunction inorder(root){ if (root == null) return; inorder(root.left); document.write(root.data + \" \"); inorder(root.right);}// To keep track of last processed// nodes parent and node itself.var lastNode = null;var parentOfLastNode = null;// Method to get the height of the treefunction height(root){ if (root == null) return 0; var lheight = height(root.left) + 1; var rheight = height(root.right) + 1; return Math.max(lheight, rheight);} // Method to delete last leaf nodefunction deleteLastNode(root){ var levelOfLastNode = height(root); // Get all nodes at last level getLastNodeAndItsParent(root, levelOfLastNode, null); if (lastNode != null && parentOfLastNode != null) { if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine(\"Empty Tree\");}// Method to keep track of parents// of every nodefunction getLastNodeAndItsParent(root, level, parent){ if (root == null) return; // The last processed node in // Level Order Traversal has to // be the node to be deleted. // This will store the last // processed node and its parent. if (level == 1) { lastNode = root; parentOfLastNode = parent; } getLastNodeAndItsParent(root.left, level - 1, root); getLastNodeAndItsParent(root.right, level - 1, root);} // Driver Codevar root = new Node(6);root.left = new Node(5);root.right = new Node(4);root.left.left = new Node(1);root.left.right = new Node(2);root.right.right = new Node(5);document.write(\"Inorder traversal \" + \"before deletion \" + \"of last node :<br>\");inorder(root);deleteLastNode(root);document.write(\"<br>Inorder traversal \" + \"after deletion of \" + \"last node :<br>\");inorder(root); // This code is contributed by rrrtnx.</script>", "e": 38593, "s": 36240, "text": null }, { "code": null, "e": 38715, "s": 38593, "text": "Inorder traversal before deletion of last node : \n1 5 2 6 4 5 \nInorder traversal after deletion of last node : \n1 5 2 6 4" }, { "code": null, "e": 39245, "s": 38717, "text": "Time Complexity: Since each node would be traversed once, the time taken would be linear to the number of nodes in a given tree.Approach 2: Performing Level Order Traversal on given Binary Tree using Queue and tracking Parent and last traversed node.This is a Non-Recursive way of achieving above Approach 1. We perform the Level Order Traversal using Queue and keeping track of every visited node and its parent. The last visited node would be the last node that is to be deleted.Below is the implementation of the approach: " }, { "code": null, "e": 39250, "s": 39245, "text": "Java" }, { "code": null, "e": 39253, "s": 39250, "text": "C#" }, { "code": "// Java implementationimport java.util.LinkedList;import java.util.Queue; public class DeleteLastNode { // Tree Node static class Node { Node left, right; int data; Node(int data) { this.data = data; } } // Function to perform the inorder traversal of the tree public void inorder(Node root) { if (root == null) return; inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } // To keep track of last // processed nodes parent // and node itself. public static Node lastLevelLevelOrder; public static Node parentOfLastNode; // Method to delete the last node // from the tree public void deleteLastNode(Node root) { // If tree is empty, it // would return without // any deletion if (root == null) return; // The queue would be needed // to maintain the level order // traversal of nodes Queue<Node> queue = new LinkedList<>(); queue.offer(root); // The traversing would // continue until all // nodes are traversed once while (!queue.isEmpty()) { Node temp = queue.poll(); // If there is left child if (temp.left != null) { queue.offer(temp.left); // For every traversed node, // we would check if it is a // leaf node by checking if // current node has children to it if (temp.left.left == null && temp.left.right == null) { // For every leaf node // encountered, we would // keep not of it as // \"Previously Visided Leaf node. lastLevelLevelOrder = temp.left; parentOfLastNode = temp; } } if (temp.right != null) { queue.offer(temp.right); if (temp.right.left == null && temp.right.right == null) { // For every leaf node // encountered, we would // keep not of it as // \"Previously Visided Leaf node. lastLevelLevelOrder = temp.right; parentOfLastNode = temp; } } } // Once out of above loop. // we would certainly have // last visited node, which // is to be deleted and its // parent node. if (lastLevelLevelOrder != null && parentOfLastNode != null) { // If last node is right child // of parent, make right node // of its parent as NULL or // make left node as NULL if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else System.out.println(\"Empty Tree\"); } // Driver Code public static void main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); System.out.println(\"Inorder traversal \" + \"before deletion of \" + \"last node : \"); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); System.out.println(\"\\nInorder traversal \" + \"after deletion \" + \"of last node : \"); deleteLastNode.inorder(root); }}", "e": 43084, "s": 39253, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic;public class DeleteLastNode { // Tree Node public class Node { public Node left, right; public int data; public Node(int data) { this.data = data; } } // Function to perform the inorder traversal of the tree public void inorder(Node root) { if (root == null) return; inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); } // To keep track of last // processed nodes parent // and node itself. public static Node lastLevelLevelOrder; public static Node parentOfLastNode; // Method to delete the last node // from the tree public void deleteLastNode(Node root) { // If tree is empty, it // would return without // any deletion if (root == null) return; // The queue would be needed // to maintain the level order // traversal of nodes Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); // The traversing would // continue until all // nodes are traversed once while (queue.Count!=0) { Node temp = queue.Dequeue(); // If there is left child if (temp.left != null) { queue.Enqueue(temp.left); // For every traversed node, // we would check if it is a // leaf node by checking if // current node has children to it if (temp.left.left == null && temp.left.right == null) { // For every leaf node // encountered, we would // keep not of it as // \"Previously Visided Leaf node. lastLevelLevelOrder = temp.left; parentOfLastNode = temp; } } if (temp.right != null) { queue.Enqueue(temp.right); if (temp.right.left == null && temp.right.right == null) { // For every leaf node // encountered, we would // keep not of it as // \"Previously Visided Leaf node. lastLevelLevelOrder = temp.right; parentOfLastNode = temp; } } } // Once out of above loop. // we would certainly have // last visited node, which // is to be deleted and its // parent node. if (lastLevelLevelOrder != null && parentOfLastNode != null) { // If last node is right child // of parent, make right node // of its parent as NULL or // make left node as NULL if (parentOfLastNode.right != null) parentOfLastNode.right = null; else parentOfLastNode.left = null; } else Console.WriteLine(\"Empty Tree\"); } // Driver Code public static void Main(String[] args) { Node root = new Node(6); root.left = new Node(5); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(2); root.right.right = new Node(5); DeleteLastNode deleteLastNode = new DeleteLastNode(); Console.WriteLine(\"Inorder traversal \" + \"before deletion of \" + \"last node : \"); deleteLastNode.inorder(root); deleteLastNode.deleteLastNode(root); Console.WriteLine(\"\\nInorder traversal \" + \"after deletion \" + \"of last node : \"); deleteLastNode.inorder(root); }} // This code contributed by Rajput-Ji", "e": 47009, "s": 43084, "text": null }, { "code": null, "e": 47131, "s": 47009, "text": "Inorder traversal before deletion of last node : \n1 5 2 6 4 5 \nInorder traversal after deletion of last node : \n1 5 2 6 4" }, { "code": null, "e": 47384, "s": 47133, "text": "Time Complexity: Since every node would be visited once, the time taken would be linear to the number of nodes present in the tree. Auxiliary Space: Since we would be maintaining a queue to do the level order traversal, the space consumed would be . " }, { "code": null, "e": 47396, "s": 47384, "text": "29AjayKumar" }, { "code": null, "e": 47406, "s": 47396, "text": "Rajput-Ji" }, { "code": null, "e": 47418, "s": 47406, "text": "sanjeev2552" }, { "code": null, "e": 47429, "s": 47418, "text": "nidhi_biet" }, { "code": null, "e": 47436, "s": 47429, "text": "rrrtnx" }, { "code": null, "e": 47445, "s": 47436, "text": "gabaa406" }, { "code": null, "e": 47455, "s": 47445, "text": "ruhelaa48" }, { "code": null, "e": 47470, "s": 47455, "text": "adnanirshad158" }, { "code": null, "e": 47482, "s": 47470, "text": "Binary Tree" }, { "code": null, "e": 47487, "s": 47482, "text": "Tree" }, { "code": null, "e": 47492, "s": 47487, "text": "Tree" }, { "code": null, "e": 47590, "s": 47492, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47626, "s": 47590, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 47666, "s": 47626, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 47709, "s": 47666, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 47766, "s": 47709, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 47800, "s": 47766, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 47841, "s": 47800, "text": "Real-time application of Data Structures" }, { "code": null, "e": 47897, "s": 47841, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 47938, "s": 47897, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 48008, "s": 47938, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" } ]
aplay command in Linux with examples - GeeksforGeeks
05 Mar, 2019 aplay is a command-line audio player for ALSA(Advanced Linux Sound Architecture) sound card drivers. It supports several file formats and multiple soundcards with multiple devices. It is basically used to play audio on command-line interface. aplay is much the same as arecord only it plays instead of recording. For supported soundfile formats, the sampling rate, bit depth, and so forth can be automatically determined from the soundfile header. Syntax: aplay [flags] [filename [filename]] ... If filename not specified uses Standard output. Options: -h, –help : Show the help information. –version : Print current version. -l, –list-devices : List all soundcards and digital audio devices. -L, –list-pcms : List all PCMs(Pulse Code Modulation) defined. -D, –device=NAME : Select PCM by name. -q –quiet : Quiet mode. Suppress messages (not sound :)). -t, –file-type TYPE : File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used. -c, –channels=# : The number of channels. The default is one channel. Valid values are 1 through 32. -f –format=FORMAT : If no format is given U8 is used. -r, –rate=# : Sampling rate in Hertz. The default rate is 8000 Hertz. -d, –duration=# : Interrupt after # seconds. -s, –sleep-min=# : Min ticks to sleep. The default is not to sleep. -M, –mmap : Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used. -N, –nonblock : Open the audio device in non-blocking mode.If the device is busy the program will exit immediately. Note: This command contain various other options that we normally don’t need. If you want to know more about you can simply run following command on your terminal. aplay --help Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE Note: Some of these may not be available on selected hardware. Examples: Plays audio for only 10 secs at 2500hz frequency. Plays full audio clip at 2500hz frezuency. Display version information. linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples Compiling with g++
[ { "code": null, "e": 25489, "s": 25461, "text": "\n05 Mar, 2019" }, { "code": null, "e": 25937, "s": 25489, "text": "aplay is a command-line audio player for ALSA(Advanced Linux Sound Architecture) sound card drivers. It supports several file formats and multiple soundcards with multiple devices. It is basically used to play audio on command-line interface. aplay is much the same as arecord only it plays instead of recording. For supported soundfile formats, the sampling rate, bit depth, and so forth can be automatically determined from the soundfile header." }, { "code": null, "e": 25945, "s": 25937, "text": "Syntax:" }, { "code": null, "e": 25986, "s": 25945, "text": "aplay [flags] [filename [filename]] ...\n" }, { "code": null, "e": 26034, "s": 25986, "text": "If filename not specified uses Standard output." }, { "code": null, "e": 26043, "s": 26034, "text": "Options:" }, { "code": null, "e": 26082, "s": 26043, "text": "-h, –help : Show the help information." }, { "code": null, "e": 26116, "s": 26082, "text": "–version : Print current version." }, { "code": null, "e": 26183, "s": 26116, "text": "-l, –list-devices : List all soundcards and digital audio devices." }, { "code": null, "e": 26246, "s": 26183, "text": "-L, –list-pcms : List all PCMs(Pulse Code Modulation) defined." }, { "code": null, "e": 26285, "s": 26246, "text": "-D, –device=NAME : Select PCM by name." }, { "code": null, "e": 26343, "s": 26285, "text": "-q –quiet : Quiet mode. Suppress messages (not sound :))." }, { "code": null, "e": 26452, "s": 26343, "text": "-t, –file-type TYPE : File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used." }, { "code": null, "e": 26553, "s": 26452, "text": "-c, –channels=# : The number of channels. The default is one channel. Valid values are 1 through 32." }, { "code": null, "e": 26607, "s": 26553, "text": "-f –format=FORMAT : If no format is given U8 is used." }, { "code": null, "e": 26677, "s": 26607, "text": "-r, –rate=# : Sampling rate in Hertz. The default rate is 8000 Hertz." }, { "code": null, "e": 26722, "s": 26677, "text": "-d, –duration=# : Interrupt after # seconds." }, { "code": null, "e": 26790, "s": 26722, "text": "-s, –sleep-min=# : Min ticks to sleep. The default is not to sleep." }, { "code": null, "e": 26923, "s": 26790, "text": "-M, –mmap : Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used." }, { "code": null, "e": 27039, "s": 26923, "text": "-N, –nonblock : Open the audio device in non-blocking mode.If the device is busy the program will exit immediately." }, { "code": null, "e": 27203, "s": 27039, "text": "Note: This command contain various other options that we normally don’t need. If you want to know more about you can simply run following command on your terminal." }, { "code": null, "e": 27216, "s": 27203, "text": "aplay --help" }, { "code": null, "e": 27640, "s": 27216, "text": "Recognized sample formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE" }, { "code": null, "e": 27703, "s": 27640, "text": "Note: Some of these may not be available on selected hardware." }, { "code": null, "e": 27713, "s": 27703, "text": "Examples:" }, { "code": null, "e": 27763, "s": 27713, "text": "Plays audio for only 10 secs at 2500hz frequency." }, { "code": null, "e": 27806, "s": 27763, "text": "Plays full audio clip at 2500hz frezuency." }, { "code": null, "e": 27835, "s": 27806, "text": "Display version information." }, { "code": null, "e": 27849, "s": 27835, "text": "linux-command" }, { "code": null, "e": 27856, "s": 27849, "text": "Picked" }, { "code": null, "e": 27867, "s": 27856, "text": "Linux-Unix" }, { "code": null, "e": 27965, "s": 27867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28000, "s": 27965, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28038, "s": 28000, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28079, "s": 28038, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28114, "s": 28079, "text": "tar command in Linux with examples" }, { "code": null, "e": 28150, "s": 28114, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28188, "s": 28150, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28224, "s": 28188, "text": "diff command in Linux with examples" }, { "code": null, "e": 28262, "s": 28224, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28298, "s": 28262, "text": "Tail command in Linux with examples" } ]
How to create a revealing sidebar using HTML, CSS and JavaScript ? - GeeksforGeeks
31 Mar, 2021 In this article, we are going to create a rotating navigation bar by using simple HTML CSS, and JavaScript. The content of the page will rotate and the navigation bar will reveal itself when the menu button is clicked. Approach: Create an HTML file in which we are going headings and a navigation bar. Create a CSS style to give some animation effects to the web-page elements. Create a JS file for adding event-listeners that can detect the mouse click event. HTML Section: In this section, we will define the structure of the page by following the below steps: We will first create an HTML file. Then we link the CSS file that provides styling to our HTML. In the body section, we add two icons for the closing and opening of the navigation bar. In the end, we add two <script> tags, one for our index.js file and the other for the icon that we have used on our web-page. index.html <html><head> <link rel="stylesheet" href="style.css"></head><body> <div class="main_box show-nav"> <div class="circle-container"> <div class="circle"> <button class="open"> <i class="fas fa-bars"></i> </button> <button class="close"> <i class="fas fa-times"></i> </button> </div> </div> <div class="content"> <h1 style="color: green;"> GeeksforGeeks </h1> <small>Hello Geeks</small> <p> GeeksforGeeks is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's and Coding question likely to be asked in the interviews and make your upcoming placement season efficient and successful. </p> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </p> </div> </div> <nav> <ul class="nav-links"> <li>home</li> <li>about</li> <li>contact</li> </ul> </nav> <script src="https://kit.fontawesome.com/704ff50790.js" crossorigin="anonymous"></script> <script src="index.js"></script></body></html> CSS Section: In this section, we will style the HTML with animations and effects to our HTML page so that it looks interactive to users. We will follow the below steps: We will first restore all the browser effects. Then we use classes and ids to give effects to HTML elements. We use the :hover selector to use hover effects. style.css * { box-sizing: border-box;} body { overflow-x: hidden; margin: 0; background: #000; color: #fff;} .main_box { background-color: #fafafa; color: #000; transform-origin: top left; transition: transform 0.5 linear; width: 100vw; min-height: 100vh; padding: 3em;} .main_box.show-nav { transform: rotate(-20deg);} .circle-container { position: fixed; top: -6em; left: -6em;} .circle { background-color: #ff7979; height: 12em; width: 12em; border-radius: 50%; position: relative; transition: transform 0.5s linear; cursor: pointer;} .circle button { position: absolute; top: 50%; left: 50%; height: 6em; background: transparent; border: 0; color: #fff; cursor: pointer;} .circle button:focus { outline: none;} .circle button.open { left: 60%;}.circle button.close { top: 60%; transform: rotate(90deg); transform-origin: top left;} .main_box.show-nav .circle { transform: rotate(-70deg);} nav { position: fixed; left: 0; bottom: 2.5em; z-index: 5;} nav ul { list-style: none; padding-left: 2em;} nav ul li { text-transform: uppercase; color: rgb(243, 243, 243); margin: 2.5em 0; transform: translateX(-100%); transition: transform 0.4 ease-in;} nav ul li + li { margin-left: 1em; transform: translateX(-150%);} nav ul li + li + li { margin-left: 2em; transform: translateX(-200%);} .main_box.show-nav + nav li { transform: translateX(0); transition-delay: 0.3s;} .nav-links { cursor: pointer;} JavaScript Section: In this section, we will configure the navigation button to listen for click events and add or remove the class that controls the navigation bar. We will follow the below steps: We will first select all the required elements from the page. We will next add an event listener to the open and close buttons. We will then add or remove the navigation bar class when the buttons are clicked. main.js // Selecting the required elementsconst open = document.querySelector(".open");const close = document.querySelector(".close");const main_box = document.querySelector(".main_box"); // Adding an event listener for the mouse// click for opening the navigation baropen.addEventListener("click", () => { main_box.classList.add("show-nav");}); // Adding an event listener for the mouse// click for closing the navigation barclose.addEventListener("click", () => { main_box.classList.remove("show-nav");}); Output: CSS-Properties HTML-Tags javascript-basics CSS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26840, "s": 26621, "text": "In this article, we are going to create a rotating navigation bar by using simple HTML CSS, and JavaScript. The content of the page will rotate and the navigation bar will reveal itself when the menu button is clicked." }, { "code": null, "e": 26850, "s": 26840, "text": "Approach:" }, { "code": null, "e": 26923, "s": 26850, "text": "Create an HTML file in which we are going headings and a navigation bar." }, { "code": null, "e": 26999, "s": 26923, "text": "Create a CSS style to give some animation effects to the web-page elements." }, { "code": null, "e": 27082, "s": 26999, "text": "Create a JS file for adding event-listeners that can detect the mouse click event." }, { "code": null, "e": 27184, "s": 27082, "text": "HTML Section: In this section, we will define the structure of the page by following the below steps:" }, { "code": null, "e": 27219, "s": 27184, "text": "We will first create an HTML file." }, { "code": null, "e": 27280, "s": 27219, "text": "Then we link the CSS file that provides styling to our HTML." }, { "code": null, "e": 27369, "s": 27280, "text": "In the body section, we add two icons for the closing and opening of the navigation bar." }, { "code": null, "e": 27495, "s": 27369, "text": "In the end, we add two <script> tags, one for our index.js file and the other for the icon that we have used on our web-page." }, { "code": null, "e": 27506, "s": 27495, "text": "index.html" }, { "code": "<html><head> <link rel=\"stylesheet\" href=\"style.css\"></head><body> <div class=\"main_box show-nav\"> <div class=\"circle-container\"> <div class=\"circle\"> <button class=\"open\"> <i class=\"fas fa-bars\"></i> </button> <button class=\"close\"> <i class=\"fas fa-times\"></i> </button> </div> </div> <div class=\"content\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <small>Hello Geeks</small> <p> GeeksforGeeks is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's and Coding question likely to be asked in the interviews and make your upcoming placement season efficient and successful. </p> <p> Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </p> </div> </div> <nav> <ul class=\"nav-links\"> <li>home</li> <li>about</li> <li>contact</li> </ul> </nav> <script src=\"https://kit.fontawesome.com/704ff50790.js\" crossorigin=\"anonymous\"></script> <script src=\"index.js\"></script></body></html>", "e": 29284, "s": 27506, "text": null }, { "code": null, "e": 29453, "s": 29284, "text": "CSS Section: In this section, we will style the HTML with animations and effects to our HTML page so that it looks interactive to users. We will follow the below steps:" }, { "code": null, "e": 29500, "s": 29453, "text": "We will first restore all the browser effects." }, { "code": null, "e": 29562, "s": 29500, "text": "Then we use classes and ids to give effects to HTML elements." }, { "code": null, "e": 29611, "s": 29562, "text": "We use the :hover selector to use hover effects." }, { "code": null, "e": 29621, "s": 29611, "text": "style.css" }, { "code": "* { box-sizing: border-box;} body { overflow-x: hidden; margin: 0; background: #000; color: #fff;} .main_box { background-color: #fafafa; color: #000; transform-origin: top left; transition: transform 0.5 linear; width: 100vw; min-height: 100vh; padding: 3em;} .main_box.show-nav { transform: rotate(-20deg);} .circle-container { position: fixed; top: -6em; left: -6em;} .circle { background-color: #ff7979; height: 12em; width: 12em; border-radius: 50%; position: relative; transition: transform 0.5s linear; cursor: pointer;} .circle button { position: absolute; top: 50%; left: 50%; height: 6em; background: transparent; border: 0; color: #fff; cursor: pointer;} .circle button:focus { outline: none;} .circle button.open { left: 60%;}.circle button.close { top: 60%; transform: rotate(90deg); transform-origin: top left;} .main_box.show-nav .circle { transform: rotate(-70deg);} nav { position: fixed; left: 0; bottom: 2.5em; z-index: 5;} nav ul { list-style: none; padding-left: 2em;} nav ul li { text-transform: uppercase; color: rgb(243, 243, 243); margin: 2.5em 0; transform: translateX(-100%); transition: transform 0.4 ease-in;} nav ul li + li { margin-left: 1em; transform: translateX(-150%);} nav ul li + li + li { margin-left: 2em; transform: translateX(-200%);} .main_box.show-nav + nav li { transform: translateX(0); transition-delay: 0.3s;} .nav-links { cursor: pointer;}", "e": 31080, "s": 29621, "text": null }, { "code": null, "e": 31278, "s": 31080, "text": "JavaScript Section: In this section, we will configure the navigation button to listen for click events and add or remove the class that controls the navigation bar. We will follow the below steps:" }, { "code": null, "e": 31340, "s": 31278, "text": "We will first select all the required elements from the page." }, { "code": null, "e": 31406, "s": 31340, "text": "We will next add an event listener to the open and close buttons." }, { "code": null, "e": 31488, "s": 31406, "text": "We will then add or remove the navigation bar class when the buttons are clicked." }, { "code": null, "e": 31496, "s": 31488, "text": "main.js" }, { "code": "// Selecting the required elementsconst open = document.querySelector(\".open\");const close = document.querySelector(\".close\");const main_box = document.querySelector(\".main_box\"); // Adding an event listener for the mouse// click for opening the navigation baropen.addEventListener(\"click\", () => { main_box.classList.add(\"show-nav\");}); // Adding an event listener for the mouse// click for closing the navigation barclose.addEventListener(\"click\", () => { main_box.classList.remove(\"show-nav\");});", "e": 32000, "s": 31496, "text": null }, { "code": null, "e": 32008, "s": 32000, "text": "Output:" }, { "code": null, "e": 32023, "s": 32008, "text": "CSS-Properties" }, { "code": null, "e": 32033, "s": 32023, "text": "HTML-Tags" }, { "code": null, "e": 32051, "s": 32033, "text": "javascript-basics" }, { "code": null, "e": 32055, "s": 32051, "text": "CSS" }, { "code": null, "e": 32066, "s": 32055, "text": "JavaScript" }, { "code": null, "e": 32083, "s": 32066, "text": "Web Technologies" }, { "code": null, "e": 32181, "s": 32083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32220, "s": 32181, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32257, "s": 32220, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32286, "s": 32257, "text": "Form validation using jQuery" }, { "code": null, "e": 32328, "s": 32286, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32363, "s": 32328, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 32403, "s": 32363, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32448, "s": 32403, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32509, "s": 32448, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32581, "s": 32509, "text": "Differences between Functional Components and Class Components in React" } ]
Queries to count connected components after removal of a vertex from a Tree - GeeksforGeeks
07 Oct, 2021 Given a Tree consisting of N nodes valued in the range [0, N) and an array Queries[] of Q integers consisting of values in the range [0, N). The task for each query is to remove the vertex valued Q[i] and count the connected components in the resulting graph. Examples: Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {0, 1, 6} Output:3 3 1Explanation:Query 1: Removal of the node valued 0 leads to removal of the edges (0, 1), (0, 2) and (0, 3). Therefore, the remaining graph has 3 connected components: [1, 4, 5], [2], [3, 6]Query 2:Removal of the node valued 1 leads to removal of the edges (1, 4), (1, 5) and (1, 0). Therefore, remaining graph has 3 connected components: [4], [5], [2, 0, 3, 6]Query 3:Removal of the node valued 6 leads to removal of the edges (3, 6). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 5]. Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {5, 3, 2} Output:1 2 1Explanation:Query 1: Removal of the node valued 5 leads to removal of the edge (1, 5). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 6]Query 2:Removal of the node valued 3 leads to removal of the edges (0, 3), (3, 6). Therefore, the remaining graph has 2 connected components: [0, 1, 2, 4, 5], [6]Query 3: Removal of the node valued 2 leads to removal of the edge (0, 2). Therefore, the remaining graph has 1 connected component: [0, 1, 3, 4, 5, 6] Approach: The idea is to observe that in a Tree, whenever a node is deleted, the nodes which were connected together to that node get separated. So, the count of connected components becomes equal to the degree of the deleted node.Therefore, the approach is to precompute and store the degree of each node in an array. For every query, the count of the connected components is simply the degree of the corresponding node in the query. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define MAX 100005 // Stores degree of the nodesint degree[MAX]; // Function that finds the degree of// each node in the given graphvoid DegreeOfNodes(int Edges[][2], int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsvoid findConnectedComponents(int x){ // Print the degree of node x cout << degree[x] << ' ';} // Function that counts the connected// components after removing a vertex// for each queryvoid countCC(int N, int Q, int Queries[], int Edges[][2]){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codeint main(){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int Queries[] = { 0, 1, 6 }; // Given Edges int Edges[][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 4 }, { 1, 5 }, { 3, 6 } }; // Function Call countCC(N, Q, Queries, Edges); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ static final int MAX = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [][]Edges, int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){ // Print the degree of node x System.out.print(degree[x] + " ");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q, int Queries[], int [][]Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codepublic static void main(String[] args){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int Queries[] = {0, 1, 6}; // Given Edges int [][]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}; // Function Call countCC(N, Q, Queries, Edges);}} // This code is contributed by Rajput-Ji # Python3 program for the above approachMAX = 100005 # Stores degree of the nodesdegree = [0] * MAX # Function that finds the degree of# each node in the given graphdef DegreeOfNodes(Edges, N): # Precompute degrees of each node for i in range(N - 1): degree[Edges[i][0]] += 1 degree[Edges[i][1]] += 1 # Function to print the number of# connected componentsdef findConnectedComponents(x): # Print the degree of node x print(degree[x], end = " ") # Function that counts the connected# components after removing a vertex# for each querydef countCC(N, Q, Queries, Edges): # Count degree of each node DegreeOfNodes(Edges, N) # Iterate over each query for i in range(Q): # Find connected components # after removing given vertex findConnectedComponents(Queries[i]) # Driver Codeif __name__ == '__main__': # Given N nodes and Q queries N = 7 Q = 3 # Given array of queries Queries = [ 0, 1, 6 ] # Given Edges Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ] ] # Function call countCC(N, Q, Queries, Edges) # This code is contributed by mohit kumar 29 // C# program for// the above approachusing System;class GFG{ static readonly int MAX = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [,]Edges, int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i, 0]]++; degree[Edges[i, 1]]++; }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){ // Print the degree of node x Console.Write(degree[x] + " ");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q, int []Queries, int [,]Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codepublic static void Main(String[] args){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int []Queries = {0, 1, 6}; // Given Edges int [,]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}; // Function Call countCC(N, Q, Queries, Edges);}} // This code is contributed by shikhasingrajput <script> // Javascript program for the above approachvar MAX = 100005 // Stores degree of the nodesvar degree = Array(MAX).fill(0) // Function that finds the degree of// each node in the given graphfunction DegreeOfNodes(Edges, N){ // Precompute degrees of each node for (var i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsfunction findConnectedComponents(x){ // Print the degree of node x document.write( degree[x] + ' ');} // Function that counts the connected// components after removing a vertex// for each queryfunction countCC(N, Q, Queries, Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (var i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Code// Given N nodes and Q queriesvar N = 7, Q = 3;// Given array of queriesvar Queries = [ 0, 1, 6 ];// Given Edgesvar Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ] ];// Function CallcountCC(N, Q, Queries, Edges); </script> 3 3 1 Time Complexity: O(E + Q), where E is the number of edges(E = N – 1) and Q is the number of queries.Auxiliary Space: O(V), where V is number the of vertices. mohit kumar 29 Rajput-Ji shikhasingrajput famously surinderdawra388 anikakapoor connected-components graph-connectivity Graph Tree Graph Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Tree Traversals (Inorder, Preorder and Postorder) AVL Tree | Set 1 (Insertion) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 26369, "s": 26341, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26629, "s": 26369, "text": "Given a Tree consisting of N nodes valued in the range [0, N) and an array Queries[] of Q integers consisting of values in the range [0, N). The task for each query is to remove the vertex valued Q[i] and count the connected components in the resulting graph." }, { "code": null, "e": 26639, "s": 26629, "text": "Examples:" }, { "code": null, "e": 26740, "s": 26639, "text": "Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {0, 1, 6} " }, { "code": null, "e": 27264, "s": 26740, "text": "Output:3 3 1Explanation:Query 1: Removal of the node valued 0 leads to removal of the edges (0, 1), (0, 2) and (0, 3). Therefore, the remaining graph has 3 connected components: [1, 4, 5], [2], [3, 6]Query 2:Removal of the node valued 1 leads to removal of the edges (1, 4), (1, 5) and (1, 0). Therefore, remaining graph has 3 connected components: [4], [5], [2, 0, 3, 6]Query 3:Removal of the node valued 6 leads to removal of the edges (3, 6). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 5]." }, { "code": null, "e": 27365, "s": 27264, "text": "Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}, Queries[] = {5, 3, 2} " }, { "code": null, "e": 27854, "s": 27365, "text": "Output:1 2 1Explanation:Query 1: Removal of the node valued 5 leads to removal of the edge (1, 5). Therefore, the remaining graph has 1 connected component: [0, 1, 2, 3, 4, 6]Query 2:Removal of the node valued 3 leads to removal of the edges (0, 3), (3, 6). Therefore, the remaining graph has 2 connected components: [0, 1, 2, 4, 5], [6]Query 3: Removal of the node valued 2 leads to removal of the edge (0, 2). Therefore, the remaining graph has 1 connected component: [0, 1, 3, 4, 5, 6]" }, { "code": null, "e": 28289, "s": 27854, "text": "Approach: The idea is to observe that in a Tree, whenever a node is deleted, the nodes which were connected together to that node get separated. So, the count of connected components becomes equal to the degree of the deleted node.Therefore, the approach is to precompute and store the degree of each node in an array. For every query, the count of the connected components is simply the degree of the corresponding node in the query." }, { "code": null, "e": 28340, "s": 28289, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28344, "s": 28340, "text": "C++" }, { "code": null, "e": 28349, "s": 28344, "text": "Java" }, { "code": null, "e": 28357, "s": 28349, "text": "Python3" }, { "code": null, "e": 28360, "s": 28357, "text": "C#" }, { "code": null, "e": 28371, "s": 28360, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define MAX 100005 // Stores degree of the nodesint degree[MAX]; // Function that finds the degree of// each node in the given graphvoid DegreeOfNodes(int Edges[][2], int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsvoid findConnectedComponents(int x){ // Print the degree of node x cout << degree[x] << ' ';} // Function that counts the connected// components after removing a vertex// for each queryvoid countCC(int N, int Q, int Queries[], int Edges[][2]){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codeint main(){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int Queries[] = { 0, 1, 6 }; // Given Edges int Edges[][2] = { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 1, 4 }, { 1, 5 }, { 3, 6 } }; // Function Call countCC(N, Q, Queries, Edges); return 0;}", "e": 29716, "s": 28371, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ static final int MAX = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [][]Edges, int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){ // Print the degree of node x System.out.print(degree[x] + \" \");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q, int Queries[], int [][]Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codepublic static void main(String[] args){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int Queries[] = {0, 1, 6}; // Given Edges int [][]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}; // Function Call countCC(N, Q, Queries, Edges);}} // This code is contributed by Rajput-Ji", "e": 31119, "s": 29716, "text": null }, { "code": "# Python3 program for the above approachMAX = 100005 # Stores degree of the nodesdegree = [0] * MAX # Function that finds the degree of# each node in the given graphdef DegreeOfNodes(Edges, N): # Precompute degrees of each node for i in range(N - 1): degree[Edges[i][0]] += 1 degree[Edges[i][1]] += 1 # Function to print the number of# connected componentsdef findConnectedComponents(x): # Print the degree of node x print(degree[x], end = \" \") # Function that counts the connected# components after removing a vertex# for each querydef countCC(N, Q, Queries, Edges): # Count degree of each node DegreeOfNodes(Edges, N) # Iterate over each query for i in range(Q): # Find connected components # after removing given vertex findConnectedComponents(Queries[i]) # Driver Codeif __name__ == '__main__': # Given N nodes and Q queries N = 7 Q = 3 # Given array of queries Queries = [ 0, 1, 6 ] # Given Edges Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ] ] # Function call countCC(N, Q, Queries, Edges) # This code is contributed by mohit kumar 29", "e": 32316, "s": 31119, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG{ static readonly int MAX = 100005; // Stores degree of the nodesstatic int []degree = new int[MAX]; // Function that finds the degree of// each node in the given graphstatic void DegreeOfNodes(int [,]Edges, int N){ // Precompute degrees of each node for (int i = 0; i < N - 1; i++) { degree[Edges[i, 0]]++; degree[Edges[i, 1]]++; }} // Function to print the number of// connected componentsstatic void findConnectedComponents(int x){ // Print the degree of node x Console.Write(degree[x] + \" \");} // Function that counts the connected// components after removing a vertex// for each querystatic void countCC(int N, int Q, int []Queries, int [,]Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (int i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Codepublic static void Main(String[] args){ // Given N nodes and Q queries int N = 7, Q = 3; // Given array of queries int []Queries = {0, 1, 6}; // Given Edges int [,]Edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}}; // Function Call countCC(N, Q, Queries, Edges);}} // This code is contributed by shikhasingrajput", "e": 33713, "s": 32316, "text": null }, { "code": "<script> // Javascript program for the above approachvar MAX = 100005 // Stores degree of the nodesvar degree = Array(MAX).fill(0) // Function that finds the degree of// each node in the given graphfunction DegreeOfNodes(Edges, N){ // Precompute degrees of each node for (var i = 0; i < N - 1; i++) { degree[Edges[i][0]]++; degree[Edges[i][1]]++; }} // Function to print the number of// connected componentsfunction findConnectedComponents(x){ // Print the degree of node x document.write( degree[x] + ' ');} // Function that counts the connected// components after removing a vertex// for each queryfunction countCC(N, Q, Queries, Edges){ // Count degree of each node DegreeOfNodes(Edges, N); // Iterate over each query for (var i = 0; i < Q; i++) { // Find connected components // after removing given vertex findConnectedComponents(Queries[i]); }} // Driver Code// Given N nodes and Q queriesvar N = 7, Q = 3;// Given array of queriesvar Queries = [ 0, 1, 6 ];// Given Edgesvar Edges = [ [ 0, 1 ], [ 0, 2 ], [ 0, 3 ], [ 1, 4 ], [ 1, 5 ], [ 3, 6 ] ];// Function CallcountCC(N, Q, Queries, Edges); </script>", "e": 34927, "s": 33713, "text": null }, { "code": null, "e": 34933, "s": 34927, "text": "3 3 1" }, { "code": null, "e": 35093, "s": 34935, "text": "Time Complexity: O(E + Q), where E is the number of edges(E = N – 1) and Q is the number of queries.Auxiliary Space: O(V), where V is number the of vertices." }, { "code": null, "e": 35108, "s": 35093, "text": "mohit kumar 29" }, { "code": null, "e": 35118, "s": 35108, "text": "Rajput-Ji" }, { "code": null, "e": 35135, "s": 35118, "text": "shikhasingrajput" }, { "code": null, "e": 35144, "s": 35135, "text": "famously" }, { "code": null, "e": 35161, "s": 35144, "text": "surinderdawra388" }, { "code": null, "e": 35173, "s": 35161, "text": "anikakapoor" }, { "code": null, "e": 35194, "s": 35173, "text": "connected-components" }, { "code": null, "e": 35213, "s": 35194, "text": "graph-connectivity" }, { "code": null, "e": 35219, "s": 35213, "text": "Graph" }, { "code": null, "e": 35224, "s": 35219, "text": "Tree" }, { "code": null, "e": 35230, "s": 35224, "text": "Graph" }, { "code": null, "e": 35235, "s": 35230, "text": "Tree" }, { "code": null, "e": 35333, "s": 35235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35353, "s": 35333, "text": "Topological Sorting" }, { "code": null, "e": 35386, "s": 35353, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 35454, "s": 35386, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 35504, "s": 35454, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 35579, "s": 35504, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 35629, "s": 35579, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 35658, "s": 35629, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 35693, "s": 35658, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 35727, "s": 35693, "text": "Level Order Binary Tree Traversal" } ]
Percentile rank of a column in a Pandas DataFrame - GeeksforGeeks
17 Aug, 2020 Let us see how to find the percentile rank of a column in a Pandas DataFrame. We will use the rank() function with the argument pct = True to find the percentile rank. Example 1 : # import the moduleimport pandas as pd # create a DataFrame data = {'Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay' : [50000, 70000, 62000, 67000, 56000]} df = pd.DataFrame(data) # create a new column of percentile rankdf['Percentile Rank'] = df.Pay.rank(pct = True) # displaying the percentile rankdisplay(df) Output : Example 2 : # import the moduleimport pandas as pd # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs) # create a new column of percentile rankdf['Percentile Rank'] = df.runs.rank(pct = True) # displaying the percentile rankdisplay(df) Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25503, "s": 25475, "text": "\n17 Aug, 2020" }, { "code": null, "e": 25671, "s": 25503, "text": "Let us see how to find the percentile rank of a column in a Pandas DataFrame. We will use the rank() function with the argument pct = True to find the percentile rank." }, { "code": null, "e": 25683, "s": 25671, "text": "Example 1 :" }, { "code": "# import the moduleimport pandas as pd # create a DataFrame data = {'Name': ['Mukul', 'Rohan', 'Mayank', 'Shubham', 'Aakash'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut'], 'Pay' : [50000, 70000, 62000, 67000, 56000]} df = pd.DataFrame(data) # create a new column of percentile rankdf['Percentile Rank'] = df.Pay.rank(pct = True) # displaying the percentile rankdisplay(df) ", "e": 26142, "s": 25683, "text": null }, { "code": null, "e": 26151, "s": 26142, "text": "Output :" }, { "code": null, "e": 26163, "s": 26151, "text": "Example 2 :" }, { "code": "# import the moduleimport pandas as pd # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs) # create a new column of percentile rankdf['Percentile Rank'] = df.runs.rank(pct = True) # displaying the percentile rankdisplay(df) ", "e": 26683, "s": 26163, "text": null }, { "code": null, "e": 26692, "s": 26683, "text": "Output :" }, { "code": null, "e": 26716, "s": 26692, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26730, "s": 26716, "text": "Python-pandas" }, { "code": null, "e": 26737, "s": 26730, "text": "Python" }, { "code": null, "e": 26835, "s": 26737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26853, "s": 26835, "text": "Python Dictionary" }, { "code": null, "e": 26888, "s": 26853, "text": "Read a file line by line in Python" }, { "code": null, "e": 26920, "s": 26888, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26942, "s": 26920, "text": "Enumerate() in Python" }, { "code": null, "e": 26984, "s": 26942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27014, "s": 26984, "text": "Iterate over a list in Python" }, { "code": null, "e": 27040, "s": 27014, "text": "Python String | replace()" }, { "code": null, "e": 27069, "s": 27040, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27113, "s": 27069, "text": "Reading and Writing to text files in Python" } ]
Java Program to Count Number of Digits in a String - GeeksforGeeks
30 Apr, 2021 The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it’s content can’t change. Complete traversal in the string is required to find the total number of digits in a string. Examples: Input : string = "GeeksforGeeks password is : 1234" Output: Total number of Digits = 4 Input : string = "G e e k s f o r G e e k 1234" Output: Total number of Digits = 4 Approach: Create one integer variable and initialize it with 0.Start string traversal.If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable.After the end of the traversal, print variable. Create one integer variable and initialize it with 0. Start string traversal. If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable. After the end of the traversal, print variable. Below is the implementation of the above approach: Java // Java Program to Count Number of Digits in a Stringpublic class GFG { public static void main(String[] args) { String str = "GeeksforGeeks password is : 1234"; int digits = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) >= 48 && str.charAt(i) <= 57) digits++; } System.out.println("Total number of Digits = " + digits); }} Total number of Digits = 4 Time Complexity: O(N), where N is the length of the string. pranaythanneru Java-String-Programs Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25673, "s": 25645, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25923, "s": 25673, "text": "The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it’s content can’t change. Complete traversal in the string is required to find the total number of digits in a string." }, { "code": null, "e": 25933, "s": 25923, "text": "Examples:" }, { "code": null, "e": 26104, "s": 25933, "text": "Input : string = \"GeeksforGeeks password is : 1234\"\nOutput: Total number of Digits = 4\n\nInput : string = \"G e e k s f o r G e e k 1234\"\nOutput: Total number of Digits = 4" }, { "code": null, "e": 26114, "s": 26104, "text": "Approach:" }, { "code": null, "e": 26380, "s": 26114, "text": "Create one integer variable and initialize it with 0.Start string traversal.If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable.After the end of the traversal, print variable." }, { "code": null, "e": 26434, "s": 26380, "text": "Create one integer variable and initialize it with 0." }, { "code": null, "e": 26458, "s": 26434, "text": "Start string traversal." }, { "code": null, "e": 26601, "s": 26458, "text": "If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable." }, { "code": null, "e": 26649, "s": 26601, "text": "After the end of the traversal, print variable." }, { "code": null, "e": 26700, "s": 26649, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26705, "s": 26700, "text": "Java" }, { "code": "// Java Program to Count Number of Digits in a Stringpublic class GFG { public static void main(String[] args) { String str = \"GeeksforGeeks password is : 1234\"; int digits = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) >= 48 && str.charAt(i) <= 57) digits++; } System.out.println(\"Total number of Digits = \" + digits); }}", "e": 27142, "s": 26705, "text": null }, { "code": null, "e": 27172, "s": 27145, "text": "Total number of Digits = 4" }, { "code": null, "e": 27234, "s": 27174, "text": "Time Complexity: O(N), where N is the length of the string." }, { "code": null, "e": 27251, "s": 27236, "text": "pranaythanneru" }, { "code": null, "e": 27272, "s": 27251, "text": "Java-String-Programs" }, { "code": null, "e": 27279, "s": 27272, "text": "Picked" }, { "code": null, "e": 27303, "s": 27279, "text": "Technical Scripter 2020" }, { "code": null, "e": 27308, "s": 27303, "text": "Java" }, { "code": null, "e": 27322, "s": 27308, "text": "Java Programs" }, { "code": null, "e": 27341, "s": 27322, "text": "Technical Scripter" }, { "code": null, "e": 27346, "s": 27341, "text": "Java" }, { "code": null, "e": 27444, "s": 27346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27495, "s": 27444, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27525, "s": 27495, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27540, "s": 27525, "text": "Stream In Java" }, { "code": null, "e": 27559, "s": 27540, "text": "Interfaces in Java" }, { "code": null, "e": 27590, "s": 27559, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27618, "s": 27590, "text": "Initializing a List in Java" }, { "code": null, "e": 27662, "s": 27618, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 27688, "s": 27662, "text": "Java Programming Examples" }, { "code": null, "e": 27722, "s": 27688, "text": "Convert Double to Integer in Java" } ]
Python | sympy.symbols() method - GeeksforGeeks
02 Aug, 2019 With the help of sympy.symbols() method, we can declare some variables for the use of mathematical expression and polynomials by using sympy.symbols() method. Syntax : sympy.symbols()Return : Return nothing or None. Example #1 :In this example we can see that by using sympy.symbols() method, we are able to get the variables for mathematical expression and polynomials. # import sympyfrom sympy import * # Use sympy.symbols() methodx, y = symbols('x y')x = 2gfg = x**2 + 4 * x + 4 print(gfg) Output : 16 Example #2 : # import sympyfrom sympy import * # Use sympy.symbols() methodx, y = symbols('x y')x = 5y = 5gfg = x**2 + y print(gfg) Output : 30 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n02 Aug, 2019" }, { "code": null, "e": 25720, "s": 25561, "text": "With the help of sympy.symbols() method, we can declare some variables for the use of mathematical expression and polynomials by using sympy.symbols() method." }, { "code": null, "e": 25777, "s": 25720, "text": "Syntax : sympy.symbols()Return : Return nothing or None." }, { "code": null, "e": 25932, "s": 25777, "text": "Example #1 :In this example we can see that by using sympy.symbols() method, we are able to get the variables for mathematical expression and polynomials." }, { "code": "# import sympyfrom sympy import * # Use sympy.symbols() methodx, y = symbols('x y')x = 2gfg = x**2 + 4 * x + 4 print(gfg)", "e": 26056, "s": 25932, "text": null }, { "code": null, "e": 26065, "s": 26056, "text": "Output :" }, { "code": null, "e": 26068, "s": 26065, "text": "16" }, { "code": null, "e": 26081, "s": 26068, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * # Use sympy.symbols() methodx, y = symbols('x y')x = 5y = 5gfg = x**2 + y print(gfg)", "e": 26202, "s": 26081, "text": null }, { "code": null, "e": 26211, "s": 26202, "text": "Output :" }, { "code": null, "e": 26214, "s": 26211, "text": "30" }, { "code": null, "e": 26220, "s": 26214, "text": "SymPy" }, { "code": null, "e": 26227, "s": 26220, "text": "Python" }, { "code": null, "e": 26325, "s": 26227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26357, "s": 26325, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26399, "s": 26357, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26441, "s": 26399, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26497, "s": 26441, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26524, "s": 26497, "text": "Python Classes and Objects" }, { "code": null, "e": 26563, "s": 26524, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26594, "s": 26563, "text": "Python | os.path.join() method" }, { "code": null, "e": 26623, "s": 26594, "text": "Create a directory in Python" }, { "code": null, "e": 26645, "s": 26623, "text": "Defaultdict in Python" } ]
Python | Catching the ball game - GeeksforGeeks
13 May, 2022 Python is a multipurpose language and can be used in almost every field of development. Python can also be used to develop different type of game. Let’s try to develop a simple Catching the ball game using Python and TKinter.Game is very simple. There is one bar at the bottom of game window which can be moved left or right using the buttons that are in the game window. Red ball will continuously fall from top to bottom and can start from any random x-axis distance. The task is to bring that bar to a suitable location by moving left or right so that the red ball will fall on that bar(catch the ball onto the bar) not on the ground. If player catches the ball onto the bar then score will get increase and that ball will disappear and again a new red ball will start falling from top to bottom starting from random x-axis distance. If player miss the ball from catching it on the bar then you will lose the game and then finally scorecard will appear on the game window.Approach: Use Tkinter package in python for building GUI(Graphical user interface).Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for drawing pictures or other complex layouts. We can place graphics, text, widgets or frames on Canvas. Use Tkinter package in python for building GUI(Graphical user interface). Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for drawing pictures or other complex layouts. We can place graphics, text, widgets or frames on Canvas. Syntax: w = Canvas ( master, option=value, ... ) Parameters: master - This represents the parent window. options - List of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. Example- width, height etc. Use canvas.create_oval for creating the ball. create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval. Use canvas.create_oval for creating the ball. create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval. Syntax: oval = canvas.create_oval(x0, y0, x1, y1, options) Use canvas.create_rectangle for creating the bar. create_rectangle creates a rectangle at the given coordinates. It takes two pairs of coordinates; the top left and bottom right coordinates. Use canvas.create_rectangle for creating the bar. create_rectangle creates a rectangle at the given coordinates. It takes two pairs of coordinates; the top left and bottom right coordinates. Syntax: rod = canvas.create_rectangle(x0, y0, x1, y1, options) Use canvas.move for moving the ball or bar. canvas.move enables the object to move with the specified (x, y) coordinates. Use canvas.move for moving the ball or bar. canvas.move enables the object to move with the specified (x, y) coordinates. Syntax: move=canvas.move(name of object, x, y) Note: *Take x=0 for moving the ball in vertical direction only and take y=0 for moving the bar in horizontal direction only. *Disappear the ball when it touches the ground or the bar using canvas.delete(object). Use Button for moving the bar in forward or backward and then apply action event on it. Refer Python gui Tkinter Use Button for moving the bar in forward or backward and then apply action event on it. Refer Python gui Tkinter Example Python3 # Python code for catching the ball game # importing suitable packagesfrom tkinter import Tk,Button,Labelfrom tkinter import Canvasfrom random import randint # defining Tk from Tkinterroot = Tk()root.title("Catch the ball Game")root.resizable(False,False) # for defining the canvascanvas = Canvas(root, width=600, height=600)canvas.pack() # variable for the vertical distance# travelled by balllimit = 0 # variable for horizontal distance# of bar from x-axisdist = 5 # variable for scorescore = 0 # Class for the Creating and moving ballclass Ball: # for creation of ball on the canvas def __init__(self, canvas, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.canvas = canvas # for creation of ball object self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill = "red",tags = 'dot1') # for moving the ball def move_ball(self): # defining offset offset = 10 global limit # checking if ball lands ground or bar if limit >= 510: global dist,score,next # checking that ball falls on the bar if(dist - offset <= self.x1 and dist + 40 + offset >= self.x2): # incrementing the score score += 10 # disappear the ball canvas.delete('dot1') # calling the function for again # creation of ball object ball_set() else: # disappear the ball canvas.delete('dot1') bar.delete_bar(self) # display the score score_board() return # incrementing the vertical distance # travelled by ball by deltay limit += 1 # moving the ball in vertical direction # by taking x=0 and y=deltay self.canvas.move(self.ball,0,1) # for continuous moving of ball again call move_ball self.canvas.after(10,self.move_ball) # class for creating and moving bar class bar: # method for creating bar def __init__(self,canvas,x1,y1,x2,y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.canvas = canvas # for creating bar using create_rectangle self.rod=canvas.create_rectangle(self.x1, self.y1, self.x2, self.y2, fill="yellow",tags='dot2') # method for moving the bar def move_bar(self,num): global dist # checking the forward or backward button if(num == 1): # moving the bar in forward direction by # taking x-axis positive distance and # taking vertical distance y=0 self.canvas.move(self.rod,20,0) # incrementing the distance of bar from x-axis dist += 20 else: # moving the bar in backward direction by taking x-axis # negative distance and taking vertical distance y=0 self.canvas.move(self.rod,-20,0) # decrementing the distance of bar from x-axis dist-=20 def delete_bar(self): canvas.delete('dot2') # Function to define the dimensions of the balldef ball_set(): global limit limit=0 # for random x-axis distance from # where the ball starts to fall value = randint(0,570) # define the dimensions of the ball ball1 = Ball(canvas,value,20,value+30,50) # call function for moving of the ball ball1.move_ball() # Function for displaying the score# after getting over of the gamedef score_board(): root2 = Tk() root2.title("Catch the ball Game") root2.resizable(False,False) canvas2 = Canvas(root2,width=300,height=300) canvas2.pack() w = Label(canvas2,text="\nOOPS...GAME IS OVER\n\nYOUR SCORE = " + str(score) + "\n\n") w.pack() button3 = Button(canvas2, text="PLAY AGAIN", bg="green", command=lambda:play_again(root2)) button3.pack() button4 = Button(canvas2,text="EXIT",bg="green", command=lambda:exit_handler(root2)) button4.pack() # Function for handling the play again requestdef play_again(root2): root2.destroy() main() # Function for handling exit requestdef exit_handler(root2): root2.destroy() root.destroy() # Main functiondef main(): global score,dist score = 0 dist = 0 # defining the dimensions of bar bar1=bar(canvas,5,560,45,575) # defining the text,colour of buttons and # also define the action after click on # the button by calling suitable methods button = Button(canvas,text="==>", bg="green", command=lambda:bar1.move_bar(1)) # placing the buttons at suitable location on the canvas button.place(x=300,y=580) button2 = Button(canvas,text="<==",bg="green", command=lambda:bar1.move_bar(0)) button2.place(x=260,y=580) # calling the function for defining # the dimensions of ball ball_set() root.mainloop() # Driver codeif(__name__=="__main__"): main() Output: Note:The above code can’t be run on online IDE as Tkinter package is imported. clintra ruhelaa48 varunsaini1506 Project Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java Swing | Simple User Registration Form Banking Transaction System using Java Face Detection using Python and OpenCV with webcam Snake Game in C Program for Employee Management System 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": 26021, "s": 25993, "text": "\n13 May, 2022" }, { "code": null, "e": 27007, "s": 26021, "text": "Python is a multipurpose language and can be used in almost every field of development. Python can also be used to develop different type of game. Let’s try to develop a simple Catching the ball game using Python and TKinter.Game is very simple. There is one bar at the bottom of game window which can be moved left or right using the buttons that are in the game window. Red ball will continuously fall from top to bottom and can start from any random x-axis distance. The task is to bring that bar to a suitable location by moving left or right so that the red ball will fall on that bar(catch the ball onto the bar) not on the ground. If player catches the ball onto the bar then score will get increase and that ball will disappear and again a new red ball will start falling from top to bottom starting from random x-axis distance. If player miss the ball from catching it on the bar then you will lose the game and then finally scorecard will appear on the game window.Approach: " }, { "code": null, "e": 27266, "s": 27007, "text": "Use Tkinter package in python for building GUI(Graphical user interface).Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for drawing pictures or other complex layouts. We can place graphics, text, widgets or frames on Canvas." }, { "code": null, "e": 27340, "s": 27266, "text": "Use Tkinter package in python for building GUI(Graphical user interface)." }, { "code": null, "e": 27526, "s": 27340, "text": "Use Canvas for drawing objects in Python – Canvas is a rectangular area intended for drawing pictures or other complex layouts. We can place graphics, text, widgets or frames on Canvas." }, { "code": null, "e": 27791, "s": 27526, "text": "Syntax: w = Canvas ( master, option=value, ... )\n\nParameters:\nmaster - This represents the parent window.\noptions - List of most commonly used options for this widget. \nThese options can be used as key-value pairs separated by commas. \nExample- width, height etc. " }, { "code": null, "e": 28020, "s": 27791, "text": "Use canvas.create_oval for creating the ball. create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval. " }, { "code": null, "e": 28249, "s": 28020, "text": "Use canvas.create_oval for creating the ball. create_oval creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval. " }, { "code": null, "e": 28308, "s": 28249, "text": "Syntax: oval = canvas.create_oval(x0, y0, x1, y1, options)" }, { "code": null, "e": 28501, "s": 28308, "text": "Use canvas.create_rectangle for creating the bar. create_rectangle creates a rectangle at the given coordinates. It takes two pairs of coordinates; the top left and bottom right coordinates. " }, { "code": null, "e": 28694, "s": 28501, "text": "Use canvas.create_rectangle for creating the bar. create_rectangle creates a rectangle at the given coordinates. It takes two pairs of coordinates; the top left and bottom right coordinates. " }, { "code": null, "e": 28757, "s": 28694, "text": "Syntax: rod = canvas.create_rectangle(x0, y0, x1, y1, options)" }, { "code": null, "e": 28880, "s": 28757, "text": "Use canvas.move for moving the ball or bar. canvas.move enables the object to move with the specified (x, y) coordinates. " }, { "code": null, "e": 29003, "s": 28880, "text": "Use canvas.move for moving the ball or bar. canvas.move enables the object to move with the specified (x, y) coordinates. " }, { "code": null, "e": 29051, "s": 29003, "text": "Syntax: move=canvas.move(name of object, x, y) " }, { "code": null, "e": 29263, "s": 29051, "text": "Note: *Take x=0 for moving the ball in vertical direction only and take y=0 for moving the bar in horizontal direction only. *Disappear the ball when it touches the ground or the bar using canvas.delete(object)." }, { "code": null, "e": 29377, "s": 29263, "text": "Use Button for moving the bar in forward or backward and then apply action event on it. Refer Python gui Tkinter " }, { "code": null, "e": 29491, "s": 29377, "text": "Use Button for moving the bar in forward or backward and then apply action event on it. Refer Python gui Tkinter " }, { "code": null, "e": 29499, "s": 29491, "text": "Example" }, { "code": null, "e": 29507, "s": 29499, "text": "Python3" }, { "code": "# Python code for catching the ball game # importing suitable packagesfrom tkinter import Tk,Button,Labelfrom tkinter import Canvasfrom random import randint # defining Tk from Tkinterroot = Tk()root.title(\"Catch the ball Game\")root.resizable(False,False) # for defining the canvascanvas = Canvas(root, width=600, height=600)canvas.pack() # variable for the vertical distance# travelled by balllimit = 0 # variable for horizontal distance# of bar from x-axisdist = 5 # variable for scorescore = 0 # Class for the Creating and moving ballclass Ball: # for creation of ball on the canvas def __init__(self, canvas, x1, y1, x2, y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.canvas = canvas # for creation of ball object self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill = \"red\",tags = 'dot1') # for moving the ball def move_ball(self): # defining offset offset = 10 global limit # checking if ball lands ground or bar if limit >= 510: global dist,score,next # checking that ball falls on the bar if(dist - offset <= self.x1 and dist + 40 + offset >= self.x2): # incrementing the score score += 10 # disappear the ball canvas.delete('dot1') # calling the function for again # creation of ball object ball_set() else: # disappear the ball canvas.delete('dot1') bar.delete_bar(self) # display the score score_board() return # incrementing the vertical distance # travelled by ball by deltay limit += 1 # moving the ball in vertical direction # by taking x=0 and y=deltay self.canvas.move(self.ball,0,1) # for continuous moving of ball again call move_ball self.canvas.after(10,self.move_ball) # class for creating and moving bar class bar: # method for creating bar def __init__(self,canvas,x1,y1,x2,y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.canvas = canvas # for creating bar using create_rectangle self.rod=canvas.create_rectangle(self.x1, self.y1, self.x2, self.y2, fill=\"yellow\",tags='dot2') # method for moving the bar def move_bar(self,num): global dist # checking the forward or backward button if(num == 1): # moving the bar in forward direction by # taking x-axis positive distance and # taking vertical distance y=0 self.canvas.move(self.rod,20,0) # incrementing the distance of bar from x-axis dist += 20 else: # moving the bar in backward direction by taking x-axis # negative distance and taking vertical distance y=0 self.canvas.move(self.rod,-20,0) # decrementing the distance of bar from x-axis dist-=20 def delete_bar(self): canvas.delete('dot2') # Function to define the dimensions of the balldef ball_set(): global limit limit=0 # for random x-axis distance from # where the ball starts to fall value = randint(0,570) # define the dimensions of the ball ball1 = Ball(canvas,value,20,value+30,50) # call function for moving of the ball ball1.move_ball() # Function for displaying the score# after getting over of the gamedef score_board(): root2 = Tk() root2.title(\"Catch the ball Game\") root2.resizable(False,False) canvas2 = Canvas(root2,width=300,height=300) canvas2.pack() w = Label(canvas2,text=\"\\nOOPS...GAME IS OVER\\n\\nYOUR SCORE = \" + str(score) + \"\\n\\n\") w.pack() button3 = Button(canvas2, text=\"PLAY AGAIN\", bg=\"green\", command=lambda:play_again(root2)) button3.pack() button4 = Button(canvas2,text=\"EXIT\",bg=\"green\", command=lambda:exit_handler(root2)) button4.pack() # Function for handling the play again requestdef play_again(root2): root2.destroy() main() # Function for handling exit requestdef exit_handler(root2): root2.destroy() root.destroy() # Main functiondef main(): global score,dist score = 0 dist = 0 # defining the dimensions of bar bar1=bar(canvas,5,560,45,575) # defining the text,colour of buttons and # also define the action after click on # the button by calling suitable methods button = Button(canvas,text=\"==>\", bg=\"green\", command=lambda:bar1.move_bar(1)) # placing the buttons at suitable location on the canvas button.place(x=300,y=580) button2 = Button(canvas,text=\"<==\",bg=\"green\", command=lambda:bar1.move_bar(0)) button2.place(x=260,y=580) # calling the function for defining # the dimensions of ball ball_set() root.mainloop() # Driver codeif(__name__==\"__main__\"): main()", "e": 35023, "s": 29507, "text": null }, { "code": null, "e": 35033, "s": 35023, "text": "Output: " }, { "code": null, "e": 35113, "s": 35033, "text": "Note:The above code can’t be run on online IDE as Tkinter package is imported. " }, { "code": null, "e": 35121, "s": 35113, "text": "clintra" }, { "code": null, "e": 35131, "s": 35121, "text": "ruhelaa48" }, { "code": null, "e": 35146, "s": 35131, "text": "varunsaini1506" }, { "code": null, "e": 35154, "s": 35146, "text": "Project" }, { "code": null, "e": 35161, "s": 35154, "text": "Python" }, { "code": null, "e": 35177, "s": 35161, "text": "Python Programs" }, { "code": null, "e": 35275, "s": 35177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35318, "s": 35275, "text": "Java Swing | Simple User Registration Form" }, { "code": null, "e": 35356, "s": 35318, "text": "Banking Transaction System using Java" }, { "code": null, "e": 35407, "s": 35356, "text": "Face Detection using Python and OpenCV with webcam" }, { "code": null, "e": 35423, "s": 35407, "text": "Snake Game in C" }, { "code": null, "e": 35462, "s": 35423, "text": "Program for Employee Management System" }, { "code": null, "e": 35490, "s": 35462, "text": "Read JSON file using Python" }, { "code": null, "e": 35540, "s": 35490, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 35562, "s": 35540, "text": "Python map() function" } ]
Python range() function - GeeksforGeeks
11 Apr, 2022 Python range() function returns the sequence of the given number between the given range. range() is a built-in function of Python. It is used when a user needs to perform an action a specific number of times. range() in Python(3.x) is just a renamed version of a function called xrange in Python(2.x). The range() function is used to generate a sequence of numbers. Python range() function for loop is commonly used hence, knowledge of same is the key aspect when dealing with any kind of Python code. The most common use of range() function in Python is to iterate sequence type (Python range() List, string, etc. ) with for and while loop. range(stop) range(start, stop, step) In simple terms, range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments. start: integer starting from which the sequence of integers is to be returned stop: integer before which the sequence of integers is to be returned. The range of integers end at stop – 1. step: integer value which determines the increment between each integer in the sequence Python3 # Python Program to# show range() basics # printing a numberfor i in range(10): print(i, end=" ")print() # using range for iterationl = [10, 20, 30, 40]for i in range(len(l)): print(l[i], end=" ")print() # performing sum of natural# numbersum = 0for i in range(1, 11): sum = sum + iprint("Sum of first 10 natural number :", sum) Output : 0 1 2 3 4 5 6 7 8 9 10 20 30 40 Sum of first 10 natural number : 55 range(stop) takes one argument. range(start, stop) takes two arguments. range(start, stop, step) takes three arguments. When user call range() with one argument, user will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number that user have provided as the stop. For Example – Python3 # Python program to# print whole number# using range() # printing first 10# whole numberfor i in range(10): print(i, end=" ")print() # printing first 20# whole numberfor i in range(20): print(i, end=" ") Output: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 When user call range() with two arguments, user get to decide not only where the series of numbers stops but also where it starts, so user don’t have to start at 0 all the time. User can use range() to generate a series of numbers from X to Y using a range(X, Y). For Example -arguments Python3 # Python program to# print natural number# using range # printing a natural# number upto 20for i in range(1, 20): print(i, end=" ")print() # printing a natural# number from 5 t0 20for i in range(5, 20): print(i, end=" ") Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 When the user call range() with three arguments, the user can choose not only where the series of numbers will start and stop but also how big the difference will be between one number and the next. If the user doesn’t provide a step, then range() will automatically behave as if the step is 1. Python3 # Python program to# print all number# divisible by 3 and 5 # using range to print number# divisible by 3for i in range(0, 30, 3): print(i, end=" ")print() # using range to print number# divisible by 5for i in range(0, 50, 5): print(i, end=" ") Output : 0 3 6 9 12 15 18 21 24 27 0 5 10 15 20 25 30 35 40 45 In this example, we are printing an even number between 0 to 10 so we choose our starting point from 0(start = 0) and stop the series at 10(stop = 10). For printing even number the difference between one number and the next must be 2 (step = 2) after providing a step we get a following output ( 0, 2, 4, 8). If a user wants to increment, then the user needs steps to be a positive number. For example: Python3 # Python program to# increment with# range() # incremented by 2for i in range(2, 25, 2): print(i, end=" ")print() # incremented by 4for i in range(0, 30, 4): print(i, end=" ")print() # incremented by 3for i in range(15, 25, 3): print(i, end=" ") Output : 2 4 6 8 10 12 14 16 18 20 22 24 0 4 8 12 16 20 24 28 15 18 21 24 If a user wants to decrement, then the user needs steps to be a negative number. For example: Python3 # Python program to# decrement with# range() # incremented by -2for i in range(25, 2, -2): print(i, end=" ")print() # incremented by -4for i in range(30, 1, -4): print(i, end=" ")print() # incremented by -3for i in range(25, -6, -3): print(i, end=" ") Output : 25 23 21 19 17 15 13 11 9 7 5 3 30 26 22 18 14 10 6 2 25 22 19 16 13 10 7 4 1 -2 -5 Python range() function doesn’t support the float numbers. i.e. user cannot use floating-point or non-integer number in any of its argument. Users can use only integer numbers. For example Python3 # Python program to# show using float# number in range() # using a float numberfor i in range(3.3): print(i) # using a float numberfor i in range(5.5): print(i) Output : for i in range(3.3): TypeError: 'float' object cannot be interpreted as an integer The result from two range() functions can be concatenated by using the chain() method of itertools module. The chain() method is used to print all the values in iterable targets one after another mentioned in its arguments. Python3 # Python program to concatenate# the result of two range functionsfrom itertools import chain # Using chain methodprint("Concatenating the result")res = chain(range(5), range(10, 20, 2)) for i in res: print(i, end=" ") Output: Concatenating the result 0 1 2 3 4 10 12 14 16 18 A sequence of numbers is returned by the range() function as its object that can be accessed by its index value. Both positive and negative indexing is supported by its object. Python3 # Python program to demonstrate# range function ele = range(10)[0]print("First element:", ele) ele = range(10)[-1]print("\nLast element:", ele) ele = range(10)[4]print("\nFifth element:", ele) Output: First element: 0 Last element: 9 Fifth element: 4 Points to remember about Python range() function : range() function only works with the integers i.e. whole numbers. All arguments must be integers. Users can not pass a string or float number or any other type in a start, stop and step argument of a range(). All three arguments can be positive or negative. The step value must not be zero. If a step is zero python raises a ValueError exception. range() is a type in Python Users can access items in a range() by index, just as users do with a list: VaibhavPandey nikhilaggarwal3 kumar_satyam sumitgumber28 rlott python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 25513, "s": 25485, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25603, "s": 25513, "text": "Python range() function returns the sequence of the given number between the given range." }, { "code": null, "e": 25881, "s": 25603, "text": "range() is a built-in function of Python. It is used when a user needs to perform an action a specific number of times. range() in Python(3.x) is just a renamed version of a function called xrange in Python(2.x). The range() function is used to generate a sequence of numbers. " }, { "code": null, "e": 26158, "s": 25881, "text": "Python range() function for loop is commonly used hence, knowledge of same is the key aspect when dealing with any kind of Python code. The most common use of range() function in Python is to iterate sequence type (Python range() List, string, etc. ) with for and while loop. " }, { "code": null, "e": 26170, "s": 26158, "text": "range(stop)" }, { "code": null, "e": 26195, "s": 26170, "text": "range(start, stop, step)" }, { "code": null, "e": 26535, "s": 26195, "text": "In simple terms, range() allows the user to generate a series of numbers within a given range. Depending on how many arguments the user is passing to the function, user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.range() takes mainly three arguments." }, { "code": null, "e": 26613, "s": 26535, "text": "start: integer starting from which the sequence of integers is to be returned" }, { "code": null, "e": 26723, "s": 26613, "text": "stop: integer before which the sequence of integers is to be returned. The range of integers end at stop – 1." }, { "code": null, "e": 26811, "s": 26723, "text": "step: integer value which determines the increment between each integer in the sequence" }, { "code": null, "e": 26819, "s": 26811, "text": "Python3" }, { "code": "# Python Program to# show range() basics # printing a numberfor i in range(10): print(i, end=\" \")print() # using range for iterationl = [10, 20, 30, 40]for i in range(len(l)): print(l[i], end=\" \")print() # performing sum of natural# numbersum = 0for i in range(1, 11): sum = sum + iprint(\"Sum of first 10 natural number :\", sum)", "e": 27157, "s": 26819, "text": null }, { "code": null, "e": 27167, "s": 27157, "text": "Output : " }, { "code": null, "e": 27237, "s": 27167, "text": "0 1 2 3 4 5 6 7 8 9 \n10 20 30 40 \nSum of first 10 natural number : 55" }, { "code": null, "e": 27269, "s": 27237, "text": "range(stop) takes one argument." }, { "code": null, "e": 27309, "s": 27269, "text": "range(start, stop) takes two arguments." }, { "code": null, "e": 27357, "s": 27309, "text": "range(start, stop, step) takes three arguments." }, { "code": null, "e": 27570, "s": 27357, "text": "When user call range() with one argument, user will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number that user have provided as the stop. For Example –" }, { "code": null, "e": 27578, "s": 27570, "text": "Python3" }, { "code": "# Python program to# print whole number# using range() # printing first 10# whole numberfor i in range(10): print(i, end=\" \")print() # printing first 20# whole numberfor i in range(20): print(i, end=\" \")", "e": 27788, "s": 27578, "text": null }, { "code": null, "e": 27797, "s": 27788, "text": "Output: " }, { "code": null, "e": 27869, "s": 27797, "text": "0 1 2 3 4 5 6 7 8 9 \n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 " }, { "code": null, "e": 28157, "s": 27869, "text": "When user call range() with two arguments, user get to decide not only where the series of numbers stops but also where it starts, so user don’t have to start at 0 all the time. User can use range() to generate a series of numbers from X to Y using a range(X, Y). For Example -arguments " }, { "code": null, "e": 28165, "s": 28157, "text": "Python3" }, { "code": "# Python program to# print natural number# using range # printing a natural# number upto 20for i in range(1, 20): print(i, end=\" \")print() # printing a natural# number from 5 t0 20for i in range(5, 20): print(i, end=\" \")", "e": 28392, "s": 28165, "text": null }, { "code": null, "e": 28401, "s": 28392, "text": "Output: " }, { "code": null, "e": 28491, "s": 28401, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 \n5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 " }, { "code": null, "e": 28787, "s": 28491, "text": "When the user call range() with three arguments, the user can choose not only where the series of numbers will start and stop but also how big the difference will be between one number and the next. If the user doesn’t provide a step, then range() will automatically behave as if the step is 1. " }, { "code": null, "e": 28795, "s": 28787, "text": "Python3" }, { "code": "# Python program to# print all number# divisible by 3 and 5 # using range to print number# divisible by 3for i in range(0, 30, 3): print(i, end=\" \")print() # using range to print number# divisible by 5for i in range(0, 50, 5): print(i, end=\" \")", "e": 29046, "s": 28795, "text": null }, { "code": null, "e": 29056, "s": 29046, "text": "Output : " }, { "code": null, "e": 29112, "s": 29056, "text": "0 3 6 9 12 15 18 21 24 27 \n0 5 10 15 20 25 30 35 40 45 " }, { "code": null, "e": 29422, "s": 29112, "text": "In this example, we are printing an even number between 0 to 10 so we choose our starting point from 0(start = 0) and stop the series at 10(stop = 10). For printing even number the difference between one number and the next must be 2 (step = 2) after providing a step we get a following output ( 0, 2, 4, 8). " }, { "code": null, "e": 29517, "s": 29422, "text": "If a user wants to increment, then the user needs steps to be a positive number. For example: " }, { "code": null, "e": 29525, "s": 29517, "text": "Python3" }, { "code": "# Python program to# increment with# range() # incremented by 2for i in range(2, 25, 2): print(i, end=\" \")print() # incremented by 4for i in range(0, 30, 4): print(i, end=\" \")print() # incremented by 3for i in range(15, 25, 3): print(i, end=\" \")", "e": 29780, "s": 29525, "text": null }, { "code": null, "e": 29790, "s": 29780, "text": "Output : " }, { "code": null, "e": 29858, "s": 29790, "text": "2 4 6 8 10 12 14 16 18 20 22 24 \n0 4 8 12 16 20 24 28 \n15 18 21 24 " }, { "code": null, "e": 29953, "s": 29858, "text": "If a user wants to decrement, then the user needs steps to be a negative number. For example: " }, { "code": null, "e": 29961, "s": 29953, "text": "Python3" }, { "code": "# Python program to# decrement with# range() # incremented by -2for i in range(25, 2, -2): print(i, end=\" \")print() # incremented by -4for i in range(30, 1, -4): print(i, end=\" \")print() # incremented by -3for i in range(25, -6, -3): print(i, end=\" \")", "e": 30222, "s": 29961, "text": null }, { "code": null, "e": 30232, "s": 30222, "text": "Output : " }, { "code": null, "e": 30319, "s": 30232, "text": "25 23 21 19 17 15 13 11 9 7 5 3 \n30 26 22 18 14 10 6 2 \n25 22 19 16 13 10 7 4 1 -2 -5 " }, { "code": null, "e": 30509, "s": 30319, "text": "Python range() function doesn’t support the float numbers. i.e. user cannot use floating-point or non-integer number in any of its argument. Users can use only integer numbers. For example " }, { "code": null, "e": 30517, "s": 30509, "text": "Python3" }, { "code": "# Python program to# show using float# number in range() # using a float numberfor i in range(3.3): print(i) # using a float numberfor i in range(5.5): print(i)", "e": 30684, "s": 30517, "text": null }, { "code": null, "e": 30694, "s": 30684, "text": "Output : " }, { "code": null, "e": 30777, "s": 30694, "text": "for i in range(3.3):\nTypeError: 'float' object cannot be interpreted as an integer" }, { "code": null, "e": 31001, "s": 30777, "text": "The result from two range() functions can be concatenated by using the chain() method of itertools module. The chain() method is used to print all the values in iterable targets one after another mentioned in its arguments." }, { "code": null, "e": 31009, "s": 31001, "text": "Python3" }, { "code": "# Python program to concatenate# the result of two range functionsfrom itertools import chain # Using chain methodprint(\"Concatenating the result\")res = chain(range(5), range(10, 20, 2)) for i in res: print(i, end=\" \")", "e": 31231, "s": 31009, "text": null }, { "code": null, "e": 31240, "s": 31231, "text": "Output: " }, { "code": null, "e": 31291, "s": 31240, "text": "Concatenating the result\n0 1 2 3 4 10 12 14 16 18 " }, { "code": null, "e": 31468, "s": 31291, "text": "A sequence of numbers is returned by the range() function as its object that can be accessed by its index value. Both positive and negative indexing is supported by its object." }, { "code": null, "e": 31476, "s": 31468, "text": "Python3" }, { "code": "# Python program to demonstrate# range function ele = range(10)[0]print(\"First element:\", ele) ele = range(10)[-1]print(\"\\nLast element:\", ele) ele = range(10)[4]print(\"\\nFifth element:\", ele)", "e": 31669, "s": 31476, "text": null }, { "code": null, "e": 31678, "s": 31669, "text": "Output: " }, { "code": null, "e": 31730, "s": 31678, "text": "First element: 0\n\nLast element: 9\n\nFifth element: 4" }, { "code": null, "e": 31782, "s": 31730, "text": "Points to remember about Python range() function : " }, { "code": null, "e": 31848, "s": 31782, "text": "range() function only works with the integers i.e. whole numbers." }, { "code": null, "e": 31991, "s": 31848, "text": "All arguments must be integers. Users can not pass a string or float number or any other type in a start, stop and step argument of a range()." }, { "code": null, "e": 32040, "s": 31991, "text": "All three arguments can be positive or negative." }, { "code": null, "e": 32129, "s": 32040, "text": "The step value must not be zero. If a step is zero python raises a ValueError exception." }, { "code": null, "e": 32157, "s": 32129, "text": "range() is a type in Python" }, { "code": null, "e": 32233, "s": 32157, "text": "Users can access items in a range() by index, just as users do with a list:" }, { "code": null, "e": 32247, "s": 32233, "text": "VaibhavPandey" }, { "code": null, "e": 32263, "s": 32247, "text": "nikhilaggarwal3" }, { "code": null, "e": 32276, "s": 32263, "text": "kumar_satyam" }, { "code": null, "e": 32290, "s": 32276, "text": "sumitgumber28" }, { "code": null, "e": 32296, "s": 32290, "text": "rlott" }, { "code": null, "e": 32310, "s": 32296, "text": "python-basics" }, { "code": null, "e": 32317, "s": 32310, "text": "Python" }, { "code": null, "e": 32415, "s": 32317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32450, "s": 32415, "text": "Read a file line by line in Python" }, { "code": null, "e": 32482, "s": 32450, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32504, "s": 32482, "text": "Enumerate() in Python" }, { "code": null, "e": 32546, "s": 32504, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32576, "s": 32546, "text": "Iterate over a list in Python" }, { "code": null, "e": 32602, "s": 32576, "text": "Python String | replace()" }, { "code": null, "e": 32631, "s": 32602, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32675, "s": 32631, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 32712, "s": 32675, "text": "Create a Pandas DataFrame from Lists" } ]
Program to print the series 2, 15, 41, 80, 132, 197... till N terms - GeeksforGeeks
19 Mar, 2021 Given a number N, the task is to print the first N terms of the following series: 2 15 41 80 132 197 275 366 470 587... Examples: Input: N = 7 Output: 2 15 41 80 132 197 275 Input: N = 3 Output: 2 15 41 Approach: From the given series we can find the formula for Nth term: 1st term = 2 2nd term = 15 = 13 * 1 + 2 3rd term = 41 = 13 * 2 + 15 = 13 * 3 + 2 4th term = 80 = 13 * 3 + 41 = 13 * 6 + 2 5th term = 132 = 13 * 4 + 80 = 13 * 10 + 2 . . Nth term = (13 * N * (N – 1)) / 2 + 2 Therefore: Nth term of the series Then iterate over numbers in the range [1, N] to find all the terms using the above formula and print them. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to print the// given with the given Nth term #include "bits/stdc++.h"using namespace std; // Function to print the seriesvoid printSeries(int N){ int ith_term = 0; // Generate the ith term and for (int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; cout << ith_term << ", "; }} // Driver Codeint main(){ int N = 7; printSeries(N); return 0;} // Java implementation to print the// given with the given Nth termimport java.util.*; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and for(int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; System.out.print(ith_term + ", "); }} // Driver Codepublic static void main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by Rajput-Ji # Python3 implementation to print the# given with the given Nth term # Function to print the seriesdef printSeries(N): ith_term = 0; # Generate the ith term and for i in range(1, N + 1): ith_term = (13 * i * (i - 1)) / 2 + 2; print(int(ith_term), ", ", end = ""); # Driver Codeif __name__ == '__main__': N = 7; printSeries(N); # This code is contributed by amal kumar choubey // C# implementation to print the// given with the given Nth termusing System; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and for(int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; Console.Write(ith_term + ", "); }} // Driver Codepublic static void Main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by Rajput-Ji <script>// javascript implementation to print the// given with the given Nth term // Function to print the seriesfunction printSeries( N){ let ith_term = 0; // Generate the ith term and for (let i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; document.write( ith_term + ", "); }} // Driver Code let N = 7; printSeries(N); // This code is contributed by gauravrajput1 </script> 2, 15, 41, 80, 132, 197, 275, Rajput-Ji Amal Kumar Choubey GauravRajput1 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python
[ { "code": null, "e": 25937, "s": 25909, "text": "\n19 Mar, 2021" }, { "code": null, "e": 26020, "s": 25937, "text": "Given a number N, the task is to print the first N terms of the following series: " }, { "code": null, "e": 26058, "s": 26020, "text": "2 15 41 80 132 197 275 366 470 587..." }, { "code": null, "e": 26068, "s": 26058, "text": "Examples:" }, { "code": null, "e": 26081, "s": 26068, "text": "Input: N = 7" }, { "code": null, "e": 26112, "s": 26081, "text": "Output: 2 15 41 80 132 197 275" }, { "code": null, "e": 26125, "s": 26112, "text": "Input: N = 3" }, { "code": null, "e": 26141, "s": 26125, "text": "Output: 2 15 41" }, { "code": null, "e": 26213, "s": 26141, "text": "Approach: From the given series we can find the formula for Nth term: " }, { "code": null, "e": 26422, "s": 26213, "text": "1st term = 2 2nd term = 15 = 13 * 1 + 2 3rd term = 41 = 13 * 2 + 15 = 13 * 3 + 2 4th term = 80 = 13 * 3 + 41 = 13 * 6 + 2 5th term = 132 = 13 * 4 + 80 = 13 * 10 + 2 . . Nth term = (13 * N * (N – 1)) / 2 + 2 " }, { "code": null, "e": 26435, "s": 26424, "text": "Therefore:" }, { "code": null, "e": 26460, "s": 26437, "text": "Nth term of the series" }, { "code": null, "e": 26570, "s": 26462, "text": "Then iterate over numbers in the range [1, N] to find all the terms using the above formula and print them." }, { "code": null, "e": 26619, "s": 26572, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 26625, "s": 26621, "text": "C++" }, { "code": null, "e": 26630, "s": 26625, "text": "Java" }, { "code": null, "e": 26638, "s": 26630, "text": "Python3" }, { "code": null, "e": 26641, "s": 26638, "text": "C#" }, { "code": null, "e": 26652, "s": 26641, "text": "Javascript" }, { "code": "// C++ implementation to print the// given with the given Nth term #include \"bits/stdc++.h\"using namespace std; // Function to print the seriesvoid printSeries(int N){ int ith_term = 0; // Generate the ith term and for (int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; cout << ith_term << \", \"; }} // Driver Codeint main(){ int N = 7; printSeries(N); return 0;}", "e": 27069, "s": 26652, "text": null }, { "code": "// Java implementation to print the// given with the given Nth termimport java.util.*; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and for(int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; System.out.print(ith_term + \", \"); }} // Driver Codepublic static void main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by Rajput-Ji", "e": 27547, "s": 27069, "text": null }, { "code": "# Python3 implementation to print the# given with the given Nth term # Function to print the seriesdef printSeries(N): ith_term = 0; # Generate the ith term and for i in range(1, N + 1): ith_term = (13 * i * (i - 1)) / 2 + 2; print(int(ith_term), \", \", end = \"\"); # Driver Codeif __name__ == '__main__': N = 7; printSeries(N); # This code is contributed by amal kumar choubey", "e": 27972, "s": 27547, "text": null }, { "code": "// C# implementation to print the// given with the given Nth termusing System; class GFG{ // Function to print the seriesstatic void printSeries(int N){ int ith_term = 0; // Generate the ith term and for(int i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; Console.Write(ith_term + \", \"); }} // Driver Codepublic static void Main(String[] args){ int N = 7; printSeries(N);}} // This code is contributed by Rajput-Ji", "e": 28439, "s": 27972, "text": null }, { "code": "<script>// javascript implementation to print the// given with the given Nth term // Function to print the seriesfunction printSeries( N){ let ith_term = 0; // Generate the ith term and for (let i = 1; i <= N; i++) { ith_term = (13 * i * (i - 1)) / 2 + 2; document.write( ith_term + \", \"); }} // Driver Code let N = 7; printSeries(N); // This code is contributed by gauravrajput1 </script>", "e": 28874, "s": 28439, "text": null }, { "code": null, "e": 28904, "s": 28874, "text": "2, 15, 41, 80, 132, 197, 275," }, { "code": null, "e": 28916, "s": 28906, "text": "Rajput-Ji" }, { "code": null, "e": 28935, "s": 28916, "text": "Amal Kumar Choubey" }, { "code": null, "e": 28949, "s": 28935, "text": "GauravRajput1" }, { "code": null, "e": 28956, "s": 28949, "text": "series" }, { "code": null, "e": 28969, "s": 28956, "text": "Mathematical" }, { "code": null, "e": 28982, "s": 28969, "text": "Mathematical" }, { "code": null, "e": 28989, "s": 28982, "text": "series" }, { "code": null, "e": 29087, "s": 28989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29131, "s": 29087, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29173, "s": 29131, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 29204, "s": 29173, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29275, "s": 29204, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 29300, "s": 29275, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29332, "s": 29300, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29365, "s": 29332, "text": "Program to multiply two matrices" }, { "code": null, "e": 29400, "s": 29365, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 29446, "s": 29400, "text": "Merge two sorted arrays with O(1) extra space" } ]
How to import and export data using CSV files in PostgreSQL - GeeksforGeeks
23 Sep, 2021 In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL. To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separated by commas to the corresponding columns in the next lines. Save the file as Demo_data.csv as shown below. Now create a new table using psycopg2 where we will import the data from the CSV file: Python3 import psycopg2 # connection establishmentconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to create a tablesql = ''' CREATE TABLE demo( id INT, name VARCHAR(50), city VARCHAR(50), age INT); ''' # executing above querycursor.execute(sql)print("Table has been created successfully!!") # Closing the connectionconn.close() Output: Table has been created successfully!! We use COPY command with FROM keyword to import the contents of the CSV file into a new table. Syntax: COPY <table name> FROM ‘location + file_name’ DELIMITER ‘,’ CSV HEADER; Where: <table name> – name of the table where we want to import data. ‘location + file_name’ – full path of the CSV file from which we are importing data (make sure you have ‘read’ access to the file). DELIMITER ‘,’ – specifies the delimiter which is comma (,) CSV – specifies the format of the file from which we are importing data. HEADER – specifies that we have a header row in our .csv file and while importing we should ignore the first row. Example: Python3 import psycopg2 # connection establishmentconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to import data from given csvsql = '''COPY demo FROM 'C:\\Users\\DELL\\Downloads\\Demo_data.csv' DELIMITER ',' CSV HEADER''' # executing above querycursor.execute(sql) # Display the tablecursor.execute('SELECT * FROM demo')print(cursor.fetchall()) # Closing the connectionconn.close() Output: [(1, ‘Harry’, ‘Delhi’, 29), (2, ‘Mira’, ‘Mumbai’, 24), (3, ‘Emma’, ‘Bangalore’, 30), (4, ‘Kevin’, ‘Mumbai’, 19)] To export data from a table into a CSV file, we use TO keyword with the COPY command. Syntax: COPY <table name> TO ‘location + file_name’ DELIMITER ‘,’ CSV HEADER; Here, <table name> is the table from which we are exporting data. ‘location + file_name’ contains the path of the CSV file into which we want to export the data. Make sure you have ‘write’ access to the file. Example: Python3 import psycopg2 # connection establishmentconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to export table into csvsql = '''COPY demo TO 'C:\\Users\\DELL\\Downloads\\Exported_data.csv' DELIMITER ',' CSV HEADER''' # executing above querycursor.execute(sql) # Closing the connectionconn.close() The exported CSV will look like this: Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n23 Sep, 2021" }, { "code": null, "e": 25710, "s": 25537, "text": "In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL." }, { "code": null, "e": 25947, "s": 25710, "text": "To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separated by commas to the corresponding columns in the next lines. Save the file as Demo_data.csv as shown below." }, { "code": null, "e": 26034, "s": 25947, "text": "Now create a new table using psycopg2 where we will import the data from the CSV file:" }, { "code": null, "e": 26042, "s": 26034, "text": "Python3" }, { "code": "import psycopg2 # connection establishmentconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to create a tablesql = ''' CREATE TABLE demo( id INT, name VARCHAR(50), city VARCHAR(50), age INT); ''' # executing above querycursor.execute(sql)print(\"Table has been created successfully!!\") # Closing the connectionconn.close()", "e": 26542, "s": 26042, "text": null }, { "code": null, "e": 26550, "s": 26542, "text": "Output:" }, { "code": null, "e": 26588, "s": 26550, "text": "Table has been created successfully!!" }, { "code": null, "e": 26683, "s": 26588, "text": "We use COPY command with FROM keyword to import the contents of the CSV file into a new table." }, { "code": null, "e": 26763, "s": 26683, "text": "Syntax: COPY <table name> FROM ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;" }, { "code": null, "e": 26770, "s": 26763, "text": "Where:" }, { "code": null, "e": 26833, "s": 26770, "text": "<table name> – name of the table where we want to import data." }, { "code": null, "e": 26965, "s": 26833, "text": "‘location + file_name’ – full path of the CSV file from which we are importing data (make sure you have ‘read’ access to the file)." }, { "code": null, "e": 27024, "s": 26965, "text": "DELIMITER ‘,’ – specifies the delimiter which is comma (,)" }, { "code": null, "e": 27097, "s": 27024, "text": "CSV – specifies the format of the file from which we are importing data." }, { "code": null, "e": 27211, "s": 27097, "text": "HEADER – specifies that we have a header row in our .csv file and while importing we should ignore the first row." }, { "code": null, "e": 27220, "s": 27211, "text": "Example:" }, { "code": null, "e": 27228, "s": 27220, "text": "Python3" }, { "code": "import psycopg2 # connection establishmentconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to import data from given csvsql = '''COPY demo FROM 'C:\\\\Users\\\\DELL\\\\Downloads\\\\Demo_data.csv' DELIMITER ',' CSV HEADER''' # executing above querycursor.execute(sql) # Display the tablecursor.execute('SELECT * FROM demo')print(cursor.fetchall()) # Closing the connectionconn.close()", "e": 27788, "s": 27228, "text": null }, { "code": null, "e": 27796, "s": 27788, "text": "Output:" }, { "code": null, "e": 27909, "s": 27796, "text": "[(1, ‘Harry’, ‘Delhi’, 29), (2, ‘Mira’, ‘Mumbai’, 24), (3, ‘Emma’, ‘Bangalore’, 30), (4, ‘Kevin’, ‘Mumbai’, 19)]" }, { "code": null, "e": 27996, "s": 27909, "text": "To export data from a table into a CSV file, we use TO keyword with the COPY command. " }, { "code": null, "e": 28074, "s": 27996, "text": "Syntax: COPY <table name> TO ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;" }, { "code": null, "e": 28140, "s": 28074, "text": "Here, <table name> is the table from which we are exporting data." }, { "code": null, "e": 28283, "s": 28140, "text": "‘location + file_name’ contains the path of the CSV file into which we want to export the data. Make sure you have ‘write’ access to the file." }, { "code": null, "e": 28292, "s": 28283, "text": "Example:" }, { "code": null, "e": 28300, "s": 28292, "text": "Python3" }, { "code": "import psycopg2 # connection establishmentconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port='5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to export table into csvsql = '''COPY demo TO 'C:\\\\Users\\\\DELL\\\\Downloads\\\\Exported_data.csv' DELIMITER ',' CSV HEADER''' # executing above querycursor.execute(sql) # Closing the connectionconn.close()", "e": 28776, "s": 28300, "text": null }, { "code": null, "e": 28814, "s": 28776, "text": "The exported CSV will look like this:" }, { "code": null, "e": 28821, "s": 28814, "text": "Picked" }, { "code": null, "e": 28839, "s": 28821, "text": "Python PostgreSQL" }, { "code": null, "e": 28855, "s": 28839, "text": "Python Pyscopg2" }, { "code": null, "e": 28862, "s": 28855, "text": "Python" }, { "code": null, "e": 28960, "s": 28862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28992, "s": 28960, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29034, "s": 28992, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29076, "s": 29034, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29132, "s": 29076, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29159, "s": 29132, "text": "Python Classes and Objects" }, { "code": null, "e": 29198, "s": 29159, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29229, "s": 29198, "text": "Python | os.path.join() method" }, { "code": null, "e": 29258, "s": 29229, "text": "Create a directory in Python" }, { "code": null, "e": 29280, "s": 29258, "text": "Defaultdict in Python" } ]