title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to input a comma separated string in C++?
23 Mar, 2021 Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.First, let us understand what difference does it create if the input string is comma-separated. Taking input a whitespace-separated stringTaking input a whitespace-separated string in C++ is very easy. The program to do so is: C++ #include <bits/stdc++.h>using namespace std; int main(){ string str; // Get the string getline(cin, str); // Print the words cout << str;} 1 2 3 4 5 6 Output: 1 2 3 4 5 6 Why can’t we use the above code for comma-separated input string? The above code works fine for a whitespace-separated input string, but for a comma-separated input string, it won’t work as expected, because the program will take complete input as a single word in the string. 1, 2, 3, 4, 5, 6 Output: 1, 2, 3, 4, 5, 6 How to input a comma separated string? Now inorder to input a comma separated string, following approach can be used: Get the string to be taken as input in stringstreamTake each character of the string one by one from the streamCheck if this character is a comma (‘, ‘).If yes, then ignore that character.Else, Insert this character in the vector which stores the words Get the string to be taken as input in stringstream Take each character of the string one by one from the stream Check if this character is a comma (‘, ‘). If yes, then ignore that character. Else, Insert this character in the vector which stores the words Below is the implementation of the above approach: CPP // C++ program to input// a comma separated string #include <bits/stdc++.h>using namespace std; int main(){ // Get the string string str = "11,21,31,41,51,61"; vector<int> v; // Get the string to be taken // as input in stringstream stringstream ss(str); // Parse the string for (int i; ss >> i;) { v.push_back(i); if (ss.peek() == ',') ss.ignore(); } // Print the words for (size_t i = 0; i < v.size(); i++) cout << v[i] << endl;} 11 21 31 41 51 61 laxmanprabha96 C++ C++ Programs Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Mar, 2021" }, { "code": null, "e": 390, "s": 52, "text": "Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.First, let us understand what difference does it create if the input string is comma-separated. Taking input a whitespace-separated stringTaking input a whitespace-separated string in C++ is very easy. The program to do so is:" }, { "code": null, "e": 394, "s": 390, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ string str; // Get the string getline(cin, str); // Print the words cout << str;}", "e": 550, "s": 394, "text": null }, { "code": null, "e": 562, "s": 550, "text": "1 2 3 4 5 6" }, { "code": null, "e": 571, "s": 562, "text": "Output: " }, { "code": null, "e": 583, "s": 571, "text": "1\n2\n3\n4\n5\n6" }, { "code": null, "e": 862, "s": 585, "text": "Why can’t we use the above code for comma-separated input string? The above code works fine for a whitespace-separated input string, but for a comma-separated input string, it won’t work as expected, because the program will take complete input as a single word in the string." }, { "code": null, "e": 879, "s": 862, "text": "1, 2, 3, 4, 5, 6" }, { "code": null, "e": 888, "s": 879, "text": "Output: " }, { "code": null, "e": 905, "s": 888, "text": "1, 2, 3, 4, 5, 6" }, { "code": null, "e": 1026, "s": 907, "text": "How to input a comma separated string? Now inorder to input a comma separated string, following approach can be used: " }, { "code": null, "e": 1279, "s": 1026, "text": "Get the string to be taken as input in stringstreamTake each character of the string one by one from the streamCheck if this character is a comma (‘, ‘).If yes, then ignore that character.Else, Insert this character in the vector which stores the words" }, { "code": null, "e": 1331, "s": 1279, "text": "Get the string to be taken as input in stringstream" }, { "code": null, "e": 1392, "s": 1331, "text": "Take each character of the string one by one from the stream" }, { "code": null, "e": 1435, "s": 1392, "text": "Check if this character is a comma (‘, ‘)." }, { "code": null, "e": 1471, "s": 1435, "text": "If yes, then ignore that character." }, { "code": null, "e": 1536, "s": 1471, "text": "Else, Insert this character in the vector which stores the words" }, { "code": null, "e": 1587, "s": 1536, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1591, "s": 1587, "text": "CPP" }, { "code": "// C++ program to input// a comma separated string #include <bits/stdc++.h>using namespace std; int main(){ // Get the string string str = \"11,21,31,41,51,61\"; vector<int> v; // Get the string to be taken // as input in stringstream stringstream ss(str); // Parse the string for (int i; ss >> i;) { v.push_back(i); if (ss.peek() == ',') ss.ignore(); } // Print the words for (size_t i = 0; i < v.size(); i++) cout << v[i] << endl;}", "e": 2092, "s": 1591, "text": null }, { "code": null, "e": 2110, "s": 2092, "text": "11\n21\n31\n41\n51\n61" }, { "code": null, "e": 2127, "s": 2112, "text": "laxmanprabha96" }, { "code": null, "e": 2131, "s": 2127, "text": "C++" }, { "code": null, "e": 2144, "s": 2131, "text": "C++ Programs" }, { "code": null, "e": 2152, "s": 2144, "text": "Strings" }, { "code": null, "e": 2160, "s": 2152, "text": "Strings" }, { "code": null, "e": 2164, "s": 2160, "text": "CPP" } ]
Quick Sort using Multi-threading
23 Feb, 2022 QuickSort is a popular sorting technique based on divide and conquer algorithm. In this technique, an element is chosen as a pivot and the array is partitioned around it. The target of partition is, given an array and an element x of the array as a pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x.Multi-threading allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.Examples: Input: arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} Output: 1 2 3 4 5 6 7 8 9 10Input: arr[] = {54, 64, 95, 82, 12, 32, 63} Output: 12 32 54 63 64 82 95 Approach: The main idea of the approach is: The main thread calls the quicksort method.The method partitions the array and checks for the number of current threads.New threads is called for next step using the same parallel method.Use the single normal quicksort method. The main thread calls the quicksort method. The method partitions the array and checks for the number of current threads. New threads is called for next step using the same parallel method. Use the single normal quicksort method. Below is the program uses ForkJoinPool thread pool to keep number of thread same as the number of CPUs and reuse the threads: Java // Java program for the above approachimport java.io.*;import java.util.Random;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; public class QuickSortMutliThreading extends RecursiveTask<Integer> { int start, end; int[] arr; /** * Finding random pivoted and partition * array on a pivot. * There are many different * partitioning algorithms. * @param start * @param end * @param arr * @return */ private int partition(int start, int end, int[] arr) { int i = start, j = end; // Decide random pivot int pivoted = new Random() .nextInt(j - i) + i; // Swap the pivoted with end // element of array; int t = arr[j]; arr[j] = arr[pivote]; arr[pivote] = t; j--; // Start partitioning while (i <= j) { if (arr[i] <= arr[end]) { i++; continue; } if (arr[j] >= arr[end]) { j--; continue; } t = arr[j]; arr[j] = arr[i]; arr[i] = t; j--; i++; } // Swap pivoted to its // correct position t = arr[j + 1]; arr[j + 1] = arr[end]; arr[end] = t; return j + 1; } // Function to implement // QuickSort method public QuickSortMutliThreading(int start, int end, int[] arr) { this.arr = arr; this.start = start; this.end = end; } @Override protected Integer compute() { // Base case if (start >= end) return null; // Find partition int p = partition(start, end, arr); // Divide array QuickSortMutliThreading left = new QuickSortMutliThreading(start, p - 1, arr); QuickSortMutliThreading right = new QuickSortMutliThreading(p + 1, end, arr); // Left subproblem as separate thread left.fork(); right.compute(); // Wait untill left thread complete left.join(); // We don't want anything as return return null; } // Driver Code public static void main(String args[]) { int n = 7; int[] arr = { 54, 64, 95, 82, 12, 32, 63 }; // Forkjoin ThreadPool to keep // thread creation as per resources ForkJoinPool pool = ForkJoinPool.commonPool(); // Start the first thread in fork // join pool for range 0, n-1 pool.invoke( new QuickSortMutliThreading( 0, n - 1, arr)); // Print shorted elements for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} 12 32 54 63 64 82 95 Time Complexity: O(N*log N) Auxiliary Space: O(N) anikaseth98 germanshephered48 Java-Multithreading Quick Sort Divide and Conquer Java Sorting Divide and Conquer Sorting Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Feb, 2022" }, { "code": null, "e": 690, "s": 52, "text": "QuickSort is a popular sorting technique based on divide and conquer algorithm. In this technique, an element is chosen as a pivot and the array is partitioned around it. The target of partition is, given an array and an element x of the array as a pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x.Multi-threading allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.Examples: " }, { "code": null, "e": 840, "s": 690, "text": "Input: arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} Output: 1 2 3 4 5 6 7 8 9 10Input: arr[] = {54, 64, 95, 82, 12, 32, 63} Output: 12 32 54 63 64 82 95 " }, { "code": null, "e": 888, "s": 842, "text": "Approach: The main idea of the approach is: " }, { "code": null, "e": 1115, "s": 888, "text": "The main thread calls the quicksort method.The method partitions the array and checks for the number of current threads.New threads is called for next step using the same parallel method.Use the single normal quicksort method." }, { "code": null, "e": 1159, "s": 1115, "text": "The main thread calls the quicksort method." }, { "code": null, "e": 1237, "s": 1159, "text": "The method partitions the array and checks for the number of current threads." }, { "code": null, "e": 1305, "s": 1237, "text": "New threads is called for next step using the same parallel method." }, { "code": null, "e": 1345, "s": 1305, "text": "Use the single normal quicksort method." }, { "code": null, "e": 1472, "s": 1345, "text": "Below is the program uses ForkJoinPool thread pool to keep number of thread same as the number of CPUs and reuse the threads: " }, { "code": null, "e": 1477, "s": 1472, "text": "Java" }, { "code": "// Java program for the above approachimport java.io.*;import java.util.Random;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; public class QuickSortMutliThreading extends RecursiveTask<Integer> { int start, end; int[] arr; /** * Finding random pivoted and partition * array on a pivot. * There are many different * partitioning algorithms. * @param start * @param end * @param arr * @return */ private int partition(int start, int end, int[] arr) { int i = start, j = end; // Decide random pivot int pivoted = new Random() .nextInt(j - i) + i; // Swap the pivoted with end // element of array; int t = arr[j]; arr[j] = arr[pivote]; arr[pivote] = t; j--; // Start partitioning while (i <= j) { if (arr[i] <= arr[end]) { i++; continue; } if (arr[j] >= arr[end]) { j--; continue; } t = arr[j]; arr[j] = arr[i]; arr[i] = t; j--; i++; } // Swap pivoted to its // correct position t = arr[j + 1]; arr[j + 1] = arr[end]; arr[end] = t; return j + 1; } // Function to implement // QuickSort method public QuickSortMutliThreading(int start, int end, int[] arr) { this.arr = arr; this.start = start; this.end = end; } @Override protected Integer compute() { // Base case if (start >= end) return null; // Find partition int p = partition(start, end, arr); // Divide array QuickSortMutliThreading left = new QuickSortMutliThreading(start, p - 1, arr); QuickSortMutliThreading right = new QuickSortMutliThreading(p + 1, end, arr); // Left subproblem as separate thread left.fork(); right.compute(); // Wait untill left thread complete left.join(); // We don't want anything as return return null; } // Driver Code public static void main(String args[]) { int n = 7; int[] arr = { 54, 64, 95, 82, 12, 32, 63 }; // Forkjoin ThreadPool to keep // thread creation as per resources ForkJoinPool pool = ForkJoinPool.commonPool(); // Start the first thread in fork // join pool for range 0, n-1 pool.invoke( new QuickSortMutliThreading( 0, n - 1, arr)); // Print shorted elements for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}", "e": 4509, "s": 1477, "text": null }, { "code": null, "e": 4530, "s": 4509, "text": "12 32 54 63 64 82 95" }, { "code": null, "e": 4583, "s": 4532, "text": "Time Complexity: O(N*log N) Auxiliary Space: O(N) " }, { "code": null, "e": 4595, "s": 4583, "text": "anikaseth98" }, { "code": null, "e": 4613, "s": 4595, "text": "germanshephered48" }, { "code": null, "e": 4633, "s": 4613, "text": "Java-Multithreading" }, { "code": null, "e": 4644, "s": 4633, "text": "Quick Sort" }, { "code": null, "e": 4663, "s": 4644, "text": "Divide and Conquer" }, { "code": null, "e": 4668, "s": 4663, "text": "Java" }, { "code": null, "e": 4676, "s": 4668, "text": "Sorting" }, { "code": null, "e": 4695, "s": 4676, "text": "Divide and Conquer" }, { "code": null, "e": 4703, "s": 4695, "text": "Sorting" }, { "code": null, "e": 4708, "s": 4703, "text": "Java" } ]
JavaScript Grouping operator
08 Oct, 2021 Below is the example of the Grouping operator. Example: jscript <script> function gfg() { // 3 * (2 + 3) let value1= 3 * (2 + 3); // (3 + 2) * 3 let value2= (3 + 2) * 3; document.write(value1 + "</br>" + value2); } gfg();</script> Output: 15 15 The Grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. This operator can only contain expressions. The parameter list is passed to function within this operator which will treat it as an expression.Syntax: ( ) This ( ) operator controls the precedence of evaluation in expressionsBelow examples illustrates the Grouping operator in JavaScript: Example 1: Function as a statement and exception. In the below code JavaScript considers a function as a statement if it is not preceded by any other statement. But applying a grouping operator that has the highest precedence over any other operator considers the function as an expression and hence it gets fully evaluated. JavaScript <script> function(x){ return x }; // SyntaxError: Function statements // require a function name. // function as expression (function(x){ return x }); // This will run without any exception.</script> Example 2: With and without grouping operator. jscript <script> function gfg() { // 5 * 5 + 5 // 25+5 // 30 let value= 5 * 5 + 5 ; document.write("Without grouping operator: " + value); // 5 * (5 + 5) // 5*10 // 50 let value1= 5 * (5 + 5); document.write("</br>With grouping operator: "+ value1); } gfg();</script> Output: Without grouping operator: 30 With grouping operator: 50 Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Opera 3 and above Safari 1 and above ysachin2314 javascript-operators JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 77, "s": 28, "text": "Below is the example of the Grouping operator. " }, { "code": null, "e": 88, "s": 77, "text": "Example: " }, { "code": null, "e": 96, "s": 88, "text": "jscript" }, { "code": "<script> function gfg() { // 3 * (2 + 3) let value1= 3 * (2 + 3); // (3 + 2) * 3 let value2= (3 + 2) * 3; document.write(value1 + \"</br>\" + value2); } gfg();</script> ", "e": 312, "s": 96, "text": null }, { "code": null, "e": 324, "s": 314, "text": "Output: " }, { "code": null, "e": 330, "s": 324, "text": "15\n15" }, { "code": null, "e": 723, "s": 330, "text": "The Grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. This operator can only contain expressions. The parameter list is passed to function within this operator which will treat it as an expression.Syntax: " }, { "code": null, "e": 727, "s": 723, "text": "( )" }, { "code": null, "e": 1188, "s": 727, "text": "This ( ) operator controls the precedence of evaluation in expressionsBelow examples illustrates the Grouping operator in JavaScript: Example 1: Function as a statement and exception. In the below code JavaScript considers a function as a statement if it is not preceded by any other statement. But applying a grouping operator that has the highest precedence over any other operator considers the function as an expression and hence it gets fully evaluated. " }, { "code": null, "e": 1199, "s": 1188, "text": "JavaScript" }, { "code": "<script> function(x){ return x }; // SyntaxError: Function statements // require a function name. // function as expression (function(x){ return x }); // This will run without any exception.</script> ", "e": 1438, "s": 1199, "text": null }, { "code": null, "e": 1487, "s": 1438, "text": "Example 2: With and without grouping operator. " }, { "code": null, "e": 1495, "s": 1487, "text": "jscript" }, { "code": "<script> function gfg() { // 5 * 5 + 5 // 25+5 // 30 let value= 5 * 5 + 5 ; document.write(\"Without grouping operator: \" + value); // 5 * (5 + 5) // 5*10 // 50 let value1= 5 * (5 + 5); document.write(\"</br>With grouping operator: \"+ value1); } gfg();</script> ", "e": 1814, "s": 1495, "text": null }, { "code": null, "e": 1824, "s": 1814, "text": "Output: " }, { "code": null, "e": 1881, "s": 1824, "text": "Without grouping operator: 30\nWith grouping operator: 50" }, { "code": null, "e": 1900, "s": 1881, "text": "Supported Browser:" }, { "code": null, "e": 1919, "s": 1900, "text": "Chrome 1 and above" }, { "code": null, "e": 1937, "s": 1919, "text": "Edge 12 and above" }, { "code": null, "e": 1957, "s": 1937, "text": "Firefox 1 and above" }, { "code": null, "e": 1987, "s": 1957, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 2005, "s": 1987, "text": "Opera 3 and above" }, { "code": null, "e": 2024, "s": 2005, "text": "Safari 1 and above" }, { "code": null, "e": 2036, "s": 2024, "text": "ysachin2314" }, { "code": null, "e": 2057, "s": 2036, "text": "javascript-operators" }, { "code": null, "e": 2068, "s": 2057, "text": "JavaScript" }, { "code": null, "e": 2085, "s": 2068, "text": "Web Technologies" } ]
Shell Script to Put File in a FTP Server
09 Apr, 2021 The File Transfer Protocol also called FTP is used to transfer files from client to server and vice-versa. It mainly uses port 21 for communication. Here we can simplify the process of uploading files using FTP. But, before we write a script, let’s look at how to get/put files onto an ftp server directly using commands. The commands to start an FTP communication and end it is shown below: ftp server #Prompts for login details and connects to server #Example: ftp 192.168.0.104 bye #Terminates the ftp connection and exits ftp Example: After typing “FTP hostname”, you will be asked for a username and password. If login is successful after entering the details, we start in the FTP user’s home directory on the server. Any file you upload now gets uploaded to this directory. If you have to upload a file in some other directory on the server, you first have to change to that directory using the “cd” command. Note that, using the cd command in an FTP prompt only changes directory on the server, i.e. we will still be in the same directory on our local computer. Commands in FTP help us to navigate the server’s directories, fetch and upload files from and to the server. To get single or multiple files, we can use commands “get” and “mget” respectively. Similarly, to put single or multiple files, we can use commands “put” and “mput” respectively. Some important ftp commands: ls #Lists files in server cd dir #Change directory in server get file1.c #Downloads file1.c put file.txt #Uploads file.txt mput *.c file.txt #Uploads all c files and file.txt Example of putting a file in server through FTP prompt: #!/bin/bash # The 3 variables below store server and login details HOST="192.168.0.104" USER="user1" PASSWORD="1234" # $1 is the first argument to the script # We are using it as upload directory path # If it is '.', file is uploaded to current directory. DESTINATION=$1 # Rest of the arguments are a list of files to be uploaded. # ${@:2} is an array of arguments without first one. ALL_FILES="${@:2}" # FTP login and upload is explained in paragraph below ftp -inv $HOST <<EOF user $USER $PASSWORD cd $DESTINATION mput $ALL_FILES bye EOF The above script requires the following data: Server’s hostnameServer user’s login detailsThe directory in which to upload files on the server (passed as an argument to the script)The list of files to be uploaded to the server (passed as an argument to script) Server’s hostname Server user’s login details The directory in which to upload files on the server (passed as an argument to the script) The list of files to be uploaded to the server (passed as an argument to script) After logging in to the server, we need to enter FTP commands manually, but by using input redirection we can supply the commands directly in the script. “<<” is used for input redirection and “EOF” is used to mark the beginning and end of the FTP input. The “mput” command has been used to upload files as mput can upload either a single file or multiple files. If login is successful and the files given as input to the script are available, all the files should have been put in the server along with a success message displayed for each file. The options -inv can also be written as -i -n -v and their functions are explained in the below table: To execute the script supply the upload directory and also a list of files: ./script_name.sh path_to_upload file1 file2 file3 File Uploading Example (Put all .c files and f1.txt in the current directory of server): Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Apr, 2021" }, { "code": null, "e": 177, "s": 28, "text": "The File Transfer Protocol also called FTP is used to transfer files from client to server and vice-versa. It mainly uses port 21 for communication." }, { "code": null, "e": 350, "s": 177, "text": "Here we can simplify the process of uploading files using FTP. But, before we write a script, let’s look at how to get/put files onto an ftp server directly using commands." }, { "code": null, "e": 420, "s": 350, "text": "The commands to start an FTP communication and end it is shown below:" }, { "code": null, "e": 570, "s": 420, "text": "ftp server #Prompts for login details and connects to server\n#Example: \nftp 192.168.0.104\n\nbye #Terminates the ftp connection and exits ftp" }, { "code": null, "e": 579, "s": 570, "text": "Example:" }, { "code": null, "e": 1109, "s": 579, "text": "After typing “FTP hostname”, you will be asked for a username and password. If login is successful after entering the details, we start in the FTP user’s home directory on the server. Any file you upload now gets uploaded to this directory. If you have to upload a file in some other directory on the server, you first have to change to that directory using the “cd” command. Note that, using the cd command in an FTP prompt only changes directory on the server, i.e. we will still be in the same directory on our local computer." }, { "code": null, "e": 1397, "s": 1109, "text": "Commands in FTP help us to navigate the server’s directories, fetch and upload files from and to the server. To get single or multiple files, we can use commands “get” and “mget” respectively. Similarly, to put single or multiple files, we can use commands “put” and “mput” respectively." }, { "code": null, "e": 1426, "s": 1397, "text": "Some important ftp commands:" }, { "code": null, "e": 1651, "s": 1426, "text": "ls #Lists files in server\ncd dir #Change directory in server\nget file1.c #Downloads file1.c\nput file.txt #Uploads file.txt\nmput *.c file.txt #Uploads all c files and file.txt" }, { "code": null, "e": 1707, "s": 1651, "text": "Example of putting a file in server through FTP prompt:" }, { "code": null, "e": 2254, "s": 1707, "text": "#!/bin/bash\n\n# The 3 variables below store server and login details\nHOST=\"192.168.0.104\"\nUSER=\"user1\"\nPASSWORD=\"1234\"\n\n\n# $1 is the first argument to the script\n# We are using it as upload directory path\n# If it is '.', file is uploaded to current directory.\nDESTINATION=$1\n\n\n# Rest of the arguments are a list of files to be uploaded.\n# ${@:2} is an array of arguments without first one.\nALL_FILES=\"${@:2}\"\n\n\n# FTP login and upload is explained in paragraph below\nftp -inv $HOST <<EOF\nuser $USER $PASSWORD\ncd $DESTINATION\nmput $ALL_FILES\nbye\nEOF" }, { "code": null, "e": 2300, "s": 2254, "text": "The above script requires the following data:" }, { "code": null, "e": 2515, "s": 2300, "text": "Server’s hostnameServer user’s login detailsThe directory in which to upload files on the server (passed as an argument to the script)The list of files to be uploaded to the server (passed as an argument to script)" }, { "code": null, "e": 2533, "s": 2515, "text": "Server’s hostname" }, { "code": null, "e": 2561, "s": 2533, "text": "Server user’s login details" }, { "code": null, "e": 2652, "s": 2561, "text": "The directory in which to upload files on the server (passed as an argument to the script)" }, { "code": null, "e": 2733, "s": 2652, "text": "The list of files to be uploaded to the server (passed as an argument to script)" }, { "code": null, "e": 2989, "s": 2733, "text": "After logging in to the server, we need to enter FTP commands manually, but by using input redirection we can supply the commands directly in the script. “<<” is used for input redirection and “EOF” is used to mark the beginning and end of the FTP input. " }, { "code": null, "e": 3097, "s": 2989, "text": "The “mput” command has been used to upload files as mput can upload either a single file or multiple files." }, { "code": null, "e": 3281, "s": 3097, "text": "If login is successful and the files given as input to the script are available, all the files should have been put in the server along with a success message displayed for each file." }, { "code": null, "e": 3384, "s": 3281, "text": "The options -inv can also be written as -i -n -v and their functions are explained in the below table:" }, { "code": null, "e": 3460, "s": 3384, "text": "To execute the script supply the upload directory and also a list of files:" }, { "code": null, "e": 3511, "s": 3460, "text": "./script_name.sh path_to_upload file1 file2 file3" }, { "code": null, "e": 3600, "s": 3511, "text": "File Uploading Example (Put all .c files and f1.txt in the current directory of server):" }, { "code": null, "e": 3607, "s": 3600, "text": "Picked" }, { "code": null, "e": 3620, "s": 3607, "text": "Shell Script" }, { "code": null, "e": 3631, "s": 3620, "text": "Linux-Unix" } ]
How to place two bootstrap cards next to each other ?
14 May, 2020 Bootstrap is the most popular, free, and open-source HTML, CSS framework that is used to make a responsive website and make them beautiful. It provides various classes to work with that can be used to make a website beautiful. It also provides classes for creating cards. Cards: A card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. Syntax: <div class="card" style="width: 20rem"> <img class="card-img-top" src="..." alt="Card image cap"> <div class="card-block"> <h4 class="card-title">Card title</h4> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-primary"> Go somewhere </a> </div></div> Example 1: This example using bootstrap’s grid to make a row and divide it. <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous"> <title> Place two bootstrap cards next to each other </title></head> <body> <div class="container"> <div class="row"> <div class="col-lg-6 mb-4"> <div class="card"> <img class="card-img-top" src="" alt=""> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-outline-primary btn-sm"> Card link </a> <a href="#" class="btn btn-outline-secondary btn-sm"> <i class="far fa-heart"></i></a> </div> </div> </div> <div class="col-lg-6 mb-4"> <div class="card"> <img class="card-img-top" src="" alt=""> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-outline-primary btn-sm"> Card link </a> <a href="#" class="btn btn-outline-secondary btn-sm"> <i class="far fa-heart"></i></a> </div> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html> Output: Example 2: To create Cards of equal width and height you can also use a class of Bootstrap card-deck. <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1,shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous"> <title> Place two bootstrap cards next to each other </title></head> <body> <div class="card-deck"> <div class="card"> <img class="card-img-top" src="" alt="Card image cap"> <div class="card-block"> <h4 class="card-title">Card title</h4> <p class="card-text"> This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. </p> <p class="card-text"> <small class="text-muted"> Last updated 3 mins ago </small> </p> </div> </div> <div class="card"> <img class="card-img-top" src=""> <div class="card-block"> <h4 class="card-title">Card title</h4> <p class="card-text"> This card has supporting text below as a natural lead-in to additional content. </p> <p class="card-text"> <small class="text-muted"> Last updated 3 mins ago </small> </p> </div> </div> <div class="card"> <img class="card-img-top" src=""> <div class="card-block"> <h4 class="card-title">Card title</h4> <p class="card-text"> This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action. </p> <p class="card-text"> <small class="text-muted"> Last updated 3 mins ago </small> </p> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></body> </html> Output: Bootstrap-Misc Picked Bootstrap Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to Add Image into Dropdown List for each items ? How to Align modal content box to center of any screen? 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 Roadmap to Learn JavaScript For Beginners How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n14 May, 2020" }, { "code": null, "e": 324, "s": 52, "text": "Bootstrap is the most popular, free, and open-source HTML, CSS framework that is used to make a responsive website and make them beautiful. It provides various classes to work with that can be used to make a website beautiful. It also provides classes for creating cards." }, { "code": null, "e": 518, "s": 324, "text": "Cards: A card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options." }, { "code": null, "e": 526, "s": 518, "text": "Syntax:" }, { "code": "<div class=\"card\" style=\"width: 20rem\"> <img class=\"card-img-top\" src=\"...\" alt=\"Card image cap\"> <div class=\"card-block\"> <h4 class=\"card-title\">Card title</h4> <p class=\"card-text\"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href=\"#\" class=\"btn btn-primary\"> Go somewhere </a> </div></div>", "e": 978, "s": 526, "text": null }, { "code": null, "e": 1054, "s": 978, "text": "Example 1: This example using bootstrap’s grid to make a row and divide it." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.4.1/css/all.css\" integrity=\"sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz\" crossorigin=\"anonymous\"> <title> Place two bootstrap cards next to each other </title></head> <body> <div class=\"container\"> <div class=\"row\"> <div class=\"col-lg-6 mb-4\"> <div class=\"card\"> <img class=\"card-img-top\" src=\"\" alt=\"\"> <div class=\"card-body\"> <h5 class=\"card-title\">Card title</h5> <p class=\"card-text\"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href=\"#\" class=\"btn btn-outline-primary btn-sm\"> Card link </a> <a href=\"#\" class=\"btn btn-outline-secondary btn-sm\"> <i class=\"far fa-heart\"></i></a> </div> </div> </div> <div class=\"col-lg-6 mb-4\"> <div class=\"card\"> <img class=\"card-img-top\" src=\"\" alt=\"\"> <div class=\"card-body\"> <h5 class=\"card-title\">Card title</h5> <p class=\"card-text\"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href=\"#\" class=\"btn btn-outline-primary btn-sm\"> Card link </a> <a href=\"#\" class=\"btn btn-outline-secondary btn-sm\"> <i class=\"far fa-heart\"></i></a> </div> </div> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 4370, "s": 1054, "text": null }, { "code": null, "e": 4378, "s": 4370, "text": "Output:" }, { "code": null, "e": 4480, "s": 4378, "text": "Example 2: To create Cards of equal width and height you can also use a class of Bootstrap card-deck." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1,shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.4.1/css/all.css\" integrity=\"sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz\" crossorigin=\"anonymous\"> <title> Place two bootstrap cards next to each other </title></head> <body> <div class=\"card-deck\"> <div class=\"card\"> <img class=\"card-img-top\" src=\"\" alt=\"Card image cap\"> <div class=\"card-block\"> <h4 class=\"card-title\">Card title</h4> <p class=\"card-text\"> This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. </p> <p class=\"card-text\"> <small class=\"text-muted\"> Last updated 3 mins ago </small> </p> </div> </div> <div class=\"card\"> <img class=\"card-img-top\" src=\"\"> <div class=\"card-block\"> <h4 class=\"card-title\">Card title</h4> <p class=\"card-text\"> This card has supporting text below as a natural lead-in to additional content. </p> <p class=\"card-text\"> <small class=\"text-muted\"> Last updated 3 mins ago </small> </p> </div> </div> <div class=\"card\"> <img class=\"card-img-top\" src=\"\"> <div class=\"card-block\"> <h4 class=\"card-title\">Card title</h4> <p class=\"card-text\"> This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action. </p> <p class=\"card-text\"> <small class=\"text-muted\"> Last updated 3 mins ago </small> </p> </div> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></body> </html>", "e": 8022, "s": 4480, "text": null }, { "code": null, "e": 8030, "s": 8022, "text": "Output:" }, { "code": null, "e": 8045, "s": 8030, "text": "Bootstrap-Misc" }, { "code": null, "e": 8052, "s": 8045, "text": "Picked" }, { "code": null, "e": 8062, "s": 8052, "text": "Bootstrap" }, { "code": null, "e": 8079, "s": 8062, "text": "Web Technologies" }, { "code": null, "e": 8106, "s": 8079, "text": "Web technologies Questions" }, { "code": null, "e": 8122, "s": 8106, "text": "Write From Home" }, { "code": null, "e": 8220, "s": 8122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8283, "s": 8220, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 8324, "s": 8283, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 8357, "s": 8324, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 8410, "s": 8357, "text": "How to Add Image into Dropdown List for each items ?" }, { "code": null, "e": 8466, "s": 8410, "text": "How to Align modal content box to center of any screen?" }, { "code": null, "e": 8499, "s": 8466, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8561, "s": 8499, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8622, "s": 8561, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8664, "s": 8622, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Python Programming Examples - GeeksforGeeks
01 Jul, 2022 The following Python section contains a wide collection of Python programming examples. The examples are categorized based on the topics including List, strings, dictionary, tuple, sets, and many more. Each program example contains multiple approaches to solve the problem. Python Programming TutorialRecent Articles on Python !Python Output & Multiple Choice Questions Topics : Basic Programs Array Programs List Programs Matrix Programs String Programs Dictionary Programs Tuple Programs Searching and Sorting Programs Pattern Printing Date-Time Programs Regex Programs File Handling Programs More Python Programs Python program to add two numbersMaximum of two numbers in PythonPython Program for factorial of a numberPython Program for simple interestPython Program for compound interestPython Program to check Armstrong NumberPython Program for Program to find area of a circlePython program to print all Prime numbers in an IntervalPython program to check whether a number is Prime or notPython Program for n-th Fibonacci numberPython Program for How to check if a given number is Fibonacci number?Python Program for n\’th multiple of a number in Fibonacci SeriesProgram to print ASCII Value of a characterPython Program for Sum of squares of first n natural numbersPython Program for cube sum of first n natural numbers Python program to add two numbers Maximum of two numbers in Python Python Program for factorial of a number Python Program for simple interest Python Program for compound interest Python Program to check Armstrong Number Python Program for Program to find area of a circle Python program to print all Prime numbers in an Interval Python program to check whether a number is Prime or not Python Program for n-th Fibonacci number Python Program for How to check if a given number is Fibonacci number? Python Program for n\’th multiple of a number in Fibonacci Series Program to print ASCII Value of a character Python Program for Sum of squares of first n natural numbers Python Program for cube sum of first n natural numbers Python Program to find sum of arrayPython Program to find largest element in an arrayPython Program for array rotationPython Program for Reversal algorithm for array rotationPython Program to Split the array and add the first part to the endPython Program for Find reminder of array multiplication divided by nPython Program to check if given array is Monotonic Python Program to find sum of array Python Program to find largest element in an array Python Program for array rotation Python Program for Reversal algorithm for array rotation Python Program to Split the array and add the first part to the end Python Program for Find reminder of array multiplication divided by n Python Program to check if given array is Monotonic Python program to interchange first and last elements in a listPython program to swap two elements in a listPython | Ways to find length of listPython | Ways to check if element exists in listDifferent ways to clear a list in PythonPython | Reversing a ListPython program to find sum of elements in listPython | Multiply all numbers in the listPython program to find smallest number in a listPython program to find largest number in a listPython program to find second largest number in a listPython program to find N largest elements from a listPython program to print even numbers in a listPython program to print odd numbers in a ListPython program to print all even numbers in a rangePython program to print all odd numbers in a rangePython program to print positive numbers in a listPython program to print negative numbers in a listPython program to print all positive numbers in a rangePython program to print all negative numbers in a rangeRemove multiple elements from a list in PythonPython – Remove empty List from ListPython | Cloning or Copying a listPython | Count occurrences of an element in a listPython | Remove empty tuples from a listPython | Program to print duplicates from a list of integersPython program to find Cumulative sum of a listPython | Sum of number digits in ListBreak a list into chunks of size N in PythonPython | Sort the values of first list using second listMore >> Python program to interchange first and last elements in a list Python program to swap two elements in a list Python | Ways to find length of list Python | Ways to check if element exists in list Different ways to clear a list in Python Python | Reversing a List Python program to find sum of elements in list Python | Multiply all numbers in the list Python program to find smallest number in a list Python program to find largest number in a list Python program to find second largest number in a list Python program to find N largest elements from a list Python program to print even numbers in a list Python program to print odd numbers in a List Python program to print all even numbers in a range Python program to print all odd numbers in a range Python program to print positive numbers in a list Python program to print negative numbers in a list Python program to print all positive numbers in a range Python program to print all negative numbers in a range Remove multiple elements from a list in Python Python – Remove empty List from List Python | Cloning or Copying a list Python | Count occurrences of an element in a list Python | Remove empty tuples from a list Python | Program to print duplicates from a list of integers Python program to find Cumulative sum of a list Python | Sum of number digits in List Break a list into chunks of size N in Python Python | Sort the values of first list using second list More >> Python program to add two MatricesPython program to multiply two matricesPython program for Matrix ProductAdding and Subtracting Matrices in PythonTranspose a matrix in Single line in PythonPython | Matrix creation of n*nPython | Get Kth Column of MatrixPython – Vertical Concatenation in Matrix Python program to add two Matrices Python program to multiply two matrices Python program for Matrix Product Adding and Subtracting Matrices in Python Transpose a matrix in Single line in Python Python | Matrix creation of n*n Python | Get Kth Column of Matrix Python – Vertical Concatenation in Matrix Python program to check if a string is palindrome or notPython program to check whether the string is Symmetrical or PalindromeReverse words in a given String in PythonWays to remove i’th character from string in PythonPython | Check if a Substring is Present in a Given StringPython – Words Frequency in String ShorthandsPython – Convert Snake case to Pascal caseFind length of a string in python (4 ways)Python program to print even length words in a stringPython program to accept the strings which contains all vowelsPython | Count the Number of matching characters in a pair of stringRemove all duplicates from a given string in PythonPython – Least Frequent Character in StringPython | Maximum frequency character in StringPython | Program to check if a string contains any special characterGenerating random strings until a given string is generatedFind words which are greater than given length kPython program for removing i-th character from a stringPython program to split and join a stringPython | Check if a given string is binary string or notPython program to find uncommon words from two StringsPython – Replace duplicate Occurrence in StringPython – Replace multiple words with KPython | Permutation of a given string using inbuilt functionPython | Check for URL in a StringExecute a String of Code in PythonString slicing in Python to rotate a stringString slicing in Python to check if a string can become empty by recursive deletionPython Counter| Find all duplicate characters in stringPython – Replace all occurrences of a substring in a stringMore >> Python program to check if a string is palindrome or not Python program to check whether the string is Symmetrical or Palindrome Reverse words in a given String in Python Ways to remove i’th character from string in Python Python | Check if a Substring is Present in a Given String Python – Words Frequency in String Shorthands Python – Convert Snake case to Pascal case Find length of a string in python (4 ways) Python program to print even length words in a string Python program to accept the strings which contains all vowels Python | Count the Number of matching characters in a pair of string Remove all duplicates from a given string in Python Python – Least Frequent Character in String Python | Maximum frequency character in String Python | Program to check if a string contains any special character Generating random strings until a given string is generated Find words which are greater than given length k Python program for removing i-th character from a string Python program to split and join a string Python | Check if a given string is binary string or not Python program to find uncommon words from two Strings Python – Replace duplicate Occurrence in String Python – Replace multiple words with K Python | Permutation of a given string using inbuilt function Python | Check for URL in a String Execute a String of Code in Python String slicing in Python to rotate a string String slicing in Python to check if a string can become empty by recursive deletion Python Counter| Find all duplicate characters in string Python – Replace all occurrences of a substring in a string More >> Python – Extract Unique values dictionary valuesPython program to find the sum of all items in a dictionaryPython | Ways to remove a key from dictionaryWays to sort list of dictionaries by values in Python – Using itemgetterWays to sort list of dictionaries by values in Python – Using lambda functionPython | Merging two DictionariesPython – Convert key-values list to flat dictionaryPython – Insertion at the beginning in OrderedDictPython | Check order of character in string using OrderedDict( )Dictionary and counter in Python to find winner of electionPython – Append Dictionary Keys and Values ( In order ) in dictionaryPython | Sort Python Dictionaries by Key or ValuePython – Sort Dictionary key and values ListHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPrint anagrams together in Python using List and DictionaryK’th Non-repeating Character in Python using List Comprehension and OrderedDictCheck if binary representations of two numbers are anagramPython Counter to find the size of largest subset of anagram wordsPython | Remove all duplicates words from a given sentencePython Dictionary to find mirror characters in a stringCounting the frequencies in a list using dictionary in PythonPython | Convert a list of Tuples into DictionaryPython counter and dictionary intersection example (Make a string using deletion and rearrangement)Python dictionary, set and counter to check if frequencies can become sameScraping And Finding Ordered Words In A Dictionary using PythonPossible Words using given characters in PythonPython – Keys associated with Values in DictionaryMore >> Python – Extract Unique values dictionary values Python program to find the sum of all items in a dictionary Python | Ways to remove a key from dictionary Ways to sort list of dictionaries by values in Python – Using itemgetter Ways to sort list of dictionaries by values in Python – Using lambda function Python | Merging two Dictionaries Python – Convert key-values list to flat dictionary Python – Insertion at the beginning in OrderedDict Python | Check order of character in string using OrderedDict( ) Dictionary and counter in Python to find winner of election Python – Append Dictionary Keys and Values ( In order ) in dictionary Python | Sort Python Dictionaries by Key or Value Python – Sort Dictionary key and values List Handling missing keys in Python dictionaries Python dictionary with keys having multiple inputs Print anagrams together in Python using List and Dictionary K’th Non-repeating Character in Python using List Comprehension and OrderedDict Check if binary representations of two numbers are anagram Python Counter to find the size of largest subset of anagram words Python | Remove all duplicates words from a given sentence Python Dictionary to find mirror characters in a string Counting the frequencies in a list using dictionary in Python Python | Convert a list of Tuples into Dictionary Python counter and dictionary intersection example (Make a string using deletion and rearrangement) Python dictionary, set and counter to check if frequencies can become same Scraping And Finding Ordered Words In A Dictionary using Python Possible Words using given characters in Python Python – Keys associated with Values in DictionaryMore >> Python program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Closest Pair to Kth index element in TuplePython – Join Tuples if similar initial elementPython – Extract digits from Tuple listPython – All pair combinations of 2 tuplesPython – Remove Tuples of Length KSort a list of tuples by second ItemPython program to Order Tuples using external ListPython – Flatten tuple of List to tuplePython – Convert Nested Tuple to Custom Key DictionaryMore >> Python program to Find the size of a Tuple Python – Maximum and Minimum K elements in Tuple Create a list of tuples from given list having number and its cube in each tuple Python – Adding Tuple to List and vice – versa Python – Closest Pair to Kth index element in Tuple Python – Join Tuples if similar initial element Python – Extract digits from Tuple list Python – All pair combinations of 2 tuples Python – Remove Tuples of Length K Sort a list of tuples by second Item Python program to Order Tuples using external List Python – Flatten tuple of List to tuple Python – Convert Nested Tuple to Custom Key Dictionary More >> Python Program for Binary Search (Recursive and Iterative)Python Program for Linear SearchPython Program for Insertion SortPython Program for Recursive Insertion SortPython Program for QuickSortPython Program for Iterative Quick SortPython Program for Selection SortPython Program for Bubble SortPython Program for Merge SortPython Program for Iterative Merge SortPython Program for Heap SortPython Program for Counting SortPython Program for ShellSortPython Program for Topological SortingPython Program for Radix SortPython Program for Binary Insertion SortPython Program for Bitonic SortPython Program for Comb SortPython Program for Pigeonhole SortPython Program for Cocktail SortPython Program for Gnome SortPython Program for Odd-Even Sort / Brick SortPython Program for BogoSort or Permutation SortPython Program for Cycle SortPython Program for Stooge Sort Python Program for Binary Search (Recursive and Iterative) Python Program for Linear Search Python Program for Insertion Sort Python Program for Recursive Insertion Sort Python Program for QuickSort Python Program for Iterative Quick Sort Python Program for Selection Sort Python Program for Bubble Sort Python Program for Merge Sort Python Program for Iterative Merge Sort Python Program for Heap Sort Python Program for Counting Sort Python Program for ShellSort Python Program for Topological Sorting Python Program for Radix Sort Python Program for Binary Insertion Sort Python Program for Bitonic Sort Python Program for Comb Sort Python Program for Pigeonhole Sort Python Program for Cocktail Sort Python Program for Gnome Sort Python Program for Odd-Even Sort / Brick Sort Python Program for BogoSort or Permutation Sort Python Program for Cycle Sort Python Program for Stooge Sort Python Program to print the pattern ‘G’Python Program to print an Inverted Star PatternPython Program to print double sided stair-case patternPython Program to print with your own font Python Program to print the pattern ‘G’ Python Program to print an Inverted Star Pattern Python Program to print double sided stair-case pattern Python Program to print with your own font Python program to get Current TimeGet Current Date and Time using PythonPython | Find yesterday’s, today’s and tomorrow’s datePython program to convert time from 12 hour to 24 hour formatPython program to find difference between current time and given timePython Program to Create a Lap TimerConvert date string to timestamp in PythonHow to convert timestamp string to datetime object in Python?Find number of times every day occurs in a Year Python program to get Current Time Get Current Date and Time using Python Python | Find yesterday’s, today’s and tomorrow’s date Python program to convert time from 12 hour to 24 hour format Python program to find difference between current time and given time Python Program to Create a Lap Timer Convert date string to timestamp in Python How to convert timestamp string to datetime object in Python? Find number of times every day occurs in a Year Python Program to Check if String Contain Only Defined Characters using RegexPython program to Count Uppercase, Lowercase, special character and numeric values using RegexPython Program to find the most occurring number in a string using RegexPython Regex to extract maximum numeric value from a stringPython Program to put spaces between words starting with capital letters using RegexPython – Check whether a string starts and ends with the same character or notPython regex to find sequences of one upper case letter followed by lower case lettersPython Program to Remove duplicate words from SentencePython | Remove all characters except letters and numbersPython Regex | Program to accept string ending with alphanumeric characterPython Regex – Program to accept string starting with vowelPython Program to check if a string starts with a substring using regexPython Program to Check if an URL is valid or not using Regular ExpressionParsing and Processing URL using Python – RegexPython Program to validate an IP address using ReGexPython Program to Check if email address valid or notPython program to find files having a particular extension using RegExPython program to extract IP address from filePython program to check the validity of a PasswordCategorize Password as Strong or Weak using Regex in Python Python Program to Check if String Contain Only Defined Characters using Regex Python program to Count Uppercase, Lowercase, special character and numeric values using Regex Python Program to find the most occurring number in a string using Regex Python Regex to extract maximum numeric value from a string Python Program to put spaces between words starting with capital letters using Regex Python – Check whether a string starts and ends with the same character or not Python regex to find sequences of one upper case letter followed by lower case letters Python Program to Remove duplicate words from Sentence Python | Remove all characters except letters and numbers Python Regex | Program to accept string ending with alphanumeric character Python Regex – Program to accept string starting with vowel Python Program to check if a string starts with a substring using regex Python Program to Check if an URL is valid or not using Regular Expression Parsing and Processing URL using Python – Regex Python Program to validate an IP address using ReGex Python Program to Check if email address valid or not Python program to find files having a particular extension using RegEx Python program to extract IP address from file Python program to check the validity of a Password Categorize Password as Strong or Weak using Regex in Python Python program to read file word by wordPython program to read character by character from a filePython – Get number of characters, words, spaces and lines in a filePython program to Count the Number of occurrences of a key-value pair in a text filePython | Finding ‘n’ Character Words in a Text FilePython Program to obtain the line number in which given word is presentCount number of lines in a text file in PythonPython Program to remove lines starting with any prefixPython Program to Eliminate repeated lines from a filePython Program to read List of Dictionaries from FilePython – Append content of one text file to anotherPython program to copy odd lines of one file to otherPython Program to merge two files into a third filePython program to Reverse a single line of a text filePython program to reverse the content of a file and store it in another filePython Program to Reverse the Content of a File using Stack Python program to read file word by word Python program to read character by character from a file Python – Get number of characters, words, spaces and lines in a file Python program to Count the Number of occurrences of a key-value pair in a text file Python | Finding ‘n’ Character Words in a Text File Python Program to obtain the line number in which given word is present Count number of lines in a text file in Python Python Program to remove lines starting with any prefix Python Program to Eliminate repeated lines from a file Python Program to read List of Dictionaries from File Python – Append content of one text file to another Python program to copy odd lines of one file to other Python Program to merge two files into a third file Python program to Reverse a single line of a text file Python program to reverse the content of a file and store it in another file Python Program to Reverse the Content of a File using Stack Python Program to Reverse a linked listPython Program for Find largest prime factor of a numberPython Program for Efficient program to print all prime factors of a given numberPython Program for Product of unique prime factors of a numberPython Program for Find sum of odd factors of a numberPython Program for Coin ChangePython Program for Tower of HanoiPython Program for Sieve of EratosthenesPython Program to Check if binary representation is palindromePython Program for Basic Euclidean algorithmsPython Program for Extended Euclidean algorithmsPython Program for Maximum height when coins are arranged in a trianglePython Program for Find minimum sum of factors of numberPython Program for Difference between sums of odd and even digitsPython Program for Program to Print Matrix in Z formPython Program for Smallest K digit number divisible by XPython Program for Print Number series without using any loopPython Program for Number of stopping station problemCheck if a triangle of positive area is possible with the given anglesPython program to find the most occurring character and its countPython Program for Find sum of even factors of a numberPython Program for Check if all digits of a number divide itCheck whether a number has consecutive 0’s in the given base or notPython Program for Number of solutions to Modular EquationsPython Program for Legendre\’s Conjecture Python Program to Reverse a linked list Python Program for Find largest prime factor of a number Python Program for Efficient program to print all prime factors of a given number Python Program for Product of unique prime factors of a number Python Program for Find sum of odd factors of a number Python Program for Coin Change Python Program for Tower of Hanoi Python Program for Sieve of Eratosthenes Python Program to Check if binary representation is palindrome Python Program for Basic Euclidean algorithms Python Program for Extended Euclidean algorithms Python Program for Maximum height when coins are arranged in a triangle Python Program for Find minimum sum of factors of number Python Program for Difference between sums of odd and even digits Python Program for Program to Print Matrix in Z form Python Program for Smallest K digit number divisible by X Python Program for Print Number series without using any loop Python Program for Number of stopping station problem Check if a triangle of positive area is possible with the given angles Python program to find the most occurring character and its count Python Program for Find sum of even factors of a number Python Program for Check if all digits of a number divide it Check whether a number has consecutive 0’s in the given base or not Python Program for Number of solutions to Modular Equations Python Program for Legendre\’s Conjecture 1. Geeks Classes LiveGet interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session 2. Complete Interview PreparationGet fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices. 3. DSA Self PacedStart learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience. If you like GeeksforGeeks and would like to contribute, you can also write an article on https://write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 43382, "s": 43354, "text": "\n01 Jul, 2022" }, { "code": null, "e": 43658, "s": 43384, "text": "The following Python section contains a wide collection of Python programming examples. The examples are categorized based on the topics including List, strings, dictionary, tuple, sets, and many more. Each program example contains multiple approaches to solve the problem." }, { "code": null, "e": 43763, "s": 43658, "text": "Python Programming TutorialRecent Articles on Python !Python Output & Multiple Choice Questions Topics :" }, { "code": null, "e": 43778, "s": 43763, "text": "Basic Programs" }, { "code": null, "e": 43793, "s": 43778, "text": "Array Programs" }, { "code": null, "e": 43807, "s": 43793, "text": "List Programs" }, { "code": null, "e": 43823, "s": 43807, "text": "Matrix Programs" }, { "code": null, "e": 43839, "s": 43823, "text": "String Programs" }, { "code": null, "e": 43859, "s": 43839, "text": "Dictionary Programs" }, { "code": null, "e": 43874, "s": 43859, "text": "Tuple Programs" }, { "code": null, "e": 43905, "s": 43874, "text": "Searching and Sorting Programs" }, { "code": null, "e": 43922, "s": 43905, "text": "Pattern Printing" }, { "code": null, "e": 43941, "s": 43922, "text": "Date-Time Programs" }, { "code": null, "e": 43956, "s": 43941, "text": "Regex Programs" }, { "code": null, "e": 43979, "s": 43956, "text": "File Handling Programs" }, { "code": null, "e": 44000, "s": 43979, "text": "More Python Programs" }, { "code": null, "e": 44714, "s": 44003, "text": "Python program to add two numbersMaximum of two numbers in PythonPython Program for factorial of a numberPython Program for simple interestPython Program for compound interestPython Program to check Armstrong NumberPython Program for Program to find area of a circlePython program to print all Prime numbers in an IntervalPython program to check whether a number is Prime or notPython Program for n-th Fibonacci numberPython Program for How to check if a given number is Fibonacci number?Python Program for n\\’th multiple of a number in Fibonacci SeriesProgram to print ASCII Value of a characterPython Program for Sum of squares of first n natural numbersPython Program for cube sum of first n natural numbers" }, { "code": null, "e": 44748, "s": 44714, "text": "Python program to add two numbers" }, { "code": null, "e": 44781, "s": 44748, "text": "Maximum of two numbers in Python" }, { "code": null, "e": 44822, "s": 44781, "text": "Python Program for factorial of a number" }, { "code": null, "e": 44857, "s": 44822, "text": "Python Program for simple interest" }, { "code": null, "e": 44894, "s": 44857, "text": "Python Program for compound interest" }, { "code": null, "e": 44935, "s": 44894, "text": "Python Program to check Armstrong Number" }, { "code": null, "e": 44987, "s": 44935, "text": "Python Program for Program to find area of a circle" }, { "code": null, "e": 45044, "s": 44987, "text": "Python program to print all Prime numbers in an Interval" }, { "code": null, "e": 45101, "s": 45044, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 45142, "s": 45101, "text": "Python Program for n-th Fibonacci number" }, { "code": null, "e": 45213, "s": 45142, "text": "Python Program for How to check if a given number is Fibonacci number?" }, { "code": null, "e": 45279, "s": 45213, "text": "Python Program for n\\’th multiple of a number in Fibonacci Series" }, { "code": null, "e": 45323, "s": 45279, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 45384, "s": 45323, "text": "Python Program for Sum of squares of first n natural numbers" }, { "code": null, "e": 45439, "s": 45384, "text": "Python Program for cube sum of first n natural numbers" }, { "code": null, "e": 45801, "s": 45439, "text": "Python Program to find sum of arrayPython Program to find largest element in an arrayPython Program for array rotationPython Program for Reversal algorithm for array rotationPython Program to Split the array and add the first part to the endPython Program for Find reminder of array multiplication divided by nPython Program to check if given array is Monotonic" }, { "code": null, "e": 45837, "s": 45801, "text": "Python Program to find sum of array" }, { "code": null, "e": 45888, "s": 45837, "text": "Python Program to find largest element in an array" }, { "code": null, "e": 45922, "s": 45888, "text": "Python Program for array rotation" }, { "code": null, "e": 45979, "s": 45922, "text": "Python Program for Reversal algorithm for array rotation" }, { "code": null, "e": 46047, "s": 45979, "text": "Python Program to Split the array and add the first part to the end" }, { "code": null, "e": 46117, "s": 46047, "text": "Python Program for Find reminder of array multiplication divided by n" }, { "code": null, "e": 46169, "s": 46117, "text": "Python Program to check if given array is Monotonic" }, { "code": null, "e": 47575, "s": 46169, "text": "Python program to interchange first and last elements in a listPython program to swap two elements in a listPython | Ways to find length of listPython | Ways to check if element exists in listDifferent ways to clear a list in PythonPython | Reversing a ListPython program to find sum of elements in listPython | Multiply all numbers in the listPython program to find smallest number in a listPython program to find largest number in a listPython program to find second largest number in a listPython program to find N largest elements from a listPython program to print even numbers in a listPython program to print odd numbers in a ListPython program to print all even numbers in a rangePython program to print all odd numbers in a rangePython program to print positive numbers in a listPython program to print negative numbers in a listPython program to print all positive numbers in a rangePython program to print all negative numbers in a rangeRemove multiple elements from a list in PythonPython – Remove empty List from ListPython | Cloning or Copying a listPython | Count occurrences of an element in a listPython | Remove empty tuples from a listPython | Program to print duplicates from a list of integersPython program to find Cumulative sum of a listPython | Sum of number digits in ListBreak a list into chunks of size N in PythonPython | Sort the values of first list using second listMore >>" }, { "code": null, "e": 47639, "s": 47575, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 47685, "s": 47639, "text": "Python program to swap two elements in a list" }, { "code": null, "e": 47722, "s": 47685, "text": "Python | Ways to find length of list" }, { "code": null, "e": 47771, "s": 47722, "text": "Python | Ways to check if element exists in list" }, { "code": null, "e": 47812, "s": 47771, "text": "Different ways to clear a list in Python" }, { "code": null, "e": 47838, "s": 47812, "text": "Python | Reversing a List" }, { "code": null, "e": 47885, "s": 47838, "text": "Python program to find sum of elements in list" }, { "code": null, "e": 47927, "s": 47885, "text": "Python | Multiply all numbers in the list" }, { "code": null, "e": 47976, "s": 47927, "text": "Python program to find smallest number in a list" }, { "code": null, "e": 48024, "s": 47976, "text": "Python program to find largest number in a list" }, { "code": null, "e": 48079, "s": 48024, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 48133, "s": 48079, "text": "Python program to find N largest elements from a list" }, { "code": null, "e": 48180, "s": 48133, "text": "Python program to print even numbers in a list" }, { "code": null, "e": 48226, "s": 48180, "text": "Python program to print odd numbers in a List" }, { "code": null, "e": 48278, "s": 48226, "text": "Python program to print all even numbers in a range" }, { "code": null, "e": 48329, "s": 48278, "text": "Python program to print all odd numbers in a range" }, { "code": null, "e": 48380, "s": 48329, "text": "Python program to print positive numbers in a list" }, { "code": null, "e": 48431, "s": 48380, "text": "Python program to print negative numbers in a list" }, { "code": null, "e": 48487, "s": 48431, "text": "Python program to print all positive numbers in a range" }, { "code": null, "e": 48543, "s": 48487, "text": "Python program to print all negative numbers in a range" }, { "code": null, "e": 48590, "s": 48543, "text": "Remove multiple elements from a list in Python" }, { "code": null, "e": 48627, "s": 48590, "text": "Python – Remove empty List from List" }, { "code": null, "e": 48662, "s": 48627, "text": "Python | Cloning or Copying a list" }, { "code": null, "e": 48713, "s": 48662, "text": "Python | Count occurrences of an element in a list" }, { "code": null, "e": 48754, "s": 48713, "text": "Python | Remove empty tuples from a list" }, { "code": null, "e": 48815, "s": 48754, "text": "Python | Program to print duplicates from a list of integers" }, { "code": null, "e": 48863, "s": 48815, "text": "Python program to find Cumulative sum of a list" }, { "code": null, "e": 48901, "s": 48863, "text": "Python | Sum of number digits in List" }, { "code": null, "e": 48946, "s": 48901, "text": "Break a list into chunks of size N in Python" }, { "code": null, "e": 49003, "s": 48946, "text": "Python | Sort the values of first list using second list" }, { "code": null, "e": 49011, "s": 49003, "text": "More >>" }, { "code": null, "e": 49307, "s": 49011, "text": "Python program to add two MatricesPython program to multiply two matricesPython program for Matrix ProductAdding and Subtracting Matrices in PythonTranspose a matrix in Single line in PythonPython | Matrix creation of n*nPython | Get Kth Column of MatrixPython – Vertical Concatenation in Matrix" }, { "code": null, "e": 49342, "s": 49307, "text": "Python program to add two Matrices" }, { "code": null, "e": 49382, "s": 49342, "text": "Python program to multiply two matrices" }, { "code": null, "e": 49416, "s": 49382, "text": "Python program for Matrix Product" }, { "code": null, "e": 49458, "s": 49416, "text": "Adding and Subtracting Matrices in Python" }, { "code": null, "e": 49502, "s": 49458, "text": "Transpose a matrix in Single line in Python" }, { "code": null, "e": 49534, "s": 49502, "text": "Python | Matrix creation of n*n" }, { "code": null, "e": 49568, "s": 49534, "text": "Python | Get Kth Column of Matrix" }, { "code": null, "e": 49610, "s": 49568, "text": "Python – Vertical Concatenation in Matrix" }, { "code": null, "e": 51184, "s": 49610, "text": "Python program to check if a string is palindrome or notPython program to check whether the string is Symmetrical or PalindromeReverse words in a given String in PythonWays to remove i’th character from string in PythonPython | Check if a Substring is Present in a Given StringPython – Words Frequency in String ShorthandsPython – Convert Snake case to Pascal caseFind length of a string in python (4 ways)Python program to print even length words in a stringPython program to accept the strings which contains all vowelsPython | Count the Number of matching characters in a pair of stringRemove all duplicates from a given string in PythonPython – Least Frequent Character in StringPython | Maximum frequency character in StringPython | Program to check if a string contains any special characterGenerating random strings until a given string is generatedFind words which are greater than given length kPython program for removing i-th character from a stringPython program to split and join a stringPython | Check if a given string is binary string or notPython program to find uncommon words from two StringsPython – Replace duplicate Occurrence in StringPython – Replace multiple words with KPython | Permutation of a given string using inbuilt functionPython | Check for URL in a StringExecute a String of Code in PythonString slicing in Python to rotate a stringString slicing in Python to check if a string can become empty by recursive deletionPython Counter| Find all duplicate characters in stringPython – Replace all occurrences of a substring in a stringMore >>" }, { "code": null, "e": 51241, "s": 51184, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 51313, "s": 51241, "text": "Python program to check whether the string is Symmetrical or Palindrome" }, { "code": null, "e": 51355, "s": 51313, "text": "Reverse words in a given String in Python" }, { "code": null, "e": 51407, "s": 51355, "text": "Ways to remove i’th character from string in Python" }, { "code": null, "e": 51466, "s": 51407, "text": "Python | Check if a Substring is Present in a Given String" }, { "code": null, "e": 51512, "s": 51466, "text": "Python – Words Frequency in String Shorthands" }, { "code": null, "e": 51555, "s": 51512, "text": "Python – Convert Snake case to Pascal case" }, { "code": null, "e": 51598, "s": 51555, "text": "Find length of a string in python (4 ways)" }, { "code": null, "e": 51652, "s": 51598, "text": "Python program to print even length words in a string" }, { "code": null, "e": 51715, "s": 51652, "text": "Python program to accept the strings which contains all vowels" }, { "code": null, "e": 51784, "s": 51715, "text": "Python | Count the Number of matching characters in a pair of string" }, { "code": null, "e": 51836, "s": 51784, "text": "Remove all duplicates from a given string in Python" }, { "code": null, "e": 51880, "s": 51836, "text": "Python – Least Frequent Character in String" }, { "code": null, "e": 51927, "s": 51880, "text": "Python | Maximum frequency character in String" }, { "code": null, "e": 51996, "s": 51927, "text": "Python | Program to check if a string contains any special character" }, { "code": null, "e": 52056, "s": 51996, "text": "Generating random strings until a given string is generated" }, { "code": null, "e": 52105, "s": 52056, "text": "Find words which are greater than given length k" }, { "code": null, "e": 52162, "s": 52105, "text": "Python program for removing i-th character from a string" }, { "code": null, "e": 52204, "s": 52162, "text": "Python program to split and join a string" }, { "code": null, "e": 52261, "s": 52204, "text": "Python | Check if a given string is binary string or not" }, { "code": null, "e": 52316, "s": 52261, "text": "Python program to find uncommon words from two Strings" }, { "code": null, "e": 52364, "s": 52316, "text": "Python – Replace duplicate Occurrence in String" }, { "code": null, "e": 52403, "s": 52364, "text": "Python – Replace multiple words with K" }, { "code": null, "e": 52465, "s": 52403, "text": "Python | Permutation of a given string using inbuilt function" }, { "code": null, "e": 52500, "s": 52465, "text": "Python | Check for URL in a String" }, { "code": null, "e": 52535, "s": 52500, "text": "Execute a String of Code in Python" }, { "code": null, "e": 52579, "s": 52535, "text": "String slicing in Python to rotate a string" }, { "code": null, "e": 52664, "s": 52579, "text": "String slicing in Python to check if a string can become empty by recursive deletion" }, { "code": null, "e": 52720, "s": 52664, "text": "Python Counter| Find all duplicate characters in string" }, { "code": null, "e": 52780, "s": 52720, "text": "Python – Replace all occurrences of a substring in a string" }, { "code": null, "e": 52788, "s": 52780, "text": "More >>" }, { "code": null, "e": 54428, "s": 52788, "text": "Python – Extract Unique values dictionary valuesPython program to find the sum of all items in a dictionaryPython | Ways to remove a key from dictionaryWays to sort list of dictionaries by values in Python – Using itemgetterWays to sort list of dictionaries by values in Python – Using lambda functionPython | Merging two DictionariesPython – Convert key-values list to flat dictionaryPython – Insertion at the beginning in OrderedDictPython | Check order of character in string using OrderedDict( )Dictionary and counter in Python to find winner of electionPython – Append Dictionary Keys and Values ( In order ) in dictionaryPython | Sort Python Dictionaries by Key or ValuePython – Sort Dictionary key and values ListHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPrint anagrams together in Python using List and DictionaryK’th Non-repeating Character in Python using List Comprehension and OrderedDictCheck if binary representations of two numbers are anagramPython Counter to find the size of largest subset of anagram wordsPython | Remove all duplicates words from a given sentencePython Dictionary to find mirror characters in a stringCounting the frequencies in a list using dictionary in PythonPython | Convert a list of Tuples into DictionaryPython counter and dictionary intersection example (Make a string using deletion and rearrangement)Python dictionary, set and counter to check if frequencies can become sameScraping And Finding Ordered Words In A Dictionary using PythonPossible Words using given characters in PythonPython – Keys associated with Values in DictionaryMore >>" }, { "code": null, "e": 54477, "s": 54428, "text": "Python – Extract Unique values dictionary values" }, { "code": null, "e": 54537, "s": 54477, "text": "Python program to find the sum of all items in a dictionary" }, { "code": null, "e": 54583, "s": 54537, "text": "Python | Ways to remove a key from dictionary" }, { "code": null, "e": 54656, "s": 54583, "text": "Ways to sort list of dictionaries by values in Python – Using itemgetter" }, { "code": null, "e": 54734, "s": 54656, "text": "Ways to sort list of dictionaries by values in Python – Using lambda function" }, { "code": null, "e": 54768, "s": 54734, "text": "Python | Merging two Dictionaries" }, { "code": null, "e": 54820, "s": 54768, "text": "Python – Convert key-values list to flat dictionary" }, { "code": null, "e": 54871, "s": 54820, "text": "Python – Insertion at the beginning in OrderedDict" }, { "code": null, "e": 54936, "s": 54871, "text": "Python | Check order of character in string using OrderedDict( )" }, { "code": null, "e": 54996, "s": 54936, "text": "Dictionary and counter in Python to find winner of election" }, { "code": null, "e": 55066, "s": 54996, "text": "Python – Append Dictionary Keys and Values ( In order ) in dictionary" }, { "code": null, "e": 55116, "s": 55066, "text": "Python | Sort Python Dictionaries by Key or Value" }, { "code": null, "e": 55161, "s": 55116, "text": "Python – Sort Dictionary key and values List" }, { "code": null, "e": 55206, "s": 55161, "text": "Handling missing keys in Python dictionaries" }, { "code": null, "e": 55257, "s": 55206, "text": "Python dictionary with keys having multiple inputs" }, { "code": null, "e": 55317, "s": 55257, "text": "Print anagrams together in Python using List and Dictionary" }, { "code": null, "e": 55397, "s": 55317, "text": "K’th Non-repeating Character in Python using List Comprehension and OrderedDict" }, { "code": null, "e": 55456, "s": 55397, "text": "Check if binary representations of two numbers are anagram" }, { "code": null, "e": 55523, "s": 55456, "text": "Python Counter to find the size of largest subset of anagram words" }, { "code": null, "e": 55582, "s": 55523, "text": "Python | Remove all duplicates words from a given sentence" }, { "code": null, "e": 55638, "s": 55582, "text": "Python Dictionary to find mirror characters in a string" }, { "code": null, "e": 55700, "s": 55638, "text": "Counting the frequencies in a list using dictionary in Python" }, { "code": null, "e": 55750, "s": 55700, "text": "Python | Convert a list of Tuples into Dictionary" }, { "code": null, "e": 55850, "s": 55750, "text": "Python counter and dictionary intersection example (Make a string using deletion and rearrangement)" }, { "code": null, "e": 55925, "s": 55850, "text": "Python dictionary, set and counter to check if frequencies can become same" }, { "code": null, "e": 55989, "s": 55925, "text": "Scraping And Finding Ordered Words In A Dictionary using Python" }, { "code": null, "e": 56037, "s": 55989, "text": "Possible Words using given characters in Python" }, { "code": null, "e": 56095, "s": 56037, "text": "Python – Keys associated with Values in DictionaryMore >>" }, { "code": null, "e": 56711, "s": 56095, "text": "Python program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Closest Pair to Kth index element in TuplePython – Join Tuples if similar initial elementPython – Extract digits from Tuple listPython – All pair combinations of 2 tuplesPython – Remove Tuples of Length KSort a list of tuples by second ItemPython program to Order Tuples using external ListPython – Flatten tuple of List to tuplePython – Convert Nested Tuple to Custom Key DictionaryMore >>" }, { "code": null, "e": 56754, "s": 56711, "text": "Python program to Find the size of a Tuple" }, { "code": null, "e": 56803, "s": 56754, "text": "Python – Maximum and Minimum K elements in Tuple" }, { "code": null, "e": 56884, "s": 56803, "text": "Create a list of tuples from given list having number and its cube in each tuple" }, { "code": null, "e": 56931, "s": 56884, "text": "Python – Adding Tuple to List and vice – versa" }, { "code": null, "e": 56983, "s": 56931, "text": "Python – Closest Pair to Kth index element in Tuple" }, { "code": null, "e": 57031, "s": 56983, "text": "Python – Join Tuples if similar initial element" }, { "code": null, "e": 57071, "s": 57031, "text": "Python – Extract digits from Tuple list" }, { "code": null, "e": 57114, "s": 57071, "text": "Python – All pair combinations of 2 tuples" }, { "code": null, "e": 57149, "s": 57114, "text": "Python – Remove Tuples of Length K" }, { "code": null, "e": 57186, "s": 57149, "text": "Sort a list of tuples by second Item" }, { "code": null, "e": 57237, "s": 57186, "text": "Python program to Order Tuples using external List" }, { "code": null, "e": 57277, "s": 57237, "text": "Python – Flatten tuple of List to tuple" }, { "code": null, "e": 57332, "s": 57277, "text": "Python – Convert Nested Tuple to Custom Key Dictionary" }, { "code": null, "e": 57340, "s": 57332, "text": "More >>" }, { "code": null, "e": 58205, "s": 57340, "text": "Python Program for Binary Search (Recursive and Iterative)Python Program for Linear SearchPython Program for Insertion SortPython Program for Recursive Insertion SortPython Program for QuickSortPython Program for Iterative Quick SortPython Program for Selection SortPython Program for Bubble SortPython Program for Merge SortPython Program for Iterative Merge SortPython Program for Heap SortPython Program for Counting SortPython Program for ShellSortPython Program for Topological SortingPython Program for Radix SortPython Program for Binary Insertion SortPython Program for Bitonic SortPython Program for Comb SortPython Program for Pigeonhole SortPython Program for Cocktail SortPython Program for Gnome SortPython Program for Odd-Even Sort / Brick SortPython Program for BogoSort or Permutation SortPython Program for Cycle SortPython Program for Stooge Sort" }, { "code": null, "e": 58264, "s": 58205, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 58297, "s": 58264, "text": "Python Program for Linear Search" }, { "code": null, "e": 58331, "s": 58297, "text": "Python Program for Insertion Sort" }, { "code": null, "e": 58375, "s": 58331, "text": "Python Program for Recursive Insertion Sort" }, { "code": null, "e": 58404, "s": 58375, "text": "Python Program for QuickSort" }, { "code": null, "e": 58444, "s": 58404, "text": "Python Program for Iterative Quick Sort" }, { "code": null, "e": 58478, "s": 58444, "text": "Python Program for Selection Sort" }, { "code": null, "e": 58509, "s": 58478, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 58539, "s": 58509, "text": "Python Program for Merge Sort" }, { "code": null, "e": 58579, "s": 58539, "text": "Python Program for Iterative Merge Sort" }, { "code": null, "e": 58608, "s": 58579, "text": "Python Program for Heap Sort" }, { "code": null, "e": 58641, "s": 58608, "text": "Python Program for Counting Sort" }, { "code": null, "e": 58670, "s": 58641, "text": "Python Program for ShellSort" }, { "code": null, "e": 58709, "s": 58670, "text": "Python Program for Topological Sorting" }, { "code": null, "e": 58739, "s": 58709, "text": "Python Program for Radix Sort" }, { "code": null, "e": 58780, "s": 58739, "text": "Python Program for Binary Insertion Sort" }, { "code": null, "e": 58812, "s": 58780, "text": "Python Program for Bitonic Sort" }, { "code": null, "e": 58841, "s": 58812, "text": "Python Program for Comb Sort" }, { "code": null, "e": 58876, "s": 58841, "text": "Python Program for Pigeonhole Sort" }, { "code": null, "e": 58909, "s": 58876, "text": "Python Program for Cocktail Sort" }, { "code": null, "e": 58939, "s": 58909, "text": "Python Program for Gnome Sort" }, { "code": null, "e": 58985, "s": 58939, "text": "Python Program for Odd-Even Sort / Brick Sort" }, { "code": null, "e": 59033, "s": 58985, "text": "Python Program for BogoSort or Permutation Sort" }, { "code": null, "e": 59063, "s": 59033, "text": "Python Program for Cycle Sort" }, { "code": null, "e": 59094, "s": 59063, "text": "Python Program for Stooge Sort" }, { "code": null, "e": 59279, "s": 59094, "text": "Python Program to print the pattern ‘G’Python Program to print an Inverted Star PatternPython Program to print double sided stair-case patternPython Program to print with your own font" }, { "code": null, "e": 59319, "s": 59279, "text": "Python Program to print the pattern ‘G’" }, { "code": null, "e": 59368, "s": 59319, "text": "Python Program to print an Inverted Star Pattern" }, { "code": null, "e": 59424, "s": 59368, "text": "Python Program to print double sided stair-case pattern" }, { "code": null, "e": 59467, "s": 59424, "text": "Python Program to print with your own font" }, { "code": null, "e": 59910, "s": 59467, "text": "Python program to get Current TimeGet Current Date and Time using PythonPython | Find yesterday’s, today’s and tomorrow’s datePython program to convert time from 12 hour to 24 hour formatPython program to find difference between current time and given timePython Program to Create a Lap TimerConvert date string to timestamp in PythonHow to convert timestamp string to datetime object in Python?Find number of times every day occurs in a Year" }, { "code": null, "e": 59945, "s": 59910, "text": "Python program to get Current Time" }, { "code": null, "e": 59984, "s": 59945, "text": "Get Current Date and Time using Python" }, { "code": null, "e": 60039, "s": 59984, "text": "Python | Find yesterday’s, today’s and tomorrow’s date" }, { "code": null, "e": 60101, "s": 60039, "text": "Python program to convert time from 12 hour to 24 hour format" }, { "code": null, "e": 60171, "s": 60101, "text": "Python program to find difference between current time and given time" }, { "code": null, "e": 60208, "s": 60171, "text": "Python Program to Create a Lap Timer" }, { "code": null, "e": 60251, "s": 60208, "text": "Convert date string to timestamp in Python" }, { "code": null, "e": 60313, "s": 60251, "text": "How to convert timestamp string to datetime object in Python?" }, { "code": null, "e": 60361, "s": 60313, "text": "Find number of times every day occurs in a Year" }, { "code": null, "e": 61678, "s": 60361, "text": "Python Program to Check if String Contain Only Defined Characters using RegexPython program to Count Uppercase, Lowercase, special character and numeric values using RegexPython Program to find the most occurring number in a string using RegexPython Regex to extract maximum numeric value from a stringPython Program to put spaces between words starting with capital letters using RegexPython – Check whether a string starts and ends with the same character or notPython regex to find sequences of one upper case letter followed by lower case lettersPython Program to Remove duplicate words from SentencePython | Remove all characters except letters and numbersPython Regex | Program to accept string ending with alphanumeric characterPython Regex – Program to accept string starting with vowelPython Program to check if a string starts with a substring using regexPython Program to Check if an URL is valid or not using Regular ExpressionParsing and Processing URL using Python – RegexPython Program to validate an IP address using ReGexPython Program to Check if email address valid or notPython program to find files having a particular extension using RegExPython program to extract IP address from filePython program to check the validity of a PasswordCategorize Password as Strong or Weak using Regex in Python" }, { "code": null, "e": 61756, "s": 61678, "text": "Python Program to Check if String Contain Only Defined Characters using Regex" }, { "code": null, "e": 61851, "s": 61756, "text": "Python program to Count Uppercase, Lowercase, special character and numeric values using Regex" }, { "code": null, "e": 61924, "s": 61851, "text": "Python Program to find the most occurring number in a string using Regex" }, { "code": null, "e": 61984, "s": 61924, "text": "Python Regex to extract maximum numeric value from a string" }, { "code": null, "e": 62069, "s": 61984, "text": "Python Program to put spaces between words starting with capital letters using Regex" }, { "code": null, "e": 62148, "s": 62069, "text": "Python – Check whether a string starts and ends with the same character or not" }, { "code": null, "e": 62235, "s": 62148, "text": "Python regex to find sequences of one upper case letter followed by lower case letters" }, { "code": null, "e": 62290, "s": 62235, "text": "Python Program to Remove duplicate words from Sentence" }, { "code": null, "e": 62348, "s": 62290, "text": "Python | Remove all characters except letters and numbers" }, { "code": null, "e": 62423, "s": 62348, "text": "Python Regex | Program to accept string ending with alphanumeric character" }, { "code": null, "e": 62483, "s": 62423, "text": "Python Regex – Program to accept string starting with vowel" }, { "code": null, "e": 62555, "s": 62483, "text": "Python Program to check if a string starts with a substring using regex" }, { "code": null, "e": 62630, "s": 62555, "text": "Python Program to Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 62678, "s": 62630, "text": "Parsing and Processing URL using Python – Regex" }, { "code": null, "e": 62731, "s": 62678, "text": "Python Program to validate an IP address using ReGex" }, { "code": null, "e": 62785, "s": 62731, "text": "Python Program to Check if email address valid or not" }, { "code": null, "e": 62856, "s": 62785, "text": "Python program to find files having a particular extension using RegEx" }, { "code": null, "e": 62903, "s": 62856, "text": "Python program to extract IP address from file" }, { "code": null, "e": 62954, "s": 62903, "text": "Python program to check the validity of a Password" }, { "code": null, "e": 63014, "s": 62954, "text": "Categorize Password as Strong or Weak using Regex in Python" }, { "code": null, "e": 63938, "s": 63014, "text": "Python program to read file word by wordPython program to read character by character from a filePython – Get number of characters, words, spaces and lines in a filePython program to Count the Number of occurrences of a key-value pair in a text filePython | Finding ‘n’ Character Words in a Text FilePython Program to obtain the line number in which given word is presentCount number of lines in a text file in PythonPython Program to remove lines starting with any prefixPython Program to Eliminate repeated lines from a filePython Program to read List of Dictionaries from FilePython – Append content of one text file to anotherPython program to copy odd lines of one file to otherPython Program to merge two files into a third filePython program to Reverse a single line of a text filePython program to reverse the content of a file and store it in another filePython Program to Reverse the Content of a File using Stack" }, { "code": null, "e": 63979, "s": 63938, "text": "Python program to read file word by word" }, { "code": null, "e": 64037, "s": 63979, "text": "Python program to read character by character from a file" }, { "code": null, "e": 64106, "s": 64037, "text": "Python – Get number of characters, words, spaces and lines in a file" }, { "code": null, "e": 64191, "s": 64106, "text": "Python program to Count the Number of occurrences of a key-value pair in a text file" }, { "code": null, "e": 64243, "s": 64191, "text": "Python | Finding ‘n’ Character Words in a Text File" }, { "code": null, "e": 64315, "s": 64243, "text": "Python Program to obtain the line number in which given word is present" }, { "code": null, "e": 64362, "s": 64315, "text": "Count number of lines in a text file in Python" }, { "code": null, "e": 64418, "s": 64362, "text": "Python Program to remove lines starting with any prefix" }, { "code": null, "e": 64473, "s": 64418, "text": "Python Program to Eliminate repeated lines from a file" }, { "code": null, "e": 64527, "s": 64473, "text": "Python Program to read List of Dictionaries from File" }, { "code": null, "e": 64579, "s": 64527, "text": "Python – Append content of one text file to another" }, { "code": null, "e": 64633, "s": 64579, "text": "Python program to copy odd lines of one file to other" }, { "code": null, "e": 64685, "s": 64633, "text": "Python Program to merge two files into a third file" }, { "code": null, "e": 64740, "s": 64685, "text": "Python program to Reverse a single line of a text file" }, { "code": null, "e": 64817, "s": 64740, "text": "Python program to reverse the content of a file and store it in another file" }, { "code": null, "e": 64877, "s": 64817, "text": "Python Program to Reverse the Content of a File using Stack" }, { "code": null, "e": 66260, "s": 64877, "text": "Python Program to Reverse a linked listPython Program for Find largest prime factor of a numberPython Program for Efficient program to print all prime factors of a given numberPython Program for Product of unique prime factors of a numberPython Program for Find sum of odd factors of a numberPython Program for Coin ChangePython Program for Tower of HanoiPython Program for Sieve of EratosthenesPython Program to Check if binary representation is palindromePython Program for Basic Euclidean algorithmsPython Program for Extended Euclidean algorithmsPython Program for Maximum height when coins are arranged in a trianglePython Program for Find minimum sum of factors of numberPython Program for Difference between sums of odd and even digitsPython Program for Program to Print Matrix in Z formPython Program for Smallest K digit number divisible by XPython Program for Print Number series without using any loopPython Program for Number of stopping station problemCheck if a triangle of positive area is possible with the given anglesPython program to find the most occurring character and its countPython Program for Find sum of even factors of a numberPython Program for Check if all digits of a number divide itCheck whether a number has consecutive 0’s in the given base or notPython Program for Number of solutions to Modular EquationsPython Program for Legendre\\’s Conjecture" }, { "code": null, "e": 66300, "s": 66260, "text": "Python Program to Reverse a linked list" }, { "code": null, "e": 66357, "s": 66300, "text": "Python Program for Find largest prime factor of a number" }, { "code": null, "e": 66439, "s": 66357, "text": "Python Program for Efficient program to print all prime factors of a given number" }, { "code": null, "e": 66502, "s": 66439, "text": "Python Program for Product of unique prime factors of a number" }, { "code": null, "e": 66557, "s": 66502, "text": "Python Program for Find sum of odd factors of a number" }, { "code": null, "e": 66588, "s": 66557, "text": "Python Program for Coin Change" }, { "code": null, "e": 66622, "s": 66588, "text": "Python Program for Tower of Hanoi" }, { "code": null, "e": 66663, "s": 66622, "text": "Python Program for Sieve of Eratosthenes" }, { "code": null, "e": 66726, "s": 66663, "text": "Python Program to Check if binary representation is palindrome" }, { "code": null, "e": 66772, "s": 66726, "text": "Python Program for Basic Euclidean algorithms" }, { "code": null, "e": 66821, "s": 66772, "text": "Python Program for Extended Euclidean algorithms" }, { "code": null, "e": 66893, "s": 66821, "text": "Python Program for Maximum height when coins are arranged in a triangle" }, { "code": null, "e": 66950, "s": 66893, "text": "Python Program for Find minimum sum of factors of number" }, { "code": null, "e": 67016, "s": 66950, "text": "Python Program for Difference between sums of odd and even digits" }, { "code": null, "e": 67069, "s": 67016, "text": "Python Program for Program to Print Matrix in Z form" }, { "code": null, "e": 67127, "s": 67069, "text": "Python Program for Smallest K digit number divisible by X" }, { "code": null, "e": 67189, "s": 67127, "text": "Python Program for Print Number series without using any loop" }, { "code": null, "e": 67243, "s": 67189, "text": "Python Program for Number of stopping station problem" }, { "code": null, "e": 67314, "s": 67243, "text": "Check if a triangle of positive area is possible with the given angles" }, { "code": null, "e": 67380, "s": 67314, "text": "Python program to find the most occurring character and its count" }, { "code": null, "e": 67436, "s": 67380, "text": "Python Program for Find sum of even factors of a number" }, { "code": null, "e": 67497, "s": 67436, "text": "Python Program for Check if all digits of a number divide it" }, { "code": null, "e": 67565, "s": 67497, "text": "Check whether a number has consecutive 0’s in the given base or not" }, { "code": null, "e": 67625, "s": 67565, "text": "Python Program for Number of solutions to Modular Equations" }, { "code": null, "e": 67667, "s": 67625, "text": "Python Program for Legendre\\’s Conjecture" }, { "code": null, "e": 67969, "s": 67667, "text": "1. Geeks Classes LiveGet interview-centric live online classes on Data Structure and Algorithms from any geographical location to learn and master DSA concepts for enhancing your problem-solving & programming skills and to crack the interview of any product-based company – Geeks Classes: Live Session" }, { "code": null, "e": 68259, "s": 67969, "text": "2. Complete Interview PreparationGet fulfilled all your interview preparation needs at a single place with the Complete Interview Preparation Course that provides you all the required stuff to prepare for any product-based, service-based, or start-up company at the most affordable prices." }, { "code": null, "e": 68551, "s": 68259, "text": "3. DSA Self PacedStart learning Data Structures and Algorithms to prepare for the interviews of top IT giants like Microsoft, Amazon, Adobe, etc. with DSA Self-Paced Course where you will get to learn and master DSA from basic to advanced level and that too at your own pace and convenience." }, { "code": null, "e": 68753, "s": 68551, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article on https://write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 68878, "s": 68753, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." } ]
Node.js zlib.deflate() Method
11 Oct, 2021 The zlib.deflate() method is an inbuilt application programming interface of the Zlib module which is used to compress a chunk of data. Syntax: zlib.deflate( buffer, options, callback ) Parameters: This method accept three parameters as mentioned above and described below: buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string. options: It is an optional parameter that holds the zlib options. callback: It holds the callback function. Return Value: It returns the chunk of data after compression. Below examples illustrate the use of zlib.deflate() method in Node.js: Example 1: // Node.js program to demonstrate the // deflate() method // Including zlib moduleconst zlib = require("zlib"); // Declaring input and assigning// it a value stringvar input = "Geeks"; // Calling deflate methodzlib.deflate(input, (err, buffer) => { if (!err) { console.log(buffer.toString('base64')); } else { console.log(err); }});console.log("Data Compressed..."); Output: Data Compressed... eJxzT03NLgYABXQB8A== Example 2: // Node.js program to demonstrate the // deflate() method // Including zlib moduleconst zlib = require("zlib"); // Declaring input and assigning// it a value stringvar input = "Geeks"; // Calling deflate methodzlib.deflate(input, (err, buffer) => { if (!err) { console.log(buffer.toString('bas64')); } else { console.log(err); }});console.log("Data Compressed..."); Output: Data Compressed... buffer.js:631 throw new ERR_UNKNOWN_ENCODING(encoding); ^ TypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: bas64 at stringSlice (buffer.js:631:9) at Buffer.toString (buffer.js:667:10) at Deflate.zlib.deflate [as cb] (/home/runner/BeautifulMiserlySourcecode/index.js:17:24) at Deflate.zlibBufferOnEnd (zlib.js:133:10) at Deflate.emit (events.js:203:15) at Deflate.EventEmitter.emit (domain.js:448:20) at endReadableNT (_stream_readable.js:1143:12) at process._tickCallback (internal/process/next_tick.js:63:19) Here, an error occurs in encoding the data so, error is thrown. Reference: https://nodejs.org/api/zlib.html#zlib_zlib_deflate_buffer_options_callback Node.js-Zlib-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 164, "s": 28, "text": "The zlib.deflate() method is an inbuilt application programming interface of the Zlib module which is used to compress a chunk of data." }, { "code": null, "e": 172, "s": 164, "text": "Syntax:" }, { "code": null, "e": 214, "s": 172, "text": "zlib.deflate( buffer, options, callback )" }, { "code": null, "e": 302, "s": 214, "text": "Parameters: This method accept three parameters as mentioned above and described below:" }, { "code": null, "e": 383, "s": 302, "text": "buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string." }, { "code": null, "e": 449, "s": 383, "text": "options: It is an optional parameter that holds the zlib options." }, { "code": null, "e": 491, "s": 449, "text": "callback: It holds the callback function." }, { "code": null, "e": 553, "s": 491, "text": "Return Value: It returns the chunk of data after compression." }, { "code": null, "e": 624, "s": 553, "text": "Below examples illustrate the use of zlib.deflate() method in Node.js:" }, { "code": null, "e": 635, "s": 624, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // deflate() method // Including zlib moduleconst zlib = require(\"zlib\"); // Declaring input and assigning// it a value stringvar input = \"Geeks\"; // Calling deflate methodzlib.deflate(input, (err, buffer) => { if (!err) { console.log(buffer.toString('base64')); } else { console.log(err); }});console.log(\"Data Compressed...\");", "e": 1024, "s": 635, "text": null }, { "code": null, "e": 1032, "s": 1024, "text": "Output:" }, { "code": null, "e": 1073, "s": 1032, "text": "Data Compressed...\neJxzT03NLgYABXQB8A==\n" }, { "code": null, "e": 1084, "s": 1073, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // deflate() method // Including zlib moduleconst zlib = require(\"zlib\"); // Declaring input and assigning// it a value stringvar input = \"Geeks\"; // Calling deflate methodzlib.deflate(input, (err, buffer) => { if (!err) { console.log(buffer.toString('bas64')); } else { console.log(err); }});console.log(\"Data Compressed...\");", "e": 1472, "s": 1084, "text": null }, { "code": null, "e": 1480, "s": 1472, "text": "Output:" }, { "code": null, "e": 2059, "s": 1480, "text": "Data Compressed...\nbuffer.js:631\n throw new ERR_UNKNOWN_ENCODING(encoding);\n ^\n\nTypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: bas64\n at stringSlice (buffer.js:631:9) \n at Buffer.toString (buffer.js:667:10) \n at Deflate.zlib.deflate [as cb] \n(/home/runner/BeautifulMiserlySourcecode/index.js:17:24)\n at Deflate.zlibBufferOnEnd (zlib.js:133:10)\n at Deflate.emit (events.js:203:15)\n at Deflate.EventEmitter.emit (domain.js:448:20)\n at endReadableNT (_stream_readable.js:1143:12)\n at process._tickCallback (internal/process/next_tick.js:63:19)\n" }, { "code": null, "e": 2123, "s": 2059, "text": "Here, an error occurs in encoding the data so, error is thrown." }, { "code": null, "e": 2209, "s": 2123, "text": "Reference: https://nodejs.org/api/zlib.html#zlib_zlib_deflate_buffer_options_callback" }, { "code": null, "e": 2229, "s": 2209, "text": "Node.js-Zlib-module" }, { "code": null, "e": 2237, "s": 2229, "text": "Node.js" }, { "code": null, "e": 2254, "s": 2237, "text": "Web Technologies" } ]
Throw Keyword in Scala
23 May, 2022 The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar. Except that scala treats all types of exceptions as runtime exceptions only, therefore it doesn’t force us to handle them instead uses pattern matching in catch block. throw is an expression that has a result type nothing in scala. If the result wont actually evaluate to anything we can use it in place of any other expression . Important things to remember: Throw expression has a return type of Nothing. Throw is the keyword used to throw an exception, whereas throws is the keyword used to declare exception. Catch block uses pattern matching to handle exceptions Syntax: throw exception object Example: throw new ArithmeticException("divide by 0") Example: val x = if (n % 10 == 0) 5 else throw new RuntimeException(“n must be a multiple of 10”) Explanation: If n is a multiple of 10 then 5 is assigned to x, but if n is not a multiple of 10 then an exception is thrown before x can be initialised to anything at all. Because of which, we can say throw has a value of any kind. In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: Example: Scala // Scala program of throw keyword // Creating objectobject Main{ // Define function def validate(article:Int)= { // Using throw keyword if(article < 20) throw new ArithmeticException("You are not eligible for internship") else println("You are eligible for internship") } // Main method def main(args: Array[String]) { validate(22) }} Output: You are eligible for internship In above code, if we have article less than 20 than we get no output. When an error occurs, a scala method can throw an exception instead of returning normally. In the below example, there we observe a single exception that is thrown from a function. Scala // Scala program of throw keyword // Creating objectobject GFG{ // Main method def main(args: Array[String]) { try { func(); } catch { case ex: Exception => println("Exception caught in main: " + ex); } } // Defining function def func() { // Using throw exception throw new Exception("Exception thrown from func"); }} Output: Exception caught in main: java.lang.Exception: Exception thrown from func simmytarika5 Picked Scala scala-exception Scala-Keyword Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 641, "s": 28, "text": "The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar. Except that scala treats all types of exceptions as runtime exceptions only, therefore it doesn’t force us to handle them instead uses pattern matching in catch block. throw is an expression that has a result type nothing in scala. If the result wont actually evaluate to anything we can use it in place of any other expression . " }, { "code": null, "e": 672, "s": 641, "text": "Important things to remember: " }, { "code": null, "e": 719, "s": 672, "text": "Throw expression has a return type of Nothing." }, { "code": null, "e": 825, "s": 719, "text": "Throw is the keyword used to throw an exception, whereas throws is the keyword used to declare exception." }, { "code": null, "e": 880, "s": 825, "text": "Catch block uses pattern matching to handle exceptions" }, { "code": null, "e": 888, "s": 880, "text": "Syntax:" }, { "code": null, "e": 968, "s": 888, "text": " throw exception object\nExample:\n throw new ArithmeticException(\"divide by 0\") " }, { "code": null, "e": 978, "s": 968, "text": "Example: " }, { "code": null, "e": 1067, "s": 978, "text": "val x = if (n % 10 == 0) 5 else throw new RuntimeException(“n must be a multiple of 10”)" }, { "code": null, "e": 1428, "s": 1067, "text": "Explanation: If n is a multiple of 10 then 5 is assigned to x, but if n is not a multiple of 10 then an exception is thrown before x can be initialised to anything at all. Because of which, we can say throw has a value of any kind. In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: " }, { "code": null, "e": 1438, "s": 1428, "text": "Example: " }, { "code": null, "e": 1444, "s": 1438, "text": "Scala" }, { "code": "// Scala program of throw keyword // Creating objectobject Main{ // Define function def validate(article:Int)= { // Using throw keyword if(article < 20) throw new ArithmeticException(\"You are not eligible for internship\") else println(\"You are eligible for internship\") } // Main method def main(args: Array[String]) { validate(22) }}", "e": 1856, "s": 1444, "text": null }, { "code": null, "e": 1864, "s": 1856, "text": "Output:" }, { "code": null, "e": 1896, "s": 1864, "text": "You are eligible for internship" }, { "code": null, "e": 2148, "s": 1896, "text": "In above code, if we have article less than 20 than we get no output. When an error occurs, a scala method can throw an exception instead of returning normally. In the below example, there we observe a single exception that is thrown from a function. " }, { "code": null, "e": 2154, "s": 2148, "text": "Scala" }, { "code": "// Scala program of throw keyword // Creating objectobject GFG{ // Main method def main(args: Array[String]) { try { func(); } catch { case ex: Exception => println(\"Exception caught in main: \" + ex); } } // Defining function def func() { // Using throw exception throw new Exception(\"Exception thrown from func\"); }}", "e": 2579, "s": 2154, "text": null }, { "code": null, "e": 2587, "s": 2579, "text": "Output:" }, { "code": null, "e": 2661, "s": 2587, "text": "Exception caught in main: java.lang.Exception: Exception thrown from func" }, { "code": null, "e": 2674, "s": 2661, "text": "simmytarika5" }, { "code": null, "e": 2681, "s": 2674, "text": "Picked" }, { "code": null, "e": 2687, "s": 2681, "text": "Scala" }, { "code": null, "e": 2703, "s": 2687, "text": "scala-exception" }, { "code": null, "e": 2717, "s": 2703, "text": "Scala-Keyword" }, { "code": null, "e": 2723, "s": 2717, "text": "Scala" } ]
How to Calculate Quantiles by Group in R? - GeeksforGeeks
23 Dec, 2021 In this article, we will discuss how to calculate quantiles by the group in R programming language. To obtain the required quartiles, quantile() function is used. Syntax: quantile( data, probs) Parameters: data: data whose percentiles are to be calculated probs: percentile value To group data, we use dplyr module. This module contains a function called group_by() in which the column to be grouped by has to be passed. Syntax: group_by(column_name) To find quantiles of the grouped data we will call summarize method with quantiles() function. Syntax: summarize( function ) Example 1: Calculate Quantiles by group by summarizing one quartile with probability 0.5 R # import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) # create groups# calculate quantiles by groupdf %>% group_by(y) %>% summarize(res=quantile(x,probs=0.5)) Output: Example 2: Calculate quantiles by group by summarizing three quartiles with probability 0.25, 0.5, and 0.75. R # import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) # create groups# find quantilesdf %>% group_by(y) %>% summarize(first=quantile(x,probs=0.25), second=quantile(x,probs=0.5), third=quantile(x,probs=0.75)) Output: simranarora5sos Picked R Dplyr R-Statistics R Language 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 import an Excel File into R ? Time Series Analysis in R How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n23 Dec, 2021" }, { "code": null, "e": 25342, "s": 25242, "text": "In this article, we will discuss how to calculate quantiles by the group in R programming language." }, { "code": null, "e": 25405, "s": 25342, "text": "To obtain the required quartiles, quantile() function is used." }, { "code": null, "e": 25413, "s": 25405, "text": "Syntax:" }, { "code": null, "e": 25436, "s": 25413, "text": "quantile( data, probs)" }, { "code": null, "e": 25448, "s": 25436, "text": "Parameters:" }, { "code": null, "e": 25498, "s": 25448, "text": "data: data whose percentiles are to be calculated" }, { "code": null, "e": 25522, "s": 25498, "text": "probs: percentile value" }, { "code": null, "e": 25663, "s": 25522, "text": "To group data, we use dplyr module. This module contains a function called group_by() in which the column to be grouped by has to be passed." }, { "code": null, "e": 25671, "s": 25663, "text": "Syntax:" }, { "code": null, "e": 25693, "s": 25671, "text": "group_by(column_name)" }, { "code": null, "e": 25788, "s": 25693, "text": "To find quantiles of the grouped data we will call summarize method with quantiles() function." }, { "code": null, "e": 25796, "s": 25788, "text": "Syntax:" }, { "code": null, "e": 25818, "s": 25796, "text": "summarize( function )" }, { "code": null, "e": 25907, "s": 25818, "text": "Example 1: Calculate Quantiles by group by summarizing one quartile with probability 0.5" }, { "code": null, "e": 25909, "s": 25907, "text": "R" }, { "code": "# import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) # create groups# calculate quantiles by groupdf %>% group_by(y) %>% summarize(res=quantile(x,probs=0.5))", "e": 26145, "s": 25909, "text": null }, { "code": null, "e": 26153, "s": 26145, "text": "Output:" }, { "code": null, "e": 26262, "s": 26153, "text": "Example 2: Calculate quantiles by group by summarizing three quartiles with probability 0.25, 0.5, and 0.75." }, { "code": null, "e": 26264, "s": 26262, "text": "R" }, { "code": "# import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50), y=c('a','b','c','c','c','b')) # create groups# find quantilesdf %>% group_by(y) %>% summarize(first=quantile(x,probs=0.25), second=quantile(x,probs=0.5), third=quantile(x,probs=0.75))", "e": 26571, "s": 26264, "text": null }, { "code": null, "e": 26579, "s": 26571, "text": "Output:" }, { "code": null, "e": 26595, "s": 26579, "text": "simranarora5sos" }, { "code": null, "e": 26602, "s": 26595, "text": "Picked" }, { "code": null, "e": 26610, "s": 26602, "text": "R Dplyr" }, { "code": null, "e": 26623, "s": 26610, "text": "R-Statistics" }, { "code": null, "e": 26634, "s": 26623, "text": "R Language" }, { "code": null, "e": 26732, "s": 26634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26784, "s": 26732, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26822, "s": 26784, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26857, "s": 26822, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26915, "s": 26857, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26964, "s": 26915, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27001, "s": 26964, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 27027, "s": 27001, "text": "Time Series Analysis in R" }, { "code": null, "e": 27077, "s": 27027, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27120, "s": 27077, "text": "Replace Specific Characters in String in R" } ]
The Match-Case In Python 3.10 Is Not That Simple | by Christopher Tao | Towards Data Science
In my previous article, I have introduced all the major new features in Python 3.10, which has just been released 2 weeks ago. One of the most important features is the Match-Case syntax. Some still argue that Python doesn’t need the “switch-case” syntax. Even Guido himself did not support adding this syntax in Python. However, why it is still released in this new version? In my opinion, the reason can be found in the name. It is called “match case” rather than “switch case” like most programming languages do. In this article, I’ll use 7 examples to demonstrate how flexible and “pythonic” the new syntax is. Hope it will help you to understand it a bit easier. If you are interested in the other features in Python 3.10, please refer to my previous post. towardsdatascience.com Before any fancy stuff, let’s start with the basic use case of this new syntax. Suppose we are writing some code to translate the HTTP status code into error messages, we can use the match-case syntax as follows. def http_status(status): match status: case 400: return "Bad request" case 401: return "Unauthorized" case 403: return "Forbidden" case 404: return "Not found" Indeed, for this particular example, the match-case didn’t bring any benefits than the if-else syntax, as follow. def http_error(status): if status == 400: return "Bad request" elif status == 401: return "Unauthorized" elif status == 403: return "Forbidden" elif status == 404: return "Not found" else: return "Unknown status code" If it can only do such a thing, I wouldn’t think it will be added. Let’s keep going with more examples to see what flexibility it can have. It’s meant to be similar to the switch-case syntax in most other languages, so it must have the “default case”. When no defined case can be matched, the code in “default case” will be executed. Python achieves this requirement in its style. It makes use of the underscore “_” that stands for an anonymous variable. The rationale is that an anonymous variable can “match” anything. Let’s see the example below. def http_status(status): match status: case 400: return "Bad request" case 401: return "Unauthorized" case 403: return "Forbidden" case 404: return "Not found" case _: return "Other error" In the code above, we have added the default case and display “Other error”. What if sometimes we have multiple cases that should be combined? In other words, these are different cases, but the way we handle them should be the same. In Python, we can use a pipe “|” to combine these cases into a single case. It is also considered an “OR” relationship. def http_status(status): match status: case 400: return "Bad request" case 401 | 403: return "Authentication error" case 404: return "Not found" case _: return "Other error" In the code above, we consider both the 401 and 403 errors as authentication issues, so we can combine them in the match-case. The more interesting stuff is coming now. Suppose we are writing an alarm logic using the match-case syntax. It accepts a list as the argument. The first element is the time of the day. Let’s keep it simple so we have “morning”, “afternoon” and “evening”. The second element will be the action that we need the alarm to remind us to do. However, we may want the alarm to remind us to do multiple things at the same time. Therefore, we want to pass more than one action in the list so that the alarm can remind us to do all of them one by one. Here is the code to achieve such a requirement. def alarm(item): match item: case [time, action]: print(f'Good {time}! It is time to {action}!') case [time, *actions]: print('Good morning!') for action in actions: print(f'It is time to {action}!') In this example, we only have two cases. The first case doesn’t need to be explained too much as it just tries to match the single-action case. In the second case, we put an asterisk in front of the variable “actions”, so it can match one or more actions in the list! Let’s give it a try. alarm(['afternoon', 'work'])alarm(('morning', 'have breakfast', 'brush teeth', 'work')) Sometimes, we may want to have patterns in a pattern. Specifically, we want the match-case to triage the flow into a particular “case”. However, inside that pattern, we want to add some more restrictions. Remember we have defined that the “time” of the day must be either “morning”, “afternoon” or “evening”? Let’s add this restriction to the match-case code. If the “time” doesn’t match one of these 3, tell the user the time is invalid. def alarm(item): match item: case [('morning' | 'afternoon' | 'evening'), action]: print(f'Good (?)! It is time to {action}!') case _: print('The time is invalid.') In the above code, it shows that we can use a pair of parentheses to enclose the “patterns” that we want to match, and use pipes to separate these patterns. If it doesn’t match one of the given 3 “times”, the default case will be executed. Why there is a question mark there? I intentionally added it because I want to emphasise the solution. Generally, it won’t be easy to match one of the sub-patterns and then reference which pattern it matched exactly. However, we can have this “reference” in Python. Let’s add an “as” keyword followed by a variable, and this variable will be the reference. def alarm(item): match item: case [('morning' | 'afternoon' | 'evening') as time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.') We need to let this alarm more “smart”. When it is evening, let’s display some messages to appreciate the user for finishing the day for work. def alarm(item): match item: case ['evening', action]: print(f'You almost finished the day! Now {action}!') case [time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.') Therefore, we have added one more case in the above code to match “evening” only. Hmmm... the second one seems a bit frustrated. Let’s make this alarm even smarter to encourage the user to be “work-life balance”. Therefore, when the user wants to work or study in the evening, the alarm recommends the user to have some rest. (I hope I can have such an alarm :D) def alarm(item): match item: case ['evening', action] if action not in ['work', 'study']: print(f'You almost finished the day! Now {action}!') case ['evening', _]: print('Come on, you deserve some rest!') case [time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.') To achieve this, we have added another case on the top. It comes with a condition. That is, when the action is either “work” or “study”, display some different messages. So far, we have explored a lot. I guess you may have such a feeling, it is a “match-case” rather than a “switch-case”, because the “pattern” is always the key. Let’s have an even more complex example — a class instance. Yes, let’s use the match-case to match an object. I’ll just make up a simple use case. A class called “Direction” is created for holding the direction on the horizontal (east or west) and vertical (north or south) axis. class Direction: def __init__(self, horizontal=None, vertical=None): self.horizontal = horizontal self.vertical = vertical Now, we want to use the match-case syntax to match an instance from this class and display a message based on the attribute. def direction(loc): match loc: case Direction(horizontal='east', vertical='north'): print('You towards northeast') case Direction(horizontal='east', vertical='south'): print('You towards southeast') case Direction(horizontal='west', vertical='north'): print('You towards northwest') case Direction(horizontal='west', vertical='south'): print('You towards southwest') case Direction(horizontal=None): print(f'You towards {loc.vertical}') case Direction(vertical=None): print(f'You towards {loc.horizontal}') case _: print('Invalid Direction') Then, let’s create some objects from the class for testing. d1 = Direction('east', 'south')d2 = Direction(vertical='north')d3 = Direction('centre', 'centre') The results show that the match-case can easily match these objects based on their attributes! direction(d1)direction(d2)direction(d3) In this article, I have introduced the new syntax “match-case” that is introduced in Python 3.10, and how flexible and powerful it is. I believe nailing this new syntax will help us to write better code in terms of readability. 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": 360, "s": 172, "text": "In my previous article, I have introduced all the major new features in Python 3.10, which has just been released 2 weeks ago. One of the most important features is the Match-Case syntax." }, { "code": null, "e": 688, "s": 360, "text": "Some still argue that Python doesn’t need the “switch-case” syntax. Even Guido himself did not support adding this syntax in Python. However, why it is still released in this new version? In my opinion, the reason can be found in the name. It is called “match case” rather than “switch case” like most programming languages do." }, { "code": null, "e": 840, "s": 688, "text": "In this article, I’ll use 7 examples to demonstrate how flexible and “pythonic” the new syntax is. Hope it will help you to understand it a bit easier." }, { "code": null, "e": 934, "s": 840, "text": "If you are interested in the other features in Python 3.10, please refer to my previous post." }, { "code": null, "e": 957, "s": 934, "text": "towardsdatascience.com" }, { "code": null, "e": 1170, "s": 957, "text": "Before any fancy stuff, let’s start with the basic use case of this new syntax. Suppose we are writing some code to translate the HTTP status code into error messages, we can use the match-case syntax as follows." }, { "code": null, "e": 1405, "s": 1170, "text": "def http_status(status): match status: case 400: return \"Bad request\" case 401: return \"Unauthorized\" case 403: return \"Forbidden\" case 404: return \"Not found\"" }, { "code": null, "e": 1519, "s": 1405, "text": "Indeed, for this particular example, the match-case didn’t bring any benefits than the if-else syntax, as follow." }, { "code": null, "e": 1787, "s": 1519, "text": "def http_error(status): if status == 400: return \"Bad request\" elif status == 401: return \"Unauthorized\" elif status == 403: return \"Forbidden\" elif status == 404: return \"Not found\" else: return \"Unknown status code\"" }, { "code": null, "e": 1927, "s": 1787, "text": "If it can only do such a thing, I wouldn’t think it will be added. Let’s keep going with more examples to see what flexibility it can have." }, { "code": null, "e": 2121, "s": 1927, "text": "It’s meant to be similar to the switch-case syntax in most other languages, so it must have the “default case”. When no defined case can be matched, the code in “default case” will be executed." }, { "code": null, "e": 2308, "s": 2121, "text": "Python achieves this requirement in its style. It makes use of the underscore “_” that stands for an anonymous variable. The rationale is that an anonymous variable can “match” anything." }, { "code": null, "e": 2337, "s": 2308, "text": "Let’s see the example below." }, { "code": null, "e": 2619, "s": 2337, "text": "def http_status(status): match status: case 400: return \"Bad request\" case 401: return \"Unauthorized\" case 403: return \"Forbidden\" case 404: return \"Not found\" case _: return \"Other error\"" }, { "code": null, "e": 2696, "s": 2619, "text": "In the code above, we have added the default case and display “Other error”." }, { "code": null, "e": 2852, "s": 2696, "text": "What if sometimes we have multiple cases that should be combined? In other words, these are different cases, but the way we handle them should be the same." }, { "code": null, "e": 2972, "s": 2852, "text": "In Python, we can use a pipe “|” to combine these cases into a single case. It is also considered an “OR” relationship." }, { "code": null, "e": 3221, "s": 2972, "text": "def http_status(status): match status: case 400: return \"Bad request\" case 401 | 403: return \"Authentication error\" case 404: return \"Not found\" case _: return \"Other error\"" }, { "code": null, "e": 3348, "s": 3221, "text": "In the code above, we consider both the 401 and 403 errors as authentication issues, so we can combine them in the match-case." }, { "code": null, "e": 3685, "s": 3348, "text": "The more interesting stuff is coming now. Suppose we are writing an alarm logic using the match-case syntax. It accepts a list as the argument. The first element is the time of the day. Let’s keep it simple so we have “morning”, “afternoon” and “evening”. The second element will be the action that we need the alarm to remind us to do." }, { "code": null, "e": 3891, "s": 3685, "text": "However, we may want the alarm to remind us to do multiple things at the same time. Therefore, we want to pass more than one action in the list so that the alarm can remind us to do all of them one by one." }, { "code": null, "e": 3939, "s": 3891, "text": "Here is the code to achieve such a requirement." }, { "code": null, "e": 4204, "s": 3939, "text": "def alarm(item): match item: case [time, action]: print(f'Good {time}! It is time to {action}!') case [time, *actions]: print('Good morning!') for action in actions: print(f'It is time to {action}!')" }, { "code": null, "e": 4472, "s": 4204, "text": "In this example, we only have two cases. The first case doesn’t need to be explained too much as it just tries to match the single-action case. In the second case, we put an asterisk in front of the variable “actions”, so it can match one or more actions in the list!" }, { "code": null, "e": 4493, "s": 4472, "text": "Let’s give it a try." }, { "code": null, "e": 4581, "s": 4493, "text": "alarm(['afternoon', 'work'])alarm(('morning', 'have breakfast', 'brush teeth', 'work'))" }, { "code": null, "e": 4786, "s": 4581, "text": "Sometimes, we may want to have patterns in a pattern. Specifically, we want the match-case to triage the flow into a particular “case”. However, inside that pattern, we want to add some more restrictions." }, { "code": null, "e": 5020, "s": 4786, "text": "Remember we have defined that the “time” of the day must be either “morning”, “afternoon” or “evening”? Let’s add this restriction to the match-case code. If the “time” doesn’t match one of these 3, tell the user the time is invalid." }, { "code": null, "e": 5224, "s": 5020, "text": "def alarm(item): match item: case [('morning' | 'afternoon' | 'evening'), action]: print(f'Good (?)! It is time to {action}!') case _: print('The time is invalid.')" }, { "code": null, "e": 5381, "s": 5224, "text": "In the above code, it shows that we can use a pair of parentheses to enclose the “patterns” that we want to match, and use pipes to separate these patterns." }, { "code": null, "e": 5464, "s": 5381, "text": "If it doesn’t match one of the given 3 “times”, the default case will be executed." }, { "code": null, "e": 5730, "s": 5464, "text": "Why there is a question mark there? I intentionally added it because I want to emphasise the solution. Generally, it won’t be easy to match one of the sub-patterns and then reference which pattern it matched exactly. However, we can have this “reference” in Python." }, { "code": null, "e": 5821, "s": 5730, "text": "Let’s add an “as” keyword followed by a variable, and this variable will be the reference." }, { "code": null, "e": 6036, "s": 5821, "text": "def alarm(item): match item: case [('morning' | 'afternoon' | 'evening') as time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.')" }, { "code": null, "e": 6179, "s": 6036, "text": "We need to let this alarm more “smart”. When it is evening, let’s display some messages to appreciate the user for finishing the day for work." }, { "code": null, "e": 6450, "s": 6179, "text": "def alarm(item): match item: case ['evening', action]: print(f'You almost finished the day! Now {action}!') case [time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.')" }, { "code": null, "e": 6532, "s": 6450, "text": "Therefore, we have added one more case in the above code to match “evening” only." }, { "code": null, "e": 6813, "s": 6532, "text": "Hmmm... the second one seems a bit frustrated. Let’s make this alarm even smarter to encourage the user to be “work-life balance”. Therefore, when the user wants to work or study in the evening, the alarm recommends the user to have some rest. (I hope I can have such an alarm :D)" }, { "code": null, "e": 7199, "s": 6813, "text": "def alarm(item): match item: case ['evening', action] if action not in ['work', 'study']: print(f'You almost finished the day! Now {action}!') case ['evening', _]: print('Come on, you deserve some rest!') case [time, action]: print(f'Good {time}! It is time to {action}!') case _: print('The time is invalid.')" }, { "code": null, "e": 7369, "s": 7199, "text": "To achieve this, we have added another case on the top. It comes with a condition. That is, when the action is either “work” or “study”, display some different messages." }, { "code": null, "e": 7529, "s": 7369, "text": "So far, we have explored a lot. I guess you may have such a feeling, it is a “match-case” rather than a “switch-case”, because the “pattern” is always the key." }, { "code": null, "e": 7639, "s": 7529, "text": "Let’s have an even more complex example — a class instance. Yes, let’s use the match-case to match an object." }, { "code": null, "e": 7809, "s": 7639, "text": "I’ll just make up a simple use case. A class called “Direction” is created for holding the direction on the horizontal (east or west) and vertical (north or south) axis." }, { "code": null, "e": 7949, "s": 7809, "text": "class Direction: def __init__(self, horizontal=None, vertical=None): self.horizontal = horizontal self.vertical = vertical" }, { "code": null, "e": 8074, "s": 7949, "text": "Now, we want to use the match-case syntax to match an instance from this class and display a message based on the attribute." }, { "code": null, "e": 8745, "s": 8074, "text": "def direction(loc): match loc: case Direction(horizontal='east', vertical='north'): print('You towards northeast') case Direction(horizontal='east', vertical='south'): print('You towards southeast') case Direction(horizontal='west', vertical='north'): print('You towards northwest') case Direction(horizontal='west', vertical='south'): print('You towards southwest') case Direction(horizontal=None): print(f'You towards {loc.vertical}') case Direction(vertical=None): print(f'You towards {loc.horizontal}') case _: print('Invalid Direction')" }, { "code": null, "e": 8805, "s": 8745, "text": "Then, let’s create some objects from the class for testing." }, { "code": null, "e": 8903, "s": 8805, "text": "d1 = Direction('east', 'south')d2 = Direction(vertical='north')d3 = Direction('centre', 'centre')" }, { "code": null, "e": 8998, "s": 8903, "text": "The results show that the match-case can easily match these objects based on their attributes!" }, { "code": null, "e": 9038, "s": 8998, "text": "direction(d1)direction(d2)direction(d3)" }, { "code": null, "e": 9266, "s": 9038, "text": "In this article, I have introduced the new syntax “match-case” that is introduced in Python 3.10, and how flexible and powerful it is. I believe nailing this new syntax will help us to write better code in terms of readability." }, { "code": null, "e": 9277, "s": 9266, "text": "medium.com" } ]
Leaking Secrets in Web Applications | by Jason Ostrom | Towards Data Science
Information disclosure is a type of vulnerability in which a system inadvertently exposes confidential information. This post walks through an example of this flaw by looking at how environment variables can be misunderstood and misused in web applications. This post will revisit the best practices and conclude with actionable advice for developers. Leaking Secrets describes an information disclosure flaw in which an application exposes sensitive credentials or API keys to an adversary. The OWASP Top Ten 2017 categorizes this flaw as “Sensitive Data Exposure”. This post will discuss how this can be exploited with a case study of a vulnerable and misconfigured middleware gem running on a rails application. These types of issues can lead to a data breach for an enterprise, resulting in significant financial and reputation harm. These issues are observed frequently, as Infrastructure as Code (IaC) and Cloud speed enable DevOps personnel to quickly spin up new web applications and environments unchecked. If you are a developer working with Rails, you need to be aware of these issues. If you’re a pentester working with web applications, you’ll find this information useful and (my hope) be better able to protect your clients. Exposing secrets over the public Internet in your web application is exactly what you never want to do. To the Rails developers reading this, a tip of the hat to the Rack-mini-profiler. Rack-mini-profiler is a middleware gem used by Rack developers as a performance tool to improve visibility and speed in Rack-based web applications. The tool has value to the developer community and is highly regarded, as shown from this enthusiast: rack-mini-profiler is a a performance tool for Rack applications, maintained by the talented @samsaffron. rack-mini-profiler provides an entire suite of tools for measuring the performance of Rack-enabled web applications, including detailed drill downs on SQL queries, server response times (with a breakdown for each template and partial), incredibly detailed millisecond-by-millisecond breakdowns of execution times with the incredible flamegraph feature, and will even help you track down memory leaks with its excellent garbage collection features. I wouldn’t hesitate to say that rack-mini-profiler is my favorite and most important tool for developing fast Ruby webapps. I recently discovered a deployment of a Rails application using Rack-mini-profiler in the wild, and it was eye-opening to see the security issues. I want to be clear that I’m not saying the gem has an inherent vulnerability; rather, it is a problem with how the middleware gem can be used or configured without proper security protections. So I set out to better understand how this could happen and the actual vulnerabilities observed. The culmination of this effort is an open-source project, “Hammer.” Hammer is an example of a vulnerable Rails application deployment that uses Rack-mini-profiler to leak API keys and sensitive information. It is vulnerable in the exact same way as a real-world application observed in the wild. It’s also a skeleton app that can be used to fork and experiment with sensitive variables in a safe way. In the process of building this tool I’ve learned a few things and want to share the lessons learned with the developer and InfoSec communities. The Hammer Github site is here. A light Hammer introduction is here. Let’s do a quick tour of the capabilities of the Middleware that offers so many benefits to a developer but at the same time makes it an attractive attack target. You can follow along at the demo application for Hammer: https://preprod.rtcfingroup.com. In the top left-hand corner, an “HTML Speed Badge” is rendered by installing this performance middleware gem. When the tool is installed the HTML speed badge can be used to profile any given page served by the Rails application. Let’s navigate over the URL where the sensitive users are publicly accessible — https://preprod.rtcfingroup.com/users/. Note that these aren’t real users. They are randomly generated from a script included with the tool that simulates users. Take a look at the HTML speed badge in the top left corner and see how it has rendered the amount of time for the page to render. Expanding the speed badge at /users/ shows the time in milliseconds spent rendering each page. Note the interesting SQL query for rendering users/index. Rack-mini-profiler creates a link that you can click on to get more information. Let’s take a look. Below, you can see that Rack-mini-profiler displays detailed call stack query information. You can see the SQL query, file, and precise line that is rendering the users. This is great information for a developer who is trying to improve performance and identify bottlenecks in the application. But from an attacker perspective, this gleans valuable information such as SQL queries that could enable other vulnerabilities to be exploited. It is considered a standard security practice to never expose SQL queries client side. When I first saw this in the wild, I couldn’t believe what I was seeing. Rack-mini-profiler’s website states that the tool can be used to profile applications in development and production. That is why it is so important to ensure that exposing the SQL call stack query aligns with your organizational security policy for application development. When I first saw this, I didn’t know that there would be something far more interesting. Read below. Rack-mini-profiler gem uses the “Pretty Print” Ruby class (pp) that can be found at the default URL by appending ?pp=help. It has a lot of nice features for developers such as memory profiling and garbage collection. The most interesting from a security perspective is pretty printing env. This env pretty print feature dumps all environment variables that are being passed to the Rails application. This includes the Rack Environment as shown below. Taking a look at the Rack-mini-profiler source code for the profiler.rb, the code shows that it first dumps env by iterating through and printing the local variables stored in env. This correlates with the output shown above starting with “Rack Environment.” Second, it dumps the ENV constant by iterating through and printing the contents of this hash. The screenshot below shows the start of dumping ENV constant hash from the sample vulnerable application, correlating with the second part of code starting with ENV.each do. In this example, the Amazon S3 API keys have been stored in ENV, leaking them out to the public. This shows how dangerous it can be storing API secrets and other sensitive credentials within environment variables stored in the ENV constant hash. We’ll talk a little more about how this happens below. Taking this a step further, the sample application leaks a variety of different cloud API and secrets, including Facebook, Twitter, LinkedIn, and Google. ENV is a hash-like class that Ruby uses to expose environment variables to our application. For example, PATH or HOME can be made available to our rails application. Rack-mini-profiler doesn’t have to do much to dump ENV because the constant is exposed upon the application launch. It is up to the developer to properly store, load, and secure ENV. ENV traditionally correlates with an environment variable and is more global than env. Each of these variables is listed as key/value pairs and they are usually used to share configuration. All Rack applications such as Rails take a single argument which is a hash called env. The env is passed to the Rails application and stores information such as HTTP header, request, and server configuration. In comparison to ENV, env is more local to Rails. Environment variables should never be used to store sensitive configuration information such as credentials and API keys. If they must be used, your security program should accept this risk, document it within your risk register, and provide appropriate security controls to mitigate the risk. Much has been said about environment variables and their proper usage. The Twelve-Factor App manifesto states that environment variables should be used to store configuration elements such as credentials to external services such as Amazon S3 or Twitter. I do not agree with this. Following this practice will increase the business risk to your company. The example application shows how easy it can be for developers to make a mistake and inadvertently expose sensitive API keys such as AWS that allow data breach. This application was created to mimic a production environment found in the wild that was secured after enumerating the issues described above. It is the case that Rails developers can use different environments such as production, QA, or development. The Rack-mini-profiler is designed to be used in any of these environments. The exposed environment variables, if containing sensitive secrets running in development environments, can give attackers credentials that allow unauthorized data access, information leakage, and privilege escalation into production. There is a good place for environment variables to store configuration elements. They should just never be used for sensitive secrets. This example application uses the Dotenv rails gem to load environment variables from .env This example app uses .env.local to load all of the populated environment variables contained in the file into the ENV constant that is dumped by Rack-mini-profiler. Take a look at the configuration that can also be seen in the Github repo for Hammer: Beyond the risk of exposing sensitive environment variables through Middleware, there are a few other solid reasons why a developer should be aware of the risks inherent in this practice. This list below summarizes some of these risks from Diogo Monica : The risk of copying unencrypted environment variables files such as .env.local into central Git repositories by not properly using the .gitignore file. The risk of tribal knowledge, when new developers who didn’t set up the system don’t take the proper care in safeguarding these files containing environmental variables. Secrets are copied to a different system and exposed.An application can grab the whole environment and print it out for debugging or error-reporting. Secrets can get leaked if they are not properly sanitized before leaving your environment.Environment variables are passed to child processes, which can lead to unintended access (i.e., a 3rd-party tool has access to your environment).When applications crash, it is common to store the environment variables in log files for debugging. This increases the risk of plain text secrets on disk. The risk of copying unencrypted environment variables files such as .env.local into central Git repositories by not properly using the .gitignore file. The risk of tribal knowledge, when new developers who didn’t set up the system don’t take the proper care in safeguarding these files containing environmental variables. Secrets are copied to a different system and exposed. An application can grab the whole environment and print it out for debugging or error-reporting. Secrets can get leaked if they are not properly sanitized before leaving your environment. Environment variables are passed to child processes, which can lead to unintended access (i.e., a 3rd-party tool has access to your environment). When applications crash, it is common to store the environment variables in log files for debugging. This increases the risk of plain text secrets on disk. Before we jump into playing with some examples of ENV and environment variables, let’s review some laws of Ruby Environment variables. Honeybadger.io gives a fantastic tutorial on this and I’ll summarize: Every process has its own set of environment variables.Environment variables die with their process.A process inherits its environment variables from its parent.Changes to the environment don’t synch between processes.Your shell is just a UI for the environment variable system. Every process has its own set of environment variables. Environment variables die with their process. A process inherits its environment variables from its parent. Changes to the environment don’t synch between processes. Your shell is just a UI for the environment variable system. This example walks through the Hammer environment, inside the home directory of the Rails application. Change into the working home directory of the Rails Hammer application: $ cd /home/<username>/hammer Grep for SECRET in the .env.local to see some of the environment variables we want to play with. $ grep SECRET .env.local You’ll see several of the crown jewel API keys. Now print your Bash shell environment variables with env. You’ll see all of the standard environment variables such as $HOME and $PATH. Verify with env | grep SECRET that those sensitive variables are not currently loaded in your Bash environment. Run the Interactive Ruby Tool (irb) and we’ll see what happens. By default, irb will not see any of the sensitive environment variables exposed by ENV. This is because we need to use the Rails ‘dotenv’ gem to load the variables from an .env file. This shows that by default a Rails application inherits the environment variables of its parent process (the Bash shell) into ENV constant when a Ruby application is instantiated. But we need to specifically load extra environment variables into ENV hash constant in a special way, as those variables are not available by default. You’ll be able to see $PATH and $HOME but not any of the others. $ irb> ENV> ENV['PATH']> ENV['S3_SECRET_ACCESS_KEY'] Instruct irb to use the dotenv gem to load the environment variables from the .env.local file. This command will load the environment variables into ENV, making them available to our irb ruby environment. > require 'dotenv';Dotenv.load('.env.local') Notice that all of the beautiful things are now available, the sensitive crown jewel API keys! Verify that you have access to a couple of these beautiful, sensitive ENV things in your irb terminal! > ENV['S3_ACCESS_KEY_ID']> ENV['S3_SECRET_ACCESS_KEY'] Next, open up a new shell. Launch irb and try to list the sensitive environment variables stored in ENV. Note that in the second shell’s irb session, no sensitive environment variables are listed. This is because of the way environment variables work. Every process has its own set of environment variables that are not automatically synced between processes. Now to experiment with exporting these variables. If you put export in front of the syntax of the variables named in .env.local, and source the file, magic happens. This converts the local shell variables into environment variables available to ENV. Which is then available to any child Rails process instantiated from that bash shell. The hammer app includes a sample exported variable file for the purpose of playing with sensitive variables in a safe way - .env.local.exported . Let’s give this a try. In the second shell, exit the irb session and type the source command. Then run env to list the environment variables in the bash shell: $ source .env.local.exported$ env | grep SECRET Now in the second shell, re-launch irb and fetch the sensitive ENV variables. $ irb> ENV['S3_ACCESS_KEY_ID']> ENV['S3_SECRET_ACCESS_KEY'] Amazing! You didn’t have to call Dotenv gem to automatically load into ENV. This shows you what Dotenv gem is doing — essentially sourcing the variables from the .env file when the environment is bootstrapped and loading them into ENV. ENV is then dumped via the Rack-mini-profiler Pretty Printer (pp) ruby class. In this example, we ended up sourcing the exported variables to our bash shell. Once we exit the shell, the environment variables are not available to the next launched bash shell. If a developer were to add the commands to a shell init script such as .bashrc, this would persist these secrets to all users of the system in cleartext. This is another reason why this practice should be avoided. Storing Secrets in Plaintext: Use Rails gem methods such as Dotenv or Figaro to store secrets in the environment, and access them through loading ENV. Other methods include rbenv-vars plugin and direnv. These are popular methods but developers should consider better security. SaaS Secrets Management Service: Use a service such as Vault, AWS Secrets Manager, and many others to synchronize and manage secrets within your app. This is a better approach than storing the secrets in plaintext, but keep in mind that you have to protect a super-secret SaaS API key that guards all of your secrets. Rails Encrypted Secrets: Starting with Rails 5.1, you can use encrypted secrets to provide better protection to your app credentials. They can be accessed with a special variable other than ENV key/value hash. Here is a good overview, and starting with Rails 6, you can do multi-environment credentials management. This is a more secure way than the first method and similar to the second one. This should keep the master encryption key on your Rails system instead of synchronizing it with a cloud SaaS. Here are some recommendations for risk mitigation. These are meant to provide ideas and should be aligned with your DevOps processes. Remove the rack-mini-profiler gem on all systems connected to the public Internet. On systems requiring Rack-mini-profiler with public Internet access: Implement strong access control by whitelisting/firewalling IP addresses to only allow developer workstations to access the web application. Use the RackMiniProfiler access control to authorize and whitelist requests. RackMiniProfiler has an authorization_mode to whitelist in production. Reference the Access control in non-development environments section of the Readme. Use Encrypted Secrets and avoid using the environment variables with ENV to store sensitive credentials. The best method to perform this locally is Rails Encrypted Secrets. This will avoid loading sensitive variables into ENV where the risk increases that they can be inadvertently exposed. Middleware such as Rack-mini-profiler provides excellent features to developers for improving the speed of Rails applications; however, security controls must be applied to ensure that secrets are properly protected in your application and not leaked to adversaries. A wise Cyber Security professional made this simple yet powerful statement: We all need to work together. Any weakness is a weakness that needs to be fixed, let’s work together to fix things.
[ { "code": null, "e": 524, "s": 172, "text": "Information disclosure is a type of vulnerability in which a system inadvertently exposes confidential information. This post walks through an example of this flaw by looking at how environment variables can be misunderstood and misused in web applications. This post will revisit the best practices and conclude with actionable advice for developers." }, { "code": null, "e": 1412, "s": 524, "text": "Leaking Secrets describes an information disclosure flaw in which an application exposes sensitive credentials or API keys to an adversary. The OWASP Top Ten 2017 categorizes this flaw as “Sensitive Data Exposure”. This post will discuss how this can be exploited with a case study of a vulnerable and misconfigured middleware gem running on a rails application. These types of issues can lead to a data breach for an enterprise, resulting in significant financial and reputation harm. These issues are observed frequently, as Infrastructure as Code (IaC) and Cloud speed enable DevOps personnel to quickly spin up new web applications and environments unchecked. If you are a developer working with Rails, you need to be aware of these issues. If you’re a pentester working with web applications, you’ll find this information useful and (my hope) be better able to protect your clients." }, { "code": null, "e": 1598, "s": 1412, "text": "Exposing secrets over the public Internet in your web application is exactly what you never want to do. To the Rails developers reading this, a tip of the hat to the Rack-mini-profiler." }, { "code": null, "e": 1848, "s": 1598, "text": "Rack-mini-profiler is a middleware gem used by Rack developers as a performance tool to improve visibility and speed in Rack-based web applications. The tool has value to the developer community and is highly regarded, as shown from this enthusiast:" }, { "code": null, "e": 2526, "s": 1848, "text": "rack-mini-profiler is a a performance tool for Rack applications, maintained by the talented @samsaffron. rack-mini-profiler provides an entire suite of tools for measuring the performance of Rack-enabled web applications, including detailed drill downs on SQL queries, server response times (with a breakdown for each template and partial), incredibly detailed millisecond-by-millisecond breakdowns of execution times with the incredible flamegraph feature, and will even help you track down memory leaks with its excellent garbage collection features. I wouldn’t hesitate to say that rack-mini-profiler is my favorite and most important tool for developing fast Ruby webapps." }, { "code": null, "e": 3509, "s": 2526, "text": "I recently discovered a deployment of a Rails application using Rack-mini-profiler in the wild, and it was eye-opening to see the security issues. I want to be clear that I’m not saying the gem has an inherent vulnerability; rather, it is a problem with how the middleware gem can be used or configured without proper security protections. So I set out to better understand how this could happen and the actual vulnerabilities observed. The culmination of this effort is an open-source project, “Hammer.” Hammer is an example of a vulnerable Rails application deployment that uses Rack-mini-profiler to leak API keys and sensitive information. It is vulnerable in the exact same way as a real-world application observed in the wild. It’s also a skeleton app that can be used to fork and experiment with sensitive variables in a safe way. In the process of building this tool I’ve learned a few things and want to share the lessons learned with the developer and InfoSec communities." }, { "code": null, "e": 3541, "s": 3509, "text": "The Hammer Github site is here." }, { "code": null, "e": 3578, "s": 3541, "text": "A light Hammer introduction is here." }, { "code": null, "e": 3831, "s": 3578, "text": "Let’s do a quick tour of the capabilities of the Middleware that offers so many benefits to a developer but at the same time makes it an attractive attack target. You can follow along at the demo application for Hammer: https://preprod.rtcfingroup.com." }, { "code": null, "e": 4060, "s": 3831, "text": "In the top left-hand corner, an “HTML Speed Badge” is rendered by installing this performance middleware gem. When the tool is installed the HTML speed badge can be used to profile any given page served by the Rails application." }, { "code": null, "e": 4432, "s": 4060, "text": "Let’s navigate over the URL where the sensitive users are publicly accessible — https://preprod.rtcfingroup.com/users/. Note that these aren’t real users. They are randomly generated from a script included with the tool that simulates users. Take a look at the HTML speed badge in the top left corner and see how it has rendered the amount of time for the page to render." }, { "code": null, "e": 4685, "s": 4432, "text": "Expanding the speed badge at /users/ shows the time in milliseconds spent rendering each page. Note the interesting SQL query for rendering users/index. Rack-mini-profiler creates a link that you can click on to get more information. Let’s take a look." }, { "code": null, "e": 5658, "s": 4685, "text": "Below, you can see that Rack-mini-profiler displays detailed call stack query information. You can see the SQL query, file, and precise line that is rendering the users. This is great information for a developer who is trying to improve performance and identify bottlenecks in the application. But from an attacker perspective, this gleans valuable information such as SQL queries that could enable other vulnerabilities to be exploited. It is considered a standard security practice to never expose SQL queries client side. When I first saw this in the wild, I couldn’t believe what I was seeing. Rack-mini-profiler’s website states that the tool can be used to profile applications in development and production. That is why it is so important to ensure that exposing the SQL call stack query aligns with your organizational security policy for application development. When I first saw this, I didn’t know that there would be something far more interesting. Read below." }, { "code": null, "e": 5948, "s": 5658, "text": "Rack-mini-profiler gem uses the “Pretty Print” Ruby class (pp) that can be found at the default URL by appending ?pp=help. It has a lot of nice features for developers such as memory profiling and garbage collection. The most interesting from a security perspective is pretty printing env." }, { "code": null, "e": 6109, "s": 5948, "text": "This env pretty print feature dumps all environment variables that are being passed to the Rails application. This includes the Rack Environment as shown below." }, { "code": null, "e": 6368, "s": 6109, "text": "Taking a look at the Rack-mini-profiler source code for the profiler.rb, the code shows that it first dumps env by iterating through and printing the local variables stored in env. This correlates with the output shown above starting with “Rack Environment.”" }, { "code": null, "e": 6463, "s": 6368, "text": "Second, it dumps the ENV constant by iterating through and printing the contents of this hash." }, { "code": null, "e": 6637, "s": 6463, "text": "The screenshot below shows the start of dumping ENV constant hash from the sample vulnerable application, correlating with the second part of code starting with ENV.each do." }, { "code": null, "e": 6938, "s": 6637, "text": "In this example, the Amazon S3 API keys have been stored in ENV, leaking them out to the public. This shows how dangerous it can be storing API secrets and other sensitive credentials within environment variables stored in the ENV constant hash. We’ll talk a little more about how this happens below." }, { "code": null, "e": 7092, "s": 6938, "text": "Taking this a step further, the sample application leaks a variety of different cloud API and secrets, including Facebook, Twitter, LinkedIn, and Google." }, { "code": null, "e": 7631, "s": 7092, "text": "ENV is a hash-like class that Ruby uses to expose environment variables to our application. For example, PATH or HOME can be made available to our rails application. Rack-mini-profiler doesn’t have to do much to dump ENV because the constant is exposed upon the application launch. It is up to the developer to properly store, load, and secure ENV. ENV traditionally correlates with an environment variable and is more global than env. Each of these variables is listed as key/value pairs and they are usually used to share configuration." }, { "code": null, "e": 7890, "s": 7631, "text": "All Rack applications such as Rails take a single argument which is a hash called env. The env is passed to the Rails application and stores information such as HTTP header, request, and server configuration. In comparison to ENV, env is more local to Rails." }, { "code": null, "e": 8184, "s": 7890, "text": "Environment variables should never be used to store sensitive configuration information such as credentials and API keys. If they must be used, your security program should accept this risk, document it within your risk register, and provide appropriate security controls to mitigate the risk." }, { "code": null, "e": 8439, "s": 8184, "text": "Much has been said about environment variables and their proper usage. The Twelve-Factor App manifesto states that environment variables should be used to store configuration elements such as credentials to external services such as Amazon S3 or Twitter." }, { "code": null, "e": 8538, "s": 8439, "text": "I do not agree with this. Following this practice will increase the business risk to your company." }, { "code": null, "e": 9398, "s": 8538, "text": "The example application shows how easy it can be for developers to make a mistake and inadvertently expose sensitive API keys such as AWS that allow data breach. This application was created to mimic a production environment found in the wild that was secured after enumerating the issues described above. It is the case that Rails developers can use different environments such as production, QA, or development. The Rack-mini-profiler is designed to be used in any of these environments. The exposed environment variables, if containing sensitive secrets running in development environments, can give attackers credentials that allow unauthorized data access, information leakage, and privilege escalation into production. There is a good place for environment variables to store configuration elements. They should just never be used for sensitive secrets." }, { "code": null, "e": 9741, "s": 9398, "text": "This example application uses the Dotenv rails gem to load environment variables from .env This example app uses .env.local to load all of the populated environment variables contained in the file into the ENV constant that is dumped by Rack-mini-profiler. Take a look at the configuration that can also be seen in the Github repo for Hammer:" }, { "code": null, "e": 9996, "s": 9741, "text": "Beyond the risk of exposing sensitive environment variables through Middleware, there are a few other solid reasons why a developer should be aware of the risks inherent in this practice. This list below summarizes some of these risks from Diogo Monica :" }, { "code": null, "e": 10859, "s": 9996, "text": "The risk of copying unencrypted environment variables files such as .env.local into central Git repositories by not properly using the .gitignore file. The risk of tribal knowledge, when new developers who didn’t set up the system don’t take the proper care in safeguarding these files containing environmental variables. Secrets are copied to a different system and exposed.An application can grab the whole environment and print it out for debugging or error-reporting. Secrets can get leaked if they are not properly sanitized before leaving your environment.Environment variables are passed to child processes, which can lead to unintended access (i.e., a 3rd-party tool has access to your environment).When applications crash, it is common to store the environment variables in log files for debugging. This increases the risk of plain text secrets on disk." }, { "code": null, "e": 11235, "s": 10859, "text": "The risk of copying unencrypted environment variables files such as .env.local into central Git repositories by not properly using the .gitignore file. The risk of tribal knowledge, when new developers who didn’t set up the system don’t take the proper care in safeguarding these files containing environmental variables. Secrets are copied to a different system and exposed." }, { "code": null, "e": 11423, "s": 11235, "text": "An application can grab the whole environment and print it out for debugging or error-reporting. Secrets can get leaked if they are not properly sanitized before leaving your environment." }, { "code": null, "e": 11569, "s": 11423, "text": "Environment variables are passed to child processes, which can lead to unintended access (i.e., a 3rd-party tool has access to your environment)." }, { "code": null, "e": 11725, "s": 11569, "text": "When applications crash, it is common to store the environment variables in log files for debugging. This increases the risk of plain text secrets on disk." }, { "code": null, "e": 11930, "s": 11725, "text": "Before we jump into playing with some examples of ENV and environment variables, let’s review some laws of Ruby Environment variables. Honeybadger.io gives a fantastic tutorial on this and I’ll summarize:" }, { "code": null, "e": 12209, "s": 11930, "text": "Every process has its own set of environment variables.Environment variables die with their process.A process inherits its environment variables from its parent.Changes to the environment don’t synch between processes.Your shell is just a UI for the environment variable system." }, { "code": null, "e": 12265, "s": 12209, "text": "Every process has its own set of environment variables." }, { "code": null, "e": 12311, "s": 12265, "text": "Environment variables die with their process." }, { "code": null, "e": 12373, "s": 12311, "text": "A process inherits its environment variables from its parent." }, { "code": null, "e": 12431, "s": 12373, "text": "Changes to the environment don’t synch between processes." }, { "code": null, "e": 12492, "s": 12431, "text": "Your shell is just a UI for the environment variable system." }, { "code": null, "e": 12595, "s": 12492, "text": "This example walks through the Hammer environment, inside the home directory of the Rails application." }, { "code": null, "e": 12667, "s": 12595, "text": "Change into the working home directory of the Rails Hammer application:" }, { "code": null, "e": 12696, "s": 12667, "text": "$ cd /home/<username>/hammer" }, { "code": null, "e": 12793, "s": 12696, "text": "Grep for SECRET in the .env.local to see some of the environment variables we want to play with." }, { "code": null, "e": 12818, "s": 12793, "text": "$ grep SECRET .env.local" }, { "code": null, "e": 13114, "s": 12818, "text": "You’ll see several of the crown jewel API keys. Now print your Bash shell environment variables with env. You’ll see all of the standard environment variables such as $HOME and $PATH. Verify with env | grep SECRET that those sensitive variables are not currently loaded in your Bash environment." }, { "code": null, "e": 13757, "s": 13114, "text": "Run the Interactive Ruby Tool (irb) and we’ll see what happens. By default, irb will not see any of the sensitive environment variables exposed by ENV. This is because we need to use the Rails ‘dotenv’ gem to load the variables from an .env file. This shows that by default a Rails application inherits the environment variables of its parent process (the Bash shell) into ENV constant when a Ruby application is instantiated. But we need to specifically load extra environment variables into ENV hash constant in a special way, as those variables are not available by default. You’ll be able to see $PATH and $HOME but not any of the others." }, { "code": null, "e": 13810, "s": 13757, "text": "$ irb> ENV> ENV['PATH']> ENV['S3_SECRET_ACCESS_KEY']" }, { "code": null, "e": 14015, "s": 13810, "text": "Instruct irb to use the dotenv gem to load the environment variables from the .env.local file. This command will load the environment variables into ENV, making them available to our irb ruby environment." }, { "code": null, "e": 14060, "s": 14015, "text": "> require 'dotenv';Dotenv.load('.env.local')" }, { "code": null, "e": 14155, "s": 14060, "text": "Notice that all of the beautiful things are now available, the sensitive crown jewel API keys!" }, { "code": null, "e": 14258, "s": 14155, "text": "Verify that you have access to a couple of these beautiful, sensitive ENV things in your irb terminal!" }, { "code": null, "e": 14313, "s": 14258, "text": "> ENV['S3_ACCESS_KEY_ID']> ENV['S3_SECRET_ACCESS_KEY']" }, { "code": null, "e": 14418, "s": 14313, "text": "Next, open up a new shell. Launch irb and try to list the sensitive environment variables stored in ENV." }, { "code": null, "e": 14673, "s": 14418, "text": "Note that in the second shell’s irb session, no sensitive environment variables are listed. This is because of the way environment variables work. Every process has its own set of environment variables that are not automatically synced between processes." }, { "code": null, "e": 15178, "s": 14673, "text": "Now to experiment with exporting these variables. If you put export in front of the syntax of the variables named in .env.local, and source the file, magic happens. This converts the local shell variables into environment variables available to ENV. Which is then available to any child Rails process instantiated from that bash shell. The hammer app includes a sample exported variable file for the purpose of playing with sensitive variables in a safe way - .env.local.exported . Let’s give this a try." }, { "code": null, "e": 15315, "s": 15178, "text": "In the second shell, exit the irb session and type the source command. Then run env to list the environment variables in the bash shell:" }, { "code": null, "e": 15363, "s": 15315, "text": "$ source .env.local.exported$ env | grep SECRET" }, { "code": null, "e": 15441, "s": 15363, "text": "Now in the second shell, re-launch irb and fetch the sensitive ENV variables." }, { "code": null, "e": 15501, "s": 15441, "text": "$ irb> ENV['S3_ACCESS_KEY_ID']> ENV['S3_SECRET_ACCESS_KEY']" }, { "code": null, "e": 15815, "s": 15501, "text": "Amazing! You didn’t have to call Dotenv gem to automatically load into ENV. This shows you what Dotenv gem is doing — essentially sourcing the variables from the .env file when the environment is bootstrapped and loading them into ENV. ENV is then dumped via the Rack-mini-profiler Pretty Printer (pp) ruby class." }, { "code": null, "e": 16210, "s": 15815, "text": "In this example, we ended up sourcing the exported variables to our bash shell. Once we exit the shell, the environment variables are not available to the next launched bash shell. If a developer were to add the commands to a shell init script such as .bashrc, this would persist these secrets to all users of the system in cleartext. This is another reason why this practice should be avoided." }, { "code": null, "e": 16487, "s": 16210, "text": "Storing Secrets in Plaintext: Use Rails gem methods such as Dotenv or Figaro to store secrets in the environment, and access them through loading ENV. Other methods include rbenv-vars plugin and direnv. These are popular methods but developers should consider better security." }, { "code": null, "e": 16805, "s": 16487, "text": "SaaS Secrets Management Service: Use a service such as Vault, AWS Secrets Manager, and many others to synchronize and manage secrets within your app. This is a better approach than storing the secrets in plaintext, but keep in mind that you have to protect a super-secret SaaS API key that guards all of your secrets." }, { "code": null, "e": 17310, "s": 16805, "text": "Rails Encrypted Secrets: Starting with Rails 5.1, you can use encrypted secrets to provide better protection to your app credentials. They can be accessed with a special variable other than ENV key/value hash. Here is a good overview, and starting with Rails 6, you can do multi-environment credentials management. This is a more secure way than the first method and similar to the second one. This should keep the master encryption key on your Rails system instead of synchronizing it with a cloud SaaS." }, { "code": null, "e": 17444, "s": 17310, "text": "Here are some recommendations for risk mitigation. These are meant to provide ideas and should be aligned with your DevOps processes." }, { "code": null, "e": 17527, "s": 17444, "text": "Remove the rack-mini-profiler gem on all systems connected to the public Internet." }, { "code": null, "e": 17737, "s": 17527, "text": "On systems requiring Rack-mini-profiler with public Internet access: Implement strong access control by whitelisting/firewalling IP addresses to only allow developer workstations to access the web application." }, { "code": null, "e": 17969, "s": 17737, "text": "Use the RackMiniProfiler access control to authorize and whitelist requests. RackMiniProfiler has an authorization_mode to whitelist in production. Reference the Access control in non-development environments section of the Readme." }, { "code": null, "e": 18260, "s": 17969, "text": "Use Encrypted Secrets and avoid using the environment variables with ENV to store sensitive credentials. The best method to perform this locally is Rails Encrypted Secrets. This will avoid loading sensitive variables into ENV where the risk increases that they can be inadvertently exposed." }, { "code": null, "e": 18527, "s": 18260, "text": "Middleware such as Rack-mini-profiler provides excellent features to developers for improving the speed of Rails applications; however, security controls must be applied to ensure that secrets are properly protected in your application and not leaked to adversaries." }, { "code": null, "e": 18603, "s": 18527, "text": "A wise Cyber Security professional made this simple yet powerful statement:" } ]
Major Kernel Functions in Support Vector Machine (SVM) - GeeksforGeeks
07 Feb, 2022 Kernel Function is a method used to take data as input and transform it into the required form of processing data. “Kernel” is used due to a set of mathematical functions used in Support Vector Machine providing the window to manipulate the data. So, Kernel Function generally transforms the training set of data so that a non-linear decision surface is able to transform to a linear equation in a higher number of dimension spaces. Basically, It returns the inner product between two points in a standard feature dimension. Standard Kernel Function Equation : Major Kernel Functions :- For Implementing Kernel Functions, first of all, we have to install the “scikit-learn” library using the command prompt terminal: pip install scikit-learn Gaussian Kernel: It is used to perform transformation when there is no prior knowledge about data. Gaussian Kernel Radial Basis Function (RBF): Same as above kernel function, adding radial basis method to improve the transformation. Gaussian Kernel Graph Code: python3 from sklearn.svm import SVCclassifier = SVC(kernel ='rbf', random_state = 0) # training set in x, y axisclassifier.fit(x_train, y_train) Sigmoid Kernel: this function is equivalent to a two-layer, perceptron model of the neural network, which is used as an activation function for artificial neurons. Sigmoid Kernel Graph Code: python3 from sklearn.svm import SVCclassifier = SVC(kernel ='sigmoid')classifier.fit(x_train, y_train) # training set in x, y axis Polynomial Kernel: It represents the similarity of vectors in the training set of data in a feature space over polynomials of the original variables used in the kernel. Polynomial Kernel Graph Code: python3 from sklearn.svm import SVCclassifier = SVC(kernel ='poly', degree = 4)classifier.fit(x_train, y_train) # training set in x, y axis Linear Kernel: used when data is linearly separable. Code: python3 from sklearn.svm import SVCclassifier = SVC(kernel ='linear')classifier.fit(x_train, y_train) # training set in x, y axis punamsingh628700 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Search Algorithms in AI Python | Decision tree implementation Decision Tree Introduction with example Reinforcement learning 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": 24732, "s": 24704, "text": "\n07 Feb, 2022" }, { "code": null, "e": 25452, "s": 24732, "text": "Kernel Function is a method used to take data as input and transform it into the required form of processing data. “Kernel” is used due to a set of mathematical functions used in Support Vector Machine providing the window to manipulate the data. So, Kernel Function generally transforms the training set of data so that a non-linear decision surface is able to transform to a linear equation in a higher number of dimension spaces. Basically, It returns the inner product between two points in a standard feature dimension. Standard Kernel Function Equation : Major Kernel Functions :- For Implementing Kernel Functions, first of all, we have to install the “scikit-learn” library using the command prompt terminal: " }, { "code": null, "e": 25481, "s": 25452, "text": " pip install scikit-learn" }, { "code": null, "e": 25580, "s": 25481, "text": "Gaussian Kernel: It is used to perform transformation when there is no prior knowledge about data." }, { "code": null, "e": 25716, "s": 25582, "text": "Gaussian Kernel Radial Basis Function (RBF): Same as above kernel function, adding radial basis method to improve the transformation." }, { "code": null, "e": 25740, "s": 25718, "text": "Gaussian Kernel Graph" }, { "code": null, "e": 25747, "s": 25740, "text": "Code: " }, { "code": null, "e": 25755, "s": 25747, "text": "python3" }, { "code": "from sklearn.svm import SVCclassifier = SVC(kernel ='rbf', random_state = 0) # training set in x, y axisclassifier.fit(x_train, y_train)", "e": 25892, "s": 25755, "text": null }, { "code": null, "e": 26056, "s": 25892, "text": "Sigmoid Kernel: this function is equivalent to a two-layer, perceptron model of the neural network, which is used as an activation function for artificial neurons." }, { "code": null, "e": 26079, "s": 26058, "text": "Sigmoid Kernel Graph" }, { "code": null, "e": 26087, "s": 26079, "text": "Code: " }, { "code": null, "e": 26095, "s": 26087, "text": "python3" }, { "code": "from sklearn.svm import SVCclassifier = SVC(kernel ='sigmoid')classifier.fit(x_train, y_train) # training set in x, y axis", "e": 26218, "s": 26095, "text": null }, { "code": null, "e": 26387, "s": 26218, "text": "Polynomial Kernel: It represents the similarity of vectors in the training set of data in a feature space over polynomials of the original variables used in the kernel." }, { "code": null, "e": 26413, "s": 26389, "text": "Polynomial Kernel Graph" }, { "code": null, "e": 26419, "s": 26413, "text": "Code:" }, { "code": null, "e": 26427, "s": 26419, "text": "python3" }, { "code": "from sklearn.svm import SVCclassifier = SVC(kernel ='poly', degree = 4)classifier.fit(x_train, y_train) # training set in x, y axis", "e": 26559, "s": 26427, "text": null }, { "code": null, "e": 26612, "s": 26559, "text": "Linear Kernel: used when data is linearly separable." }, { "code": null, "e": 26619, "s": 26612, "text": "Code: " }, { "code": null, "e": 26627, "s": 26619, "text": "python3" }, { "code": "from sklearn.svm import SVCclassifier = SVC(kernel ='linear')classifier.fit(x_train, y_train) # training set in x, y axis", "e": 26749, "s": 26627, "text": null }, { "code": null, "e": 26766, "s": 26749, "text": "punamsingh628700" }, { "code": null, "e": 26783, "s": 26766, "text": "Machine Learning" }, { "code": null, "e": 26790, "s": 26783, "text": "Python" }, { "code": null, "e": 26807, "s": 26790, "text": "Machine Learning" }, { "code": null, "e": 26905, "s": 26807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26914, "s": 26905, "text": "Comments" }, { "code": null, "e": 26927, "s": 26914, "text": "Old Comments" }, { "code": null, "e": 26941, "s": 26927, "text": "Decision Tree" }, { "code": null, "e": 26965, "s": 26941, "text": "Search Algorithms in AI" }, { "code": null, "e": 27003, "s": 26965, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27043, "s": 27003, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27066, "s": 27043, "text": "Reinforcement learning" }, { "code": null, "e": 27094, "s": 27066, "text": "Read JSON file using Python" }, { "code": null, "e": 27144, "s": 27094, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27166, "s": 27144, "text": "Python map() function" } ]
ES6 - Loops
At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration. The following figure illustrates the classification of loops − A loop whose number of iterations are definite/fixed is termed as a definite loop. The ‘for loop’ is an implementation of a definite loop. for (initial_count_value; termination-condition; step) { //statements } The for loop executes the code block for a specified number of times. The for...in loop is used to loop through an object's properties. The for...of loop is used to iterate iterables instead of object literals. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − The while loop executes the instructions each time the condition specified evaluates to true. The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. The break statement is used to take the control out of a construct. The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely. Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop A label can be used with break and continue to control the flow more precisely. Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2499, "s": 2277, "text": "At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration." }, { "code": null, "e": 2562, "s": 2499, "text": "The following figure illustrates the classification of loops −" }, { "code": null, "e": 2701, "s": 2562, "text": "A loop whose number of iterations are definite/fixed is termed as a definite loop. The ‘for loop’ is an implementation of a definite loop." }, { "code": null, "e": 2781, "s": 2701, "text": "for (initial_count_value; termination-condition; step) { \n //statements\n} \n" }, { "code": null, "e": 2851, "s": 2781, "text": "The for loop executes the code block for a specified number of times." }, { "code": null, "e": 2917, "s": 2851, "text": "The for...in loop is used to loop through an object's properties." }, { "code": null, "e": 2992, "s": 2917, "text": "The for...of loop is used to iterate iterables instead of object literals." }, { "code": null, "e": 3088, "s": 2992, "text": "An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown." }, { "code": null, "e": 3132, "s": 3088, "text": "Indefinite loops can be implemented using −" }, { "code": null, "e": 3226, "s": 3132, "text": "The while loop executes the instructions each time the condition specified evaluates to true." }, { "code": null, "e": 3376, "s": 3226, "text": "The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes." }, { "code": null, "e": 3444, "s": 3376, "text": "The break statement is used to take the control out of a construct." }, { "code": null, "e": 3581, "s": 3444, "text": "The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop." }, { "code": null, "e": 3768, "s": 3581, "text": "A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely." }, { "code": null, "e": 3953, "s": 3768, "text": "Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop" }, { "code": null, "e": 4033, "s": 3953, "text": "A label can be used with break and continue to control the flow more precisely." }, { "code": null, "e": 4125, "s": 4033, "text": "Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name." }, { "code": null, "e": 4160, "s": 4125, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4174, "s": 4160, "text": " Sharad Kumar" }, { "code": null, "e": 4207, "s": 4174, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 4225, "s": 4207, "text": " Richa Maheshwari" }, { "code": null, "e": 4258, "s": 4225, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4272, "s": 4258, "text": " Anadi Sharma" }, { "code": null, "e": 4307, "s": 4272, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4324, "s": 4307, "text": " Gowthami Swarna" }, { "code": null, "e": 4357, "s": 4324, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4373, "s": 4357, "text": " Deepti Trivedi" }, { "code": null, "e": 4408, "s": 4373, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4416, "s": 4408, "text": " Shweta" }, { "code": null, "e": 4423, "s": 4416, "text": " Print" }, { "code": null, "e": 4434, "s": 4423, "text": " Add Notes" } ]
How to sort a big array with many repetitions? - GeeksforGeeks
02 Mar, 2022 Consider a big array where elements are from a small set and in any range, i.e. there are many repetitions. How to efficiently sort the array? Example: Input: arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1} Output: arr[] = {1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100} We strongly recommend you to minimize your browser and try this yourself first.A Basic Sorting algorithm like MergeSort, HeapSort would take O(nLogn) time where n is number of elements, can we do better?A Better Solution is to use Self-Balancing Binary Search Tree like AVL or Red-Black to sort in O(n Log m) time where m is number of distinct elements. The idea is to extend tree node to have count of keys also. struct Node { int key; struct Node *left. *right; int count; // Added to handle duplicates // Other tree node info for balancing like height in AVL } Below is complete algorithm using AVL tree. 1) Create an empty AVL Tree with count as an additional field. 2) Traverse input array and do following for every element ‘arr[i]’ .....a) If arr[i] is not present in tree, then insert it and initialize count as 1 .....b) Else increment its count in tree. 3) Do Inorder Traversal of tree. While doing inorder put every key its count times in arr[].The 2nd step takes O(n Log m) time and 3rd step takes O(n) time. So overall time complexity is O(n Log m)Below is C++ implementation of above idea. C++ Java C# // C++ program to sort an array using AVL tree#include<iostream>using namespace std; // An AVL tree Nodestruct Node{ int key; struct Node *left, *right; int height, count;}; // Function to insert a key in AVL Tree, if key is already present,// then it increments count in key's node.struct Node* insert(struct Node* Node, int key); // This function puts inorder traversal of AVL Tree in arr[]void inorder(int arr[], struct Node *root, int *index_ptr); // An AVL tree based sorting function for sorting an array with// duplicatesvoid sort(int arr[], int n){ // Create an empty AVL Tree struct Node *root = NULL; // Insert all nodes one by one in AVL tree. The insert function // increments count if key is already present for (int i=0; i<n; i++) root = insert(root, arr[i]); // Do inorder traversal to put elements back in sorted order int index = 0; inorder(arr, root, &index);} // This function puts inorder traversal of AVL Tree in arr[]void inorder(int arr[], struct Node *root, int *index_ptr){ if (root != NULL) { // Recur for left child inorder(arr, root->left, index_ptr); // Put all occurrences of root's key in arr[] for (int i=0; i<root->count; i++) { arr[*index_ptr] = root->key; (*index_ptr)++; } // Recur for right child inorder(arr, root->right, index_ptr); }} // A utility function to get height of the treeint height(struct Node *N){ if (N == NULL) return 0; return N->height;} // Helper function that allocates a new Nodestruct Node* newNode(int key){ struct Node* node = new Node; node->key = key; node->left = node->right = NULL; node->height = node->count = 1; return(node);} // A utility function to right rotate subtree rooted// with y.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x;} // A utility function to left rotate subtree rooted with xstruct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y;} // Get Balance factor of Node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Function to insert a key in AVL Tree, if key is already// present, then it increments count in key's node.struct Node* insert(struct Node* Node, int key){ /* 1. Perform the normal BST rotation */ if (Node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == Node->key) { (Node->count)++; return Node; } /* Otherwise, recur down the tree */ if (key < Node->key) Node->left = insert(Node->left, key); else Node->right = insert(Node->right, key); /* 2. Update height of this ancestor Node */ Node->height = max(height(Node->left), height(Node->right)) + 1; /* 3. Get the balance factor of this ancestor Node to check whether this Node became unbalanced */ int balance = getBalance(Node); // If this Node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < Node->left->key) return rightRotate(Node); // Right Right Case if (balance < -1 && key > Node->right->key) return leftRotate(Node); // Left Right Case if (balance > 1 && key > Node->left->key) { Node->left = leftRotate(Node->left); return rightRotate(Node); } // Right Left Case if (balance < -1 && key < Node->right->key) { Node->right = rightRotate(Node->right); return leftRotate(Node); } /* return the (unchanged) Node pointer */ return Node;} // A utility function to print an arrayvoid printArr(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << ", "; cout << endl;} /* Driver program to test above function*/int main(){ int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Input array is\n"; printArr(arr, n); sort(arr, n); cout << "Sorted array is\n"; printArr(arr, n);} // Java program for insertion in AVL Treepublic class AvlTree{ static Node root = null; static class Node { int key, height, count; Node left, right; Node(int d) { key = d; height = 1; count = 1; left = right = null; } } // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Duplicate keys not allowed else { node.count++; return node; } /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // inorder traversal in BST always give sorted // order. Put the sorted elements back into the array int inorder(Node n, int arr[], int i) { if (n != null) { i = inorder(n.left, arr, i); for(int j = 0; j < n.count; j++) { arr[i] = n.key; i++; } i = inorder(n.right, arr, i); } return i; } // Driver code public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; System.out.println("Input array "); for (int i = 0; i < arr.length; i++) System.out.print(" "+ arr[i]); AvlTree at= new AvlTree(); // insert all element in AVL tree for (int i = 0; i < arr.length; i++) root = at.insert(root, arr[i]); // Do inorder traversal to put // elements back in sorted order int index = 0; at.inorder(root, arr, index); System.out.println("\nOutput array "); for (int i = 0; i < arr.length; i++) System.out.print(" "+ arr[i]); }} // This code is contributed by moonishussain // C# program for insertion in AVL Treeusing System; public class AvlTree{ static Node root = null; public class Node { public int key, height, count; public Node left, right; public Node(int d) { key = d; height = 1; count = 1; left = right = null; } } // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Duplicate keys not allowed else { node.count++; return node; } /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* * 3. Get the balance factor of this ancestor node to check whether this node * became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // inorder traversal in BST always give sorted // order. Put the sorted elements back into the array int inorder(Node n, int []arr, int i) { if (n != null) { i = inorder(n.left, arr, i); for (int j = 0; j < n.count; j++) { arr[i] = n.key; i++; } i = inorder(n.right, arr, i); } return i; } // Driver code public static void Main(String[] args) { // TODO Auto-generated method stub int []arr = { 100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1 }; Console.WriteLine("Input array "); for (int i = 0; i < arr.Length; i++) Console.Write(" " + arr[i]); AvlTree at = new AvlTree(); // insert all element in AVL tree for (int i = 0; i < arr.Length; i++) root = at.insert(root, arr[i]); // Do inorder traversal to put // elements back in sorted order int index = 0; at.inorder(root, arr, index); Console.WriteLine("\nOutput array "); for (int i = 0; i < arr.Length; i++) Console.Write(" " + arr[i]); }} // This code is contributed by gauravrajput1 Output: Input array is 100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1, Sorted array is 1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100, We can also use Binary Heap to solve in O(n Log m) time. We can also use Hashing to solve above problem in O(n + m Log m) time. 1) Create an empty hash table. Input array values are stores as key and their counts are stored as value in hash table. 2) For every element ‘x’ of arr[], do following .....a) If x ix present in hash table, increment its value .....b) Else insert x with value equals to 1. 3) Consider all keys of hash table and sort them. 4) Traverse all sorted keys and print every key its value times.Time complexity of 2nd step is O(n) under the assumption that hash search and insert take O(1) time. Step 3 takes O(m Log m) time where m is total number of distinct keys in input array. Step 4 takes O(n) time. So overall time complexity is O(n + m Log m).Program implementation using Hash Table C // A C++ program to sort a big array with many repetitions #include <iostream>#include <algorithm>#include <map>using namespace std; void sort(int arr[], int n){ //1. Create an empty hash table. map<int, int> count; //2. Input array values are stores as key and their //counts are stored as value in hash table. for (int i=0; i<n; i++) count[arr[i]]++; map<int, int>::iterator it; int index = 0; //3. Consider all keys of hash table and sort them. //In std::map, keys are already sorted. //4. Traverse all sorted keys and print every key its value times. for (it=count.begin(); it!=count.end(); ++it) { while(it->second--) arr[index++]=it->first; }} // Utility function to print an arrayvoid printArray(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << " "; cout << endl; } // Driver program to test above function.int main(){ int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Input array is\n"; printArray(arr, n); sort(arr, n); cout << "Sorted array is\n"; printArray(arr, n); return 0;}// Contributed by Aditya Goel Output: Input array is 100 12 100 1 1 12 100 1 12 100 1 1 Sorted array is 1 1 1 1 1 12 12 12 100 100 100 100 This article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai moonishussain varshagumber28 GauravRajput1 AVL-Tree Merge Sort Self-Balancing-BST Sorting Sorting Merge Sort AVL-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort Quick Sort vs Merge Sort Stability in sorting algorithms Chocolate Distribution Problem Quickselect Algorithm Segregate 0s and 1s in an array Sorting in Java Sort a nearly sorted (or K sorted) array QuickSort using Random Pivoting Binary Insertion Sort
[ { "code": null, "e": 24076, "s": 24048, "text": "\n02 Mar, 2022" }, { "code": null, "e": 24221, "s": 24076, "text": "Consider a big array where elements are from a small set and in any range, i.e. there are many repetitions. How to efficiently sort the array? " }, { "code": null, "e": 24359, "s": 24221, "text": "Example: \nInput: arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}\nOutput: arr[] = {1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100}" }, { "code": null, "e": 24775, "s": 24359, "text": "We strongly recommend you to minimize your browser and try this yourself first.A Basic Sorting algorithm like MergeSort, HeapSort would take O(nLogn) time where n is number of elements, can we do better?A Better Solution is to use Self-Balancing Binary Search Tree like AVL or Red-Black to sort in O(n Log m) time where m is number of distinct elements. The idea is to extend tree node to have count of keys also. " }, { "code": null, "e": 24939, "s": 24775, "text": "struct Node\n{\n int key;\n struct Node *left. *right;\n int count; // Added to handle duplicates\n\n // Other tree node info for balancing like height in AVL\n}" }, { "code": null, "e": 25481, "s": 24939, "text": "Below is complete algorithm using AVL tree. 1) Create an empty AVL Tree with count as an additional field. 2) Traverse input array and do following for every element ‘arr[i]’ .....a) If arr[i] is not present in tree, then insert it and initialize count as 1 .....b) Else increment its count in tree. 3) Do Inorder Traversal of tree. While doing inorder put every key its count times in arr[].The 2nd step takes O(n Log m) time and 3rd step takes O(n) time. So overall time complexity is O(n Log m)Below is C++ implementation of above idea. " }, { "code": null, "e": 25485, "s": 25481, "text": "C++" }, { "code": null, "e": 25490, "s": 25485, "text": "Java" }, { "code": null, "e": 25493, "s": 25490, "text": "C#" }, { "code": "// C++ program to sort an array using AVL tree#include<iostream>using namespace std; // An AVL tree Nodestruct Node{ int key; struct Node *left, *right; int height, count;}; // Function to insert a key in AVL Tree, if key is already present,// then it increments count in key's node.struct Node* insert(struct Node* Node, int key); // This function puts inorder traversal of AVL Tree in arr[]void inorder(int arr[], struct Node *root, int *index_ptr); // An AVL tree based sorting function for sorting an array with// duplicatesvoid sort(int arr[], int n){ // Create an empty AVL Tree struct Node *root = NULL; // Insert all nodes one by one in AVL tree. The insert function // increments count if key is already present for (int i=0; i<n; i++) root = insert(root, arr[i]); // Do inorder traversal to put elements back in sorted order int index = 0; inorder(arr, root, &index);} // This function puts inorder traversal of AVL Tree in arr[]void inorder(int arr[], struct Node *root, int *index_ptr){ if (root != NULL) { // Recur for left child inorder(arr, root->left, index_ptr); // Put all occurrences of root's key in arr[] for (int i=0; i<root->count; i++) { arr[*index_ptr] = root->key; (*index_ptr)++; } // Recur for right child inorder(arr, root->right, index_ptr); }} // A utility function to get height of the treeint height(struct Node *N){ if (N == NULL) return 0; return N->height;} // Helper function that allocates a new Nodestruct Node* newNode(int key){ struct Node* node = new Node; node->key = key; node->left = node->right = NULL; node->height = node->count = 1; return(node);} // A utility function to right rotate subtree rooted// with y.struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x;} // A utility function to left rotate subtree rooted with xstruct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y;} // Get Balance factor of Node Nint getBalance(struct Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} // Function to insert a key in AVL Tree, if key is already// present, then it increments count in key's node.struct Node* insert(struct Node* Node, int key){ /* 1. Perform the normal BST rotation */ if (Node == NULL) return (newNode(key)); // If key already exists in BST, increment count and return if (key == Node->key) { (Node->count)++; return Node; } /* Otherwise, recur down the tree */ if (key < Node->key) Node->left = insert(Node->left, key); else Node->right = insert(Node->right, key); /* 2. Update height of this ancestor Node */ Node->height = max(height(Node->left), height(Node->right)) + 1; /* 3. Get the balance factor of this ancestor Node to check whether this Node became unbalanced */ int balance = getBalance(Node); // If this Node becomes unbalanced, then there are 4 cases // Left Left Case if (balance > 1 && key < Node->left->key) return rightRotate(Node); // Right Right Case if (balance < -1 && key > Node->right->key) return leftRotate(Node); // Left Right Case if (balance > 1 && key > Node->left->key) { Node->left = leftRotate(Node->left); return rightRotate(Node); } // Right Left Case if (balance < -1 && key < Node->right->key) { Node->right = rightRotate(Node->right); return leftRotate(Node); } /* return the (unchanged) Node pointer */ return Node;} // A utility function to print an arrayvoid printArr(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << \", \"; cout << endl;} /* Driver program to test above function*/int main(){ int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Input array is\\n\"; printArr(arr, n); sort(arr, n); cout << \"Sorted array is\\n\"; printArr(arr, n);}", "e": 30047, "s": 25493, "text": null }, { "code": "// Java program for insertion in AVL Treepublic class AvlTree{ static Node root = null; static class Node { int key, height, count; Node left, right; Node(int d) { key = d; height = 1; count = 1; left = right = null; } } // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Duplicate keys not allowed else { node.count++; return node; } /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // inorder traversal in BST always give sorted // order. Put the sorted elements back into the array int inorder(Node n, int arr[], int i) { if (n != null) { i = inorder(n.left, arr, i); for(int j = 0; j < n.count; j++) { arr[i] = n.key; i++; } i = inorder(n.right, arr, i); } return i; } // Driver code public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; System.out.println(\"Input array \"); for (int i = 0; i < arr.length; i++) System.out.print(\" \"+ arr[i]); AvlTree at= new AvlTree(); // insert all element in AVL tree for (int i = 0; i < arr.length; i++) root = at.insert(root, arr[i]); // Do inorder traversal to put // elements back in sorted order int index = 0; at.inorder(root, arr, index); System.out.println(\"\\nOutput array \"); for (int i = 0; i < arr.length; i++) System.out.print(\" \"+ arr[i]); }} // This code is contributed by moonishussain", "e": 34420, "s": 30047, "text": null }, { "code": "// C# program for insertion in AVL Treeusing System; public class AvlTree{ static Node root = null; public class Node { public int key, height, count; public Node left, right; public Node(int d) { key = d; height = 1; count = 1; left = right = null; } } // A utility function to get the height of the tree int height(Node N) { if (N == null) return 0; return N.height; } // A utility function to get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // A utility function to right rotate subtree rooted with y // See the diagram given above. Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { /* 1. Perform the normal BST insertion */ if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Duplicate keys not allowed else { node.count++; return node; } /* 2. Update height of this ancestor node */ node.height = 1 + max(height(node.left), height(node.right)); /* * 3. Get the balance factor of this ancestor node to check whether this node * became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there // are 4 cases Left Left Case if (balance > 1 && key < node.left.key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node.right.key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // inorder traversal in BST always give sorted // order. Put the sorted elements back into the array int inorder(Node n, int []arr, int i) { if (n != null) { i = inorder(n.left, arr, i); for (int j = 0; j < n.count; j++) { arr[i] = n.key; i++; } i = inorder(n.right, arr, i); } return i; } // Driver code public static void Main(String[] args) { // TODO Auto-generated method stub int []arr = { 100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1 }; Console.WriteLine(\"Input array \"); for (int i = 0; i < arr.Length; i++) Console.Write(\" \" + arr[i]); AvlTree at = new AvlTree(); // insert all element in AVL tree for (int i = 0; i < arr.Length; i++) root = at.insert(root, arr[i]); // Do inorder traversal to put // elements back in sorted order int index = 0; at.inorder(root, arr, index); Console.WriteLine(\"\\nOutput array \"); for (int i = 0; i < arr.Length; i++) Console.Write(\" \" + arr[i]); }} // This code is contributed by gauravrajput1", "e": 38176, "s": 34420, "text": null }, { "code": null, "e": 38186, "s": 38176, "text": "Output: " }, { "code": null, "e": 38311, "s": 38186, "text": "Input array is\n100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1,\nSorted array is\n1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100," }, { "code": null, "e": 39123, "s": 38311, "text": "We can also use Binary Heap to solve in O(n Log m) time. We can also use Hashing to solve above problem in O(n + m Log m) time. 1) Create an empty hash table. Input array values are stores as key and their counts are stored as value in hash table. 2) For every element ‘x’ of arr[], do following .....a) If x ix present in hash table, increment its value .....b) Else insert x with value equals to 1. 3) Consider all keys of hash table and sort them. 4) Traverse all sorted keys and print every key its value times.Time complexity of 2nd step is O(n) under the assumption that hash search and insert take O(1) time. Step 3 takes O(m Log m) time where m is total number of distinct keys in input array. Step 4 takes O(n) time. So overall time complexity is O(n + m Log m).Program implementation using Hash Table " }, { "code": null, "e": 39125, "s": 39123, "text": "C" }, { "code": "// A C++ program to sort a big array with many repetitions #include <iostream>#include <algorithm>#include <map>using namespace std; void sort(int arr[], int n){ //1. Create an empty hash table. map<int, int> count; //2. Input array values are stores as key and their //counts are stored as value in hash table. for (int i=0; i<n; i++) count[arr[i]]++; map<int, int>::iterator it; int index = 0; //3. Consider all keys of hash table and sort them. //In std::map, keys are already sorted. //4. Traverse all sorted keys and print every key its value times. for (it=count.begin(); it!=count.end(); ++it) { while(it->second--) arr[index++]=it->first; }} // Utility function to print an arrayvoid printArray(int arr[], int n){ for (int i=0; i<n; i++) cout << arr[i] << \" \"; cout << endl; } // Driver program to test above function.int main(){ int arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Input array is\\n\"; printArray(arr, n); sort(arr, n); cout << \"Sorted array is\\n\"; printArray(arr, n); return 0;}// Contributed by Aditya Goel", "e": 40319, "s": 39125, "text": null }, { "code": null, "e": 40329, "s": 40319, "text": "Output: " }, { "code": null, "e": 40434, "s": 40329, "text": "Input array is\n\n100 12 100 1 1 12 100 1 12 100 1 1 \n\nSorted array is\n\n1 1 1 1 1 12 12 12 100 100 100 100" }, { "code": null, "e": 40598, "s": 40434, "text": "This article is contributed by Ankur. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40611, "s": 40598, "text": "Akanksha_Rai" }, { "code": null, "e": 40625, "s": 40611, "text": "moonishussain" }, { "code": null, "e": 40640, "s": 40625, "text": "varshagumber28" }, { "code": null, "e": 40654, "s": 40640, "text": "GauravRajput1" }, { "code": null, "e": 40663, "s": 40654, "text": "AVL-Tree" }, { "code": null, "e": 40674, "s": 40663, "text": "Merge Sort" }, { "code": null, "e": 40693, "s": 40674, "text": "Self-Balancing-BST" }, { "code": null, "e": 40701, "s": 40693, "text": "Sorting" }, { "code": null, "e": 40709, "s": 40701, "text": "Sorting" }, { "code": null, "e": 40720, "s": 40709, "text": "Merge Sort" }, { "code": null, "e": 40729, "s": 40720, "text": "AVL-Tree" }, { "code": null, "e": 40827, "s": 40729, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40853, "s": 40827, "text": "C++ Program for QuickSort" }, { "code": null, "e": 40878, "s": 40853, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 40910, "s": 40878, "text": "Stability in sorting algorithms" }, { "code": null, "e": 40941, "s": 40910, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 40963, "s": 40941, "text": "Quickselect Algorithm" }, { "code": null, "e": 40995, "s": 40963, "text": "Segregate 0s and 1s in an array" }, { "code": null, "e": 41011, "s": 40995, "text": "Sorting in Java" }, { "code": null, "e": 41052, "s": 41011, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 41084, "s": 41052, "text": "QuickSort using Random Pivoting" } ]
CSS - Paddings
The padding property allows you to specify how much space should appear between the content of an element and its border − The value of this attribute should be either a length, a percentage, or the word inherit. If the value is inherit, it will have the same padding as its parent element. If a percentage is used, the percentage is of the containing box. The following CSS properties can be used to control lists. You can also set different values for the padding on each side of the box using the following properties − The padding-bottom specifies the bottom padding of an element. The padding-bottom specifies the bottom padding of an element. The padding-top specifies the top padding of an element. The padding-top specifies the top padding of an element. The padding-left specifies the left padding of an element. The padding-left specifies the left padding of an element. The padding-right specifies the right padding of an element. The padding-right specifies the right padding of an element. The padding serves as shorthand for the preceding properties. The padding serves as shorthand for the preceding properties. Now, we will see how to use these properties with examples. The padding-bottom property sets the bottom padding (space) of an element. This can take a value in terms of length of %. Here is an example − <html> <head> </head> <body> <p style = "padding-bottom: 15px; border:1px solid black;"> This is a paragraph with a specified bottom padding </p> <p style = "padding-bottom: 5%; border:1px solid black;"> This is another paragraph with a specified bottom padding in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified bottom padding This is another paragraph with a specified bottom padding in percent The padding-top property sets the top padding (space) of an element. This can take a value in terms of length of %. Here is an example − <html> <head> </head> <body> <p style = "padding-top: 15px; border:1px solid black;"> This is a paragraph with a specified top padding </p> <p style = "padding-top: 5%; border:1px solid black;"> This is another paragraph with a specified top padding in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified top padding This is another paragraph with a specified top padding in percent The padding-left property sets the left padding (space) of an element. This can take a value in terms of length of %. Here is an example − <html> <head> </head> <body> <p style = "padding-left: 15px; border:1px solid black;"> This is a paragraph with a specified left padding </p> <p style = "padding-left: 15%; border:1px solid black;"> This is another paragraph with a specified left padding in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified left padding This is another paragraph with a specified left padding in percent The padding-right property sets the right padding (space) of an element. This can take a value in terms of length of %. Here is an example − <html> <head> </head> <body> <p style = "padding-right: 15px; border:1px solid black;"> This is a paragraph with a specified right padding </p> <p style = "padding-right: 5%; border:1px solid black;"> This is another paragraph with a specified right padding in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified right padding This is another paragraph with a specified right padding in percent The padding property sets the left, right, top and bottom padding (space) of an element. This can take a value in terms of length of %. Here is an example − <html> <head> </head> <body> <p style = "padding: 15px; border:1px solid black;"> all four padding will be 15px </p> <p style = "padding:10px 2%; border:1px solid black;"> top and bottom padding will be 10px, left and right padding will be 2% of the total width of the document. </p> <p style = "padding: 10px 2% 10px; border:1px solid black;"> top padding will be 10px, left and right padding will be 2% of the total width of the document, bottom padding will be 10px </p> <p style = "padding: 10px 2% 10px 10px; border:1px solid black;"> top padding will be 10px, right padding will be 2% of the total width of the document, bottom padding and top padding will be 10px </p> </body> </html> It will produce the following result − all four padding will be 15px top and bottom padding will be 10px, left and right padding will be 2% of the total width of the document. top padding will be 10px, left and right padding will be 2% of the total width of the document, bottom padding will be 10px top padding will be 10px, right padding will be 2% of the total width of the document, bottom padding and top padding will be 10px 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2749, "s": 2626, "text": "The padding property allows you to specify how much space should appear between the content of an element and its border −" }, { "code": null, "e": 2983, "s": 2749, "text": "The value of this attribute should be either a length, a percentage, or the word inherit. If the value is inherit, it will have the same padding as its parent element. If a percentage is used, the percentage is of the containing box." }, { "code": null, "e": 3149, "s": 2983, "text": "The following CSS properties can be used to control lists. You can also set different values for the padding on each side of the box using the following properties −" }, { "code": null, "e": 3212, "s": 3149, "text": "The padding-bottom specifies the bottom padding of an element." }, { "code": null, "e": 3275, "s": 3212, "text": "The padding-bottom specifies the bottom padding of an element." }, { "code": null, "e": 3332, "s": 3275, "text": "The padding-top specifies the top padding of an element." }, { "code": null, "e": 3389, "s": 3332, "text": "The padding-top specifies the top padding of an element." }, { "code": null, "e": 3448, "s": 3389, "text": "The padding-left specifies the left padding of an element." }, { "code": null, "e": 3507, "s": 3448, "text": "The padding-left specifies the left padding of an element." }, { "code": null, "e": 3568, "s": 3507, "text": "The padding-right specifies the right padding of an element." }, { "code": null, "e": 3629, "s": 3568, "text": "The padding-right specifies the right padding of an element." }, { "code": null, "e": 3691, "s": 3629, "text": "The padding serves as shorthand for the preceding properties." }, { "code": null, "e": 3753, "s": 3691, "text": "The padding serves as shorthand for the preceding properties." }, { "code": null, "e": 3813, "s": 3753, "text": "Now, we will see how to use these properties with examples." }, { "code": null, "e": 3935, "s": 3813, "text": "The padding-bottom property sets the bottom padding (space) of an element. This can take a value in terms of length of %." }, { "code": null, "e": 3956, "s": 3935, "text": "Here is an example −" }, { "code": null, "e": 4316, "s": 3956, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"padding-bottom: 15px; border:1px solid black;\">\n This is a paragraph with a specified bottom padding\n </p>\n \n <p style = \"padding-bottom: 5%; border:1px solid black;\">\n This is another paragraph with a specified bottom padding in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 4355, "s": 4316, "text": "It will produce the following result −" }, { "code": null, "e": 4412, "s": 4355, "text": "\n This is a paragraph with a specified bottom padding\n" }, { "code": null, "e": 4486, "s": 4412, "text": "\n This is another paragraph with a specified bottom padding in percent\n" }, { "code": null, "e": 4602, "s": 4486, "text": "The padding-top property sets the top padding (space) of an element. This can take a value in terms of length of %." }, { "code": null, "e": 4623, "s": 4602, "text": "Here is an example −" }, { "code": null, "e": 4971, "s": 4623, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"padding-top: 15px; border:1px solid black;\">\n This is a paragraph with a specified top padding\n </p>\n \n <p style = \"padding-top: 5%; border:1px solid black;\">\n This is another paragraph with a specified top padding in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 5010, "s": 4971, "text": "It will produce the following result −" }, { "code": null, "e": 5064, "s": 5010, "text": "\n This is a paragraph with a specified top padding\n" }, { "code": null, "e": 5135, "s": 5064, "text": "\n This is another paragraph with a specified top padding in percent\n" }, { "code": null, "e": 5253, "s": 5135, "text": "The padding-left property sets the left padding (space) of an element. This can take a value in terms of length of %." }, { "code": null, "e": 5274, "s": 5253, "text": "Here is an example −" }, { "code": null, "e": 5626, "s": 5274, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"padding-left: 15px; border:1px solid black;\">\n This is a paragraph with a specified left padding\n </p>\n \n <p style = \"padding-left: 15%; border:1px solid black;\">\n This is another paragraph with a specified left padding in percent\n </p>\n </body>\n</html>" }, { "code": null, "e": 5665, "s": 5626, "text": "It will produce the following result −" }, { "code": null, "e": 5720, "s": 5665, "text": "\n This is a paragraph with a specified left padding\n" }, { "code": null, "e": 5792, "s": 5720, "text": "\n This is another paragraph with a specified left padding in percent\n" }, { "code": null, "e": 5912, "s": 5792, "text": "The padding-right property sets the right padding (space) of an element. This can take a value in terms of length of %." }, { "code": null, "e": 5933, "s": 5912, "text": "Here is an example −" }, { "code": null, "e": 6289, "s": 5933, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"padding-right: 15px; border:1px solid black;\">\n This is a paragraph with a specified right padding\n </p>\n \n <p style = \"padding-right: 5%; border:1px solid black;\">\n This is another paragraph with a specified right padding in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 6328, "s": 6289, "text": "It will produce the following result −" }, { "code": null, "e": 6384, "s": 6328, "text": "\n This is a paragraph with a specified right padding\n" }, { "code": null, "e": 6457, "s": 6384, "text": "\n This is another paragraph with a specified right padding in percent\n" }, { "code": null, "e": 6593, "s": 6457, "text": "The padding property sets the left, right, top and bottom padding (space) of an element. This can take a value in terms of length of %." }, { "code": null, "e": 6614, "s": 6593, "text": "Here is an example −" }, { "code": null, "e": 7463, "s": 6614, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"padding: 15px; border:1px solid black;\">\n all four padding will be 15px \n </p> \n \n <p style = \"padding:10px 2%; border:1px solid black;\"> \n top and bottom padding will be 10px, left and right\n padding will be 2% of the total width of the document. \n </p> \n \n <p style = \"padding: 10px 2% 10px; border:1px solid black;\">\n top padding will be 10px, left and right padding will \n be 2% of the total width of the document, bottom padding will be 10px\n </p> \n \n <p style = \"padding: 10px 2% 10px 10px; border:1px solid black;\">\n top padding will be 10px, right padding will be 2% of\n the total width of the document, bottom padding and top padding will be 10px \n </p>\n </body>\n</html> " }, { "code": null, "e": 7502, "s": 7463, "text": "It will produce the following result −" }, { "code": null, "e": 7538, "s": 7502, "text": "\n all four padding will be 15px \n" }, { "code": null, "e": 7652, "s": 7538, "text": " \n top and bottom padding will be 10px, left and right padding will be 2% of the total width of the document. \n" }, { "code": null, "e": 7781, "s": 7652, "text": "\n top padding will be 10px, left and right padding will be 2% of the total width of the document, bottom padding will be 10px\n" }, { "code": null, "e": 7918, "s": 7781, "text": "\n top padding will be 10px, right padding will be 2% of the total width of the document, bottom padding and top padding will be 10px \n" }, { "code": null, "e": 7953, "s": 7918, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7967, "s": 7953, "text": " Anadi Sharma" }, { "code": null, "e": 8002, "s": 7967, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8019, "s": 8002, "text": " Frahaan Hussain" }, { "code": null, "e": 8054, "s": 8019, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8085, "s": 8054, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8120, "s": 8085, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8151, "s": 8120, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8186, "s": 8151, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8217, "s": 8186, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8250, "s": 8217, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8281, "s": 8250, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8288, "s": 8281, "text": " Print" }, { "code": null, "e": 8299, "s": 8288, "text": " Add Notes" } ]
Review: CRF-RNN — Conditional Random Fields as Recurrent Neural Networks (Semantic Segmentation) | by Sik-Ho Tsang | Towards Data Science
In this story, CRF-RNN, Conditional Random Fields as Recurrent Neural Networks, by University of Oxford, Stanford University, and Baidu, is reviewed. CRF is one of the most successful graphical models in computer vision. It is found that Fully Convolutional Network (FCN) outputs a very coarse segmentation results. Thus, many approaches use CRF as post-processing steps to refine the output semantic segmentation map obtained from the the network, such as DeepLabv1 & DeepLabv2, to have a more fine-grained segmentation results. However, the parameters of CRF are not trained together with FCN. In other words, the FCN is unaware of CRF during training. This might limit the network capability. In CRF-RNN, authors proposed to formulate CRF as RNN so that they can integrated with FCN and train the whole network in an end-to-end manner to obtain a better results. It is a 2015 ICCV paper with over 1300 citations. (Sik-Ho Tsang @ Medium) Authors have also created a live demo for it: http://www.robots.ox.ac.uk/~szheng/crfasrnndemo Here are my trials, it is quite funny: It is quite accurate, of course I also tried some that CRF-RNN can’t work. Conditional Random Field (CRF)CRF as CNN for One IterationCRF as RNN for Multiple IterationsResults Conditional Random Field (CRF) CRF as CNN for One Iteration CRF as RNN for Multiple Iterations Results The purpose of CRF is to refine the coarse output based on the label at each location itself, and the neighboring positions’ labels and locations. Fully connected pairwise CRF is considered. Fully connected means all locations are connected as shown in the middle of the figure above. Pairwise means the connections are connected in pairs. When we are talking about CRF, we are talking about how to minimize an energy function. Here, we need to minimize the energy of a label assignment. I just treat energy as a kind of cost function. By assigning of the most probable label to each location, we can get lower energy, i.e. lower cost, and thus, higher accuracy. The CRF is characterized by Gibbs distribution of a form: where I is the input. Xi is the random variable at location i which represents the assigned label. I is discarded for simplicity. E(x) is the energy function and Z(I) is the partition function which is just the sum of all exp(-E(x)). This CRF distribution P(X) is approximated by Q(X), which is a product of independent Qi(Xi): In the paper, authors mentioned that they follows [29]. (If interested, please visit [29]. It is a 2011 NIPS paper called “Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials”.) The energy function: 1st Term, Unary Energy Ψu(xi): measures the cost if the label assignment disagrees with the initial classifier. Unary means it just takes the label of the single position into consideration at each time. 2nd Term, Pairwise Energy Ψp(xi, xj): measures the cost if two similar pixels (e.g. neighbor pixels or the pixels have similar color) take different labels: where kG is the Gaussian kernel applied on feature vectors. The feature vector can be spatial locations and RGB values, e.g. Gaussian filter and bilateral filter. And μ is the label compatibility function which assigns penalty when the labels are different. CRF is a very powerful statistical modeling method applied in various pattern recognition tasks such as text sequence classification. I can only present CRF that mentioned in this paper and in a very brief way. To be brief, the input image will go through FCN then CRF. This CRF will consider both the unary energy term and pairwise energy term, then output a more precise segmentation map. This CRF is implemented as a stack of CNN as below. Ui(l) is the unary potential provided by FCN-8s which based on VGG-16. The Qi(l) is obtained using softmax. After initialization, there will be iterations (the while loop) for a sequence of processes. M Gaussian filters are used. Following [29], two Gaussian kernels are used, one spatial and one bilateral. A weighted sum of the M filter outputs from the previous step for each class label l. When each label is considered individually, it can be viewed as 1×1 convolution with M input channels and one output channel. In contrast to [29], individual kernel weights are used for each class label. A penalty is assigned when different labels are assigned. e.g.: assigning labels “person” and “bicycle” to nearby pixels should have a lesser penalty than assigning labels “sky” and “bicycle”. Thus, μ(l, l’) is learned from the data. The output from Compatibility Transform step is subtracted element-wise from the unary inputs U. Another softmax operation. Above is the overview of one mean-field iteration. By repeating the above module, we can have multiple mean-field iterations. I is the image. U is the unary potentials from FCN. T is the total number of iterations. fθ(U,H1(t),I) is the mean-field iteration as described in the previous section where θ is the CRF parameters described in the previous section, i.e. w, μ, m, l, l’. At t = 0, the first iteration, H1(t) = softmax(U), otherwise H1(t) is the output of the previous mean-field iteration, H2(t-1). H2(t) is the output of the mean-field iteration fθ(U,H1(t),I). The final output, Y(t)=H2(T) when t=T, i.e. when the last iterations are finished. Recurrent Neural Network (RNN) setting is used, i.e. the parameters here are shared among all iterations. During training, T=5 is used to avoid vanishing/exploding gradient problem. During testing, T=10. With/Without COCO: Whether the model is trained by COCO as well. Plain FCN-8s: Lowest mean IU accuracy. With CRF but disconnected: That means CRF is not trained with FCN in end-to-end manner, higher mean IU accuracy is obtained End-to-end CRF-RNN: The highest mean IU accuracy is obtained which means end-to-end FCN+CRF is the best solution. CRF-RNN w/o COCO: It outperforms FCN-8s and DeepLab-v1. CRF-RNN with COCO: The results are even better. CRF-RNN: Higher mean IU accuracy than FCN-8s. Additional experiments are performed on PASCAL VOC 2012 Validation Set. Using different weights w for different classes increases 1.8% mean IU. T=10 during both training and testing induces 0.7% drops, which argues that there is vanishing gradient effect. Independent parameters for each iteration instead of sharing parameters, only 70.9% mean IU accuracy is obtained, which shows that recurrent structure is important. Though CRF-RNN is published in 2015, this paper has introduced an important concept/logic to me, i.e. converting/approximating a conventional/non-deep-learning approach into deep-learning-based approach and turn it into an end-to-end solution. [2015 ICCV] [CRF-RNN]Conditional Random Fields as Recurrent Neural Networks Image Classification[LeNet] [AlexNet] [ZFNet] [VGGNet] [Highway] [SPPNet] [PReLU-Net] [STN] [DeepImage] [GoogLeNet / Inception-v1] [BN-Inception / Inception-v2] [Inception-v3] [Inception-v4] [Xception] [MobileNetV1] [ResNet] [Pre-Activation ResNet] [RiR] [RoR] [Stochastic Depth] [WRN] [FractalNet] [Trimps-Soushen] [PolyNet] [ResNeXt] [DenseNet] [PyramidNet] [DRN] Object Detection[OverFeat] [R-CNN] [Fast R-CNN] [Faster R-CNN] [DeepID-Net] [CRAFT] [R-FCN] [ION] [MultiPathNet] [NoC] [G-RMI] [TDM] [SSD] [DSSD] [YOLOv1] [YOLOv2 / YOLO9000] [YOLOv3] [FPN] [RetinaNet] [DCN] Semantic Segmentation[FCN] [DeconvNet] [DeepLabv1 & DeepLabv2] [SegNet] [ParseNet] [DilatedNet] [PSPNet] [DeepLabv3] [DRN] Biomedical Image Segmentation[CUMedVision1] [CUMedVision2 / DCAN] [U-Net] [CFS-FCN] [U-Net+ResNet] [MultiChannel] Instance Segmentation[DeepMask] [SharpMask] [MultiPathNet] [MNC] [InstanceFCN] [FCIS] Super Resolution[SRCNN] [FSRCNN] [VDSR] [ESPCN] [RED-Net] [DRCN] [DRRN] [LapSRN & MS-LapSRN] [SRDenseNet]
[ { "code": null, "e": 867, "s": 171, "text": "In this story, CRF-RNN, Conditional Random Fields as Recurrent Neural Networks, by University of Oxford, Stanford University, and Baidu, is reviewed. CRF is one of the most successful graphical models in computer vision. It is found that Fully Convolutional Network (FCN) outputs a very coarse segmentation results. Thus, many approaches use CRF as post-processing steps to refine the output semantic segmentation map obtained from the the network, such as DeepLabv1 & DeepLabv2, to have a more fine-grained segmentation results. However, the parameters of CRF are not trained together with FCN. In other words, the FCN is unaware of CRF during training. This might limit the network capability." }, { "code": null, "e": 1111, "s": 867, "text": "In CRF-RNN, authors proposed to formulate CRF as RNN so that they can integrated with FCN and train the whole network in an end-to-end manner to obtain a better results. It is a 2015 ICCV paper with over 1300 citations. (Sik-Ho Tsang @ Medium)" }, { "code": null, "e": 1157, "s": 1111, "text": "Authors have also created a live demo for it:" }, { "code": null, "e": 1205, "s": 1157, "text": "http://www.robots.ox.ac.uk/~szheng/crfasrnndemo" }, { "code": null, "e": 1244, "s": 1205, "text": "Here are my trials, it is quite funny:" }, { "code": null, "e": 1319, "s": 1244, "text": "It is quite accurate, of course I also tried some that CRF-RNN can’t work." }, { "code": null, "e": 1419, "s": 1319, "text": "Conditional Random Field (CRF)CRF as CNN for One IterationCRF as RNN for Multiple IterationsResults" }, { "code": null, "e": 1450, "s": 1419, "text": "Conditional Random Field (CRF)" }, { "code": null, "e": 1479, "s": 1450, "text": "CRF as CNN for One Iteration" }, { "code": null, "e": 1514, "s": 1479, "text": "CRF as RNN for Multiple Iterations" }, { "code": null, "e": 1522, "s": 1514, "text": "Results" }, { "code": null, "e": 1669, "s": 1522, "text": "The purpose of CRF is to refine the coarse output based on the label at each location itself, and the neighboring positions’ labels and locations." }, { "code": null, "e": 1862, "s": 1669, "text": "Fully connected pairwise CRF is considered. Fully connected means all locations are connected as shown in the middle of the figure above. Pairwise means the connections are connected in pairs." }, { "code": null, "e": 2185, "s": 1862, "text": "When we are talking about CRF, we are talking about how to minimize an energy function. Here, we need to minimize the energy of a label assignment. I just treat energy as a kind of cost function. By assigning of the most probable label to each location, we can get lower energy, i.e. lower cost, and thus, higher accuracy." }, { "code": null, "e": 2243, "s": 2185, "text": "The CRF is characterized by Gibbs distribution of a form:" }, { "code": null, "e": 2477, "s": 2243, "text": "where I is the input. Xi is the random variable at location i which represents the assigned label. I is discarded for simplicity. E(x) is the energy function and Z(I) is the partition function which is just the sum of all exp(-E(x))." }, { "code": null, "e": 2571, "s": 2477, "text": "This CRF distribution P(X) is approximated by Q(X), which is a product of independent Qi(Xi):" }, { "code": null, "e": 2792, "s": 2571, "text": "In the paper, authors mentioned that they follows [29]. (If interested, please visit [29]. It is a 2011 NIPS paper called “Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials”.) The energy function:" }, { "code": null, "e": 2996, "s": 2792, "text": "1st Term, Unary Energy Ψu(xi): measures the cost if the label assignment disagrees with the initial classifier. Unary means it just takes the label of the single position into consideration at each time." }, { "code": null, "e": 3153, "s": 2996, "text": "2nd Term, Pairwise Energy Ψp(xi, xj): measures the cost if two similar pixels (e.g. neighbor pixels or the pixels have similar color) take different labels:" }, { "code": null, "e": 3316, "s": 3153, "text": "where kG is the Gaussian kernel applied on feature vectors. The feature vector can be spatial locations and RGB values, e.g. Gaussian filter and bilateral filter." }, { "code": null, "e": 3411, "s": 3316, "text": "And μ is the label compatibility function which assigns penalty when the labels are different." }, { "code": null, "e": 3622, "s": 3411, "text": "CRF is a very powerful statistical modeling method applied in various pattern recognition tasks such as text sequence classification. I can only present CRF that mentioned in this paper and in a very brief way." }, { "code": null, "e": 3802, "s": 3622, "text": "To be brief, the input image will go through FCN then CRF. This CRF will consider both the unary energy term and pairwise energy term, then output a more precise segmentation map." }, { "code": null, "e": 3854, "s": 3802, "text": "This CRF is implemented as a stack of CNN as below." }, { "code": null, "e": 3925, "s": 3854, "text": "Ui(l) is the unary potential provided by FCN-8s which based on VGG-16." }, { "code": null, "e": 3962, "s": 3925, "text": "The Qi(l) is obtained using softmax." }, { "code": null, "e": 4055, "s": 3962, "text": "After initialization, there will be iterations (the while loop) for a sequence of processes." }, { "code": null, "e": 4084, "s": 4055, "text": "M Gaussian filters are used." }, { "code": null, "e": 4162, "s": 4084, "text": "Following [29], two Gaussian kernels are used, one spatial and one bilateral." }, { "code": null, "e": 4248, "s": 4162, "text": "A weighted sum of the M filter outputs from the previous step for each class label l." }, { "code": null, "e": 4374, "s": 4248, "text": "When each label is considered individually, it can be viewed as 1×1 convolution with M input channels and one output channel." }, { "code": null, "e": 4452, "s": 4374, "text": "In contrast to [29], individual kernel weights are used for each class label." }, { "code": null, "e": 4510, "s": 4452, "text": "A penalty is assigned when different labels are assigned." }, { "code": null, "e": 4645, "s": 4510, "text": "e.g.: assigning labels “person” and “bicycle” to nearby pixels should have a lesser penalty than assigning labels “sky” and “bicycle”." }, { "code": null, "e": 4686, "s": 4645, "text": "Thus, μ(l, l’) is learned from the data." }, { "code": null, "e": 4783, "s": 4686, "text": "The output from Compatibility Transform step is subtracted element-wise from the unary inputs U." }, { "code": null, "e": 4810, "s": 4783, "text": "Another softmax operation." }, { "code": null, "e": 4861, "s": 4810, "text": "Above is the overview of one mean-field iteration." }, { "code": null, "e": 4936, "s": 4861, "text": "By repeating the above module, we can have multiple mean-field iterations." }, { "code": null, "e": 5025, "s": 4936, "text": "I is the image. U is the unary potentials from FCN. T is the total number of iterations." }, { "code": null, "e": 5190, "s": 5025, "text": "fθ(U,H1(t),I) is the mean-field iteration as described in the previous section where θ is the CRF parameters described in the previous section, i.e. w, μ, m, l, l’." }, { "code": null, "e": 5318, "s": 5190, "text": "At t = 0, the first iteration, H1(t) = softmax(U), otherwise H1(t) is the output of the previous mean-field iteration, H2(t-1)." }, { "code": null, "e": 5381, "s": 5318, "text": "H2(t) is the output of the mean-field iteration fθ(U,H1(t),I)." }, { "code": null, "e": 5464, "s": 5381, "text": "The final output, Y(t)=H2(T) when t=T, i.e. when the last iterations are finished." }, { "code": null, "e": 5570, "s": 5464, "text": "Recurrent Neural Network (RNN) setting is used, i.e. the parameters here are shared among all iterations." }, { "code": null, "e": 5646, "s": 5570, "text": "During training, T=5 is used to avoid vanishing/exploding gradient problem." }, { "code": null, "e": 5668, "s": 5646, "text": "During testing, T=10." }, { "code": null, "e": 5733, "s": 5668, "text": "With/Without COCO: Whether the model is trained by COCO as well." }, { "code": null, "e": 5772, "s": 5733, "text": "Plain FCN-8s: Lowest mean IU accuracy." }, { "code": null, "e": 5896, "s": 5772, "text": "With CRF but disconnected: That means CRF is not trained with FCN in end-to-end manner, higher mean IU accuracy is obtained" }, { "code": null, "e": 6010, "s": 5896, "text": "End-to-end CRF-RNN: The highest mean IU accuracy is obtained which means end-to-end FCN+CRF is the best solution." }, { "code": null, "e": 6066, "s": 6010, "text": "CRF-RNN w/o COCO: It outperforms FCN-8s and DeepLab-v1." }, { "code": null, "e": 6114, "s": 6066, "text": "CRF-RNN with COCO: The results are even better." }, { "code": null, "e": 6160, "s": 6114, "text": "CRF-RNN: Higher mean IU accuracy than FCN-8s." }, { "code": null, "e": 6232, "s": 6160, "text": "Additional experiments are performed on PASCAL VOC 2012 Validation Set." }, { "code": null, "e": 6304, "s": 6232, "text": "Using different weights w for different classes increases 1.8% mean IU." }, { "code": null, "e": 6416, "s": 6304, "text": "T=10 during both training and testing induces 0.7% drops, which argues that there is vanishing gradient effect." }, { "code": null, "e": 6581, "s": 6416, "text": "Independent parameters for each iteration instead of sharing parameters, only 70.9% mean IU accuracy is obtained, which shows that recurrent structure is important." }, { "code": null, "e": 6825, "s": 6581, "text": "Though CRF-RNN is published in 2015, this paper has introduced an important concept/logic to me, i.e. converting/approximating a conventional/non-deep-learning approach into deep-learning-based approach and turn it into an end-to-end solution." }, { "code": null, "e": 6901, "s": 6825, "text": "[2015 ICCV] [CRF-RNN]Conditional Random Fields as Recurrent Neural Networks" }, { "code": null, "e": 7267, "s": 6901, "text": "Image Classification[LeNet] [AlexNet] [ZFNet] [VGGNet] [Highway] [SPPNet] [PReLU-Net] [STN] [DeepImage] [GoogLeNet / Inception-v1] [BN-Inception / Inception-v2] [Inception-v3] [Inception-v4] [Xception] [MobileNetV1] [ResNet] [Pre-Activation ResNet] [RiR] [RoR] [Stochastic Depth] [WRN] [FractalNet] [Trimps-Soushen] [PolyNet] [ResNeXt] [DenseNet] [PyramidNet] [DRN]" }, { "code": null, "e": 7475, "s": 7267, "text": "Object Detection[OverFeat] [R-CNN] [Fast R-CNN] [Faster R-CNN] [DeepID-Net] [CRAFT] [R-FCN] [ION] [MultiPathNet] [NoC] [G-RMI] [TDM] [SSD] [DSSD] [YOLOv1] [YOLOv2 / YOLO9000] [YOLOv3] [FPN] [RetinaNet] [DCN]" }, { "code": null, "e": 7598, "s": 7475, "text": "Semantic Segmentation[FCN] [DeconvNet] [DeepLabv1 & DeepLabv2] [SegNet] [ParseNet] [DilatedNet] [PSPNet] [DeepLabv3] [DRN]" }, { "code": null, "e": 7712, "s": 7598, "text": "Biomedical Image Segmentation[CUMedVision1] [CUMedVision2 / DCAN] [U-Net] [CFS-FCN] [U-Net+ResNet] [MultiChannel]" }, { "code": null, "e": 7798, "s": 7712, "text": "Instance Segmentation[DeepMask] [SharpMask] [MultiPathNet] [MNC] [InstanceFCN] [FCIS]" } ]
RESTful Web Services - Methods
As we have discussed so far that RESTful web service makes heavy uses of HTTP verbs to determine the operation to be carried out on the specified resource(s). Following table states the examples of common use of HTTP Verbs. Here are important points 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 means their result will always same no matter how many times these operations are invoked. PUT and DELETE operations are idempotent means their result will always same no matter how many times these operations are invoked. PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result. PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result. Let's update Example created in RESTful Web Services - First Application tutorial to create a Web service which can perform CRUD (Create, Read, Update, Delete) operations. For simplicity, we've used a file I/O to replace Database operations. Update 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; } @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; } } 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; } 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(); } } } UserService.java 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); } @POST @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; } @PUT @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 WAR file using eclipse, follow the option File -> export -> Web > War File and finally select project UserManagement and destination folder. To deploy war file in Tomcat, place the UserManagement.war in Tomcat Installation Directory > webapps directory and start the Tomcat. Jersey provides APIs to create a Web Service Client to test web services. We've created a sample test class WebServiceTester.java under the com.tutorialspoint package in the same project. WebServiceTester.java 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) .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: 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) .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: 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'll see the following result in 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 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": 2079, "s": 1855, "text": "As we have discussed so far that RESTful web service makes heavy uses of HTTP verbs to determine the operation to be carried out on the specified resource(s). Following table states the examples of common use of HTTP Verbs." }, { "code": null, "e": 2123, "s": 2079, "text": "Here are important points to be considered:" }, { "code": null, "e": 2166, "s": 2123, "text": "GET operations are read only and are safe." }, { "code": null, "e": 2209, "s": 2166, "text": "GET operations are read only and are safe." }, { "code": null, "e": 2341, "s": 2209, "text": "PUT and DELETE operations are idempotent means their result will always same no matter how many times these operations are invoked." }, { "code": null, "e": 2473, "s": 2341, "text": "PUT and DELETE operations are idempotent means their result will always same no matter how many times these operations are invoked." }, { "code": null, "e": 2638, "s": 2473, "text": "PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result." }, { "code": null, "e": 2803, "s": 2638, "text": "PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result." }, { "code": null, "e": 3045, "s": 2803, "text": "Let's update Example created in RESTful Web Services - First Application tutorial to create a Web service which can perform CRUD (Create, Read, Update, Delete) operations. For simplicity, we've used a file I/O to replace Database operations." }, { "code": null, "e": 3137, "s": 3045, "text": "Update UserService.java, User.java,UserDao.java files under the com.tutorialspoint package." }, { "code": null, "e": 3147, "s": 3137, "text": "User.java" }, { "code": null, "e": 4526, "s": 3147, "text": "package com.tutorialspoint;\n\nimport java.io.Serializable;\n\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n@XmlRootElement(name = \"user\")\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 1L;\n private int id;\n private String name;\n private String profession;\n\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 }\t\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 ){\n return true;\n }\t\t\t\n }\n return false;\n }\t\n}" }, { "code": null, "e": 4539, "s": 4526, "text": "UserDao.java" }, { "code": null, "e": 7347, "s": 4539, "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);\t\t\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 }\t\t\n return userList;\n }\n\n public User getUser(int id){\n List<User> users = getAllUsers();\n\n for(User user: users){\n if(user.getId() == id){\n return user;\n }\n }\n return null;\n }\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 }\t\t\n if(!userExists){\n userList.add(pUser);\n saveUserList(userList);\n return 1;\n }\n return 0;\n }\n\n public int updateUser(User pUser){\n List<User> userList = getAllUsers();\n\n for(User user: userList){\n if(user.getId() == pUser.getId()){\n int index = userList.indexOf(user);\t\t\t\n userList.set(index, pUser);\n saveUserList(userList);\n return 1;\n }\n }\t\t\n return 0;\n }\n\n public int deleteUser(int id){\n List<User> userList = getAllUsers();\n\n for(User user: userList){\n if(user.getId() == id){\n int index = userList.indexOf(user);\t\t\t\n userList.remove(index);\n saveUserList(userList);\n return 1; \n }\n }\t\t\n return 0;\n }\n\n private void saveUserList(List<User> userList){\n try {\n File file = new File(\"Users.dat\");\n FileOutputStream fos;\n\n fos = new FileOutputStream(file);\n\n ObjectOutputStream oos = new ObjectOutputStream(fos);\t\t\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": 7364, "s": 7347, "text": "UserService.java" }, { "code": null, "e": 9907, "s": 7364, "text": "package com.tutorialspoint;\n\nimport java.io.IOException;\nimport java.util.List;\n\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\n@Path(\"/UserService\")\npublic class UserService {\n\t\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\n\n @GET\n @Path(\"/users\")\n @Produces(MediaType.APPLICATION_XML)\n public List<User> getUsers(){\n return userDao.getAllUsers();\n }\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\n @POST\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\n @PUT\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\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\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": 10281, "s": 9907, "text": "Now using Eclipse, export your application as a war file and deploy the same in tomcat. To create WAR file using eclipse, follow the option File -> export -> Web > War File and finally select project UserManagement and destination folder. To deploy war file in Tomcat, place the UserManagement.war in Tomcat Installation Directory > webapps directory and start the Tomcat. " }, { "code": null, "e": 10469, "s": 10281, "text": "Jersey provides APIs to create a Web Service Client to test web services. We've created a sample test class WebServiceTester.java under the com.tutorialspoint package in the same project." }, { "code": null, "e": 10491, "s": 10469, "text": "WebServiceTester.java" }, { "code": null, "e": 14592, "s": 10491, "text": "package com.tutorialspoint;\n\nimport java.util.List;\n\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\n private Client client;\n private String REST_SERVICE_URL = \"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\n private void init(){\n this.client = ClientBuilder.newClient();\n }\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\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\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 String result = PASS;\n if(!SUCCESS_RESULT.equals(callResult)){\n result = FAIL;\n }\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\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 \n String result = PASS;\n if(!SUCCESS_RESULT.equals(callResult)){\n result = FAIL;\n }\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\n String result = PASS;\n if(!SUCCESS_RESULT.equals(callResult)){\n result = FAIL;\n }\n\n System.out.println(\"Test case name: testDeleteUser, Result: \" + result );\n }\n}" }, { "code": null, "e": 14754, "s": 14592, "text": "Now run the tester using Eclipse. Right click on the file, and follow the option Run as -> Java Application. You'll see the following result in Eclipse console −" }, { "code": null, "e": 14975, "s": 14754, "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": 15009, "s": 14975, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 15024, "s": 15009, "text": " Chaand Sheikh" }, { "code": null, "e": 15057, "s": 15024, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 15080, "s": 15057, "text": " Vinod Kumar Kayartaya" }, { "code": null, "e": 15115, "s": 15080, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 15130, "s": 15115, "text": " Chaand Sheikh" }, { "code": null, "e": 15165, "s": 15130, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 15179, "s": 15165, "text": " Antonio Papa" }, { "code": null, "e": 15186, "s": 15179, "text": " Print" }, { "code": null, "e": 15197, "s": 15186, "text": " Add Notes" } ]
How can a particular group of test cases get executed in TestNG?
We can run a particular set of test cases by including a group of test cases in the execution. Testng xml files with groups. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Tutorialspoint Test"> <test name = "Regression Cycle 1"> <groups> <run> <include name = "Smoke"/> </run> </groups> <classes> <class name = "TestParam" /> </classes> </test> </suite> To run a group of test cases from the set of test cases, we have to define <groups > in the testng xml file. Here the testNG xml contains group Smoke to be included in execution. @Test(groups={"Smoke"}) public void Payment(){ System.out.println(“Payment is successful”); } In the Java class file only the test method with group as Smoke will be run out of the entire regression suite.
[ { "code": null, "e": 1157, "s": 1062, "text": "We can run a particular set of test cases by including a group of test cases\nin the execution." }, { "code": null, "e": 1187, "s": 1157, "text": "Testng xml files with groups." }, { "code": null, "e": 1556, "s": 1187, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name = \"Tutorialspoint Test\">\n <test name = \"Regression Cycle 1\">\n <groups>\n <run>\n <include name = \"Smoke\"/>\n </run>\n </groups>\n <classes>\n <class name = \"TestParam\" />\n </classes>\n </test>\n</suite>" }, { "code": null, "e": 1735, "s": 1556, "text": "To run a group of test cases from the set of test cases, we have to define <groups > in the testng xml file. Here the testNG xml contains group Smoke to be included in execution." }, { "code": null, "e": 1832, "s": 1735, "text": "@Test(groups={\"Smoke\"})\npublic void Payment(){\n System.out.println(“Payment is successful”);\n}" }, { "code": null, "e": 1944, "s": 1832, "text": "In the Java class file only the test method with group as Smoke will be run out of the entire regression suite." } ]
Organizing machine learning projects | by Jack Leitch | Towards Data Science
I just want to start with a brief disclaimer. This is how I personally organize my projects and it’s what works for me, that doesn't necessarily mean it will work for you. However, there is definitely something to be said about how good organization streamlines your workflow. Building my ML framework the way I do allows me to work in a very plug n’ play way: I can train, change, adjust my models without making too many changes to my code. Productivity. If you have a well-organized project, with everything in the same directory, you don't waste time searching for files, datasets, codes, models, etc.Reproducibility. You’ll find that a lot of your data science projects have at least some repetitively to them. For example, with the proper organization, you could easily go back and find/use the same script to split your data into folds.Understandability. A well-organized project can easily be understood by other data scientists when shared on Github. Productivity. If you have a well-organized project, with everything in the same directory, you don't waste time searching for files, datasets, codes, models, etc. Reproducibility. You’ll find that a lot of your data science projects have at least some repetitively to them. For example, with the proper organization, you could easily go back and find/use the same script to split your data into folds. Understandability. A well-organized project can easily be understood by other data scientists when shared on Github. The first thing I do whenever I start a new project is to make a folder and name it something appropriate, for example, “MNIST” or “digit_recognition”. Inside the main project folder, I always create the same subfolders: notes, input, src, models, notebooks. Don’t forget to add a README.md file as well! As intuitive as this breakdown seems, it makes one hell of a difference in productivity. What do I put in each folder? notes: I add any notes to this folder, this can be anything! URLs to useful webpages, chapters/pages of books, descriptions of variables, a rough outline of the task at hand, etc. input: This folder contains all of the input files and data for the machine learning project. For example, it may contain CSV files, text embedding, or images (in another subfolder though), to list a few things. src: Any .py file is kept in this folder. Simple. models: We keep all of our trained models in here (the useful ones...). notebooks: We can store our Jupyter notebooks here (any .ipynb file). Note that I tend to only use notebooks for data exploration and plotting. When I build my projects I like to automate as much as possible. That is, I try to repeat myself as little as possible and I like to change things like models and hyperparameters with as little code as I can. Let's look to build a very simple model to classify the MNIST dataset. For those of you that have been living under a rock, this dataset is the de facto “hello world” of computer vision. The data files train.csv and test.csv contain gray-scale images of hand-drawn digits, from zero through nine. Given the pixel intensity values (each column represents a pixel) of an image, we aim to identify which digit the image is. This is a supervised problem. Please note that the models I am creating are by no means the best for classifying this dataset, that isn't the point of this blog post. So, how do we start? Well, as with most things data science, we first need to decide on a metric. By looking at a count plot (sns.countplot() (this was done in a Jupyter notebook in the notebooks folder!)) we can see that the distribution of labels is fairly uniform, so plain and simple accuracy should do the trick! The next thing we need to do is create some cross-validation folds. The first script I added to my src folder was to do exactly this. create_folds.py reads mnist_train.csv from the input folder and creates a new file mnist_train_folds.csv (saved to the input folder) which has a new column, kfolds, containing fold numbers. As with most classification problems, I used stratified k-folds. To see the script, please check out my Github page. Now that we have decided on a metric and created folds, we can start making some basic models. With the aim of this post in mind, I decided to completely skip any kind of preprocessing (sorry!). What we are going to do is create a general python script to train our model(s), train.py, and then we will make some changes so that we hardcode as little as possible. The aim here is to be able to change a lot of things without changing much (if any) code. So, let's get cracking! # src/train.pyimport joblibimport pandas as pd from sklearn import metrics, treedef run(fold): # we first read in data with our folds df = pd.read_csv("../input/mnist_train_folds.csv") # we then split it into our training and validation data df_train = df[df.kfold != fold].reset_index(drop=True) df_valid = df[df.kfold == fold].reset_index(drop=True) # drop target column (label) and turn to np array x_train = df_train.drop('label', axis=1).values y_train = df_train.label.values # same for validation x_valid = df_valid.drop('label', axis=1).values y_valid = df_valid.label.values # initialize simple decision tree classifier and fit data clf = tree.DecisionTreeClassifier() clf.fit(x_train, y_train) # create predictions for validation data preds = clf.predict(x_valid) # calculate and print accuracy score = metrics.accuracy_score(y_valid, preds) print(f"Fold={fold}, Accuracy={score}") # save the model (not very necessary for a smaller model though) joblib.dump(clf, f"../models/dt_{fold}.bin") if __name__ == "__main__": for i in range(3): run(fold=i) We can then run this script by calling python train.py in the terminal. This script will read our data, train a decision tree classifier, score our predictions, and save the model for each fold. Note that you will need to set the working directory. For example: > cd "/Users/Jack/Documents/MNIST/src"> python train.pyFold=0, Accuracy=0.858Fold=1, Accuracy=0.860Fold=2, Accuracy=0.859 We can do a lot better than this... We have hardcoded the fold numbers, the training file, the output folder, the model, and the hyperparameters. We can change all of this. The first easy thing we can do is create a config.py file with all of the training files and output folder. # config.pyTRAINING_FILE = "../input/mnist_train_folds.csv"OUTPUT_PATH = "../models/" Changing the script to incorporate this is easy! The changes are in bold. # src/train.pyimport os import configimport joblibimport pandas as pd from sklearn import metrics, treedef run(fold): # we first read in data with our folds df = pd.read_csv(config.TRAINING_FILE) . . . # save the model joblib.dump( clf, os.path.join(config.OUTPUT_PATH, f"../models/dt_{fold}.bin") )if __name__ == "__main__": for i in range(3): run(fold=i) In our script, we call the run function for each fold. When training bigger models this can be an issue as running multiple folds in the same script will keep increasing the memory consumption. This could potentially lead to the program crashing. We can get around this by using argparse. Argparse allows us to specify arguments in the command line which get parsed through to the script. Let's see how to implement this. # src/train.pyimport argparse...if __name__ == "__main__": # initialize Argument Parser parser = argparse.ArgumentParser() # we can add any different arguments we want to parse parser.add_argument("--fold", type=int) # we then read the arguments from the comand line args = parser.parse_args() # run the fold that we specified in the command line run(fold=args.fold) So what have we done here? We have allowed us to specify the fold in the terminal. > python train.py --fold 3Fold=3, Accuracy=0.861 We can use argparse in an even more useful way though, we can change the model with this! We can create a new python script, model_dispatcher.py, that has a dictionary containing different models. In this dictionary, the keys are the names of the models and the values are the models themselves. from sklearn import tree, ensemble, linear_model, svmmodels = { "decision_tree_gini": tree.DecisionTreeClassifier( criterion="gini" ), "decision_tree_entropy": tree.DecisionTreeClassifier( criterion='entropy' ), "rf": ensemble.RandomForestClassifier(), "log_reg": linear_model.LogisticRegression(), "svc": svm.SVC(C=10, gamma=0.001, kernel="rbf")} We can then add the following things to our code. import os, argparse, joblibimport pandas as pdfrom sklearn import metricsimport configimport model_dispatcherdef run(fold, model): # we first read in data with our folds df = pd.read_csv(config.TRAINING_FILE) # we then split it into our training and validation data df_train = df[df.kfold != fold].reset_index(drop=True) df_valid = df[df.kfold == fold].reset_index(drop=True) # drop target column (label) and turn to np array x_train = df_train.drop('label', axis=1).values y_train = df_train.label.values x_valid = df_valid.drop('label', axis=1).values y_valid = df_valid.label.values # fetch model from model dispatcher clf = model_dispatcher.models[model] # fit model on training data clf.fit(x_train, y_train) # create predictions for validation data preds = clf.predict(x_valid) # calculate and print accuracy score = metrics.accuracy_score(y_valid, preds) print(f"Model={model}, Fold={fold}, Accuracy={score}") # save the model joblib.dump( clf, os.path.join(config.OUTPUT_PATH, f"../models/dt_{fold}.bin") )if __name__ == "__main__": # initialize ArgumentParser class of argparse parser = argparse.ArgumentParser() # add different arguments and their types parser.add_argument('--fold', type=int) parser.add_argument('--model', type=str) # read arguments from command line args = parser.parse_args() # run with the fold and model specified by command line arguments run( fold=args.fold, model=args.model ) And that's it, now we can choose the fold and model in the terminal! What's great about this is that to try a new model/tweak hyperparameters, all we need to do is change our model dispatcher. > python train.py --fold 2 --model rf Model=rf, Fold=2, Accuracy=0.9658333333333333 We also aren’t limited to just doing this. We can make dispatchers for loads of other things too: categorical encoders, feature selection, hyperparameter optimization, the list goes on! To go even further, we can create a shell script to try a few different models from our dispatcher at once. #!/bin/shpython train.py --fold 0 --model rfpython train.py --fold 0 --model decision_tree_ginipython train.py --fold 0 --model log_regpython train.py --fold 0 --model svc Which, when run, gives: > sh run.shModel=rf, Fold=0, Accuracy=0.9661666666666666Model=decision_tree_gini, Fold=0, Accuracy=0.8658333333333333Model=log_reg, Fold=0, Accuracy=0.917Model=svc, Fold=0, Accuracy=0.9671812654676666 I first learned how to do all of this in Abhishek Thakur’s (quadruple Kaggle Grand Master) book: Approaching (Almost) Any Machine Learning Problem. It’s a fantastic and pragmatic exploration of data science problems. I would highly recommend it. Once you’ve finished up (or during!) a problem that you find interesting make sure to create a Github repository and upload your datasets, python scripts, models, Jupyter notebooks, R scripts, etc. Creating Github repositories to showcase your work is extremely important! It also means you have some version control and you can access your code at all times. Thanks for reading and I hope you enjoyed it. Here are some of my other stories you may be interested in...
[ { "code": null, "e": 615, "s": 172, "text": "I just want to start with a brief disclaimer. This is how I personally organize my projects and it’s what works for me, that doesn't necessarily mean it will work for you. However, there is definitely something to be said about how good organization streamlines your workflow. Building my ML framework the way I do allows me to work in a very plug n’ play way: I can train, change, adjust my models without making too many changes to my code." }, { "code": null, "e": 1132, "s": 615, "text": "Productivity. If you have a well-organized project, with everything in the same directory, you don't waste time searching for files, datasets, codes, models, etc.Reproducibility. You’ll find that a lot of your data science projects have at least some repetitively to them. For example, with the proper organization, you could easily go back and find/use the same script to split your data into folds.Understandability. A well-organized project can easily be understood by other data scientists when shared on Github." }, { "code": null, "e": 1295, "s": 1132, "text": "Productivity. If you have a well-organized project, with everything in the same directory, you don't waste time searching for files, datasets, codes, models, etc." }, { "code": null, "e": 1534, "s": 1295, "text": "Reproducibility. You’ll find that a lot of your data science projects have at least some repetitively to them. For example, with the proper organization, you could easily go back and find/use the same script to split your data into folds." }, { "code": null, "e": 1651, "s": 1534, "text": "Understandability. A well-organized project can easily be understood by other data scientists when shared on Github." }, { "code": null, "e": 2045, "s": 1651, "text": "The first thing I do whenever I start a new project is to make a folder and name it something appropriate, for example, “MNIST” or “digit_recognition”. Inside the main project folder, I always create the same subfolders: notes, input, src, models, notebooks. Don’t forget to add a README.md file as well! As intuitive as this breakdown seems, it makes one hell of a difference in productivity." }, { "code": null, "e": 2075, "s": 2045, "text": "What do I put in each folder?" }, { "code": null, "e": 2255, "s": 2075, "text": "notes: I add any notes to this folder, this can be anything! URLs to useful webpages, chapters/pages of books, descriptions of variables, a rough outline of the task at hand, etc." }, { "code": null, "e": 2467, "s": 2255, "text": "input: This folder contains all of the input files and data for the machine learning project. For example, it may contain CSV files, text embedding, or images (in another subfolder though), to list a few things." }, { "code": null, "e": 2517, "s": 2467, "text": "src: Any .py file is kept in this folder. Simple." }, { "code": null, "e": 2589, "s": 2517, "text": "models: We keep all of our trained models in here (the useful ones...)." }, { "code": null, "e": 2733, "s": 2589, "text": "notebooks: We can store our Jupyter notebooks here (any .ipynb file). Note that I tend to only use notebooks for data exploration and plotting." }, { "code": null, "e": 3530, "s": 2733, "text": "When I build my projects I like to automate as much as possible. That is, I try to repeat myself as little as possible and I like to change things like models and hyperparameters with as little code as I can. Let's look to build a very simple model to classify the MNIST dataset. For those of you that have been living under a rock, this dataset is the de facto “hello world” of computer vision. The data files train.csv and test.csv contain gray-scale images of hand-drawn digits, from zero through nine. Given the pixel intensity values (each column represents a pixel) of an image, we aim to identify which digit the image is. This is a supervised problem. Please note that the models I am creating are by no means the best for classifying this dataset, that isn't the point of this blog post." }, { "code": null, "e": 3848, "s": 3530, "text": "So, how do we start? Well, as with most things data science, we first need to decide on a metric. By looking at a count plot (sns.countplot() (this was done in a Jupyter notebook in the notebooks folder!)) we can see that the distribution of labels is fairly uniform, so plain and simple accuracy should do the trick!" }, { "code": null, "e": 4289, "s": 3848, "text": "The next thing we need to do is create some cross-validation folds. The first script I added to my src folder was to do exactly this. create_folds.py reads mnist_train.csv from the input folder and creates a new file mnist_train_folds.csv (saved to the input folder) which has a new column, kfolds, containing fold numbers. As with most classification problems, I used stratified k-folds. To see the script, please check out my Github page." }, { "code": null, "e": 4767, "s": 4289, "text": "Now that we have decided on a metric and created folds, we can start making some basic models. With the aim of this post in mind, I decided to completely skip any kind of preprocessing (sorry!). What we are going to do is create a general python script to train our model(s), train.py, and then we will make some changes so that we hardcode as little as possible. The aim here is to be able to change a lot of things without changing much (if any) code. So, let's get cracking!" }, { "code": null, "e": 5908, "s": 4767, "text": "# src/train.pyimport joblibimport pandas as pd from sklearn import metrics, treedef run(fold): # we first read in data with our folds df = pd.read_csv(\"../input/mnist_train_folds.csv\") # we then split it into our training and validation data df_train = df[df.kfold != fold].reset_index(drop=True) df_valid = df[df.kfold == fold].reset_index(drop=True) # drop target column (label) and turn to np array x_train = df_train.drop('label', axis=1).values y_train = df_train.label.values # same for validation x_valid = df_valid.drop('label', axis=1).values y_valid = df_valid.label.values # initialize simple decision tree classifier and fit data clf = tree.DecisionTreeClassifier() clf.fit(x_train, y_train) # create predictions for validation data preds = clf.predict(x_valid) # calculate and print accuracy score = metrics.accuracy_score(y_valid, preds) print(f\"Fold={fold}, Accuracy={score}\") # save the model (not very necessary for a smaller model though) joblib.dump(clf, f\"../models/dt_{fold}.bin\") if __name__ == \"__main__\": for i in range(3): run(fold=i)" }, { "code": null, "e": 6170, "s": 5908, "text": "We can then run this script by calling python train.py in the terminal. This script will read our data, train a decision tree classifier, score our predictions, and save the model for each fold. Note that you will need to set the working directory. For example:" }, { "code": null, "e": 6292, "s": 6170, "text": "> cd \"/Users/Jack/Documents/MNIST/src\"> python train.pyFold=0, Accuracy=0.858Fold=1, Accuracy=0.860Fold=2, Accuracy=0.859" }, { "code": null, "e": 6465, "s": 6292, "text": "We can do a lot better than this... We have hardcoded the fold numbers, the training file, the output folder, the model, and the hyperparameters. We can change all of this." }, { "code": null, "e": 6573, "s": 6465, "text": "The first easy thing we can do is create a config.py file with all of the training files and output folder." }, { "code": null, "e": 6659, "s": 6573, "text": "# config.pyTRAINING_FILE = \"../input/mnist_train_folds.csv\"OUTPUT_PATH = \"../models/\"" }, { "code": null, "e": 6733, "s": 6659, "text": "Changing the script to incorporate this is easy! The changes are in bold." }, { "code": null, "e": 7139, "s": 6733, "text": "# src/train.pyimport os import configimport joblibimport pandas as pd from sklearn import metrics, treedef run(fold): # we first read in data with our folds df = pd.read_csv(config.TRAINING_FILE) . . . # save the model joblib.dump( clf, os.path.join(config.OUTPUT_PATH, f\"../models/dt_{fold}.bin\") )if __name__ == \"__main__\": for i in range(3): run(fold=i)" }, { "code": null, "e": 7561, "s": 7139, "text": "In our script, we call the run function for each fold. When training bigger models this can be an issue as running multiple folds in the same script will keep increasing the memory consumption. This could potentially lead to the program crashing. We can get around this by using argparse. Argparse allows us to specify arguments in the command line which get parsed through to the script. Let's see how to implement this." }, { "code": null, "e": 7957, "s": 7561, "text": "# src/train.pyimport argparse...if __name__ == \"__main__\": # initialize Argument Parser parser = argparse.ArgumentParser() # we can add any different arguments we want to parse parser.add_argument(\"--fold\", type=int) # we then read the arguments from the comand line args = parser.parse_args() # run the fold that we specified in the command line run(fold=args.fold)" }, { "code": null, "e": 8040, "s": 7957, "text": "So what have we done here? We have allowed us to specify the fold in the terminal." }, { "code": null, "e": 8089, "s": 8040, "text": "> python train.py --fold 3Fold=3, Accuracy=0.861" }, { "code": null, "e": 8385, "s": 8089, "text": "We can use argparse in an even more useful way though, we can change the model with this! We can create a new python script, model_dispatcher.py, that has a dictionary containing different models. In this dictionary, the keys are the names of the models and the values are the models themselves." }, { "code": null, "e": 8777, "s": 8385, "text": "from sklearn import tree, ensemble, linear_model, svmmodels = { \"decision_tree_gini\": tree.DecisionTreeClassifier( criterion=\"gini\" ), \"decision_tree_entropy\": tree.DecisionTreeClassifier( criterion='entropy' ), \"rf\": ensemble.RandomForestClassifier(), \"log_reg\": linear_model.LogisticRegression(), \"svc\": svm.SVC(C=10, gamma=0.001, kernel=\"rbf\")}" }, { "code": null, "e": 8827, "s": 8777, "text": "We can then add the following things to our code." }, { "code": null, "e": 10343, "s": 8827, "text": "import os, argparse, joblibimport pandas as pdfrom sklearn import metricsimport configimport model_dispatcherdef run(fold, model): # we first read in data with our folds df = pd.read_csv(config.TRAINING_FILE) # we then split it into our training and validation data df_train = df[df.kfold != fold].reset_index(drop=True) df_valid = df[df.kfold == fold].reset_index(drop=True) # drop target column (label) and turn to np array x_train = df_train.drop('label', axis=1).values y_train = df_train.label.values x_valid = df_valid.drop('label', axis=1).values y_valid = df_valid.label.values # fetch model from model dispatcher clf = model_dispatcher.models[model] # fit model on training data clf.fit(x_train, y_train) # create predictions for validation data preds = clf.predict(x_valid) # calculate and print accuracy score = metrics.accuracy_score(y_valid, preds) print(f\"Model={model}, Fold={fold}, Accuracy={score}\") # save the model joblib.dump( clf, os.path.join(config.OUTPUT_PATH, f\"../models/dt_{fold}.bin\") )if __name__ == \"__main__\": # initialize ArgumentParser class of argparse parser = argparse.ArgumentParser() # add different arguments and their types parser.add_argument('--fold', type=int) parser.add_argument('--model', type=str) # read arguments from command line args = parser.parse_args() # run with the fold and model specified by command line arguments run( fold=args.fold, model=args.model )" }, { "code": null, "e": 10536, "s": 10343, "text": "And that's it, now we can choose the fold and model in the terminal! What's great about this is that to try a new model/tweak hyperparameters, all we need to do is change our model dispatcher." }, { "code": null, "e": 10621, "s": 10536, "text": "> python train.py --fold 2 --model rf Model=rf, Fold=2, Accuracy=0.9658333333333333" }, { "code": null, "e": 10807, "s": 10621, "text": "We also aren’t limited to just doing this. We can make dispatchers for loads of other things too: categorical encoders, feature selection, hyperparameter optimization, the list goes on!" }, { "code": null, "e": 10915, "s": 10807, "text": "To go even further, we can create a shell script to try a few different models from our dispatcher at once." }, { "code": null, "e": 11087, "s": 10915, "text": "#!/bin/shpython train.py --fold 0 --model rfpython train.py --fold 0 --model decision_tree_ginipython train.py --fold 0 --model log_regpython train.py --fold 0 --model svc" }, { "code": null, "e": 11111, "s": 11087, "text": "Which, when run, gives:" }, { "code": null, "e": 11312, "s": 11111, "text": "> sh run.shModel=rf, Fold=0, Accuracy=0.9661666666666666Model=decision_tree_gini, Fold=0, Accuracy=0.8658333333333333Model=log_reg, Fold=0, Accuracy=0.917Model=svc, Fold=0, Accuracy=0.9671812654676666" }, { "code": null, "e": 11558, "s": 11312, "text": "I first learned how to do all of this in Abhishek Thakur’s (quadruple Kaggle Grand Master) book: Approaching (Almost) Any Machine Learning Problem. It’s a fantastic and pragmatic exploration of data science problems. I would highly recommend it." }, { "code": null, "e": 11918, "s": 11558, "text": "Once you’ve finished up (or during!) a problem that you find interesting make sure to create a Github repository and upload your datasets, python scripts, models, Jupyter notebooks, R scripts, etc. Creating Github repositories to showcase your work is extremely important! It also means you have some version control and you can access your code at all times." } ]
Normalize A Column In Pandas - GeeksforGeeks
11 Dec, 2020 In this article, we will learn how to normalize a column in Pandas. Let’s discuss some concepts first : Pandas: Pandas is an open-source library that’s built on top of the NumPy library. It is a Python package that provides various data structures and operations for manipulating numerical data and statistics. It’s mainly popular for importing and analyzing data much easier. Pandas is fast and it’s high-performance & productive for users. Data Normalization: Data Normalization could also be a typical practice in machine learning which consists of transforming numeric columns to a standard scale. In machine learning, some feature values differ from others multiple times. The features with higher values will dominate the learning process. Here, we will apply some techniques to normalize the column values and discuss these with the help of examples. For this, let’s understand the steps needed for normalization with Pandas. Import Library (Pandas)Import / Load / Create data.Use the technique to normalize the column. Import Library (Pandas) Import / Load / Create data. Use the technique to normalize the column. Here, we create data by some random values and apply some normalization techniques on a column. Python3 # importing packagesimport pandas as pd # create datadf = pd.DataFrame({'Column 1':[200,-4,90,13.9,5, -90,20,300.7,30,-200,400], 'Column 2':[20,30,23,45,19,38, 25,45,34,37,12]}) # view datadisplay(df) Output: Dataset consists of two columns where Column 1 is not normalized but Column 2 is normalized. So we apply normalization techniques in Column 1. Python3 df['Column 1'].plot(kind = 'bar') Output: The maximum absolute scaling rescales each feature between -1 and 1 by dividing every observation by its maximum absolute value. We can apply the maximum absolute scaling in Pandas using the .max() and .abs() methods, as shown below. Python3 # copy the datadf_max_scaled = df.copy() # apply normalization techniques on Column 1column = 'Column 1'df_max_scaled[column] = df_max_scaled[column] /df_max_scaled[column].abs().max() # view normalized datadisplay(df_max_scaled) Output: The min-max approach (often called normalization) rescales the feature to a hard and fast range of [0,1] by subtracting the minimum value of the feature then dividing by the range. We can apply the min-max scaling in Pandas using the .min() and .max() methods. Python3 # copy the datadf_min_max_scaled = df.copy() # apply normalization techniques by Column 1column = 'Column 1'df_min_max_scaled[column] = (df_min_max_scaled[column] - df_min_max_scaled[column].min()) / (df_min_max_scaled[column].max() - df_min_max_scaled[column].min()) # view normalized datadisplay(df_min_max_scaled) Output : Let’s check with this plot. Python3 df_min_max_scaled['Column 1'].plot(kind = 'bar') The z-score method (often called standardization) transforms the info into distribution with a mean of 0 and a typical deviation of 1. Each standardized value is computed by subtracting the mean of the corresponding feature then dividing by the quality deviation. Python3 # copy the datadf_z_scaled = df.copy() # apply normalization technique to Column 1column = 'Column 1'df_z_scaled[column] = (df_z_scaled[column] - df_z_scaled[column].mean()) / df_z_scaled[column].std() # view normalized data display(df_z_scaled) Output : Let’s check with this plot. Python3 df_z_scaled['Column 1'].plot(kind = 'bar') Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one. Here, we will use minmax scaler. Python3 from sklearn.preprocessing import MinMaxScalerimport numpy as np # copy the datadf_sklearn = df.copy() # apply normalization techniquescolumn = 'Column 1'df_sklearn[column] = MinMaxScaler().fit_transform(np.array(df_sklearn[column]).reshape(-1,1)) # view normalized data display(df_sklearn) Output : Let’s check with this plot: Python3 df_sklearn['Column 1'].plot(kind = 'bar') Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24874, "s": 24846, "text": "\n11 Dec, 2020" }, { "code": null, "e": 24978, "s": 24874, "text": "In this article, we will learn how to normalize a column in Pandas. Let’s discuss some concepts first :" }, { "code": null, "e": 25316, "s": 24978, "text": "Pandas: Pandas is an open-source library that’s built on top of the NumPy library. It is a Python package that provides various data structures and operations for manipulating numerical data and statistics. It’s mainly popular for importing and analyzing data much easier. Pandas is fast and it’s high-performance & productive for users." }, { "code": null, "e": 25620, "s": 25316, "text": "Data Normalization: Data Normalization could also be a typical practice in machine learning which consists of transforming numeric columns to a standard scale. In machine learning, some feature values differ from others multiple times. The features with higher values will dominate the learning process." }, { "code": null, "e": 25807, "s": 25620, "text": "Here, we will apply some techniques to normalize the column values and discuss these with the help of examples. For this, let’s understand the steps needed for normalization with Pandas." }, { "code": null, "e": 25901, "s": 25807, "text": "Import Library (Pandas)Import / Load / Create data.Use the technique to normalize the column." }, { "code": null, "e": 25925, "s": 25901, "text": "Import Library (Pandas)" }, { "code": null, "e": 25954, "s": 25925, "text": "Import / Load / Create data." }, { "code": null, "e": 25997, "s": 25954, "text": "Use the technique to normalize the column." }, { "code": null, "e": 26093, "s": 25997, "text": "Here, we create data by some random values and apply some normalization techniques on a column." }, { "code": null, "e": 26101, "s": 26093, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # create datadf = pd.DataFrame({'Column 1':[200,-4,90,13.9,5, -90,20,300.7,30,-200,400], 'Column 2':[20,30,23,45,19,38, 25,45,34,37,12]}) # view datadisplay(df)", "e": 26403, "s": 26101, "text": null }, { "code": null, "e": 26411, "s": 26403, "text": "Output:" }, { "code": null, "e": 26554, "s": 26411, "text": "Dataset consists of two columns where Column 1 is not normalized but Column 2 is normalized. So we apply normalization techniques in Column 1." }, { "code": null, "e": 26562, "s": 26554, "text": "Python3" }, { "code": "df['Column 1'].plot(kind = 'bar')", "e": 26596, "s": 26562, "text": null }, { "code": null, "e": 26604, "s": 26596, "text": "Output:" }, { "code": null, "e": 26838, "s": 26604, "text": "The maximum absolute scaling rescales each feature between -1 and 1 by dividing every observation by its maximum absolute value. We can apply the maximum absolute scaling in Pandas using the .max() and .abs() methods, as shown below." }, { "code": null, "e": 26846, "s": 26838, "text": "Python3" }, { "code": "# copy the datadf_max_scaled = df.copy() # apply normalization techniques on Column 1column = 'Column 1'df_max_scaled[column] = df_max_scaled[column] /df_max_scaled[column].abs().max() # view normalized datadisplay(df_max_scaled)", "e": 27078, "s": 26846, "text": null }, { "code": null, "e": 27086, "s": 27078, "text": "Output:" }, { "code": null, "e": 27347, "s": 27086, "text": "The min-max approach (often called normalization) rescales the feature to a hard and fast range of [0,1] by subtracting the minimum value of the feature then dividing by the range. We can apply the min-max scaling in Pandas using the .min() and .max() methods." }, { "code": null, "e": 27355, "s": 27347, "text": "Python3" }, { "code": "# copy the datadf_min_max_scaled = df.copy() # apply normalization techniques by Column 1column = 'Column 1'df_min_max_scaled[column] = (df_min_max_scaled[column] - df_min_max_scaled[column].min()) / (df_min_max_scaled[column].max() - df_min_max_scaled[column].min()) # view normalized datadisplay(df_min_max_scaled)", "e": 27678, "s": 27355, "text": null }, { "code": null, "e": 27687, "s": 27678, "text": "Output :" }, { "code": null, "e": 27715, "s": 27687, "text": "Let’s check with this plot." }, { "code": null, "e": 27723, "s": 27715, "text": "Python3" }, { "code": "df_min_max_scaled['Column 1'].plot(kind = 'bar')", "e": 27772, "s": 27723, "text": null }, { "code": null, "e": 28036, "s": 27772, "text": "The z-score method (often called standardization) transforms the info into distribution with a mean of 0 and a typical deviation of 1. Each standardized value is computed by subtracting the mean of the corresponding feature then dividing by the quality deviation." }, { "code": null, "e": 28044, "s": 28036, "text": "Python3" }, { "code": "# copy the datadf_z_scaled = df.copy() # apply normalization technique to Column 1column = 'Column 1'df_z_scaled[column] = (df_z_scaled[column] - df_z_scaled[column].mean()) / df_z_scaled[column].std() # view normalized data display(df_z_scaled)", "e": 28297, "s": 28044, "text": null }, { "code": null, "e": 28306, "s": 28297, "text": "Output :" }, { "code": null, "e": 28334, "s": 28306, "text": "Let’s check with this plot." }, { "code": null, "e": 28342, "s": 28334, "text": "Python3" }, { "code": "df_z_scaled['Column 1'].plot(kind = 'bar')", "e": 28385, "s": 28342, "text": null }, { "code": null, "e": 28625, "s": 28385, "text": "Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one. Here, we will use minmax scaler." }, { "code": null, "e": 28633, "s": 28625, "text": "Python3" }, { "code": "from sklearn.preprocessing import MinMaxScalerimport numpy as np # copy the datadf_sklearn = df.copy() # apply normalization techniquescolumn = 'Column 1'df_sklearn[column] = MinMaxScaler().fit_transform(np.array(df_sklearn[column]).reshape(-1,1)) # view normalized data display(df_sklearn)", "e": 28928, "s": 28633, "text": null }, { "code": null, "e": 28937, "s": 28928, "text": "Output :" }, { "code": null, "e": 28965, "s": 28937, "text": "Let’s check with this plot:" }, { "code": null, "e": 28973, "s": 28965, "text": "Python3" }, { "code": "df_sklearn['Column 1'].plot(kind = 'bar')", "e": 29015, "s": 28973, "text": null }, { "code": null, "e": 29039, "s": 29015, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29053, "s": 29039, "text": "Python-pandas" }, { "code": null, "e": 29060, "s": 29053, "text": "Python" }, { "code": null, "e": 29158, "s": 29060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29167, "s": 29158, "text": "Comments" }, { "code": null, "e": 29180, "s": 29167, "text": "Old Comments" }, { "code": null, "e": 29198, "s": 29180, "text": "Python Dictionary" }, { "code": null, "e": 29233, "s": 29198, "text": "Read a file line by line in Python" }, { "code": null, "e": 29255, "s": 29233, "text": "Enumerate() in Python" }, { "code": null, "e": 29287, "s": 29255, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29317, "s": 29287, "text": "Iterate over a list in Python" }, { "code": null, "e": 29359, "s": 29317, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29402, "s": 29359, "text": "Python program to convert a list to string" }, { "code": null, "e": 29439, "s": 29402, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29483, "s": 29439, "text": "Reading and Writing to text files in Python" } ]
Resolve java.sql.SQLException: No suitable driver found for localhost test?
You will get this type of exception whenever your JDBC URL is not accepted by any of the loaded JDBC drivers by the method acceptsURL. You need to mention the MySQL JDBC driver which is as follows − The MySQL JDBC url is as follows − jdbc:mysql://localhost:3306/test?useSSL=false The prototype of acceptsURL is as follows − boolean acceptsURL(String url) throws SQLException The acceptsURL returns boolean that means if the JDBC driver understands the database URL it returns true otherwise false. It takes one parameter of type String which is a database URL. The entire database URL connection is as follows. The syntax − con = DriverManager. getConnection("jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false", "yourUserName", " yourPassword"); The Java code is as follows − import java.sql.Connection; import java.sql.DriverManager; public class AvoidSQLException { public static void main(String[]args){ Connection con = null; try { con = DriverManager. getConnection("jdbc:mysql://localhost:3306/sample?useSSL=false", "root", "123456"); System.out.println("Connection is successful !!!!!"); } catch(Exception e) { e.printStackTrace(); } } } The snapshot of code is as follows − The following is the output − Connection is successful !!!!! The snapshot of the sample code is as follows −
[ { "code": null, "e": 1261, "s": 1062, "text": "You will get this type of exception whenever your JDBC URL is not accepted by any of the loaded JDBC drivers by the method acceptsURL. You need to mention the MySQL JDBC driver which is as follows −" }, { "code": null, "e": 1296, "s": 1261, "text": "The MySQL JDBC url is as follows −" }, { "code": null, "e": 1342, "s": 1296, "text": "jdbc:mysql://localhost:3306/test?useSSL=false" }, { "code": null, "e": 1386, "s": 1342, "text": "The prototype of acceptsURL is as follows −" }, { "code": null, "e": 1437, "s": 1386, "text": "boolean acceptsURL(String url) throws SQLException" }, { "code": null, "e": 1623, "s": 1437, "text": "The acceptsURL returns boolean that means if the JDBC driver understands the database URL it returns true otherwise false. It takes one parameter of type String which is a database URL." }, { "code": null, "e": 1686, "s": 1623, "text": "The entire database URL connection is as follows. The syntax −" }, { "code": null, "e": 1816, "s": 1686, "text": "con = DriverManager.\ngetConnection(\"jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false\", \"yourUserName\", \" yourPassword\");" }, { "code": null, "e": 1846, "s": 1816, "text": "The Java code is as follows −" }, { "code": null, "e": 2281, "s": 1846, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class AvoidSQLException {\n public static void main(String[]args){\n Connection con = null;\n try {\n con = DriverManager.\n getConnection(\"jdbc:mysql://localhost:3306/sample?useSSL=false\", \"root\", \"123456\");\n System.out.println(\"Connection is successful !!!!!\");\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2318, "s": 2281, "text": "The snapshot of code is as follows −" }, { "code": null, "e": 2348, "s": 2318, "text": "The following is the output −" }, { "code": null, "e": 2379, "s": 2348, "text": "Connection is successful !!!!!" }, { "code": null, "e": 2427, "s": 2379, "text": "The snapshot of the sample code is as follows −" } ]
Search insert position of K in a sorted array | Practice | GeeksforGeeks
Given a sorted array Arr[](0-index based) consisting of N distinct integers and an integer k, the task is to find the index of k, if its present in the array Arr[]. Otherwise, find the index where k must be inserted to keep the array sorted. Example 1: Input: N = 4 Arr = {1, 3, 5, 6} k = 5 Output: 2 Explaination: Since 5 is found at index 2 as Arr[2] = 5, the output is 2. Example 2: Input: N = 4 Arr = {1, 3, 5, 6} k = 2 Output: 1 Explaination: Since 2 is not present in the array but can be inserted at index 1 to make the array sorted. Your Task: You don't need to read input or print anything. Your task is to complete the function searchInsertK() which takes the array Arr[] and its size N and k as input parameters and returns the index. Expected Time Complexity: O(logN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 104 -103 ≤ Arr[i] ≤ 103 -103 ≤ k ≤ 103 0 sunnysharawat100023 minutes ago for(int i = 0;i < N; i++) { if(Arr[i] == k) { return i; } else { int j; for(int i = 0 ; i < N ; i++) { if(Arr[i] < k) { j = i; } else if(Arr[0] > k) { return 0; } } return j+1; } } +1 juyal_sid3 hours ago //C++ One Liner | Fast and Efficient Solutio | return lower_bound(Arr.begin(),Arr.end(),k)-Arr.begin(); 0 abhishek2061a1 day ago Simple C++ Solution using Binary Search int searchInsertK(vector<int>Arr, int N, int k) { // code here int low = 0, high = N-1; while(low <= high) { int mid = low + (high-low)/2; if(Arr[mid] == k) return mid; else if(Arr[mid] < k) low = mid+1; else high = mid-1; } return low; } 0 2019sushilkumarkori2 days ago class Solution{ public: int searchInsertK(vector<int>Arr, int N, int k) { // code here int low = 0; int high = N-1; while(low<=high){ int mid = (low+high)/2; if(Arr[mid] == k){ return mid; } else if(Arr[mid]>k){ high = mid-1; } else{ low = mid+1; } } return high+1; } }; 0 prabathsaisumanth2 days ago JAVA Solution(0.39/3.09) class Solution { static int searchInsertK(int arr[], int N, int k) { // code here for(int i=0;i<N-1;i++) { if(arr[i]<k&&arr[i+1]>=k) { return i+1; } else if(arr[N-2]<k&&arr[N-1]<k) { return N; } } return 0; } } 0 rohankundu8593 days ago //C++ Solution int searchInsertK(vector<int>Arr, int N, int k) { // Searching bool isfound=false; int lb=0; int ub=N-1; int mid=(lb+ub)/2; while(lb<=ub) { if(Arr[mid]==k) { isfound=true; break; } else if(Arr[mid]>k) { ub=mid-1; } else if(Arr[mid]<k) { lb=mid+1; } mid=(lb+ub)/2; } if(isfound) { return mid; } else { //inserting int count=0; bool i=false; for(auto it=Arr.begin();it!=Arr.end();it++) { count++; if(k<(*it)) { Arr.insert(it,k); i=true; break; } } if(i==false) { Arr.push_back(k); count++; } return (count-1); } } 0 debajyoti dev3 days ago O(logN) int left=0, right=N-1; while(left<=right){ int mid=(left+right)/2; if(Arr[mid]>k) right=mid-1; else if(Arr[mid]<k) left=mid+1; else return mid; } return left ; 0 ps253723 days ago Easy C++ Solution just check if the element in the array is greater than or equal to the given k Now return the index wherever you find the element greater than the given k int searchInsertK(vector<int>Arr, int N, int k) { // code here for(int i=0; i<N; i++){ if(Arr[i] >= k){ return i; } } } 0 sarthakpandey20023 days ago EASY C++ SOLUTION int ans=0; int searchInsertK(vector<int>Arr, int N, int k) { // code here for(int i=0;i<N;i++){ if(Arr[i]<k) ans=i+1; else if(Arr[i]==k) ans=i; } return ans; } -1 sarthakjagetiya10013 days ago Total Time Taken: 0.03/2.2 C++ int searchInsertK(vector<int>Arr, int N, int k) { for(int i=0; i<N; i++){ if(Arr[i]==k || Arr[i]>k){ return i; } } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 480, "s": 238, "text": "Given a sorted array Arr[](0-index based) consisting of N distinct integers and an integer k, the task is to find the index of k, if its present in the array Arr[]. Otherwise, find the index where k must be inserted to keep the array sorted." }, { "code": null, "e": 492, "s": 480, "text": "\nExample 1:" }, { "code": null, "e": 615, "s": 492, "text": "Input:\nN = 4\nArr = {1, 3, 5, 6}\nk = 5\nOutput: 2\nExplaination: Since 5 is found at index 2 \nas Arr[2] = 5, the output is 2." }, { "code": null, "e": 627, "s": 615, "text": "\nExample 2:" }, { "code": null, "e": 785, "s": 627, "text": "Input:\nN = 4\nArr = {1, 3, 5, 6}\nk = 2\nOutput: 1\nExplaination: Since 2 is not present in \nthe array but can be inserted at index 1 \nto make the array sorted.\n" }, { "code": null, "e": 991, "s": 785, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function searchInsertK() which takes the array Arr[] and its size N and k as input parameters and returns the index." }, { "code": null, "e": 1057, "s": 991, "text": "\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1118, "s": 1057, "text": "\nConstraints:\n1 ≤ N ≤ 104\n-103 ≤ Arr[i] ≤ 103\n-103 ≤ k ≤ 103" }, { "code": null, "e": 1120, "s": 1118, "text": "0" }, { "code": null, "e": 1152, "s": 1120, "text": "sunnysharawat100023 minutes ago" }, { "code": null, "e": 1675, "s": 1152, "text": " for(int i = 0;i < N; i++)\n {\n if(Arr[i] == k)\n {\n return i;\n }\n else \n {\n int j;\n for(int i = 0 ; i < N ; i++)\n {\n if(Arr[i] < k)\n {\n j = i;\n }\n else if(Arr[0] > k)\n {\n return 0;\n }\n }\n return j+1;\n }\n }\n\n\n " }, { "code": null, "e": 1682, "s": 1679, "text": "+1" }, { "code": null, "e": 1703, "s": 1682, "text": "juyal_sid3 hours ago" }, { "code": null, "e": 1808, "s": 1703, "text": "//C++ One Liner | Fast and Efficient Solutio | \nreturn lower_bound(Arr.begin(),Arr.end(),k)-Arr.begin();" }, { "code": null, "e": 1810, "s": 1808, "text": "0" }, { "code": null, "e": 1833, "s": 1810, "text": "abhishek2061a1 day ago" }, { "code": null, "e": 1873, "s": 1833, "text": "Simple C++ Solution using Binary Search" }, { "code": null, "e": 2311, "s": 1875, "text": "int searchInsertK(vector<int>Arr, int N, int k)\n {\n // code here\n int low = 0, high = N-1;\n \n while(low <= high)\n {\n int mid = low + (high-low)/2;\n \n if(Arr[mid] == k)\n return mid;\n \n else if(Arr[mid] < k)\n low = mid+1;\n \n else\n high = mid-1;\n }\n \n return low;\n }" }, { "code": null, "e": 2313, "s": 2311, "text": "0" }, { "code": null, "e": 2343, "s": 2313, "text": "2019sushilkumarkori2 days ago" }, { "code": null, "e": 2810, "s": 2343, "text": "class Solution{\n public:\n int searchInsertK(vector<int>Arr, int N, int k)\n {\n // code here\n int low = 0;\n int high = N-1;\n while(low<=high){\n int mid = (low+high)/2;\n if(Arr[mid] == k){\n return mid;\n }\n else if(Arr[mid]>k){\n high = mid-1;\n }\n else{\n low = mid+1;\n }\n }\n return high+1;\n }\n};" }, { "code": null, "e": 2812, "s": 2810, "text": "0" }, { "code": null, "e": 2840, "s": 2812, "text": "prabathsaisumanth2 days ago" }, { "code": null, "e": 2865, "s": 2840, "text": "JAVA Solution(0.39/3.09)" }, { "code": null, "e": 3232, "s": 2865, "text": "class Solution\n{\n static int searchInsertK(int arr[], int N, int k)\n {\n // code here\n for(int i=0;i<N-1;i++)\n {\n if(arr[i]<k&&arr[i+1]>=k)\n {\n return i+1;\n }\n else if(arr[N-2]<k&&arr[N-1]<k)\n {\n return N;\n }\n }\n return 0;\n }\n}" }, { "code": null, "e": 3234, "s": 3232, "text": "0" }, { "code": null, "e": 3258, "s": 3234, "text": "rohankundu8593 days ago" }, { "code": null, "e": 3274, "s": 3258, "text": "//C++ Solution " }, { "code": null, "e": 4282, "s": 3276, "text": " int searchInsertK(vector<int>Arr, int N, int k) { // Searching bool isfound=false; int lb=0; int ub=N-1; int mid=(lb+ub)/2; while(lb<=ub) { if(Arr[mid]==k) { isfound=true; break; } else if(Arr[mid]>k) { ub=mid-1; } else if(Arr[mid]<k) { lb=mid+1; } mid=(lb+ub)/2; } if(isfound) { return mid; } else { //inserting int count=0; bool i=false; for(auto it=Arr.begin();it!=Arr.end();it++) { count++; if(k<(*it)) { Arr.insert(it,k); i=true; break; } } if(i==false) { Arr.push_back(k); count++; } return (count-1); } }" }, { "code": null, "e": 4284, "s": 4282, "text": "0" }, { "code": null, "e": 4308, "s": 4284, "text": "debajyoti dev3 days ago" }, { "code": null, "e": 4316, "s": 4308, "text": "O(logN)" }, { "code": null, "e": 4553, "s": 4316, "text": "\t\tint left=0, right=N-1;\n\t\t\n while(left<=right){\n int mid=(left+right)/2;\n if(Arr[mid]>k) right=mid-1;\n else if(Arr[mid]<k) left=mid+1;\n else return mid;\n }\n return left ;" }, { "code": null, "e": 4557, "s": 4555, "text": "0" }, { "code": null, "e": 4575, "s": 4557, "text": "ps253723 days ago" }, { "code": null, "e": 4672, "s": 4575, "text": "Easy C++ Solution just check if the element in the array is greater than or equal to the given k" }, { "code": null, "e": 4748, "s": 4672, "text": "Now return the index wherever you find the element greater than the given k" }, { "code": null, "e": 4924, "s": 4748, "text": "int searchInsertK(vector<int>Arr, int N, int k) { // code here for(int i=0; i<N; i++){ if(Arr[i] >= k){ return i; } } }" }, { "code": null, "e": 4926, "s": 4924, "text": "0" }, { "code": null, "e": 4954, "s": 4926, "text": "sarthakpandey20023 days ago" }, { "code": null, "e": 4972, "s": 4954, "text": "EASY C++ SOLUTION" }, { "code": null, "e": 5202, "s": 4972, "text": "int ans=0; int searchInsertK(vector<int>Arr, int N, int k) { // code here for(int i=0;i<N;i++){ if(Arr[i]<k) ans=i+1; else if(Arr[i]==k) ans=i; } return ans; }" }, { "code": null, "e": 5205, "s": 5202, "text": "-1" }, { "code": null, "e": 5235, "s": 5205, "text": "sarthakjagetiya10013 days ago" }, { "code": null, "e": 5262, "s": 5235, "text": "Total Time Taken: 0.03/2.2" }, { "code": null, "e": 5266, "s": 5262, "text": "C++" }, { "code": null, "e": 5447, "s": 5266, "text": "int searchInsertK(vector<int>Arr, int N, int k)\n {\n for(int i=0; i<N; i++){\n if(Arr[i]==k || Arr[i]>k){\n return i;\n }\n }\n }" }, { "code": null, "e": 5593, "s": 5447, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5629, "s": 5593, "text": " Login to access your submissions. " }, { "code": null, "e": 5639, "s": 5629, "text": "\nProblem\n" }, { "code": null, "e": 5649, "s": 5639, "text": "\nContest\n" }, { "code": null, "e": 5712, "s": 5649, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5860, "s": 5712, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6068, "s": 5860, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6174, "s": 6068, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C Program to count trailing and leading zeros in a binary number
To begin with, let us understand what are trailing zeros in a binary number. The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number. 104 is decimal number Binary number of 104 is: (MSB) 1101000(LSB) Here, MSB refers to Most Significant Bit. LSB refers to Least Significant Bit. From LSB after the first bit set, there are three zero. The number of trailing zeros is three. Following is the program to count number of trailing zeros for a given number − Live Demo #include<stdio.h> #include<stdlib.h> int main(){ int number, i, trail = 0, size; printf("Enter a number\n"); scanf("%d",&number); size = sizeof(number) * 8; for(i = 0; i < size; i++){ if((number >> i) & 1) { break; } trail++; } printf("Number of trailing ZERO is = %d", trail); return 0; } When the above program is executed, it produces the following result − Enter a number 24 Number of trailing ZERO is = 3 If the position of zero before bit is set to one, they are termed as leading zeros. 94 is decimal number. Binary number of 94 is: (MSB) .....001011110(LSB) Number of Leading ZERO is = 25 Given below is the program to count number of leading zeros for a given number. Live Demo #include<stdio.h> #include<stdlib.h> int main(){ int number, i, lead = 0, Msb,size; printf("Enter a number\n"); scanf("%d",&number); size = sizeof(number) * 8; Msb=1<<(size-1); for(i = 0; i < size; i++){ if((number << i) & Msb) { break; } lead++; } printf("Number of Leading ZERO is = %d", lead); return 0; } When the above program is executed, it produces the following result − Enter a number 94 Number of Leading ZERO is = 25
[ { "code": null, "e": 1139, "s": 1062, "text": "To begin with, let us understand what are trailing zeros in a binary number." }, { "code": null, "e": 1260, "s": 1139, "text": "The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number." }, { "code": null, "e": 1282, "s": 1260, "text": "104 is decimal number" }, { "code": null, "e": 1326, "s": 1282, "text": "Binary number of 104 is: (MSB) 1101000(LSB)" }, { "code": null, "e": 1332, "s": 1326, "text": "Here," }, { "code": null, "e": 1368, "s": 1332, "text": "MSB refers to Most Significant Bit." }, { "code": null, "e": 1405, "s": 1368, "text": "LSB refers to Least Significant Bit." }, { "code": null, "e": 1461, "s": 1405, "text": "From LSB after the first bit set, there are three zero." }, { "code": null, "e": 1500, "s": 1461, "text": "The number of trailing zeros is three." }, { "code": null, "e": 1580, "s": 1500, "text": "Following is the program to count number of trailing zeros for a given number −" }, { "code": null, "e": 1591, "s": 1580, "text": " Live Demo" }, { "code": null, "e": 1932, "s": 1591, "text": "#include<stdio.h>\n#include<stdlib.h>\nint main(){\n int number, i, trail = 0, size;\n printf(\"Enter a number\\n\");\n scanf(\"%d\",&number);\n size = sizeof(number) * 8;\n for(i = 0; i < size; i++){\n if((number >> i) & 1) {\n break;\n }\n trail++;\n }\n printf(\"Number of trailing ZERO is = %d\", trail);\n return 0;\n}" }, { "code": null, "e": 2003, "s": 1932, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2052, "s": 2003, "text": "Enter a number\n24\nNumber of trailing ZERO is = 3" }, { "code": null, "e": 2136, "s": 2052, "text": "If the position of zero before bit is set to one, they are termed as leading zeros." }, { "code": null, "e": 2158, "s": 2136, "text": "94 is decimal number." }, { "code": null, "e": 2208, "s": 2158, "text": "Binary number of 94 is: (MSB) .....001011110(LSB)" }, { "code": null, "e": 2239, "s": 2208, "text": "Number of Leading ZERO is = 25" }, { "code": null, "e": 2319, "s": 2239, "text": "Given below is the program to count number of leading zeros for a given number." }, { "code": null, "e": 2330, "s": 2319, "text": " Live Demo" }, { "code": null, "e": 2693, "s": 2330, "text": "#include<stdio.h>\n#include<stdlib.h>\nint main(){\n int number, i, lead = 0, Msb,size;\n printf(\"Enter a number\\n\");\n scanf(\"%d\",&number);\n size = sizeof(number) * 8;\n Msb=1<<(size-1);\n for(i = 0; i < size; i++){\n if((number << i) & Msb) {\n break;\n }\n lead++;\n }\n printf(\"Number of Leading ZERO is = %d\", lead);\n return 0;\n}" }, { "code": null, "e": 2764, "s": 2693, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2813, "s": 2764, "text": "Enter a number\n94\nNumber of Leading ZERO is = 25" } ]
Custom list split in Python
Data analytics throws complex scenarios where the data need to be wrangled to moved around. In this context let’s see how we can take a big list and split it into many sublists as per the requirement. In this article we will explore the approaches to achieve this. In this approach we use list dicing to get the elements from the point at which the splitting has to happen. Then we use zip and for loop to create the sublists using a for loop. Live Demo Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] # The indexes to split at split_points = [2, 5, 8] # Given list print("Given list : " + str(Alist)) # SPlit at print("The points of splitting : ",split_points) #Perform the split split_list = [Alist[i: j] for i, j in zip([0] + split_points, split_points + [None])] # printing result print("The split lists are : ", split_list) Running the above code gives us the following result − Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] The points of splitting : [2, 5, 8] The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]] The chain function makes an iterator that returns elements from the first iterable until it is exhausted. So it marks the points where the splitting happens. Then we use the zip function to package the result of splitting into sublists. Live Demo from itertools import chain Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] # The indexes to split at split_points = [2, 5, 8] # Given list print("Given list : ", str(Alist)) # Split at print("The points of splitting : ",split_points) # to perform custom list split sublists = zip(chain([0], split_points), chain(split_points, [None])) split_list = list(Alist[i : j] for i, j in sublists) # printing result print("The split lists are : ", split_list) Running the above code gives us the following result − Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4] The points of splitting : [2, 5, 8] The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]
[ { "code": null, "e": 1327, "s": 1062, "text": "Data analytics throws complex scenarios where the data need to be wrangled to moved around. In this context let’s see how we can take a big list and split it into many sublists as per the requirement. In this article we will explore the approaches to achieve this." }, { "code": null, "e": 1506, "s": 1327, "text": "In this approach we use list dicing to get the elements from the point at which the splitting has to happen. Then we use zip and for loop to create the sublists using a for loop." }, { "code": null, "e": 1517, "s": 1506, "text": " Live Demo" }, { "code": null, "e": 1911, "s": 1517, "text": "Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]\n\n# The indexes to split at\nsplit_points = [2, 5, 8]\n\n# Given list\nprint(\"Given list : \" + str(Alist))\n\n# SPlit at\nprint(\"The points of splitting : \",split_points)\n\n#Perform the split\nsplit_list = [Alist[i: j] for i, j in zip([0] +\nsplit_points, split_points + [None])]\n\n# printing result\nprint(\"The split lists are : \", split_list)\n" }, { "code": null, "e": 1966, "s": 1911, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2151, "s": 1966, "text": "Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]\nThe points of splitting : [2, 5, 8]\nThe split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]" }, { "code": null, "e": 2388, "s": 2151, "text": "The chain function makes an iterator that returns elements from the first iterable until it is exhausted. So it marks the points where the splitting happens. Then we use the zip function to package the result of splitting into sublists." }, { "code": null, "e": 2399, "s": 2388, "text": " Live Demo" }, { "code": null, "e": 2869, "s": 2399, "text": "from itertools import chain\nAlist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]\n\n# The indexes to split at\nsplit_points = [2, 5, 8]\n\n# Given list\nprint(\"Given list : \", str(Alist))\n\n# Split at\nprint(\"The points of splitting : \",split_points)\n\n# to perform custom list split\nsublists = zip(chain([0], split_points), chain(split_points, [None]))\nsplit_list = list(Alist[i : j] for i, j in sublists)\n\n# printing result\nprint(\"The split lists are : \", split_list)\n" }, { "code": null, "e": 2924, "s": 2869, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3109, "s": 2924, "text": "Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]\nThe points of splitting : [2, 5, 8]\nThe split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]" } ]
When to use yield instead of return in Python?
In short, whenever control reach the return statement in your program, the execution of the program is terminated and the remaining statements will not executed. However, in case of yield, whenever control reach the yield statement in your program, the execution of your program is paused and later we can continue other statements in function. Let’s understand both the statements in detail. Using yield statement in a function makes the function a generator function which can be used in a loop. When the function is running and the yield statement exeucutes, the value after the yield is passed back to the loop that called it. The next time the loop iterates, the function starts immediately after the yield statements. def func(): yield 1 yield 2 yield 3 for num in func(): print(num * num) 1 4 9 In above program, the loop that invokes the function will complete when the func function completes – either meets the end of the function (func()) or a return statement. However, any new loop that uses the same generator function will execute the function from the start again. A return statement, Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above). Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above). If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above). If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above). It is recommended to use yield when we want to iterate over a sequence however, because of resource constraints or simply don’t want to store the entire sequence in memory. For other cases we can think of using return statement. Let’s look at another program using yield statement to generate square of integer number. def Square(): i = 1; # An Infinite loop to generate squares while True: yield i*i i += 1 # Next execution resumes from this point for num in Square(): if num > 100: break print(num) 1 4 9 16 25 36 49 64 81 100 The yield statement is generally not used in the try clause of a try .... finally block because there’s no guarantee that the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.
[ { "code": null, "e": 1224, "s": 1062, "text": "In short, whenever control reach the return statement in your program, the execution of the program is terminated and the remaining statements will not executed." }, { "code": null, "e": 1407, "s": 1224, "text": "However, in case of yield, whenever control reach the yield statement in your program, the execution of your program is paused and later we can continue other statements in function." }, { "code": null, "e": 1455, "s": 1407, "text": "Let’s understand both the statements in detail." }, { "code": null, "e": 1786, "s": 1455, "text": "Using yield statement in a function makes the function a generator function which can be used in a loop. When the function is running and the yield statement exeucutes, the value after the yield is passed back to the loop that called it. The next time the loop iterates, the function starts immediately after the yield statements." }, { "code": null, "e": 1871, "s": 1786, "text": "def func():\n yield 1\n yield 2\n yield 3\n\nfor num in func():\n print(num * num)" }, { "code": null, "e": 1877, "s": 1871, "text": "1\n4\n9" }, { "code": null, "e": 2048, "s": 1877, "text": "In above program, the loop that invokes the function will complete when the func function completes – either meets the end of the function (func()) or a return statement." }, { "code": null, "e": 2156, "s": 2048, "text": "However, any new loop that uses the same generator function will execute the function from the start again." }, { "code": null, "e": 2176, "s": 2156, "text": "A return statement," }, { "code": null, "e": 2361, "s": 2176, "text": "Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above)." }, { "code": null, "e": 2546, "s": 2361, "text": "Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above)." }, { "code": null, "e": 2678, "s": 2546, "text": "If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above)." }, { "code": null, "e": 2810, "s": 2678, "text": "If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above)." }, { "code": null, "e": 3039, "s": 2810, "text": "It is recommended to use yield when we want to iterate over a sequence however, because of resource constraints or simply don’t want to store the entire sequence in memory. For other cases we can think of using return statement." }, { "code": null, "e": 3129, "s": 3039, "text": "Let’s look at another program using yield statement to generate square of integer number." }, { "code": null, "e": 3344, "s": 3129, "text": "def Square():\n i = 1;\n # An Infinite loop to generate squares\n while True:\n yield i*i\n i += 1 # Next execution resumes from this point\nfor num in Square():\n if num > 100:\n break\n print(num)" }, { "code": null, "e": 3372, "s": 3344, "text": "1\n4\n9\n16\n25\n36\n49\n64\n81\n100" }, { "code": null, "e": 3596, "s": 3372, "text": "The yield statement is generally not used in the try clause of a try .... finally block because there’s no guarantee that the generator will ever be resumed, hence no guarantee that the finally block will ever get executed." } ]
How to get the square root of 2 in JavaScript?
To get the square root of 2, use the JavaScript Math SQRT2 property. It returns the square root of 2 which is approximately 1.414. You can try to run the following code to get the square root of 2 in JavaScript − <html> <head> <title>JavaScript Math SQRT2 Property</title> </head> <body> <script> var property_value = Math.SQRT2 document.write("Property Value: " + property_value); </script> </body> </html>
[ { "code": null, "e": 1193, "s": 1062, "text": "To get the square root of 2, use the JavaScript Math SQRT2 property. It returns the square root of 2 which is approximately 1.414." }, { "code": null, "e": 1275, "s": 1193, "text": "You can try to run the following code to get the square root of 2 in JavaScript −" }, { "code": null, "e": 1518, "s": 1275, "text": "<html>\n <head>\n <title>JavaScript Math SQRT2 Property</title>\n </head>\n <body>\n <script>\n var property_value = Math.SQRT2\n document.write(\"Property Value: \" + property_value);\n </script>\n </body>\n</html>" } ]
GANs vs. Autoencoders: Comparison of Deep Generative Models | by Matthew Stewart, PhD Researcher | Towards Data Science
“Generative Adversarial Networks is the most interesting idea in the last 10 years in Machine Learning.” — Yann LeCun, Director of AI Research at Facebook AI Part 1 of this tutorial can be found here: towardsdatascience.com Part 2of this tutorial can be found here: towardsdatascience.com These articles are based on lectures taken at Harvard on AC209b, with major credit going to lecturer Pavlos Protopapas of the Harvard IACS department. This is the third part of a three-part tutorial on creating deep generative models specifically using generative adversarial networks. This is a natural extension to the previous topic on variational autoencoders (found here). We will see that GANs are typically superior as deep generative models as compared to variational autoencoders. However, they are notoriously difficult to work with and require a lot of data and tuning. We will also examine a hybrid model of GAN called a VAE-GAN. This part of the tutorial will mostly be a coding implementation of variational autoencoders (VAEs), GANs, and will also show the reader how to make a VAE-GAN. VAE for CelebA Dataset DC-GAN for CelebA Dataset DC-GAN for Anime Dataset VAE-GAN for Anime Dataset I strongly recommend the reader to review at least part 1 of the GAN tutorial, as well as my variational autoencoder walkthrough before going further, as otherwise, the implementation may not may much sense to the reader. All related code can now be found in my GitHub repository: github.com Let’s begin! The CelebFaces Attributes Dataset (CelebA) is a large-scale face attributes dataset with more than 200K celebrity images, each with 40 attribute annotations. The images in this dataset cover large pose variations and background clutter. CelebA has large diversities, large quantities, and rich annotations, including 10,177 number of identities, 202,599 number of face images, and 5 landmark locations, 40 binary attributes annotations per image. You can download the dataset from Kaggle here: www.kaggle.com The first step is to import all our necessary functions and extract the data. Imports import shutilimport errnoimport zipfileimport osimport matplotlib.pyplot as plt Extract Data # Only run once to unzip imageszip_ref = zipfile.ZipFile('img_align_celeba.zip','r')zip_ref.extractall()zip_ref.close() Custom Image Generator This step is likely something most readers have not used before. Due to the huge size of our data, it may not be possible to load the dataset into the memory of your Jupyter Notebook. This is a pretty normal problem to have when working on large datasets. A workaround for this is to use a stream generator, which streams batches of data (images in this case) into memory sequentially, thereby limiting the amount of memory that is required for the function. The caveat to this is that they are a bit complicated to understand and code, as they require a reasonable understanding of computer memory, GPU architecture, etc. # data generator# source from https://medium.com/@ensembledme/writing-custom-keras-generators-fe815d992c5afrom skimage.io import imreaddef get_input(path): """get specific image from path""" img = imread(path) return imgdef get_output(path, label_file = None): """get all the labels relative to the image of path""" img_id = path.split('/')[-1] labels = label_file.loc[img_id].values return labelsdef preprocess_input(img): # convert between 0 and 1 return img.astype('float32') / 127.5 -1def image_generator(files, label_file, batch_size = 32): while True: batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] for input_path in batch_paths: input = get_input(input_path) input = preprocess_input(input) output = get_output(input_path, label_file = label_file) batch_input += [input] batch_output += [output] batch_x = np.array(batch_input) batch_y = np.array(batch_output) yield batch_x, batch_ydef auto_encoder_generator(files, batch_size = 32): while True: batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] for input_path in batch_paths: input = get_input(input_path) input = preprocess_input(input) output = input batch_input += [input] batch_output += [output] batch_x = np.array(batch_input) batch_y = np.array(batch_output) yield batch_x, batch_y For more information on writing custom generators in Keras, a good article to check out is the one I referenced in the above code: medium.com Load the Attribute Data Not only do we have images for this dataset, but each image also has a list of attributes corresponding to aspects of the celebrity. For example, there are attributes describing whether the celebrity is wearing lipstick, or a hat, whether they are young or not, whether they have black hair, etc. # now load attribute# 1.A.2import pandas as pdattr = pd.read_csv('list_attr_celeba.csv')attr = attr.set_index('image_id')# check if attribute successful loadedattr.describe() Finish Making the Generator Now we finish making the generator. We set the image name length to 6 since we have a 6 digit number of images in our dataset. This section of code should make sense after reading the custom Keras generator article. import numpy as npfrom sklearn.model_selection import train_test_splitIMG_NAME_LENGTH = 6file_path = "img_align_celeba/"img_id = np.arange(1,len(attr.index)+1)img_path = []for i in range(len(img_id)): img_path.append(file_path + (IMG_NAME_LENGTH - len(str(img_id[i])))*'0' + str(img_id[i]) + '.jpg')# pick 80% as training set and 20% as validation settrain_path = img_path[:int((0.8)*len(img_path))]val_path = img_path[int((0.8)*len(img_path)):]train_generator = auto_encoder_generator(train_path,32)val_generator = auto_encoder_generator(val_path,32) We can now pick three images and check that attributes make sense. fig, ax = plt.subplots(1, 3, figsize=(12, 4))for i in range(3): ax[i].imshow(get_input(img_path[i])) ax[i].axis('off') ax[i].set_title(img_path[i][-10:])plt.show() attr.iloc[:3] First, we will create and compile a Convolutional VAE Model (including encoder and decoder) for the celebrity faces dataset. More Imports from keras.models import Sequential, Modelfrom keras.layers import Dropout, Flatten, Dense, Conv2D, MaxPooling2D, Input, Reshape, UpSampling2D, InputLayer, Lambda, ZeroPadding2D, Cropping2D, Conv2DTranspose, BatchNormalizationfrom keras.utils import np_utils, to_categoricalfrom keras.losses import binary_crossentropyfrom keras import backend as K,objectivesfrom keras.losses import mse, binary_crossentropy Model Architecture Now we can create and make a summary of the model. b_size = 128n_size = 512def sampling(args): z_mean, z_log_sigma = args epsilon = K.random_normal(shape = (n_size,) , mean = 0, stddev = 1) return z_mean + K.exp(z_log_sigma/2) * epsilon def build_conv_vae(input_shape, bottleneck_size, sampling, batch_size = 32): # ENCODER input = Input(shape=(input_shape[0],input_shape[1],input_shape[2])) x = Conv2D(32,(3,3),activation = 'relu', padding = 'same')(input) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(64,(3,3),activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(128,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(256,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) # Latent Variable Calculation shape = K.int_shape(x) flatten_1 = Flatten()(x) dense_1 = Dense(bottleneck_size, name='z_mean')(flatten_1) z_mean = BatchNormalization()(dense_1) flatten_2 = Flatten()(x) dense_2 = Dense(bottleneck_size, name ='z_log_sigma')(flatten_2) z_log_sigma = BatchNormalization()(dense_2) z = Lambda(sampling)([z_mean, z_log_sigma]) encoder = Model(input, [z_mean, z_log_sigma, z], name = 'encoder') # DECODER latent_input = Input(shape=(bottleneck_size,), name = 'decoder_input') x = Dense(shape[1]*shape[2]*shape[3])(latent_input) x = Reshape((shape[1],shape[2],shape[3]))(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,0],[0,1]])(x) x = Conv2DTranspose(256,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,1],[0,1]])(x) x = Conv2DTranspose(128,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,1],[0,1]])(x) x = Conv2DTranspose(64,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Conv2DTranspose(32,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) output = Conv2DTranspose(3,(3,3), activation = 'tanh', padding ='same')(x) decoder = Model(latent_input, output, name = 'decoder') output_2 = decoder(encoder(input)[2]) vae = Model(input, output_2, name ='vae') return vae, encoder, decoder, z_mean, z_log_sigmavae_2, encoder, decoder, z_mean, z_log_sigma = build_conv_vae(img_sample.shape, n_size, sampling, batch_size = b_size)print("encoder summary:")encoder.summary()print("decoder summary:")decoder.summary()print("vae summary:")vae_2.summary() Define the VAE Loss def vae_loss(input_img, output): # Compute error in reconstruction reconstruction_loss = mse(K.flatten(input_img) , K.flatten(output)) # Compute the KL Divergence regularization term kl_loss = - 0.5 * K.sum(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis = -1) # Return the average loss over all images in batch total_loss = (reconstruction_loss + 0.0001 * kl_loss) return total_loss Compile the Model vae_2.compile(optimizer='rmsprop', loss= vae_loss)encoder.compile(optimizer = 'rmsprop', loss = vae_loss)decoder.compile(optimizer = 'rmsprop', loss = vae_loss) Train the Model vae_2.fit_generator(train_generator, steps_per_epoch = 4000, validation_data = val_generator, epochs=7, validation_steps= 500) We randomly choose some images of the training set, run them through the encoder to parameterize the latent code, and then reconstruct the images with the decoder. import randomx_test = []for i in range(64): x_test.append(get_input(img_path[random.randint(0,len(img_id))]))x_test = np.array(x_test)figure_Decoded = vae_2.predict(x_test.astype('float32')/127.5 -1, batch_size = b_size)figure_original = x_test[0]figure_decoded = (figure_Decoded[0]+1)/2for i in range(4): plt.axis('off') plt.subplot(2,4,1+i*2) plt.imshow(x_test[i]) plt.axis('off') plt.subplot(2,4,2 + i*2) plt.imshow((figure_Decoded[i]+1)/2) plt.axis('off')plt.show() Notice that the reconstructed images share similarities with the original versions. However, the new images are a bit blurry, which is a known phenomenon of VAEs. This has been hypothesized to be due to the fact that variational inference optimizes a lower bound to the likelihood, not the actual likelihood itself. Latent Space Representation We can choose two images with different attributes and plot their latent space representations. Notice that we can see some differences between the latent codes, which we might hypothesize as explaining the differences between the original images. # Choose two images of different attributes, and plot the original and latent space of itx_test1 = []for i in range(64): x_test1.append(get_input(img_path[np.random.randint(0,len(img_id))]))x_test1 = np.array(x_test)x_test_encoded = np.array(encoder.predict(x_test1/127.5-1, batch_size = b_size))figure_original_1 = x_test[0]figure_original_2 = x_test[1]Encoded1 = (x_test_encoded[0,0,:].reshape(32, 16,)+1)/2 Encoded2 = (x_test_encoded[0,1,:].reshape(32, 16)+1)/2plt.figure(figsize=(8, 8))plt.subplot(2,2,1)plt.imshow(figure_original_1)plt.subplot(2,2,2)plt.imshow(Encoded1)plt.subplot(2,2,3)plt.imshow(figure_original_2)plt.subplot(2,2,4)plt.imshow(Encoded2)plt.show() Sampling from Latent Space We can randomly sample 15 latent codes and decode them to generate new celebrity faces. We can see from this representation that the images generated by our model is of great similar styles with those images in our training set and it is also of good reality and variations. # We randomly generated 15 images from 15 series of noise informationn = 3m = 5digit_size1 = 218digit_size2 = 178figure = np.zeros((digit_size1 * n, digit_size2 * m,3)) for i in range(3): for j in range(5): z_sample = np.random.rand(1,512) x_decoded = decoder.predict([z_sample]) figure[i * digit_size1: (i + 1) * digit_size1, j * digit_size2: (j + 1) * digit_size2,:] = (x_decoded[0]+1)/2 plt.figure(figsize=(10, 10))plt.imshow(figure)plt.show() So it seems that our VAE model is not particularly good. With more time and better selection of hyperparameters and so on, we would probably have achieved a better result than this. Now let us compare this result to a DC-GAN on the same dataset. Since we have already set up the stream generator, there is not too much work to do to get the DC-GAN model up and running. # Create and compile a DC-GAN model, and print the summaryfrom keras.utils import np_utilsfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, Flatten, LeakyReLU,\ BatchNormalization, Conv2DTranspose, Conv2D, Reshapefrom keras.layers.advanced_activations import LeakyReLUfrom keras.optimizers import Adam, RMSpropfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport randomfrom tqdm import tqdm_notebookfrom scipy.misc import imresizedef generator_model(latent_dim=100, leaky_alpha=0.2, init_stddev=0.02): g = Sequential() g.add(Dense(4*4*512, input_shape=(latent_dim,), kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(Reshape(target_shape=(4, 4, 512))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(256, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(128, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(3, kernel_size=4, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(Activation('tanh')) g.summary() #g.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return g def discriminator_model(leaky_alpha=0.2, init_stddev=0.02): d = Sequential() d.add(Conv2D(64, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev), input_shape=(32, 32, 3))) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Conv2D(128, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(BatchNormalization()) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Conv2D(256, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(BatchNormalization()) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Flatten()) d.add(Dense(1, kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(Activation('sigmoid')) d.summary() return ddef DCGAN(sample_size=100): # Generator g = generator_model(sample_size, 0.2, 0.02) # Discriminator d = discriminator_model(0.2, 0.02) d.compile(optimizer=Adam(lr=0.001, beta_1=0.5), loss='binary_crossentropy') d.trainable = False # GAN gan = Sequential([g, d]) gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return gan, g, d The above code is just for the architecture of the generator and discriminator network. Comparing this method of coding the GAN to that which I did in part 2 is a good idea, you can see this one is less clean and we did not define global parameters, so there are many places we could have potential errors. Now we define a bunch of functions to make our life easier, these are mostly just for the preprocessing and plotting of images to help us in analyzing the network output. def load_image(filename, size=(32, 32)): img = plt.imread(filename) # crop rows, cols = img.shape[:2] crop_r, crop_c = 150, 150 start_row, start_col = (rows - crop_r) // 2, (cols - crop_c) // 2 end_row, end_col = rows - start_row, cols - start_row img = img[start_row:end_row, start_col:end_col, :] # resize img = imresize(img, size) return imgdef preprocess(x): return (x/255)*2-1def deprocess(x): return np.uint8((x+1)/2*255)def make_labels(size): return np.ones([size, 1]), np.zeros([size, 1]) def show_losses(losses): losses = np.array(losses) fig, ax = plt.subplots() plt.plot(losses.T[0], label='Discriminator') plt.plot(losses.T[1], label='Generator') plt.title("Validation Losses") plt.legend() plt.show()def show_images(generated_images): n_images = len(generated_images) cols = 5 rows = n_images//cols plt.figure(figsize=(8, 6)) for i in range(n_images): img = deprocess(generated_images[i]) ax = plt.subplot(rows, cols, i+1) plt.imshow(img) plt.xticks([]) plt.yticks([]) plt.tight_layout() plt.show() Train the Model We now define the training function. As we did before, notice that we switch between setting the discriminator to be trainable and untrainable (we did this implicitly in part 2). def train(sample_size=100, epochs=3, batch_size=128, eval_size=16, smooth=0.1): batchCount=len(train_path)//batch_size y_train_real, y_train_fake = make_labels(batch_size) y_eval_real, y_eval_fake = make_labels(eval_size) # create a GAN, a generator and a discriminator gan, g, d = DCGAN(sample_size) losses = [] for e in range(epochs): print('-'*15, 'Epoch %d' % (e+1), '-'*15) for i in tqdm_notebook(range(batchCount)): path_batch = train_path[i*batch_size:(i+1)*batch_size] image_batch = np.array([preprocess(load_image(filename)) for filename in path_batch]) noise = np.random.normal(0, 1, size=(batch_size, noise_dim)) generated_images = g.predict_on_batch(noise) # Train discriminator on generated images d.trainable = True d.train_on_batch(image_batch, y_train_real*(1-smooth)) d.train_on_batch(generated_images, y_train_fake) # Train generator d.trainable = False g_loss=gan.train_on_batch(noise, y_train_real) # evaluate test_path = np.array(val_path)[np.random.choice(len(val_path), eval_size, replace=False)] x_eval_real = np.array([preprocess(load_image(filename)) for filename in test_path]) noise = np.random.normal(loc=0, scale=1, size=(eval_size, sample_size)) x_eval_fake = g.predict_on_batch(noise) d_loss = d.test_on_batch(x_eval_real, y_eval_real) d_loss += d.test_on_batch(x_eval_fake, y_eval_fake) g_loss = gan.test_on_batch(noise, y_eval_real) losses.append((d_loss/2, g_loss)) print("Epoch: {:>3}/{} Discriminator Loss: {:>6.4f} Generator Loss: {:>6.4f}".format( e+1, epochs, d_loss, g_loss)) show_images(x_eval_fake[:10]) # show the result show_losses(losses) show_images(g.predict(np.random.normal(loc=0, scale=1, size=(15, sample_size)))) return gnoise_dim=100train() The output of this function will give us the following output for each epoch: It will also plot our validation losses for the discriminator and generator. The generated images look reasonable. Here we can see that our model performed adequately, though the quality of images is not so good as those in the training set (since we reshaped the images to become smaller and made them more blurry than the original ones). However, they are vivid enough to create valid faces, and these faces are close enough to reality. Also, compared with images produced by VAE, the images are more creative and real-looking. So it seems that the GAN performs superior in this circumstance. Now let us try a new dataset and see how well a GAN can perform compared to a hybrid variant, the VAE-GAN. In this section, we will aim to generate faces in the same style as the Anime dataset using a GAN, as well as another special form of GAN, a VAE-GAN. The term VAE-GAN was first used by Larsen et. al in their paper “Autoencoding beyond pixels using a learned similarity metric”. VAE-GAN models differentiate themselves from GANs in that their generators are variation autoencoders. First, we will focus on the DC-GAN. The Anime dataset consists of over 20K anime faces in the form of 64x64 images. We will also need to create another Keras Custom Data Generator. A link to the dataset can be found here: github.com The first thing we need to do is create anime directory and download the data. This can be done from the link above. It is always good practice to check the data before moving ahead, so we do this now. from skimage import ioimport matplotlib.pyplot as pltfilePath='anime-faces/data/'imgSets=[]for i in range(1,20001): imgName=filePath+str(i)+'.png' imgSets.append(io.imread(imgName))plt.imshow(imgSets[1234])plt.axis('off')plt.show() We now create and compile our DC-GAN model. # Create and compile a DC-GAN modelfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, \ Flatten, LeakyReLU, BatchNormalization, Conv2DTranspose, Conv2D, Reshapefrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2Dfrom keras.optimizers import Adam, RMSprop,SGDfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport os, globfrom PIL import Imagefrom tqdm import tqdm_notebookimage_shape = (64, 64, 3)#noise_shape = (100,)Noise_dim = 128img_rows = 64img_cols = 64channels = 3def generator_model(latent_dim=100, leaky_alpha=0.2): model = Sequential() # layer1 (None,500)>>(None,128*16*16) model.add(Dense(128 * 16 * 16, activation="relu", input_shape=(Noise_dim,))) # (None,16*16*128)>>(None,16,16,128) model.add(Reshape((16, 16, 128))) # (None,16,16,128)>>(None,32,32,128) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation("relu")) #(None,32,32,128)>>(None,64,64,128) model.add(UpSampling2D()) # (None,64,64,128)>>(None,64,64,64) model.add(Conv2D(128, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation("relu")) # (None,64,64,128)>>(None,64,64,32) model.add(Conv2D(32, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation("relu")) # (None,64,64,32)>>(None,64,64,3) model.add(Conv2D(channels, kernel_size=3, padding="same")) model.add(Activation("tanh")) model.summary() model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef discriminator_model(leaky_alpha=0.2, dropRate=0.3): model = Sequential() # layer1 (None,64,64,3)>>(None,32,32,32) model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding="same")) model.add(LeakyReLU(alpha=leaky_alpha)) model.add(Dropout(dropRate)) # layer2 (None,32,32,32)>>(None,16,16,64) model.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) # model.add(ZeroPadding2D(padding=((0, 1), (0, 1)))) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=leaky_alpha)) model.add(Dropout(dropRate)) # (None,16,16,64)>>(None,8,8,128) model.add(Conv2D(128, kernel_size=3, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,128)>>(None,8,8,256) model.add(Conv2D(256, kernel_size=3, strides=1, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,256)>>(None,8,8,64) model.add(Conv2D(64, kernel_size=3, strides=1, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,64) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) model.summary() sgd=SGD(lr=0.0002) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef DCGAN(sample_size=Noise_dim): # generator g = generator_model(sample_size, 0.2) # discriminator d = discriminator_model(0.2) d.trainable = False # GAN gan = Sequential([g, d]) sgd=SGD() gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return gan, g, ddef get_image(image_path, width, height, mode): image = Image.open(image_path) #print(image.size) return np.array(image.convert(mode))def get_batch(image_files, width, height, mode): data_batch = np.array([get_image(sample_file, width, height, mode) \ for sample_file in image_files]) return data_batchdef show_imgs(generator,epoch): row=3 col = 5 noise = np.random.normal(0, 1, (row * col, Noise_dim)) gen_imgs = generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(row, col) #fig.suptitle("DCGAN: Generated digits", fontsize=12) cnt = 0 for i in range(row): for j in range(col): axs[i, j].imshow(gen_imgs[cnt, :, :, :]) axs[i, j].axis('off') cnt += 1 #plt.close() plt.show() We can now train the model on the Anime dataset. We will do this in two different ways, the first will involve training the discriminator and generator with a 1:1 proportion of training times. # Training the discriminator and generator with the 1:1 proportion of training timesdef train(epochs=30, batchSize=128): filePath = r'anime-faces/data/' X_train = get_batch(glob.glob(os.path.join(filePath, '*.png'))[:20000], 64, 64, 'RGB') X_train = (X_train.astype(np.float32) - 127.5) / 127.5 halfSize = int(batchSize / 2) batchCount=int(len(X_train)/batchSize) dLossReal = [] dLossFake = [] gLossLogs = [] gan, generator, discriminator = DCGAN(Noise_dim) for e in range(epochs): for i in tqdm_notebook(range(batchCount)): index = np.random.randint(0, X_train.shape[0], halfSize) images = X_train[index] noise = np.random.normal(0, 1, (halfSize, Noise_dim)) genImages = generator.predict(noise) # one-sided labels discriminator.trainable = True dLossR = discriminator.train_on_batch(images, np.ones([halfSize, 1])) dLossF = discriminator.train_on_batch(genImages, np.zeros([halfSize, 1])) dLoss = np.add(dLossF, dLossR) * 0.5 discriminator.trainable = False noise = np.random.normal(0, 1, (batchSize, Noise_dim)) gLoss = gan.train_on_batch(noise, np.ones([batchSize, 1])) dLossReal.append([e, dLoss[0]]) dLossFake.append([e, dLoss[1]]) gLossLogs.append([e, gLoss]) dLossRealArr = np.array(dLossReal) dLossFakeArr = np.array(dLossFake) gLossLogsArr = np.array(gLossLogs) # At the end of training plot the losses vs epochs show_imgs(generator, e) plt.plot(dLossRealArr[:, 0], dLossRealArr[:, 1], label="Discriminator Loss - Real") plt.plot(dLossFakeArr[:, 0], dLossFakeArr[:, 1], label="Discriminator Loss - Fake") plt.plot(gLossLogsArr[:, 0], gLossLogsArr[:, 1], label="Generator Loss") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.title('GAN') plt.grid(True) plt.show() return gan, generator, discriminatorGAN,Generator,Discriminator=train(epochs=20, batchSize=128) train(epochs=1000, batchSize=128, plotInternal=200) The output will now start printing a series of anime characters. They are very grainy at first, and over time gradually become more and more pronounced. We will also get a plot of our generator and discriminator loss functions. Now we will do the same but with different training times for the discriminator and generator to see what the effect has been. Before moving forward, it is good to save the weights of the model somewhere so that you do not need to run the entire training again, and can instead just load the weights into the network. To save the weights: discriminator.save_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')gan.save_weights('/content/gdrive/My Drive/gan_DCGAN_lr0.0001_deepgenerator+proportion2.h5')generator.save_weights('/content/gdrive/My Drive/generator_DCGAN_lr0.0001_deepgenerator+proportion2.h5') To load the weights: discriminator.load_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')gan.load_weights('/content/gdrive/My Drive/gan_DCGAN_lr0.0001_deepgenerator+proportion2.h5')generator.load_weights('/content/gdrive/My Drive/generator_DCGAN_lr0.0001_deepgenerator+proportion2.h5') Now we move onto the second network implementation without worrying about saving over our previous network. # Train the discriminator and generator separately and with different training timesdef train(epochs=300, batchSize=128, plotInternal=50): gLoss = 1 filePath = r'anime-faces/data/' X_train = get_batch(glob.glob(os.path.join(filePath,'*.png'))[:20000],64,64,'RGB') X_train=(X_train.astype(np.float32)-127.5)/127.5 halfSize= int (batchSize/2) dLossReal=[] dLossFake=[] gLossLogs=[] for e in range(epochs): index=np.random.randint(0,X_train.shape[0],halfSize) images=X_train[index] noise=np.random.normal(0,1,(halfSize,Noise_dim)) genImages=generator.predict(noise) if e < int(epochs*0.5): #one-sided labels discriminator.trainable=True dLossR=discriminator.train_on_batch(images,np.ones([halfSize,1])) dLossF=discriminator.train_on_batch(genImages,np.zeros([halfSize,1])) dLoss=np.add(dLossF,dLossR)*0.5 discriminator.trainable=False cnt = e while cnt > 3: cnt = cnt - 4 if cnt == 0: noise=np.random.normal(0,1,(batchSize,Noise_dim)) gLoss=gan.train_on_batch(noise,np.ones([batchSize,1])) elif e>= int(epochs*0.5) : cnt = e while cnt > 3: cnt = cnt - 4 if cnt == 0: #one-sided labels discriminator.trainable=True dLossR=discriminator.train_on_batch(images,np.ones([halfSize,1])) dLossF=discriminator.train_on_batch(genImages,np.zeros([halfSize,1])) dLoss=np.add(dLossF,dLossR)*0.5 discriminator.trainable=False noise=np.random.normal(0,1,(batchSize,Noise_dim)) gLoss=gan.train_on_batch(noise,np.ones([batchSize,1])) if e % 20 == 0: print("epoch: %d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (e, dLoss[0], 100 * dLoss[1], gLoss)) dLossReal.append([e,dLoss[0]]) dLossFake.append([e,dLoss[1]]) gLossLogs.append([e,gLoss]) if e % plotInternal == 0 and e!=0: show_imgs(generator, e) dLossRealArr= np.array(dLossReal) dLossFakeArr = np.array(dLossFake) gLossLogsArr = np.array(gLossLogs) chk = e while chk > 50: chk = chk - 51 if chk == 0: discriminator.save_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') gan.save_weights('/content/gdrive/My Drive/gan_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') generator.save_weights('/content/gdrive/My Drive/generator_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') # At the end of training plot the losses vs epochs plt.plot(dLossRealArr[:, 0], dLossRealArr[:, 1], label="Discriminator Loss - Real") plt.plot(dLossFakeArr[:, 0], dLossFakeArr[:, 1], label="Discriminator Loss - Fake") plt.plot(gLossLogsArr[:, 0], gLossLogsArr[:, 1], label="Generator Loss") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.title('GAN') plt.grid(True) plt.show() return gan, generator, discriminatorgan, generator, discriminator = DCGAN(Noise_dim)train(epochs=4000, batchSize=128, plotInternal=200) Let us compare the output of these two networks. By running the line: show_imgs(Generator) the network will output some images from the generator (this is one of the functions we defined earlier). Now let’s check the second model. We can see that the details of the generated images are improved and the texture of them are slightly more detailed. However, in comparison to the training images they are still sub-par. Perhaps the VAE-GAN will perform better? To reiterate what I said previously about the VAE-GAN, the term VAE-GAN was first used by Larsen et. al in their paper “Autoencoding beyond pixels using a learned similarity metric”. VAE-GAN models differentiate themselves from GANs in that their generators are variation autoencoders. First we need to create and compile the VAE-GAN and make a summary for each of the networks (this is a good way to simply check the architecture). # Create and compile a VAE-GAN, and make a summary for themfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, \ Flatten, LeakyReLU, BatchNormalization, Conv2DTranspose, Conv2D, Reshape,MaxPooling2D,UpSampling2D,InputLayer, Lambdafrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2Dfrom keras.optimizers import Adam, RMSprop,SGDfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport os, globfrom PIL import Imageimport pandas as pdfrom scipy.stats import normimport kerasfrom keras.utils import np_utils, to_categoricalfrom keras import backend as Kimport randomfrom keras import metricsfrom tqdm import tqdm# plotInternalplotInternal = 50#######latent_dim = 256batch_size = 256rows = 64columns = 64channel = 3epochs = 4000# datasize = len(dataset)# optimizersSGDop = SGD(lr=0.0003)ADAMop = Adam(lr=0.0002)# filtersfilter_of_dis = 16filter_of_decgen = 16filter_of_encoder = 16def sampling(args): mean, logsigma = args epsilon = K.random_normal(shape=(K.shape(mean)[0], latent_dim), mean=0., stddev=1.0) return mean + K.exp(logsigma / 2) * epsilondef vae_loss(X , output , E_mean, E_logsigma): # compute the average MSE error, then scale it up, ie. simply sum on all axes reconstruction_loss = 2 * metrics.mse(K.flatten(X), K.flatten(output)) # compute the KL loss kl_loss = - 0.5 * K.sum(1 + E_logsigma - K.square(E_mean) - K.exp(E_logsigma), axis=-1) total_loss = K.mean(reconstruction_loss + kl_loss) return total_loss def encoder(kernel, filter, rows, columns, channel): X = Input(shape=(rows, columns, channel)) model = Conv2D(filters=filter, kernel_size=kernel, strides=2, padding='same')(X) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Flatten()(model) mean = Dense(latent_dim)(model) logsigma = Dense(latent_dim, activation='tanh')(model) latent = Lambda(sampling, output_shape=(latent_dim,))([mean, logsigma]) meansigma = Model([X], [mean, logsigma, latent]) meansigma.compile(optimizer=SGDop, loss='mse') return meansigmadef decgen(kernel, filter, rows, columns, channel): X = Input(shape=(latent_dim,)) model = Dense(2*2*256)(X) model = Reshape((2, 2, 256))(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=channel, kernel_size=kernel, strides=2, padding='same')(model) model = Activation('tanh')(model) model = Model(X, model) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef discriminator(kernel, filter, rows, columns, channel): X = Input(shape=(rows, columns, channel)) model = Conv2D(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(X) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) dec = BatchNormalization(epsilon=1e-5)(model) dec = LeakyReLU(alpha=0.2)(dec) dec = Flatten()(dec) dec = Dense(1, activation='sigmoid')(dec) output = Model(X, dec) output.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5), metrics=['accuracy']) return output def VAEGAN(decgen,discriminator): # generator g = decgen # discriminator d = discriminator d.trainable = False # GAN gan = Sequential([g, d]) # sgd=SGD() gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return g, d, gan We once again define some functions so that we can just print images from the generator. def get_image(image_path, width, height, mode): image = Image.open(image_path) #print(image.size) return np.array(image.convert(mode))def show_imgs(generator): row=3 col = 5 noise = np.random.normal(0, 1, (row*col, latent_dim)) gen_imgs = generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(row, col) #fig.suptitle("DCGAN: Generated digits", fontsize=12) cnt = 0 for i in range(row): for j in range(col): axs[i, j].imshow(gen_imgs[cnt, :, :, :]) axs[i, j].axis('off') cnt += 1 #plt.close() plt.show() The parameters of the generator will be affected by both the GAN and VAE training. # note: The parameters of the generator will be affected by both the GAN and VAE trainingG, D, GAN = VAEGAN(decgen(5, filter_of_decgen, rows, columns, channel),discriminator(5, filter_of_dis, rows, columns, channel))# encoderE = encoder(5, filter_of_encoder, rows, columns, channel)print("This is the summary for encoder:")E.summary()# generator/decoder# G = decgen(5, filter_of_decgen, rows, columns, channel)print("This is the summary for dencoder/generator:")G.summary()# discriminator# D = discriminator(5, filter_of_dis, rows, columns, channel)print("This is the summary for discriminator:")D.summary()D_fixed = discriminator(5, filter_of_dis, rows, columns, channel)D_fixed.compile(optimizer=SGDop, loss='mse')# ganprint("This is the summary for GAN:")GAN.summary()# VAEX = Input(shape=(rows, columns, channel))E_mean, E_logsigma, Z = E(X)output = G(Z)# G_dec = G(E_mean + E_logsigma)# D_fake, F_fake = D(output)# D_fromGen, F_fromGen = D(G_dec)# D_true, F_true = D(X)# print("type(E)",type(E))# print("type(output)",type(output))# print("type(D_fake)",type(D_fake))VAE = Model(X, output)VAE.add_loss(vae_loss(X, output, E_mean, E_logsigma))VAE.compile(optimizer=SGDop)print("This is the summary for vae:")VAE.summary() In the below cell we begin training our model. Note that we use the previous method to train the discriminator and GAN and VAE for different lengths of time. We emphasize the training of the discriminator in the first half of the training process and we train the generator more in the second half because we want to improve the quality of output images. # We train our model in this celldLoss=[]gLoss=[]GLoss = 1GlossEnc = 1GlossGen = 1Eloss = 1halfbatch_size = int(batch_size*0.5)for epoch in tqdm(range(epochs)): if epoch < int(epochs*0.5): noise = np.random.normal(0, 1, (halfbatch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], halfbatch_size) images = dataset[index] latent_vect = E.predict(images)[0] encImg = G.predict(latent_vect) fakeImg = G.predict(noise) D.Trainable = True DlossTrue = D.train_on_batch(images, np.ones((halfbatch_size, 1))) DlossEnc = D.train_on_batch(encImg, np.ones((halfbatch_size, 1))) DlossFake = D.train_on_batch(fakeImg, np.zeros((halfbatch_size, 1)))# DLoss=np.add(DlossTrue,DlossFake)*0.5 DLoss=np.add(DlossTrue,DlossEnc) DLoss=np.add(DLoss,DlossFake)*0.33 D.Trainable = False cnt = epoch while cnt > 3: cnt = cnt - 4 if cnt == 0: noise = np.random.normal(0, 1, (batch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], batch_size) images = dataset[index] latent_vect = E.predict(images)[0] GlossEnc = GAN.train_on_batch(latent_vect, np.ones((batch_size, 1))) GlossGen = GAN.train_on_batch(noise, np.ones((batch_size, 1))) Eloss = VAE.train_on_batch(images, None) GLoss=np.add(GlossEnc,GlossGen) GLoss=np.add(GLoss,Eloss)*0.33 dLoss.append([epoch,DLoss[0]]) gLoss.append([epoch,GLoss]) elif epoch >= int(epochs*0.5): cnt = epoch while cnt > 3: cnt = cnt - 4 if cnt == 0: noise = np.random.normal(0, 1, (halfbatch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], halfbatch_size) images = dataset[index] latent_vect = E.predict(images)[0] encImg = G.predict(latent_vect) fakeImg = G.predict(noise) D.Trainable = True DlossTrue = D.train_on_batch(images, np.ones((halfbatch_size, 1))) # DlossEnc = D.train_on_batch(encImg, np.ones((halfbatch_size, 1))) DlossFake = D.train_on_batch(fakeImg, np.zeros((halfbatch_size, 1))) DLoss=np.add(DlossTrue,DlossFake)*0.5 # DLoss=np.add(DlossTrue,DlossEnc)# DLoss=np.add(DLoss,DlossFake)*0.33 D.Trainable = False noise = np.random.normal(0, 1, (batch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], batch_size) images = dataset[index] latent_vect = E.predict(images)[0] GlossEnc = GAN.train_on_batch(latent_vect, np.ones((batch_size, 1))) GlossGen = GAN.train_on_batch(noise, np.ones((batch_size, 1))) Eloss = VAE.train_on_batch(images, None) GLoss=np.add(GlossEnc,GlossGen) GLoss=np.add(GLoss,Eloss)*0.33 dLoss.append([epoch,DLoss[0]]) gLoss.append([epoch,GLoss]) if epoch % plotInternal == 0 and epoch!=0: show_imgs(G) dLossArr= np.array(dLoss) gLossArr = np.array(gLoss) # print("dLossArr.shape:",dLossArr.shape)# print("gLossArr.shape:",gLossArr.shape) chk = epoch while chk > 50: chk = chk - 51 if chk == 0: D.save_weights('/content/gdrive/My Drive/VAE discriminator_kernalsize5_proportion_32.h5') G.save_weights('/content/gdrive/My Drive/VAE generator_kernalsize5_proportion_32.h5') E.save_weights('/content/gdrive/My Drive/VAE encoder_kernalsize5_proportion_32.h5') if epoch%20 == 0: print("epoch:", epoch + 1," ", "DislossTrue loss:",DlossTrue[0],"D accuracy:",100* DlossTrue[1], "DlossFake loss:", DlossFake[0],"GlossEnc loss:", GlossEnc, "GlossGen loss:",GlossGen, "Eloss loss:",Eloss)# print("loss:")# print("D:", DlossTrue, DlossEnc, DlossFake)# print("G:", GlossEnc, GlossGen)# print("VAE:", Eloss)print('Training done,saving weights')D.save_weights('/content/gdrive/My Drive/VAE discriminator_kernalsize5_proportion_32.h5')G.save_weights('/content/gdrive/My Drive/VAE generator_kernalsize5_proportion_32.h5')E.save_weights('/content/gdrive/My Drive/VAE encoder_kernalsize5_proportion_32.h5')print('painting losses')# At the end of training plot the losses vs epochsplt.plot(dLossArr[:, 0], dLossArr[:, 1], label="Discriminator Loss")plt.plot(gLossArr[:, 0], gLossArr[:, 1], label="Generator Loss")plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()plt.title('GAN')plt.grid(True)plt.show()print('end') If you are planning on running this network, beware that the training process takes a REALLY long time. I would not attempt this unless you have access to some powerful GPUs or are willing to run the model for an entire day. Now our VAE-GAN training is complete, we can check to see how our output images look and compare them to our previous GANs. # In this cell, we generate and visualize 15 images. show_imgs(G) We can see that in this implementation of VAE-GAN, we got a nice model which can generate images that are clear and of a similar style to the original images. Our VAE-GAN can create images more robustly and this can be done without extra noise of the anime faces. However, the competence of generalization of our model is not very good, it seldom changes the manner or sex of the character, so this is a point that we could try to improve. It is not necessarily clear that any one of the models is better than the others, and none of these methods have been optimized properly so it is difficult to make a comparison. This is still an active area of research, so if you are interested I recommend getting yourself stuck in and try and use GANs within your own work to see what you can come up with. I hope you have enjoyed this trilogy of articles on GANs and now have a much better idea of what they are, what they can do, and how to make your own. Thank you for reading! For updates on new blog posts and extra content, sign up for my newsletter. mailchi.mp Run BigGAN in COLAB: https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/biggan_generation_with_tf_hub.ipynb More code help + examples: https://www.jessicayung.com/explaining-tensorflow-code-for-a-convolutional-neural-network/ https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html https://github.com/tensorlayer/srgan https://junyanz.github.io/CycleGAN/ https://affinelayer.com/pixsrv/ https://tcwang0509.github.io/pix2pixHD/ Influential Papers: DCGAN https://arxiv.org/pdf/1511.06434v2.pdf Wasserstein GAN (WGAN) https://arxiv.org/pdf/1701.07875.pdf Conditional Generative Adversarial Nets (CGAN) https://arxiv.org/pdf/1411.1784v1.pdf Deep Generative Image Models using a Laplacian Pyramid of Adversarial Networks (LAPGAN) https://arxiv.org/pdf/1506.05751.pdf Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network (SRGAN) https://arxiv.org/pdf/1609.04802.pdf Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks (CycleGAN) https://arxiv.org/pdf/1703.10593.pdf InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets https://arxiv.org/pdf/1606.03657 DCGAN https://arxiv.org/pdf/1704.00028.pdf Improved Training of Wasserstein GANs (WGAN-GP) https://arxiv.org/pdf/1701.07875.pdf Energy-based Generative Adversarial Network (EBGAN) https://arxiv.org/pdf/1609.03126.pdf Autoencoding beyond pixels using a learned similarity metric (VAE-GAN) https://arxiv.org/pdf/1512.09300.pdf Adversarial Feature Learning (BiGAN) https://arxiv.org/pdf/1605.09782v6.pdf Stacked Generative Adversarial Networks (SGAN) https://arxiv.org/pdf/1612.04357.pdf StackGAN++: Realistic Image Synthesis with Stacked Generative Adversarial Networks https://arxiv.org/pdf/1710.10916.pdf Learning from Simulated and Unsupervised Images through Adversarial Training (SimGAN) https://arxiv.org/pdf/1612.07828v1.pdf
[ { "code": null, "e": 330, "s": 172, "text": "“Generative Adversarial Networks is the most interesting idea in the last 10 years in Machine Learning.” — Yann LeCun, Director of AI Research at Facebook AI" }, { "code": null, "e": 373, "s": 330, "text": "Part 1 of this tutorial can be found here:" }, { "code": null, "e": 396, "s": 373, "text": "towardsdatascience.com" }, { "code": null, "e": 438, "s": 396, "text": "Part 2of this tutorial can be found here:" }, { "code": null, "e": 461, "s": 438, "text": "towardsdatascience.com" }, { "code": null, "e": 612, "s": 461, "text": "These articles are based on lectures taken at Harvard on AC209b, with major credit going to lecturer Pavlos Protopapas of the Harvard IACS department." }, { "code": null, "e": 1103, "s": 612, "text": "This is the third part of a three-part tutorial on creating deep generative models specifically using generative adversarial networks. This is a natural extension to the previous topic on variational autoencoders (found here). We will see that GANs are typically superior as deep generative models as compared to variational autoencoders. However, they are notoriously difficult to work with and require a lot of data and tuning. We will also examine a hybrid model of GAN called a VAE-GAN." }, { "code": null, "e": 1263, "s": 1103, "text": "This part of the tutorial will mostly be a coding implementation of variational autoencoders (VAEs), GANs, and will also show the reader how to make a VAE-GAN." }, { "code": null, "e": 1286, "s": 1263, "text": "VAE for CelebA Dataset" }, { "code": null, "e": 1312, "s": 1286, "text": "DC-GAN for CelebA Dataset" }, { "code": null, "e": 1337, "s": 1312, "text": "DC-GAN for Anime Dataset" }, { "code": null, "e": 1363, "s": 1337, "text": "VAE-GAN for Anime Dataset" }, { "code": null, "e": 1585, "s": 1363, "text": "I strongly recommend the reader to review at least part 1 of the GAN tutorial, as well as my variational autoencoder walkthrough before going further, as otherwise, the implementation may not may much sense to the reader." }, { "code": null, "e": 1644, "s": 1585, "text": "All related code can now be found in my GitHub repository:" }, { "code": null, "e": 1655, "s": 1644, "text": "github.com" }, { "code": null, "e": 1668, "s": 1655, "text": "Let’s begin!" }, { "code": null, "e": 1985, "s": 1668, "text": "The CelebFaces Attributes Dataset (CelebA) is a large-scale face attributes dataset with more than 200K celebrity images, each with 40 attribute annotations. The images in this dataset cover large pose variations and background clutter. CelebA has large diversities, large quantities, and rich annotations, including" }, { "code": null, "e": 2014, "s": 1985, "text": "10,177 number of identities," }, { "code": null, "e": 2049, "s": 2014, "text": "202,599 number of face images, and" }, { "code": null, "e": 2115, "s": 2049, "text": "5 landmark locations, 40 binary attributes annotations per image." }, { "code": null, "e": 2162, "s": 2115, "text": "You can download the dataset from Kaggle here:" }, { "code": null, "e": 2177, "s": 2162, "text": "www.kaggle.com" }, { "code": null, "e": 2255, "s": 2177, "text": "The first step is to import all our necessary functions and extract the data." }, { "code": null, "e": 2263, "s": 2255, "text": "Imports" }, { "code": null, "e": 2343, "s": 2263, "text": "import shutilimport errnoimport zipfileimport osimport matplotlib.pyplot as plt" }, { "code": null, "e": 2356, "s": 2343, "text": "Extract Data" }, { "code": null, "e": 2476, "s": 2356, "text": "# Only run once to unzip imageszip_ref = zipfile.ZipFile('img_align_celeba.zip','r')zip_ref.extractall()zip_ref.close()" }, { "code": null, "e": 2499, "s": 2476, "text": "Custom Image Generator" }, { "code": null, "e": 2755, "s": 2499, "text": "This step is likely something most readers have not used before. Due to the huge size of our data, it may not be possible to load the dataset into the memory of your Jupyter Notebook. This is a pretty normal problem to have when working on large datasets." }, { "code": null, "e": 3122, "s": 2755, "text": "A workaround for this is to use a stream generator, which streams batches of data (images in this case) into memory sequentially, thereby limiting the amount of memory that is required for the function. The caveat to this is that they are a bit complicated to understand and code, as they require a reasonable understanding of computer memory, GPU architecture, etc." }, { "code": null, "e": 4706, "s": 3122, "text": "# data generator# source from https://medium.com/@ensembledme/writing-custom-keras-generators-fe815d992c5afrom skimage.io import imreaddef get_input(path): \"\"\"get specific image from path\"\"\" img = imread(path) return imgdef get_output(path, label_file = None): \"\"\"get all the labels relative to the image of path\"\"\" img_id = path.split('/')[-1] labels = label_file.loc[img_id].values return labelsdef preprocess_input(img): # convert between 0 and 1 return img.astype('float32') / 127.5 -1def image_generator(files, label_file, batch_size = 32): while True: batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] for input_path in batch_paths: input = get_input(input_path) input = preprocess_input(input) output = get_output(input_path, label_file = label_file) batch_input += [input] batch_output += [output] batch_x = np.array(batch_input) batch_y = np.array(batch_output) yield batch_x, batch_ydef auto_encoder_generator(files, batch_size = 32): while True: batch_paths = np.random.choice(a = files, size = batch_size) batch_input = [] batch_output = [] for input_path in batch_paths: input = get_input(input_path) input = preprocess_input(input) output = input batch_input += [input] batch_output += [output] batch_x = np.array(batch_input) batch_y = np.array(batch_output) yield batch_x, batch_y" }, { "code": null, "e": 4837, "s": 4706, "text": "For more information on writing custom generators in Keras, a good article to check out is the one I referenced in the above code:" }, { "code": null, "e": 4848, "s": 4837, "text": "medium.com" }, { "code": null, "e": 4872, "s": 4848, "text": "Load the Attribute Data" }, { "code": null, "e": 5169, "s": 4872, "text": "Not only do we have images for this dataset, but each image also has a list of attributes corresponding to aspects of the celebrity. For example, there are attributes describing whether the celebrity is wearing lipstick, or a hat, whether they are young or not, whether they have black hair, etc." }, { "code": null, "e": 5344, "s": 5169, "text": "# now load attribute# 1.A.2import pandas as pdattr = pd.read_csv('list_attr_celeba.csv')attr = attr.set_index('image_id')# check if attribute successful loadedattr.describe()" }, { "code": null, "e": 5372, "s": 5344, "text": "Finish Making the Generator" }, { "code": null, "e": 5588, "s": 5372, "text": "Now we finish making the generator. We set the image name length to 6 since we have a 6 digit number of images in our dataset. This section of code should make sense after reading the custom Keras generator article." }, { "code": null, "e": 6143, "s": 5588, "text": "import numpy as npfrom sklearn.model_selection import train_test_splitIMG_NAME_LENGTH = 6file_path = \"img_align_celeba/\"img_id = np.arange(1,len(attr.index)+1)img_path = []for i in range(len(img_id)): img_path.append(file_path + (IMG_NAME_LENGTH - len(str(img_id[i])))*'0' + str(img_id[i]) + '.jpg')# pick 80% as training set and 20% as validation settrain_path = img_path[:int((0.8)*len(img_path))]val_path = img_path[int((0.8)*len(img_path)):]train_generator = auto_encoder_generator(train_path,32)val_generator = auto_encoder_generator(val_path,32)" }, { "code": null, "e": 6210, "s": 6143, "text": "We can now pick three images and check that attributes make sense." }, { "code": null, "e": 6404, "s": 6210, "text": "fig, ax = plt.subplots(1, 3, figsize=(12, 4))for i in range(3): ax[i].imshow(get_input(img_path[i])) ax[i].axis('off') ax[i].set_title(img_path[i][-10:])plt.show() attr.iloc[:3]" }, { "code": null, "e": 6529, "s": 6404, "text": "First, we will create and compile a Convolutional VAE Model (including encoder and decoder) for the celebrity faces dataset." }, { "code": null, "e": 6542, "s": 6529, "text": "More Imports" }, { "code": null, "e": 6951, "s": 6542, "text": "from keras.models import Sequential, Modelfrom keras.layers import Dropout, Flatten, Dense, Conv2D, MaxPooling2D, Input, Reshape, UpSampling2D, InputLayer, Lambda, ZeroPadding2D, Cropping2D, Conv2DTranspose, BatchNormalizationfrom keras.utils import np_utils, to_categoricalfrom keras.losses import binary_crossentropyfrom keras import backend as K,objectivesfrom keras.losses import mse, binary_crossentropy" }, { "code": null, "e": 6970, "s": 6951, "text": "Model Architecture" }, { "code": null, "e": 7021, "s": 6970, "text": "Now we can create and make a summary of the model." }, { "code": null, "e": 9783, "s": 7021, "text": "b_size = 128n_size = 512def sampling(args): z_mean, z_log_sigma = args epsilon = K.random_normal(shape = (n_size,) , mean = 0, stddev = 1) return z_mean + K.exp(z_log_sigma/2) * epsilon def build_conv_vae(input_shape, bottleneck_size, sampling, batch_size = 32): # ENCODER input = Input(shape=(input_shape[0],input_shape[1],input_shape[2])) x = Conv2D(32,(3,3),activation = 'relu', padding = 'same')(input) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(64,(3,3),activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(128,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) x = Conv2D(256,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = MaxPooling2D((2,2), padding ='same')(x) # Latent Variable Calculation shape = K.int_shape(x) flatten_1 = Flatten()(x) dense_1 = Dense(bottleneck_size, name='z_mean')(flatten_1) z_mean = BatchNormalization()(dense_1) flatten_2 = Flatten()(x) dense_2 = Dense(bottleneck_size, name ='z_log_sigma')(flatten_2) z_log_sigma = BatchNormalization()(dense_2) z = Lambda(sampling)([z_mean, z_log_sigma]) encoder = Model(input, [z_mean, z_log_sigma, z], name = 'encoder') # DECODER latent_input = Input(shape=(bottleneck_size,), name = 'decoder_input') x = Dense(shape[1]*shape[2]*shape[3])(latent_input) x = Reshape((shape[1],shape[2],shape[3]))(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,0],[0,1]])(x) x = Conv2DTranspose(256,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,1],[0,1]])(x) x = Conv2DTranspose(128,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Cropping2D([[0,1],[0,1]])(x) x = Conv2DTranspose(64,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) x = UpSampling2D((2,2))(x) x = Conv2DTranspose(32,(3,3), activation = 'relu', padding = 'same')(x) x = BatchNormalization()(x) output = Conv2DTranspose(3,(3,3), activation = 'tanh', padding ='same')(x) decoder = Model(latent_input, output, name = 'decoder') output_2 = decoder(encoder(input)[2]) vae = Model(input, output_2, name ='vae') return vae, encoder, decoder, z_mean, z_log_sigmavae_2, encoder, decoder, z_mean, z_log_sigma = build_conv_vae(img_sample.shape, n_size, sampling, batch_size = b_size)print(\"encoder summary:\")encoder.summary()print(\"decoder summary:\")decoder.summary()print(\"vae summary:\")vae_2.summary()" }, { "code": null, "e": 9803, "s": 9783, "text": "Define the VAE Loss" }, { "code": null, "e": 10234, "s": 9803, "text": "def vae_loss(input_img, output): # Compute error in reconstruction reconstruction_loss = mse(K.flatten(input_img) , K.flatten(output)) # Compute the KL Divergence regularization term kl_loss = - 0.5 * K.sum(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma), axis = -1) # Return the average loss over all images in batch total_loss = (reconstruction_loss + 0.0001 * kl_loss) return total_loss" }, { "code": null, "e": 10252, "s": 10234, "text": "Compile the Model" }, { "code": null, "e": 10413, "s": 10252, "text": "vae_2.compile(optimizer='rmsprop', loss= vae_loss)encoder.compile(optimizer = 'rmsprop', loss = vae_loss)decoder.compile(optimizer = 'rmsprop', loss = vae_loss)" }, { "code": null, "e": 10429, "s": 10413, "text": "Train the Model" }, { "code": null, "e": 10556, "s": 10429, "text": "vae_2.fit_generator(train_generator, steps_per_epoch = 4000, validation_data = val_generator, epochs=7, validation_steps= 500)" }, { "code": null, "e": 10720, "s": 10556, "text": "We randomly choose some images of the training set, run them through the encoder to parameterize the latent code, and then reconstruct the images with the decoder." }, { "code": null, "e": 11214, "s": 10720, "text": "import randomx_test = []for i in range(64): x_test.append(get_input(img_path[random.randint(0,len(img_id))]))x_test = np.array(x_test)figure_Decoded = vae_2.predict(x_test.astype('float32')/127.5 -1, batch_size = b_size)figure_original = x_test[0]figure_decoded = (figure_Decoded[0]+1)/2for i in range(4): plt.axis('off') plt.subplot(2,4,1+i*2) plt.imshow(x_test[i]) plt.axis('off') plt.subplot(2,4,2 + i*2) plt.imshow((figure_Decoded[i]+1)/2) plt.axis('off')plt.show()" }, { "code": null, "e": 11530, "s": 11214, "text": "Notice that the reconstructed images share similarities with the original versions. However, the new images are a bit blurry, which is a known phenomenon of VAEs. This has been hypothesized to be due to the fact that variational inference optimizes a lower bound to the likelihood, not the actual likelihood itself." }, { "code": null, "e": 11558, "s": 11530, "text": "Latent Space Representation" }, { "code": null, "e": 11806, "s": 11558, "text": "We can choose two images with different attributes and plot their latent space representations. Notice that we can see some differences between the latent codes, which we might hypothesize as explaining the differences between the original images." }, { "code": null, "e": 12480, "s": 11806, "text": "# Choose two images of different attributes, and plot the original and latent space of itx_test1 = []for i in range(64): x_test1.append(get_input(img_path[np.random.randint(0,len(img_id))]))x_test1 = np.array(x_test)x_test_encoded = np.array(encoder.predict(x_test1/127.5-1, batch_size = b_size))figure_original_1 = x_test[0]figure_original_2 = x_test[1]Encoded1 = (x_test_encoded[0,0,:].reshape(32, 16,)+1)/2 Encoded2 = (x_test_encoded[0,1,:].reshape(32, 16)+1)/2plt.figure(figsize=(8, 8))plt.subplot(2,2,1)plt.imshow(figure_original_1)plt.subplot(2,2,2)plt.imshow(Encoded1)plt.subplot(2,2,3)plt.imshow(figure_original_2)plt.subplot(2,2,4)plt.imshow(Encoded2)plt.show()" }, { "code": null, "e": 12507, "s": 12480, "text": "Sampling from Latent Space" }, { "code": null, "e": 12782, "s": 12507, "text": "We can randomly sample 15 latent codes and decode them to generate new celebrity faces. We can see from this representation that the images generated by our model is of great similar styles with those images in our training set and it is also of good reality and variations." }, { "code": null, "e": 13267, "s": 12782, "text": "# We randomly generated 15 images from 15 series of noise informationn = 3m = 5digit_size1 = 218digit_size2 = 178figure = np.zeros((digit_size1 * n, digit_size2 * m,3)) for i in range(3): for j in range(5): z_sample = np.random.rand(1,512) x_decoded = decoder.predict([z_sample]) figure[i * digit_size1: (i + 1) * digit_size1, j * digit_size2: (j + 1) * digit_size2,:] = (x_decoded[0]+1)/2 plt.figure(figsize=(10, 10))plt.imshow(figure)plt.show()" }, { "code": null, "e": 13449, "s": 13267, "text": "So it seems that our VAE model is not particularly good. With more time and better selection of hyperparameters and so on, we would probably have achieved a better result than this." }, { "code": null, "e": 13513, "s": 13449, "text": "Now let us compare this result to a DC-GAN on the same dataset." }, { "code": null, "e": 13637, "s": 13513, "text": "Since we have already set up the stream generator, there is not too much work to do to get the DC-GAN model up and running." }, { "code": null, "e": 16530, "s": 13637, "text": "# Create and compile a DC-GAN model, and print the summaryfrom keras.utils import np_utilsfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, Flatten, LeakyReLU,\\ BatchNormalization, Conv2DTranspose, Conv2D, Reshapefrom keras.layers.advanced_activations import LeakyReLUfrom keras.optimizers import Adam, RMSpropfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport randomfrom tqdm import tqdm_notebookfrom scipy.misc import imresizedef generator_model(latent_dim=100, leaky_alpha=0.2, init_stddev=0.02): g = Sequential() g.add(Dense(4*4*512, input_shape=(latent_dim,), kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(Reshape(target_shape=(4, 4, 512))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(256, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(128, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(BatchNormalization()) g.add(Activation(LeakyReLU(alpha=leaky_alpha))) g.add(Conv2DTranspose(3, kernel_size=4, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) g.add(Activation('tanh')) g.summary() #g.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return g def discriminator_model(leaky_alpha=0.2, init_stddev=0.02): d = Sequential() d.add(Conv2D(64, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev), input_shape=(32, 32, 3))) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Conv2D(128, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(BatchNormalization()) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Conv2D(256, kernel_size=5, strides=2, padding='same', kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(BatchNormalization()) d.add(Activation(LeakyReLU(alpha=leaky_alpha))) d.add(Flatten()) d.add(Dense(1, kernel_initializer=RandomNormal(stddev=init_stddev))) d.add(Activation('sigmoid')) d.summary() return ddef DCGAN(sample_size=100): # Generator g = generator_model(sample_size, 0.2, 0.02) # Discriminator d = discriminator_model(0.2, 0.02) d.compile(optimizer=Adam(lr=0.001, beta_1=0.5), loss='binary_crossentropy') d.trainable = False # GAN gan = Sequential([g, d]) gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return gan, g, d" }, { "code": null, "e": 16837, "s": 16530, "text": "The above code is just for the architecture of the generator and discriminator network. Comparing this method of coding the GAN to that which I did in part 2 is a good idea, you can see this one is less clean and we did not define global parameters, so there are many places we could have potential errors." }, { "code": null, "e": 17008, "s": 16837, "text": "Now we define a bunch of functions to make our life easier, these are mostly just for the preprocessing and plotting of images to help us in analyzing the network output." }, { "code": null, "e": 18145, "s": 17008, "text": "def load_image(filename, size=(32, 32)): img = plt.imread(filename) # crop rows, cols = img.shape[:2] crop_r, crop_c = 150, 150 start_row, start_col = (rows - crop_r) // 2, (cols - crop_c) // 2 end_row, end_col = rows - start_row, cols - start_row img = img[start_row:end_row, start_col:end_col, :] # resize img = imresize(img, size) return imgdef preprocess(x): return (x/255)*2-1def deprocess(x): return np.uint8((x+1)/2*255)def make_labels(size): return np.ones([size, 1]), np.zeros([size, 1]) def show_losses(losses): losses = np.array(losses) fig, ax = plt.subplots() plt.plot(losses.T[0], label='Discriminator') plt.plot(losses.T[1], label='Generator') plt.title(\"Validation Losses\") plt.legend() plt.show()def show_images(generated_images): n_images = len(generated_images) cols = 5 rows = n_images//cols plt.figure(figsize=(8, 6)) for i in range(n_images): img = deprocess(generated_images[i]) ax = plt.subplot(rows, cols, i+1) plt.imshow(img) plt.xticks([]) plt.yticks([]) plt.tight_layout() plt.show()" }, { "code": null, "e": 18161, "s": 18145, "text": "Train the Model" }, { "code": null, "e": 18340, "s": 18161, "text": "We now define the training function. As we did before, notice that we switch between setting the discriminator to be trainable and untrainable (we did this implicitly in part 2)." }, { "code": null, "e": 20371, "s": 18340, "text": "def train(sample_size=100, epochs=3, batch_size=128, eval_size=16, smooth=0.1): batchCount=len(train_path)//batch_size y_train_real, y_train_fake = make_labels(batch_size) y_eval_real, y_eval_fake = make_labels(eval_size) # create a GAN, a generator and a discriminator gan, g, d = DCGAN(sample_size) losses = [] for e in range(epochs): print('-'*15, 'Epoch %d' % (e+1), '-'*15) for i in tqdm_notebook(range(batchCount)): path_batch = train_path[i*batch_size:(i+1)*batch_size] image_batch = np.array([preprocess(load_image(filename)) for filename in path_batch]) noise = np.random.normal(0, 1, size=(batch_size, noise_dim)) generated_images = g.predict_on_batch(noise) # Train discriminator on generated images d.trainable = True d.train_on_batch(image_batch, y_train_real*(1-smooth)) d.train_on_batch(generated_images, y_train_fake) # Train generator d.trainable = False g_loss=gan.train_on_batch(noise, y_train_real) # evaluate test_path = np.array(val_path)[np.random.choice(len(val_path), eval_size, replace=False)] x_eval_real = np.array([preprocess(load_image(filename)) for filename in test_path]) noise = np.random.normal(loc=0, scale=1, size=(eval_size, sample_size)) x_eval_fake = g.predict_on_batch(noise) d_loss = d.test_on_batch(x_eval_real, y_eval_real) d_loss += d.test_on_batch(x_eval_fake, y_eval_fake) g_loss = gan.test_on_batch(noise, y_eval_real) losses.append((d_loss/2, g_loss)) print(\"Epoch: {:>3}/{} Discriminator Loss: {:>6.4f} Generator Loss: {:>6.4f}\".format( e+1, epochs, d_loss, g_loss)) show_images(x_eval_fake[:10]) # show the result show_losses(losses) show_images(g.predict(np.random.normal(loc=0, scale=1, size=(15, sample_size)))) return gnoise_dim=100train()" }, { "code": null, "e": 20449, "s": 20371, "text": "The output of this function will give us the following output for each epoch:" }, { "code": null, "e": 20526, "s": 20449, "text": "It will also plot our validation losses for the discriminator and generator." }, { "code": null, "e": 20979, "s": 20526, "text": "The generated images look reasonable. Here we can see that our model performed adequately, though the quality of images is not so good as those in the training set (since we reshaped the images to become smaller and made them more blurry than the original ones). However, they are vivid enough to create valid faces, and these faces are close enough to reality. Also, compared with images produced by VAE, the images are more creative and real-looking." }, { "code": null, "e": 21151, "s": 20979, "text": "So it seems that the GAN performs superior in this circumstance. Now let us try a new dataset and see how well a GAN can perform compared to a hybrid variant, the VAE-GAN." }, { "code": null, "e": 21532, "s": 21151, "text": "In this section, we will aim to generate faces in the same style as the Anime dataset using a GAN, as well as another special form of GAN, a VAE-GAN. The term VAE-GAN was first used by Larsen et. al in their paper “Autoencoding beyond pixels using a learned similarity metric”. VAE-GAN models differentiate themselves from GANs in that their generators are variation autoencoders." }, { "code": null, "e": 21754, "s": 21532, "text": "First, we will focus on the DC-GAN. The Anime dataset consists of over 20K anime faces in the form of 64x64 images. We will also need to create another Keras Custom Data Generator. A link to the dataset can be found here:" }, { "code": null, "e": 21765, "s": 21754, "text": "github.com" }, { "code": null, "e": 21967, "s": 21765, "text": "The first thing we need to do is create anime directory and download the data. This can be done from the link above. It is always good practice to check the data before moving ahead, so we do this now." }, { "code": null, "e": 22205, "s": 21967, "text": "from skimage import ioimport matplotlib.pyplot as pltfilePath='anime-faces/data/'imgSets=[]for i in range(1,20001): imgName=filePath+str(i)+'.png' imgSets.append(io.imread(imgName))plt.imshow(imgSets[1234])plt.axis('off')plt.show()" }, { "code": null, "e": 22249, "s": 22205, "text": "We now create and compile our DC-GAN model." }, { "code": null, "e": 26721, "s": 22249, "text": "# Create and compile a DC-GAN modelfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, \\ Flatten, LeakyReLU, BatchNormalization, Conv2DTranspose, Conv2D, Reshapefrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2Dfrom keras.optimizers import Adam, RMSprop,SGDfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport os, globfrom PIL import Imagefrom tqdm import tqdm_notebookimage_shape = (64, 64, 3)#noise_shape = (100,)Noise_dim = 128img_rows = 64img_cols = 64channels = 3def generator_model(latent_dim=100, leaky_alpha=0.2): model = Sequential() # layer1 (None,500)>>(None,128*16*16) model.add(Dense(128 * 16 * 16, activation=\"relu\", input_shape=(Noise_dim,))) # (None,16*16*128)>>(None,16,16,128) model.add(Reshape((16, 16, 128))) # (None,16,16,128)>>(None,32,32,128) model.add(UpSampling2D()) model.add(Conv2D(256, kernel_size=3, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(\"relu\")) #(None,32,32,128)>>(None,64,64,128) model.add(UpSampling2D()) # (None,64,64,128)>>(None,64,64,64) model.add(Conv2D(128, kernel_size=3, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(\"relu\")) # (None,64,64,128)>>(None,64,64,32) model.add(Conv2D(32, kernel_size=3, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(Activation(\"relu\")) # (None,64,64,32)>>(None,64,64,3) model.add(Conv2D(channels, kernel_size=3, padding=\"same\")) model.add(Activation(\"tanh\")) model.summary() model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef discriminator_model(leaky_alpha=0.2, dropRate=0.3): model = Sequential() # layer1 (None,64,64,3)>>(None,32,32,32) model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=\"same\")) model.add(LeakyReLU(alpha=leaky_alpha)) model.add(Dropout(dropRate)) # layer2 (None,32,32,32)>>(None,16,16,64) model.add(Conv2D(64, kernel_size=3, strides=2, padding=\"same\")) # model.add(ZeroPadding2D(padding=((0, 1), (0, 1)))) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=leaky_alpha)) model.add(Dropout(dropRate)) # (None,16,16,64)>>(None,8,8,128) model.add(Conv2D(128, kernel_size=3, strides=2, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,128)>>(None,8,8,256) model.add(Conv2D(256, kernel_size=3, strides=1, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,256)>>(None,8,8,64) model.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(dropRate)) # (None,8,8,64) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) model.summary() sgd=SGD(lr=0.0002) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef DCGAN(sample_size=Noise_dim): # generator g = generator_model(sample_size, 0.2) # discriminator d = discriminator_model(0.2) d.trainable = False # GAN gan = Sequential([g, d]) sgd=SGD() gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return gan, g, ddef get_image(image_path, width, height, mode): image = Image.open(image_path) #print(image.size) return np.array(image.convert(mode))def get_batch(image_files, width, height, mode): data_batch = np.array([get_image(sample_file, width, height, mode) \\ for sample_file in image_files]) return data_batchdef show_imgs(generator,epoch): row=3 col = 5 noise = np.random.normal(0, 1, (row * col, Noise_dim)) gen_imgs = generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(row, col) #fig.suptitle(\"DCGAN: Generated digits\", fontsize=12) cnt = 0 for i in range(row): for j in range(col): axs[i, j].imshow(gen_imgs[cnt, :, :, :]) axs[i, j].axis('off') cnt += 1 #plt.close() plt.show()" }, { "code": null, "e": 26914, "s": 26721, "text": "We can now train the model on the Anime dataset. We will do this in two different ways, the first will involve training the discriminator and generator with a 1:1 proportion of training times." }, { "code": null, "e": 29022, "s": 26914, "text": "# Training the discriminator and generator with the 1:1 proportion of training timesdef train(epochs=30, batchSize=128): filePath = r'anime-faces/data/' X_train = get_batch(glob.glob(os.path.join(filePath, '*.png'))[:20000], 64, 64, 'RGB') X_train = (X_train.astype(np.float32) - 127.5) / 127.5 halfSize = int(batchSize / 2) batchCount=int(len(X_train)/batchSize) dLossReal = [] dLossFake = [] gLossLogs = [] gan, generator, discriminator = DCGAN(Noise_dim) for e in range(epochs): for i in tqdm_notebook(range(batchCount)): index = np.random.randint(0, X_train.shape[0], halfSize) images = X_train[index] noise = np.random.normal(0, 1, (halfSize, Noise_dim)) genImages = generator.predict(noise) # one-sided labels discriminator.trainable = True dLossR = discriminator.train_on_batch(images, np.ones([halfSize, 1])) dLossF = discriminator.train_on_batch(genImages, np.zeros([halfSize, 1])) dLoss = np.add(dLossF, dLossR) * 0.5 discriminator.trainable = False noise = np.random.normal(0, 1, (batchSize, Noise_dim)) gLoss = gan.train_on_batch(noise, np.ones([batchSize, 1])) dLossReal.append([e, dLoss[0]]) dLossFake.append([e, dLoss[1]]) gLossLogs.append([e, gLoss]) dLossRealArr = np.array(dLossReal) dLossFakeArr = np.array(dLossFake) gLossLogsArr = np.array(gLossLogs) # At the end of training plot the losses vs epochs show_imgs(generator, e) plt.plot(dLossRealArr[:, 0], dLossRealArr[:, 1], label=\"Discriminator Loss - Real\") plt.plot(dLossFakeArr[:, 0], dLossFakeArr[:, 1], label=\"Discriminator Loss - Fake\") plt.plot(gLossLogsArr[:, 0], gLossLogsArr[:, 1], label=\"Generator Loss\") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.title('GAN') plt.grid(True) plt.show() return gan, generator, discriminatorGAN,Generator,Discriminator=train(epochs=20, batchSize=128) train(epochs=1000, batchSize=128, plotInternal=200)" }, { "code": null, "e": 29175, "s": 29022, "text": "The output will now start printing a series of anime characters. They are very grainy at first, and over time gradually become more and more pronounced." }, { "code": null, "e": 29250, "s": 29175, "text": "We will also get a plot of our generator and discriminator loss functions." }, { "code": null, "e": 29377, "s": 29250, "text": "Now we will do the same but with different training times for the discriminator and generator to see what the effect has been." }, { "code": null, "e": 29568, "s": 29377, "text": "Before moving forward, it is good to save the weights of the model somewhere so that you do not need to run the entire training again, and can instead just load the weights into the network." }, { "code": null, "e": 29589, "s": 29568, "text": "To save the weights:" }, { "code": null, "e": 29898, "s": 29589, "text": "discriminator.save_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')gan.save_weights('/content/gdrive/My Drive/gan_DCGAN_lr0.0001_deepgenerator+proportion2.h5')generator.save_weights('/content/gdrive/My Drive/generator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')" }, { "code": null, "e": 29919, "s": 29898, "text": "To load the weights:" }, { "code": null, "e": 30228, "s": 29919, "text": "discriminator.load_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')gan.load_weights('/content/gdrive/My Drive/gan_DCGAN_lr0.0001_deepgenerator+proportion2.h5')generator.load_weights('/content/gdrive/My Drive/generator_DCGAN_lr0.0001_deepgenerator+proportion2.h5')" }, { "code": null, "e": 30336, "s": 30228, "text": "Now we move onto the second network implementation without worrying about saving over our previous network." }, { "code": null, "e": 33662, "s": 30336, "text": "# Train the discriminator and generator separately and with different training timesdef train(epochs=300, batchSize=128, plotInternal=50): gLoss = 1 filePath = r'anime-faces/data/' X_train = get_batch(glob.glob(os.path.join(filePath,'*.png'))[:20000],64,64,'RGB') X_train=(X_train.astype(np.float32)-127.5)/127.5 halfSize= int (batchSize/2) dLossReal=[] dLossFake=[] gLossLogs=[] for e in range(epochs): index=np.random.randint(0,X_train.shape[0],halfSize) images=X_train[index] noise=np.random.normal(0,1,(halfSize,Noise_dim)) genImages=generator.predict(noise) if e < int(epochs*0.5): #one-sided labels discriminator.trainable=True dLossR=discriminator.train_on_batch(images,np.ones([halfSize,1])) dLossF=discriminator.train_on_batch(genImages,np.zeros([halfSize,1])) dLoss=np.add(dLossF,dLossR)*0.5 discriminator.trainable=False cnt = e while cnt > 3: cnt = cnt - 4 if cnt == 0: noise=np.random.normal(0,1,(batchSize,Noise_dim)) gLoss=gan.train_on_batch(noise,np.ones([batchSize,1])) elif e>= int(epochs*0.5) : cnt = e while cnt > 3: cnt = cnt - 4 if cnt == 0: #one-sided labels discriminator.trainable=True dLossR=discriminator.train_on_batch(images,np.ones([halfSize,1])) dLossF=discriminator.train_on_batch(genImages,np.zeros([halfSize,1])) dLoss=np.add(dLossF,dLossR)*0.5 discriminator.trainable=False noise=np.random.normal(0,1,(batchSize,Noise_dim)) gLoss=gan.train_on_batch(noise,np.ones([batchSize,1])) if e % 20 == 0: print(\"epoch: %d [D loss: %f, acc.: %.2f%%] [G loss: %f]\" % (e, dLoss[0], 100 * dLoss[1], gLoss)) dLossReal.append([e,dLoss[0]]) dLossFake.append([e,dLoss[1]]) gLossLogs.append([e,gLoss]) if e % plotInternal == 0 and e!=0: show_imgs(generator, e) dLossRealArr= np.array(dLossReal) dLossFakeArr = np.array(dLossFake) gLossLogsArr = np.array(gLossLogs) chk = e while chk > 50: chk = chk - 51 if chk == 0: discriminator.save_weights('/content/gdrive/My Drive/discriminator_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') gan.save_weights('/content/gdrive/My Drive/gan_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') generator.save_weights('/content/gdrive/My Drive/generator_DCGAN_lr=0.0001,proportion2,deepgenerator_Fake.h5') # At the end of training plot the losses vs epochs plt.plot(dLossRealArr[:, 0], dLossRealArr[:, 1], label=\"Discriminator Loss - Real\") plt.plot(dLossFakeArr[:, 0], dLossFakeArr[:, 1], label=\"Discriminator Loss - Fake\") plt.plot(gLossLogsArr[:, 0], gLossLogsArr[:, 1], label=\"Generator Loss\") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.title('GAN') plt.grid(True) plt.show() return gan, generator, discriminatorgan, generator, discriminator = DCGAN(Noise_dim)train(epochs=4000, batchSize=128, plotInternal=200)" }, { "code": null, "e": 33732, "s": 33662, "text": "Let us compare the output of these two networks. By running the line:" }, { "code": null, "e": 33753, "s": 33732, "text": "show_imgs(Generator)" }, { "code": null, "e": 33859, "s": 33753, "text": "the network will output some images from the generator (this is one of the functions we defined earlier)." }, { "code": null, "e": 33893, "s": 33859, "text": "Now let’s check the second model." }, { "code": null, "e": 34080, "s": 33893, "text": "We can see that the details of the generated images are improved and the texture of them are slightly more detailed. However, in comparison to the training images they are still sub-par." }, { "code": null, "e": 34121, "s": 34080, "text": "Perhaps the VAE-GAN will perform better?" }, { "code": null, "e": 34407, "s": 34121, "text": "To reiterate what I said previously about the VAE-GAN, the term VAE-GAN was first used by Larsen et. al in their paper “Autoencoding beyond pixels using a learned similarity metric”. VAE-GAN models differentiate themselves from GANs in that their generators are variation autoencoders." }, { "code": null, "e": 34554, "s": 34407, "text": "First we need to create and compile the VAE-GAN and make a summary for each of the networks (this is a good way to simply check the architecture)." }, { "code": null, "e": 39839, "s": 34554, "text": "# Create and compile a VAE-GAN, and make a summary for themfrom keras.models import Sequential, Modelfrom keras.layers import Input, Dense, Dropout, Activation, \\ Flatten, LeakyReLU, BatchNormalization, Conv2DTranspose, Conv2D, Reshape,MaxPooling2D,UpSampling2D,InputLayer, Lambdafrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2Dfrom keras.optimizers import Adam, RMSprop,SGDfrom keras.initializers import RandomNormalimport numpy as npimport matplotlib.pyplot as pltimport os, globfrom PIL import Imageimport pandas as pdfrom scipy.stats import normimport kerasfrom keras.utils import np_utils, to_categoricalfrom keras import backend as Kimport randomfrom keras import metricsfrom tqdm import tqdm# plotInternalplotInternal = 50#######latent_dim = 256batch_size = 256rows = 64columns = 64channel = 3epochs = 4000# datasize = len(dataset)# optimizersSGDop = SGD(lr=0.0003)ADAMop = Adam(lr=0.0002)# filtersfilter_of_dis = 16filter_of_decgen = 16filter_of_encoder = 16def sampling(args): mean, logsigma = args epsilon = K.random_normal(shape=(K.shape(mean)[0], latent_dim), mean=0., stddev=1.0) return mean + K.exp(logsigma / 2) * epsilondef vae_loss(X , output , E_mean, E_logsigma):\t# compute the average MSE error, then scale it up, ie. simply sum on all axes reconstruction_loss = 2 * metrics.mse(K.flatten(X), K.flatten(output)) \t# compute the KL loss kl_loss = - 0.5 * K.sum(1 + E_logsigma - K.square(E_mean) - K.exp(E_logsigma), axis=-1) total_loss = K.mean(reconstruction_loss + kl_loss) return total_loss def encoder(kernel, filter, rows, columns, channel): X = Input(shape=(rows, columns, channel)) model = Conv2D(filters=filter, kernel_size=kernel, strides=2, padding='same')(X) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Flatten()(model) mean = Dense(latent_dim)(model) logsigma = Dense(latent_dim, activation='tanh')(model) latent = Lambda(sampling, output_shape=(latent_dim,))([mean, logsigma]) meansigma = Model([X], [mean, logsigma, latent]) meansigma.compile(optimizer=SGDop, loss='mse') return meansigmadef decgen(kernel, filter, rows, columns, channel): X = Input(shape=(latent_dim,)) model = Dense(2*2*256)(X) model = Reshape((2, 2, 256))(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=filter, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = Activation('relu')(model) model = Conv2DTranspose(filters=channel, kernel_size=kernel, strides=2, padding='same')(model) model = Activation('tanh')(model) model = Model(X, model) model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0001, beta_1=0.5), metrics=['accuracy']) return modeldef discriminator(kernel, filter, rows, columns, channel): X = Input(shape=(rows, columns, channel)) model = Conv2D(filters=filter*2, kernel_size=kernel, strides=2, padding='same')(X) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*4, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) model = BatchNormalization(epsilon=1e-5)(model) model = LeakyReLU(alpha=0.2)(model) model = Conv2D(filters=filter*8, kernel_size=kernel, strides=2, padding='same')(model) dec = BatchNormalization(epsilon=1e-5)(model) dec = LeakyReLU(alpha=0.2)(dec) dec = Flatten()(dec) dec = Dense(1, activation='sigmoid')(dec) output = Model(X, dec) output.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.0002, beta_1=0.5), metrics=['accuracy']) return output def VAEGAN(decgen,discriminator): # generator g = decgen # discriminator d = discriminator d.trainable = False # GAN gan = Sequential([g, d]) # sgd=SGD() gan.compile(optimizer=Adam(lr=0.0001, beta_1=0.5), loss='binary_crossentropy') return g, d, gan" }, { "code": null, "e": 39928, "s": 39839, "text": "We once again define some functions so that we can just print images from the generator." }, { "code": null, "e": 40566, "s": 39928, "text": "def get_image(image_path, width, height, mode): image = Image.open(image_path) #print(image.size) return np.array(image.convert(mode))def show_imgs(generator): row=3 col = 5 noise = np.random.normal(0, 1, (row*col, latent_dim)) gen_imgs = generator.predict(noise) # Rescale images 0 - 1 gen_imgs = 0.5 * gen_imgs + 0.5 fig, axs = plt.subplots(row, col) #fig.suptitle(\"DCGAN: Generated digits\", fontsize=12) cnt = 0 for i in range(row): for j in range(col): axs[i, j].imshow(gen_imgs[cnt, :, :, :]) axs[i, j].axis('off') cnt += 1 #plt.close() plt.show()" }, { "code": null, "e": 40649, "s": 40566, "text": "The parameters of the generator will be affected by both the GAN and VAE training." }, { "code": null, "e": 41875, "s": 40649, "text": "# note: The parameters of the generator will be affected by both the GAN and VAE trainingG, D, GAN = VAEGAN(decgen(5, filter_of_decgen, rows, columns, channel),discriminator(5, filter_of_dis, rows, columns, channel))# encoderE = encoder(5, filter_of_encoder, rows, columns, channel)print(\"This is the summary for encoder:\")E.summary()# generator/decoder# G = decgen(5, filter_of_decgen, rows, columns, channel)print(\"This is the summary for dencoder/generator:\")G.summary()# discriminator# D = discriminator(5, filter_of_dis, rows, columns, channel)print(\"This is the summary for discriminator:\")D.summary()D_fixed = discriminator(5, filter_of_dis, rows, columns, channel)D_fixed.compile(optimizer=SGDop, loss='mse')# ganprint(\"This is the summary for GAN:\")GAN.summary()# VAEX = Input(shape=(rows, columns, channel))E_mean, E_logsigma, Z = E(X)output = G(Z)# G_dec = G(E_mean + E_logsigma)# D_fake, F_fake = D(output)# D_fromGen, F_fromGen = D(G_dec)# D_true, F_true = D(X)# print(\"type(E)\",type(E))# print(\"type(output)\",type(output))# print(\"type(D_fake)\",type(D_fake))VAE = Model(X, output)VAE.add_loss(vae_loss(X, output, E_mean, E_logsigma))VAE.compile(optimizer=SGDop)print(\"This is the summary for vae:\")VAE.summary()" }, { "code": null, "e": 42230, "s": 41875, "text": "In the below cell we begin training our model. Note that we use the previous method to train the discriminator and GAN and VAE for different lengths of time. We emphasize the training of the discriminator in the first half of the training process and we train the generator more in the second half because we want to improve the quality of output images." }, { "code": null, "e": 46836, "s": 42230, "text": "# We train our model in this celldLoss=[]gLoss=[]GLoss = 1GlossEnc = 1GlossGen = 1Eloss = 1halfbatch_size = int(batch_size*0.5)for epoch in tqdm(range(epochs)): if epoch < int(epochs*0.5): noise = np.random.normal(0, 1, (halfbatch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], halfbatch_size) images = dataset[index] latent_vect = E.predict(images)[0] encImg = G.predict(latent_vect) fakeImg = G.predict(noise) D.Trainable = True DlossTrue = D.train_on_batch(images, np.ones((halfbatch_size, 1))) DlossEnc = D.train_on_batch(encImg, np.ones((halfbatch_size, 1))) DlossFake = D.train_on_batch(fakeImg, np.zeros((halfbatch_size, 1)))# DLoss=np.add(DlossTrue,DlossFake)*0.5 DLoss=np.add(DlossTrue,DlossEnc) DLoss=np.add(DLoss,DlossFake)*0.33 D.Trainable = False cnt = epoch while cnt > 3: cnt = cnt - 4 if cnt == 0: noise = np.random.normal(0, 1, (batch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], batch_size) images = dataset[index] latent_vect = E.predict(images)[0] GlossEnc = GAN.train_on_batch(latent_vect, np.ones((batch_size, 1))) GlossGen = GAN.train_on_batch(noise, np.ones((batch_size, 1))) Eloss = VAE.train_on_batch(images, None) GLoss=np.add(GlossEnc,GlossGen) GLoss=np.add(GLoss,Eloss)*0.33 dLoss.append([epoch,DLoss[0]]) gLoss.append([epoch,GLoss]) elif epoch >= int(epochs*0.5): cnt = epoch while cnt > 3: cnt = cnt - 4 if cnt == 0: noise = np.random.normal(0, 1, (halfbatch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], halfbatch_size) images = dataset[index] latent_vect = E.predict(images)[0] encImg = G.predict(latent_vect) fakeImg = G.predict(noise) D.Trainable = True DlossTrue = D.train_on_batch(images, np.ones((halfbatch_size, 1))) # DlossEnc = D.train_on_batch(encImg, np.ones((halfbatch_size, 1))) DlossFake = D.train_on_batch(fakeImg, np.zeros((halfbatch_size, 1))) DLoss=np.add(DlossTrue,DlossFake)*0.5 # DLoss=np.add(DlossTrue,DlossEnc)# DLoss=np.add(DLoss,DlossFake)*0.33 D.Trainable = False noise = np.random.normal(0, 1, (batch_size, latent_dim)) index = np.random.randint(0,dataset.shape[0], batch_size) images = dataset[index] latent_vect = E.predict(images)[0] GlossEnc = GAN.train_on_batch(latent_vect, np.ones((batch_size, 1))) GlossGen = GAN.train_on_batch(noise, np.ones((batch_size, 1))) Eloss = VAE.train_on_batch(images, None) GLoss=np.add(GlossEnc,GlossGen) GLoss=np.add(GLoss,Eloss)*0.33 dLoss.append([epoch,DLoss[0]]) gLoss.append([epoch,GLoss]) if epoch % plotInternal == 0 and epoch!=0: show_imgs(G) dLossArr= np.array(dLoss) gLossArr = np.array(gLoss) # print(\"dLossArr.shape:\",dLossArr.shape)# print(\"gLossArr.shape:\",gLossArr.shape) chk = epoch while chk > 50: chk = chk - 51 if chk == 0: D.save_weights('/content/gdrive/My Drive/VAE discriminator_kernalsize5_proportion_32.h5') G.save_weights('/content/gdrive/My Drive/VAE generator_kernalsize5_proportion_32.h5') E.save_weights('/content/gdrive/My Drive/VAE encoder_kernalsize5_proportion_32.h5') if epoch%20 == 0: print(\"epoch:\", epoch + 1,\" \", \"DislossTrue loss:\",DlossTrue[0],\"D accuracy:\",100* DlossTrue[1], \"DlossFake loss:\", DlossFake[0],\"GlossEnc loss:\", GlossEnc, \"GlossGen loss:\",GlossGen, \"Eloss loss:\",Eloss)# print(\"loss:\")# print(\"D:\", DlossTrue, DlossEnc, DlossFake)# print(\"G:\", GlossEnc, GlossGen)# print(\"VAE:\", Eloss)print('Training done,saving weights')D.save_weights('/content/gdrive/My Drive/VAE discriminator_kernalsize5_proportion_32.h5')G.save_weights('/content/gdrive/My Drive/VAE generator_kernalsize5_proportion_32.h5')E.save_weights('/content/gdrive/My Drive/VAE encoder_kernalsize5_proportion_32.h5')print('painting losses')# At the end of training plot the losses vs epochsplt.plot(dLossArr[:, 0], dLossArr[:, 1], label=\"Discriminator Loss\")plt.plot(gLossArr[:, 0], gLossArr[:, 1], label=\"Generator Loss\")plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()plt.title('GAN')plt.grid(True)plt.show()print('end')" }, { "code": null, "e": 47061, "s": 46836, "text": "If you are planning on running this network, beware that the training process takes a REALLY long time. I would not attempt this unless you have access to some powerful GPUs or are willing to run the model for an entire day." }, { "code": null, "e": 47185, "s": 47061, "text": "Now our VAE-GAN training is complete, we can check to see how our output images look and compare them to our previous GANs." }, { "code": null, "e": 47251, "s": 47185, "text": "# In this cell, we generate and visualize 15 images. show_imgs(G)" }, { "code": null, "e": 47691, "s": 47251, "text": "We can see that in this implementation of VAE-GAN, we got a nice model which can generate images that are clear and of a similar style to the original images. Our VAE-GAN can create images more robustly and this can be done without extra noise of the anime faces. However, the competence of generalization of our model is not very good, it seldom changes the manner or sex of the character, so this is a point that we could try to improve." }, { "code": null, "e": 47869, "s": 47691, "text": "It is not necessarily clear that any one of the models is better than the others, and none of these methods have been optimized properly so it is difficult to make a comparison." }, { "code": null, "e": 48050, "s": 47869, "text": "This is still an active area of research, so if you are interested I recommend getting yourself stuck in and try and use GANs within your own work to see what you can come up with." }, { "code": null, "e": 48201, "s": 48050, "text": "I hope you have enjoyed this trilogy of articles on GANs and now have a much better idea of what they are, what they can do, and how to make your own." }, { "code": null, "e": 48224, "s": 48201, "text": "Thank you for reading!" }, { "code": null, "e": 48300, "s": 48224, "text": "For updates on new blog posts and extra content, sign up for my newsletter." }, { "code": null, "e": 48311, "s": 48300, "text": "mailchi.mp" }, { "code": null, "e": 48332, "s": 48311, "text": "Run BigGAN in COLAB:" }, { "code": null, "e": 48451, "s": 48332, "text": "https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/biggan_generation_with_tf_hub.ipynb" }, { "code": null, "e": 48478, "s": 48451, "text": "More code help + examples:" }, { "code": null, "e": 48569, "s": 48478, "text": "https://www.jessicayung.com/explaining-tensorflow-code-for-a-convolutional-neural-network/" }, { "code": null, "e": 48639, "s": 48569, "text": "https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html" }, { "code": null, "e": 48704, "s": 48639, "text": "https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html" }, { "code": null, "e": 48741, "s": 48704, "text": "https://github.com/tensorlayer/srgan" }, { "code": null, "e": 48809, "s": 48741, "text": "https://junyanz.github.io/CycleGAN/ https://affinelayer.com/pixsrv/" }, { "code": null, "e": 48849, "s": 48809, "text": "https://tcwang0509.github.io/pix2pixHD/" }, { "code": null, "e": 48869, "s": 48849, "text": "Influential Papers:" }, { "code": null, "e": 48914, "s": 48869, "text": "DCGAN https://arxiv.org/pdf/1511.06434v2.pdf" }, { "code": null, "e": 48974, "s": 48914, "text": "Wasserstein GAN (WGAN) https://arxiv.org/pdf/1701.07875.pdf" }, { "code": null, "e": 49059, "s": 48974, "text": "Conditional Generative Adversarial Nets (CGAN) https://arxiv.org/pdf/1411.1784v1.pdf" }, { "code": null, "e": 49184, "s": 49059, "text": "Deep Generative Image Models using a Laplacian Pyramid of Adversarial Networks (LAPGAN) https://arxiv.org/pdf/1506.05751.pdf" }, { "code": null, "e": 49314, "s": 49184, "text": "Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network (SRGAN) https://arxiv.org/pdf/1609.04802.pdf" }, { "code": null, "e": 49442, "s": 49314, "text": "Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks (CycleGAN) https://arxiv.org/pdf/1703.10593.pdf" }, { "code": null, "e": 49576, "s": 49442, "text": "InfoGAN: Interpretable Representation Learning by Information Maximizing Generative Adversarial Nets https://arxiv.org/pdf/1606.03657" }, { "code": null, "e": 49619, "s": 49576, "text": "DCGAN https://arxiv.org/pdf/1704.00028.pdf" }, { "code": null, "e": 49704, "s": 49619, "text": "Improved Training of Wasserstein GANs (WGAN-GP) https://arxiv.org/pdf/1701.07875.pdf" }, { "code": null, "e": 49793, "s": 49704, "text": "Energy-based Generative Adversarial Network (EBGAN) https://arxiv.org/pdf/1609.03126.pdf" }, { "code": null, "e": 49901, "s": 49793, "text": "Autoencoding beyond pixels using a learned similarity metric (VAE-GAN) https://arxiv.org/pdf/1512.09300.pdf" }, { "code": null, "e": 49977, "s": 49901, "text": "Adversarial Feature Learning (BiGAN) https://arxiv.org/pdf/1605.09782v6.pdf" }, { "code": null, "e": 50061, "s": 49977, "text": "Stacked Generative Adversarial Networks (SGAN) https://arxiv.org/pdf/1612.04357.pdf" }, { "code": null, "e": 50181, "s": 50061, "text": "StackGAN++: Realistic Image Synthesis with Stacked Generative Adversarial Networks https://arxiv.org/pdf/1710.10916.pdf" } ]
fread() function in C++ program
Given the task is to show the working of fread() in C++. In this article we will also look into the different parameters which are passed to fread() and what this function returns. fread() is an inbuilt function of C++ which reads a block of data from the stream. This function counts the number of objects each with the size of “size” bytes from the stream and stores them in buffer memory, then position pointer advanced by the total amount of bytes read. The amount of bytes read if successful will be size *count. fread(void *buffer, size_t size, size_t count, FILE *file_stream); This function will require all 4 parameters. Let’s understand the parameters. buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored. buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored. size − It defines the size of each element to be read in bytes. (size_t is unsigned int). size − It defines the size of each element to be read in bytes. (size_t is unsigned int). count − The number of elements to be read.\ count − The number of elements to be read.\ file_stream − Pointer of the file stream from which we want to read the bytes. file_stream − Pointer of the file stream from which we want to read the bytes. The number of elements successfully read is returned. If any reading error occurs or it reaches end-of-file the number of elements returned will vary from the count variable. #include <bits/stdc++.h> #include <cstdio> using namespace std; int main() { FILE* file_stream; char buf[100]; file_stream = fopen("tp.txt", "r"); while (!feof(file_stream)) //will read the file { // will read the contents of the file. fread(buf, sizeof(buf), 1, file_stream); cout << buf; } return 0; } Assuming the tp.txt file have the following content tutorialspoint Contribution anything here If we run the above code it will generate the following output − tutorialspoint Contribution anything here Let’s take example and check the output when the count is zero and the size is zero. Live Demo #include <iostream> #include <cstdio> using namespace std; int main() { FILE *fp; char buffer[100]; int retVal; fp = fopen("tpempty.txt","rb"); retVal = fread(buffer,sizeof(buffer),0,fp); cout << "The count = 0, then return value = " << retVal << endl; retVal = fread(buffer,0,1,fp); cout << "The size = 0, then value = " << retVal << endl; return 0; } If we run the above code it will generate the following output − The count = 0, then return value = 0 The size = 0, then value = 0
[ { "code": null, "e": 1243, "s": 1062, "text": "Given the task is to show the working of fread() in C++. In this article we will also look into the different parameters which are passed to fread() and what this function returns." }, { "code": null, "e": 1580, "s": 1243, "text": "fread() is an inbuilt function of C++ which reads a block of data from the stream. This function counts the number of objects each with the size of “size” bytes from the stream and stores them in buffer memory, then position pointer advanced by the total amount of bytes read. The amount of bytes read if successful will be size *count." }, { "code": null, "e": 1647, "s": 1580, "text": "fread(void *buffer, size_t size, size_t count, FILE *file_stream);" }, { "code": null, "e": 1725, "s": 1647, "text": "This function will require all 4 parameters. Let’s understand the parameters." }, { "code": null, "e": 1822, "s": 1725, "text": "buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored." }, { "code": null, "e": 1919, "s": 1822, "text": "buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored." }, { "code": null, "e": 2009, "s": 1919, "text": "size − It defines the size of each element to be read in bytes. (size_t is unsigned int)." }, { "code": null, "e": 2099, "s": 2009, "text": "size − It defines the size of each element to be read in bytes. (size_t is unsigned int)." }, { "code": null, "e": 2143, "s": 2099, "text": "count − The number of elements to be read.\\" }, { "code": null, "e": 2187, "s": 2143, "text": "count − The number of elements to be read.\\" }, { "code": null, "e": 2266, "s": 2187, "text": "file_stream − Pointer of the file stream from which we want to read the bytes." }, { "code": null, "e": 2345, "s": 2266, "text": "file_stream − Pointer of the file stream from which we want to read the bytes." }, { "code": null, "e": 2399, "s": 2345, "text": "The number of elements successfully read is returned." }, { "code": null, "e": 2520, "s": 2399, "text": "If any reading error occurs or it reaches end-of-file the number of elements returned will vary from the count variable." }, { "code": null, "e": 2860, "s": 2520, "text": "#include <bits/stdc++.h>\n#include <cstdio>\nusing namespace std;\nint main() {\n FILE* file_stream;\n char buf[100];\n file_stream = fopen(\"tp.txt\", \"r\");\n while (!feof(file_stream)) //will read the file {\n // will read the contents of the file.\n fread(buf, sizeof(buf), 1, file_stream);\n cout << buf;\n }\n return 0;\n}" }, { "code": null, "e": 2912, "s": 2860, "text": "Assuming the tp.txt file have the following content" }, { "code": null, "e": 2927, "s": 2912, "text": "tutorialspoint" }, { "code": null, "e": 2940, "s": 2927, "text": "Contribution" }, { "code": null, "e": 2954, "s": 2940, "text": "anything here" }, { "code": null, "e": 3019, "s": 2954, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3061, "s": 3019, "text": "tutorialspoint\nContribution\nanything here" }, { "code": null, "e": 3146, "s": 3061, "text": "Let’s take example and check the output when the count is zero and the size is zero." }, { "code": null, "e": 3157, "s": 3146, "text": " Live Demo" }, { "code": null, "e": 3537, "s": 3157, "text": "#include <iostream>\n#include <cstdio>\nusing namespace std; int main() {\n FILE *fp;\n char buffer[100];\n int retVal;\n fp = fopen(\"tpempty.txt\",\"rb\");\n retVal = fread(buffer,sizeof(buffer),0,fp);\n cout << \"The count = 0, then return value = \" << retVal << endl;\n retVal = fread(buffer,0,1,fp);\n cout << \"The size = 0, then value = \" << retVal << endl;\n return 0;\n}" }, { "code": null, "e": 3602, "s": 3537, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3668, "s": 3602, "text": "The count = 0, then return value = 0\nThe size = 0, then value = 0" } ]
MySQL new user access denied even after giving privileges?
After creating a user and giving all privileges to the user, you need to FLUSH PRIVILEGES to set up and want the new settings to work correctly. The syntax is as follows − FLUSH PRIVILEGES; Here is the query to create a new user which has the name ‘Bob’ in my case. The query to create a new user is as follows − mysql> CREATE USER 'Bob'@'%' IDENTIFIED BY '123456'; Query OK, 0 rows affected (0.56 sec) Now given all privileges to user Bob − mysql> GRANT ALL PRIVILEGES ON *.* TO 'Bob'@'%' WITH GRANT OPTION; Query OK, 0 rows affected (0.23 sec) Now flush the privileges. The query is as follows − mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.14 sec) Now here I am using user Bob with password 123456. The snapshot is as follows −
[ { "code": null, "e": 1207, "s": 1062, "text": "After creating a user and giving all privileges to the user, you need to FLUSH PRIVILEGES to set up and want the new settings to work correctly." }, { "code": null, "e": 1234, "s": 1207, "text": "The syntax is as follows −" }, { "code": null, "e": 1252, "s": 1234, "text": "FLUSH PRIVILEGES;" }, { "code": null, "e": 1375, "s": 1252, "text": "Here is the query to create a new user which has the name ‘Bob’ in my case. The query to create a new user is as follows −" }, { "code": null, "e": 1465, "s": 1375, "text": "mysql> CREATE USER 'Bob'@'%' IDENTIFIED BY '123456';\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1504, "s": 1465, "text": "Now given all privileges to user Bob −" }, { "code": null, "e": 1608, "s": 1504, "text": "mysql> GRANT ALL PRIVILEGES ON *.* TO 'Bob'@'%' WITH GRANT OPTION;\nQuery OK, 0 rows affected (0.23 sec)" }, { "code": null, "e": 1660, "s": 1608, "text": "Now flush the privileges. The query is as follows −" }, { "code": null, "e": 1722, "s": 1660, "text": "mysql> FLUSH PRIVILEGES;\nQuery OK, 0 rows affected (0.14 sec)" }, { "code": null, "e": 1802, "s": 1722, "text": "Now here I am using user Bob with password 123456. The snapshot is as follows −" } ]
C program to print number series without using any loop
In this problem, we are given two numbers N and K. Our task is to create a program that will print number series without using any loop. The series that is to be printed will start from n and will be subtracted by k till it becomes zero or negative. After that, we will start to add k to it till it becomes n again. If this process we cannot use any type of loop. Let’s take an example to understand the problem, n = 12 , k = 3 12 9 6 3 0 3 6 9 12 To solve this problem without using a loop we will use recursion. We will create a recursive function that will call itself again and keep a check on the value of the number to ensure which operation out of addition or subtraction is to be one on the number. The function will use a flag that will help us to keep track of whether the value is to be subtracted or added. // C program to print number series without using any loop Live Demo #include <iostream> using namespace std; void PrintSeriesRec(int current, int N, int K, bool flag){ cout<<current<<"\t"; if (current <= 0) flag = !flag; if (current == N && !flag) return; if (flag == true) PrintSeriesRec(current - K, N, K, flag); else if (!flag) PrintSeriesRec(current + K, N, K, flag); } int main(){ int N = 12, K = 4; cout<<"The series is : \n"; PrintSeriesRec(N, N, K, true); return 0; } The series is − 12 8 4 0 4 8 12
[ { "code": null, "e": 1199, "s": 1062, "text": "In this problem, we are given two numbers N and K. Our task is to create a program that will print number series without using any loop." }, { "code": null, "e": 1426, "s": 1199, "text": "The series that is to be printed will start from n and will be subtracted by k till it becomes zero or negative. After that, we will start to add k to it till it becomes n again. If this process we cannot use any type of loop." }, { "code": null, "e": 1475, "s": 1426, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1490, "s": 1475, "text": "n = 12 , k = 3" }, { "code": null, "e": 1510, "s": 1490, "text": "12 9 6 3 0 3 6 9 12" }, { "code": null, "e": 1769, "s": 1510, "text": "To solve this problem without using a loop we will use recursion. We will create a recursive function that will call itself again and keep a check on the value of the number to ensure which operation out of addition or subtraction is to be one on the number." }, { "code": null, "e": 1881, "s": 1769, "text": "The function will use a flag that will help us to keep track of whether the value is to be subtracted or added." }, { "code": null, "e": 1940, "s": 1881, "text": "// C program to print number series without using any loop" }, { "code": null, "e": 1951, "s": 1940, "text": " Live Demo" }, { "code": null, "e": 2410, "s": 1951, "text": "#include <iostream>\nusing namespace std;\nvoid PrintSeriesRec(int current, int N, int K, bool flag){\n cout<<current<<\"\\t\";\n if (current <= 0)\n flag = !flag;\n if (current == N && !flag)\n return;\n if (flag == true)\n PrintSeriesRec(current - K, N, K, flag);\n else if (!flag)\n PrintSeriesRec(current + K, N, K, flag);\n}\nint main(){\n int N = 12, K = 4;\n cout<<\"The series is : \\n\";\n PrintSeriesRec(N, N, K, true);\n return 0;\n}" }, { "code": null, "e": 2426, "s": 2410, "text": "The series is −" }, { "code": null, "e": 2442, "s": 2426, "text": "12 8 4 0 4 8 12" } ]
border-info class in Bootstrap 4
Use the border-info class in Bootstrap, to set a border that indicates information. Set the class as if you use any other class in Bootstrap: <div class="one border border-info"> Details </div> Above, we added border-info class. Another class, “one” is used to give shape to the div element − .one { width: 180px; height: 180px; margin: 55px; } You can try to run the following code to implement the border-info class on a rectangle − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <style> .one { width: 180px; height: 180px; margin: 55px; } </style> </head> <body> <div class="container"> <p>Rectangle with a border to set information:</p> <div class="one border border-info">Details</div> </div> </body> </html>
[ { "code": null, "e": 1204, "s": 1062, "text": "Use the border-info class in Bootstrap, to set a border that indicates information. Set the class as if you use any other class in Bootstrap:" }, { "code": null, "e": 1258, "s": 1204, "text": "<div class=\"one border border-info\">\n Details\n</div>" }, { "code": null, "e": 1357, "s": 1258, "text": "Above, we added border-info class. Another class, “one” is used to give shape to the div element −" }, { "code": null, "e": 1415, "s": 1357, "text": ".one {\n width: 180px;\n height: 180px;\n margin: 55px;\n}" }, { "code": null, "e": 1505, "s": 1415, "text": "You can try to run the following code to implement the border-info class on a rectangle −" }, { "code": null, "e": 1515, "s": 1505, "text": "Live Demo" }, { "code": null, "e": 2239, "s": 1515, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n <style>\n .one {\n width: 180px;\n height: 180px;\n margin: 55px;\n }\n </style>\n </head>\n<body>\n\n<div class=\"container\">\n <p>Rectangle with a border to set information:</p>\n <div class=\"one border border-info\">Details</div>\n</div>\n\n</body>\n</html>" } ]
MySQL - SHOW CREATE TABLE Statement
This query shows/displays the statement used to create the specified table. This displays the create statements along with the clauses. Following is the syntax of the SHOW CREATE TABLE statement − SHOW CREATE TABLE [IF NOT EXISTS] table_name Where, table_name is the name of the table. Suppose we have created a database as shown below − mysql> CREATE TABLE Employee( Name VARCHAR(255), Salary INT NOT NULL, Location VARCHAR(255) ); Query OK, 0 rows affected (1.34 sec) The following query displays the query used to create the database − mysql> SHOW CREATE TABLE Employee; +----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Employee | CREATE TABLE `employee` ( `ID` int NOT NULL, `Name` varchar(255) DEFAULT NULL, `Salary` int NOT NULL, `Location` varchar(255) DEFAULT NULL, `Address` varchar(50) DEFAULT NULL, `Phone` int DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `con` (`Phone`), CONSTRAINT `MyPrimaryKey` FOREIGN KEY (`ID`) REFERENCES `test` (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | +----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.07 sec) If you try to create a table with an existing name an error will be generated − mysql> CREATE TABLE Employee(ID int); ERROR 1050 (42S01): Table 'employee' already exists If you use the IF NOT EXISTS clause along with the CREATE statement as shown below a new table will be created and if a table with the given name, already exists the query will be ignored. mysql> CREATE TABLE IF NOT EXISTS Employee(ID int); Query OK, 0 rows affected, 1 warning (0.10 sec) If the CREATE TABLE statement has an IF NOT EXISTS clause in it, then the result of the SHOW CREATE TABLE Statement of the respective database also contains the IF NOT EXISTS clause. mysql> Show create table TestTable; +-----------+-----------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+-----------------------------------------------------------------------------------------------------------------------+ | TestTable | CREATE TABLE `testtable` (`ID` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | +-----------+-----------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2469, "s": 2333, "text": "This query shows/displays the statement used to create the specified table. This displays the create statements along with the clauses." }, { "code": null, "e": 2530, "s": 2469, "text": "Following is the syntax of the SHOW CREATE TABLE statement −" }, { "code": null, "e": 2576, "s": 2530, "text": "SHOW CREATE TABLE [IF NOT EXISTS] table_name\n" }, { "code": null, "e": 2620, "s": 2576, "text": "Where, table_name is the name of the table." }, { "code": null, "e": 2672, "s": 2620, "text": "Suppose we have created a database as shown below −" }, { "code": null, "e": 2813, "s": 2672, "text": "mysql> CREATE TABLE Employee(\n Name VARCHAR(255),\n Salary INT NOT NULL,\n Location VARCHAR(255)\n);\nQuery OK, 0 rows affected (1.34 sec)" }, { "code": null, "e": 2882, "s": 2813, "text": "The following query displays the query used to create the database −" }, { "code": null, "e": 5041, "s": 2882, "text": "mysql> SHOW CREATE TABLE Employee;\n+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table |\n+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Employee | CREATE TABLE `employee` ( `ID` int NOT NULL, `Name` varchar(255) DEFAULT NULL, `Salary` int NOT NULL, `Location` varchar(255) DEFAULT NULL, `Address` varchar(50) DEFAULT NULL, `Phone` int DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `con` (`Phone`), CONSTRAINT `MyPrimaryKey` FOREIGN KEY (`ID`) REFERENCES `test` (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.07 sec)" }, { "code": null, "e": 5121, "s": 5041, "text": "If you try to create a table with an existing name an error will be generated −" }, { "code": null, "e": 5211, "s": 5121, "text": "mysql> CREATE TABLE Employee(ID int);\nERROR 1050 (42S01): Table 'employee' already exists" }, { "code": null, "e": 5400, "s": 5211, "text": "If you use the IF NOT EXISTS clause along with the CREATE statement as shown below a new table will be created and if a table with the given name, already exists the query will be ignored." }, { "code": null, "e": 5500, "s": 5400, "text": "mysql> CREATE TABLE IF NOT EXISTS Employee(ID int);\nQuery OK, 0 rows affected, 1 warning (0.10 sec)" }, { "code": null, "e": 5683, "s": 5500, "text": "If the CREATE TABLE statement has an IF NOT EXISTS clause in it, then the result of the SHOW CREATE TABLE Statement of the respective database also contains the IF NOT EXISTS clause." }, { "code": null, "e": 6414, "s": 5683, "text": "mysql> Show create table TestTable;\n+-----------+-----------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table | \n+-----------+-----------------------------------------------------------------------------------------------------------------------+\n| TestTable | CREATE TABLE `testtable` (`ID` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+-----------+-----------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 6447, "s": 6414, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 6475, "s": 6447, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6510, "s": 6475, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6527, "s": 6510, "text": " Frahaan Hussain" }, { "code": null, "e": 6561, "s": 6527, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6596, "s": 6561, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 6630, "s": 6596, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 6658, "s": 6630, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6691, "s": 6658, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6711, "s": 6691, "text": " Harshit Srivastava" }, { "code": null, "e": 6744, "s": 6711, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 6762, "s": 6744, "text": " Trevoir Williams" }, { "code": null, "e": 6769, "s": 6762, "text": " Print" }, { "code": null, "e": 6780, "s": 6769, "text": " Add Notes" } ]
Matplotlib.pyplot.xticks() in Python - GeeksforGeeks
12 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The annotate() function in pyplot module of matplotlib library is used to get and set the current tick locations and labels of the x-axis. Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs) Parameters: This method accept the following parameters that are described below: ticks: This parameter is the list of xtick locations. and an optional parameter. If an empty list is passed as an argument then it will removes all xticks labels: This parameter contains labels to place at the given ticks locations. And it is an optional parameter. **kwargs: This parameter is Text properties that is used to control the appearance of the labels. Returns: This returns the following: locs :This returns the list of ytick locations. labels :This returns the list of ylabel Text objects. The resultant is (locs, labels) Below examples illustrate the matplotlib.pyplot.xticks() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib.pyplot.xticks()# function import numpy as npimport matplotlib.pyplot as plt x = [1, 2, 3, 4]y = [95, 38, 54, 35]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4'] plt.plot(x, y) # You can specify a rotation for the tick# labels in degrees or with keywords.plt.xticks(x, labels, rotation ='vertical') # Pad margins so that markers don't get # clipped by the axesplt.margins(0.2) # Tweak spacing to prevent clipping of tick-labelsplt.subplots_adjust(bottom = 0.15)plt.show() Output: Example #2: # Implementation of matplotlib.pyplot.xticks()# function import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes def get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data("axes_grid / bivariate_normal.npy", asfileobj = False) z = np.load(f) # z is a numpy array of 15x15 return z, (3, 19, 4, 13) fig, ax = plt.subplots(figsize =[5, 4]) Z, extent = get_demo_image() ax.set(aspect = 1, xlim =(0, 65), ylim =(0, 50)) axins = zoomed_inset_axes(ax, zoom = 2, loc ='upper right') im = axins.imshow(Z, extent = extent, interpolation ="nearest", origin ="upper") plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.xticks(visible = False)plt.show() Output: Python-matplotlib 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 Convert integer to string in Python
[ { "code": null, "e": 26181, "s": 26153, "text": "\n12 Apr, 2020" }, { "code": null, "e": 26376, "s": 26181, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 26515, "s": 26376, "text": "The annotate() function in pyplot module of matplotlib library is used to get and set the current tick locations and labels of the x-axis." }, { "code": null, "e": 26523, "s": 26515, "text": "Syntax:" }, { "code": null, "e": 26583, "s": 26523, "text": "matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)" }, { "code": null, "e": 26665, "s": 26583, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26820, "s": 26665, "text": "ticks: This parameter is the list of xtick locations. and an optional parameter. If an empty list is passed as an argument then it will removes all xticks" }, { "code": null, "e": 26931, "s": 26820, "text": "labels: This parameter contains labels to place at the given ticks locations. And it is an optional parameter." }, { "code": null, "e": 27029, "s": 26931, "text": "**kwargs: This parameter is Text properties that is used to control the appearance of the labels." }, { "code": null, "e": 27066, "s": 27029, "text": "Returns: This returns the following:" }, { "code": null, "e": 27114, "s": 27066, "text": "locs :This returns the list of ytick locations." }, { "code": null, "e": 27168, "s": 27114, "text": "labels :This returns the list of ylabel Text objects." }, { "code": null, "e": 27200, "s": 27168, "text": "The resultant is (locs, labels)" }, { "code": null, "e": 27288, "s": 27200, "text": "Below examples illustrate the matplotlib.pyplot.xticks() function in matplotlib.pyplot:" }, { "code": null, "e": 27300, "s": 27288, "text": "Example #1:" }, { "code": "# Implementation of matplotlib.pyplot.xticks()# function import numpy as npimport matplotlib.pyplot as plt x = [1, 2, 3, 4]y = [95, 38, 54, 35]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4'] plt.plot(x, y) # You can specify a rotation for the tick# labels in degrees or with keywords.plt.xticks(x, labels, rotation ='vertical') # Pad margins so that markers don't get # clipped by the axesplt.margins(0.2) # Tweak spacing to prevent clipping of tick-labelsplt.subplots_adjust(bottom = 0.15)plt.show()", "e": 27811, "s": 27300, "text": null }, { "code": null, "e": 27819, "s": 27811, "text": "Output:" }, { "code": null, "e": 27831, "s": 27819, "text": "Example #2:" }, { "code": "# Implementation of matplotlib.pyplot.xticks()# function import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes def get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data(\"axes_grid / bivariate_normal.npy\", asfileobj = False) z = np.load(f) # z is a numpy array of 15x15 return z, (3, 19, 4, 13) fig, ax = plt.subplots(figsize =[5, 4]) Z, extent = get_demo_image() ax.set(aspect = 1, xlim =(0, 65), ylim =(0, 50)) axins = zoomed_inset_axes(ax, zoom = 2, loc ='upper right') im = axins.imshow(Z, extent = extent, interpolation =\"nearest\", origin =\"upper\") plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.xticks(visible = False)plt.show() ", "e": 28706, "s": 27831, "text": null }, { "code": null, "e": 28714, "s": 28706, "text": "Output:" }, { "code": null, "e": 28732, "s": 28714, "text": "Python-matplotlib" }, { "code": null, "e": 28739, "s": 28732, "text": "Python" }, { "code": null, "e": 28837, "s": 28739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28855, "s": 28837, "text": "Python Dictionary" }, { "code": null, "e": 28890, "s": 28855, "text": "Read a file line by line in Python" }, { "code": null, "e": 28922, "s": 28890, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28944, "s": 28922, "text": "Enumerate() in Python" }, { "code": null, "e": 28986, "s": 28944, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29016, "s": 28986, "text": "Iterate over a list in Python" }, { "code": null, "e": 29042, "s": 29016, "text": "Python String | replace()" }, { "code": null, "e": 29071, "s": 29042, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29115, "s": 29071, "text": "Reading and Writing to text files in Python" } ]
Rearrange and update array elements as specified by the given queries - GeeksforGeeks
22 Jun, 2021 Given an array arr[] of size N and queries Q[][], the task is to perform the following types of queries on the given array. 0: Left shift the array by one position. 1: Right shift the array by one position. 2 X Y: Update the value of arr[X] = Y. 3 X: Print arr[X]. Example: Input: arr[]={1, 2, 3, 4, 5}, Q[][]={{0}, {1}, {3, 1}, {2, 2, 54}, {3, 2}}.Output:4 54Explanation: Query1: The array arr[] modifies to {2, 3, 4, 5, 1} Query2: The array arr[] modifies to {1, 2, 3, 4, 5} Query3: Print the value of arr[1] i.e. 2 Query4: The array arr[] modifies to {1, 54, 3, 4, 5} Query5: Print the value of arr[2], i.e. 54. Input: arr[]={1}, Q[][]={{0}, {1}, {2, 0, 54}, {3, 0}}Output: 54 Approach: The problem can be solved using Deque(Double Ended queue) to perform the insert and delete operation at the front and back of the queue in O(1). Follow the below steps to solve the problem. Create a double-ended Queue, dq.Push all elements of the array arr[] to dq.For the query of type 0(Left Shift), pop an element from the front of dq and push the element to the back of dq.For the query of type 1(Right Shift), pop an element from the back of dq and push the element to the front of dq.For the query of type 2, update dq[X] = Y.For the query of type 3, print dq[X]. Create a double-ended Queue, dq. Push all elements of the array arr[] to dq. For the query of type 0(Left Shift), pop an element from the front of dq and push the element to the back of dq. For the query of type 1(Right Shift), pop an element from the back of dq and push the element to the front of dq. For the query of type 2, update dq[X] = Y. For the query of type 3, print dq[X]. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to perform the// given operationsvoid Queries(int arr[], int N, vector<vector<int> >& Q){ // Dequeue to store the // array elements deque<int> dq; // Insert all element of // the array into the dequeue for (int i = 0; i < N; i++) { dq.push_back(arr[i]); } // Stores the size of the queue int sz = Q.size(); // Traverse each query for (int i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue int front = dq[0]; // Pop the element at // the front of the queue dq.pop_front(); // Push the element at // the back of the queue dq.push_back(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue int back = dq[N - 1]; // Pop the element at // the back of the queue dq.pop_back(); // Push the element at // the front of the queue dq.push_front(back); } // Query for update else if (Q[i][0] == 2) { dq[Q[i][1]] = Q[i][2]; } // Query to get the value else { cout << dq[Q[i][1]] << " "; } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); vector<vector<int> > Q; // All possible Queries Q = { { 0 }, { 1 }, { 3, 1 }, { 2, 2, 54 }, { 3, 2 } }; Queries(arr, N, Q); return 0;} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to perform the// given operationsstatic void Queries(int arr[], int N, int [][]Q){ // Dequeue to store the // array elements Vector<Integer> dq = new Vector<>(); // Insert all element of // the array into the dequeue for (int i = 0; i < N; i++) { dq.add(arr[i]); } // Stores the size of the queue int sz = Q.length; // Traverse each query for (int i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue int front = dq.get(0); // Pop the element at // the front of the queue dq.remove(0); // Push the element at // the back of the queue dq.add(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue int back = dq.elementAt(dq.size() - 1); // Pop the element at // the back of the queue dq.remove(dq.size() - 1); // Push the element at // the front of the queue dq.add(0, back); } // Query for update else if (Q[i][0] == 2) { dq.set(Q[i][1], Q[i][2]); } // Query to get the value else { System.out.print(dq.get(Q[i][1]) + " "); } }} // Driver Codepublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5}; int N = arr.length; // Vector<Vector<Integer> // > Q = new Vector<>(); // All possible Queries int [][]Q = {{0}, {1}, {3, 1}, {2, 2, 54}, {3, 2}}; Queries(arr, N, Q);}} // This code is contributed by Princi Singh # Python3 program to implement# the above approachfrom collections import deque # Function to perform the# given operationsdef Queries(arr, N, Q): # Dequeue to store the # array elements dq = deque() # Insert all element of # the array into the dequeue for i in range(N): dq.append(arr[i]) # Stores the size of the queue sz = len(Q) # Traverse each query for i in range(sz): # Query for left shift. if (Q[i][0] == 0): # Extract the element at # the front of the queue front = dq[0] # Pop the element at # the front of the queue dq.popleft() # Push the element at # the back of the queue dq.appendleft(front) # Query for right shift elif (Q[i][0] == 1): # Extract the element at # the back of the queue back = dq[N - 1] # Pop the element at # the back of the queue dq.popleft() # Push the element at # the front of the queue dq.appendleft(back) # Query for update elif (Q[i][0] == 2): dq[Q[i][1]] = Q[i][2] # Query to get the value else: print(dq[Q[i][1]], end = " ") # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ] N = len(arr) # All possible Queries Q = [ [ 0 ], [ 1 ], [ 3, 1 ], [ 2, 2, 54 ], [ 3, 2 ] ] Queries(arr, N, Q) # This code is contributed by mohit kumar 29 <script>// Javascript program to implement// the above approach // Function to perform the// given operationsfunction Queries(arr,N,Q){ // Dequeue to store the // array elements let dq = []; // Insert all element of // the array into the dequeue for (let i = 0; i < N; i++) { dq.push(arr[i]); } // Stores the size of the queue let sz = Q.length; // Traverse each query for (let i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue let front = dq[0]; // Pop the element at // the front of the queue dq.shift(); // Push the element at // the back of the queue dq.push(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue let back = dq[dq.length - 1]; // Pop the element at // the back of the queue dq.pop(); // Push the element at // the front of the queue dq.unshift( back); } // Query for update else if (Q[i][0] == 2) { dq[Q[i][1]] = Q[i][2]; } // Query to get the value else { document.write(dq[Q[i][1]] + " "); } }} // Driver Codelet arr=[1, 2, 3, 4, 5];let N = arr.length; // Vector<Vector<Integer>// > Q = new Vector<>(); // All possible Querieslet Q = [[0], [1], [3, 1],[2, 2, 54], [3, 2]];Queries(arr, N, Q); // This code is contributed by unknown2108</script> 2 54 Time Complexity: O(N+|Q|)Auxiliary Space: O(N) mohit kumar 29 princi singh unknown2108 array-range-queries array-rearrange deque Arrays Mathematical Queue Arrays Mathematical Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 26349, "s": 26321, "text": "\n22 Jun, 2021" }, { "code": null, "e": 26514, "s": 26349, "text": "Given an array arr[] of size N and queries Q[][], the task is to perform the following types of queries on the given array. 0: Left shift the array by one position." }, { "code": null, "e": 26556, "s": 26514, "text": "1: Right shift the array by one position." }, { "code": null, "e": 26595, "s": 26556, "text": "2 X Y: Update the value of arr[X] = Y." }, { "code": null, "e": 26614, "s": 26595, "text": "3 X: Print arr[X]." }, { "code": null, "e": 26623, "s": 26614, "text": "Example:" }, { "code": null, "e": 26964, "s": 26623, "text": "Input: arr[]={1, 2, 3, 4, 5}, Q[][]={{0}, {1}, {3, 1}, {2, 2, 54}, {3, 2}}.Output:4 54Explanation: Query1: The array arr[] modifies to {2, 3, 4, 5, 1} Query2: The array arr[] modifies to {1, 2, 3, 4, 5} Query3: Print the value of arr[1] i.e. 2 Query4: The array arr[] modifies to {1, 54, 3, 4, 5} Query5: Print the value of arr[2], i.e. 54." }, { "code": null, "e": 27029, "s": 26964, "text": "Input: arr[]={1}, Q[][]={{0}, {1}, {2, 0, 54}, {3, 0}}Output: 54" }, { "code": null, "e": 27229, "s": 27029, "text": "Approach: The problem can be solved using Deque(Double Ended queue) to perform the insert and delete operation at the front and back of the queue in O(1). Follow the below steps to solve the problem." }, { "code": null, "e": 27609, "s": 27229, "text": "Create a double-ended Queue, dq.Push all elements of the array arr[] to dq.For the query of type 0(Left Shift), pop an element from the front of dq and push the element to the back of dq.For the query of type 1(Right Shift), pop an element from the back of dq and push the element to the front of dq.For the query of type 2, update dq[X] = Y.For the query of type 3, print dq[X]." }, { "code": null, "e": 27642, "s": 27609, "text": "Create a double-ended Queue, dq." }, { "code": null, "e": 27686, "s": 27642, "text": "Push all elements of the array arr[] to dq." }, { "code": null, "e": 27799, "s": 27686, "text": "For the query of type 0(Left Shift), pop an element from the front of dq and push the element to the back of dq." }, { "code": null, "e": 27913, "s": 27799, "text": "For the query of type 1(Right Shift), pop an element from the back of dq and push the element to the front of dq." }, { "code": null, "e": 27956, "s": 27913, "text": "For the query of type 2, update dq[X] = Y." }, { "code": null, "e": 27994, "s": 27956, "text": "For the query of type 3, print dq[X]." }, { "code": null, "e": 28045, "s": 27994, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28049, "s": 28045, "text": "C++" }, { "code": null, "e": 28054, "s": 28049, "text": "Java" }, { "code": null, "e": 28062, "s": 28054, "text": "Python3" }, { "code": null, "e": 28073, "s": 28062, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to perform the// given operationsvoid Queries(int arr[], int N, vector<vector<int> >& Q){ // Dequeue to store the // array elements deque<int> dq; // Insert all element of // the array into the dequeue for (int i = 0; i < N; i++) { dq.push_back(arr[i]); } // Stores the size of the queue int sz = Q.size(); // Traverse each query for (int i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue int front = dq[0]; // Pop the element at // the front of the queue dq.pop_front(); // Push the element at // the back of the queue dq.push_back(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue int back = dq[N - 1]; // Pop the element at // the back of the queue dq.pop_back(); // Push the element at // the front of the queue dq.push_front(back); } // Query for update else if (Q[i][0] == 2) { dq[Q[i][1]] = Q[i][2]; } // Query to get the value else { cout << dq[Q[i][1]] << \" \"; } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); vector<vector<int> > Q; // All possible Queries Q = { { 0 }, { 1 }, { 3, 1 }, { 2, 2, 54 }, { 3, 2 } }; Queries(arr, N, Q); return 0;}", "e": 29820, "s": 28073, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to perform the// given operationsstatic void Queries(int arr[], int N, int [][]Q){ // Dequeue to store the // array elements Vector<Integer> dq = new Vector<>(); // Insert all element of // the array into the dequeue for (int i = 0; i < N; i++) { dq.add(arr[i]); } // Stores the size of the queue int sz = Q.length; // Traverse each query for (int i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue int front = dq.get(0); // Pop the element at // the front of the queue dq.remove(0); // Push the element at // the back of the queue dq.add(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue int back = dq.elementAt(dq.size() - 1); // Pop the element at // the back of the queue dq.remove(dq.size() - 1); // Push the element at // the front of the queue dq.add(0, back); } // Query for update else if (Q[i][0] == 2) { dq.set(Q[i][1], Q[i][2]); } // Query to get the value else { System.out.print(dq.get(Q[i][1]) + \" \"); } }} // Driver Codepublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5}; int N = arr.length; // Vector<Vector<Integer> // > Q = new Vector<>(); // All possible Queries int [][]Q = {{0}, {1}, {3, 1}, {2, 2, 54}, {3, 2}}; Queries(arr, N, Q);}} // This code is contributed by Princi Singh", "e": 31477, "s": 29820, "text": null }, { "code": "# Python3 program to implement# the above approachfrom collections import deque # Function to perform the# given operationsdef Queries(arr, N, Q): # Dequeue to store the # array elements dq = deque() # Insert all element of # the array into the dequeue for i in range(N): dq.append(arr[i]) # Stores the size of the queue sz = len(Q) # Traverse each query for i in range(sz): # Query for left shift. if (Q[i][0] == 0): # Extract the element at # the front of the queue front = dq[0] # Pop the element at # the front of the queue dq.popleft() # Push the element at # the back of the queue dq.appendleft(front) # Query for right shift elif (Q[i][0] == 1): # Extract the element at # the back of the queue back = dq[N - 1] # Pop the element at # the back of the queue dq.popleft() # Push the element at # the front of the queue dq.appendleft(back) # Query for update elif (Q[i][0] == 2): dq[Q[i][1]] = Q[i][2] # Query to get the value else: print(dq[Q[i][1]], end = \" \") # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ] N = len(arr) # All possible Queries Q = [ [ 0 ], [ 1 ], [ 3, 1 ], [ 2, 2, 54 ], [ 3, 2 ] ] Queries(arr, N, Q) # This code is contributed by mohit kumar 29", "e": 33017, "s": 31477, "text": null }, { "code": "<script>// Javascript program to implement// the above approach // Function to perform the// given operationsfunction Queries(arr,N,Q){ // Dequeue to store the // array elements let dq = []; // Insert all element of // the array into the dequeue for (let i = 0; i < N; i++) { dq.push(arr[i]); } // Stores the size of the queue let sz = Q.length; // Traverse each query for (let i = 0; i < sz; i++) { // Query for left shift. if (Q[i][0] == 0) { // Extract the element at // the front of the queue let front = dq[0]; // Pop the element at // the front of the queue dq.shift(); // Push the element at // the back of the queue dq.push(front); } // Query for right shift else if (Q[i][0] == 1) { // Extract the element at // the back of the queue let back = dq[dq.length - 1]; // Pop the element at // the back of the queue dq.pop(); // Push the element at // the front of the queue dq.unshift( back); } // Query for update else if (Q[i][0] == 2) { dq[Q[i][1]] = Q[i][2]; } // Query to get the value else { document.write(dq[Q[i][1]] + \" \"); } }} // Driver Codelet arr=[1, 2, 3, 4, 5];let N = arr.length; // Vector<Vector<Integer>// > Q = new Vector<>(); // All possible Querieslet Q = [[0], [1], [3, 1],[2, 2, 54], [3, 2]];Queries(arr, N, Q); // This code is contributed by unknown2108</script>", "e": 34498, "s": 33017, "text": null }, { "code": null, "e": 34503, "s": 34498, "text": "2 54" }, { "code": null, "e": 34550, "s": 34503, "text": "Time Complexity: O(N+|Q|)Auxiliary Space: O(N)" }, { "code": null, "e": 34565, "s": 34550, "text": "mohit kumar 29" }, { "code": null, "e": 34578, "s": 34565, "text": "princi singh" }, { "code": null, "e": 34590, "s": 34578, "text": "unknown2108" }, { "code": null, "e": 34610, "s": 34590, "text": "array-range-queries" }, { "code": null, "e": 34626, "s": 34610, "text": "array-rearrange" }, { "code": null, "e": 34632, "s": 34626, "text": "deque" }, { "code": null, "e": 34639, "s": 34632, "text": "Arrays" }, { "code": null, "e": 34652, "s": 34639, "text": "Mathematical" }, { "code": null, "e": 34658, "s": 34652, "text": "Queue" }, { "code": null, "e": 34665, "s": 34658, "text": "Arrays" }, { "code": null, "e": 34678, "s": 34665, "text": "Mathematical" }, { "code": null, "e": 34684, "s": 34678, "text": "Queue" }, { "code": null, "e": 34782, "s": 34684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34850, "s": 34782, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34894, "s": 34850, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34942, "s": 34894, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34965, "s": 34942, "text": "Introduction to Arrays" }, { "code": null, "e": 34997, "s": 34965, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35027, "s": 34997, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35042, "s": 35027, "text": "C++ Data Types" }, { "code": null, "e": 35085, "s": 35042, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 35104, "s": 35085, "text": "Coin Change | DP-7" } ]
SQL - SELECT from Multiple Tables with MS SQL Server - GeeksforGeeks
14 Jun, 2021 In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n rows then the resulting table after selecting two tables i.e cross join of two tables contains m*n rows. Let us see how to select multiple tables using the MSSQL server: Creating a database GeeksForGeeks by using the following SQL query as follows. CREATE DATABASE GeeksForGeeks; Using the database student using the following SQL query as follows. USE GeeksForGeeks; Creating three tables student, branch_details, credit_details with SQL query as follows: CREATE TABLE student ( stu_id varchar(10), stu_name varchar(20), branch varchar(20) ); CREATE TABLE branch_details ( branch_name varchar(10), subjects INT ); CREATE TABLE credit_details ( branch varchar(20), max_credits INT, min_credits_required INT ); To view the description of the three tables in the database GeeksForGeeks using the following SQL query as follows. EXEC sp_columns student; EXEC sp_columns branch_details; EXEC sp_columns credit_details; Inserting rows into tables using the following SQL query as follows: INSERT INTO student VALUES ('1901401','DEVA','C.S'), ('1901402','HARSH','C.S'), ('1901403','DAVID','E.C'), ('1901404','GAURAV','E.C'); INSERT INTO branch_details VALUES ('C.S',8), ('E.C',7), ('M.E',7), ('I.C.E',9), ('E.E.E',8); INSERT INTO credit_details VALUES ('C.S',24, 12), ('E.C',21, 11), ('M.E',21, 11), ('I.C.E',27,14), ('E.E.E',24,12); Viewing the three tables after inserting rows by using the following SQL query as follows. SELECT * FROM student; SELECT * FROM branch_details; SELECT * FROM credit_details; SYNTAX: SELECT columns FROM table_1, table_2,...table_n WHERE condition; Using SELECT statements for 2 tables student, branch_details: SELECT * FROM student, branch_details; This table contains 4*5 = 20 rows. Using SELECT statements for 3 tables student, branch_details, credit_details: SELECT * FROM student, branch_details, credit_details; The resulting table contains 5*4*5 = 100 rows. We can obtain other types of join by selecting multiple tables and mentioning appropriate condition in the WHERE clause but instead of using the SELECT with multiple tables and adding conditions using the keywords of joins is more optimal. Example: Query to display students who have enrolled in a course and their particulars. SELECT student.stu_id, student.stu_name, student.branch, subjects, max_credits FROM student, branch_details, credit_details WHERE student.branch = branch_details.branch_name AND branch_details.branch_name = credit_details.branch; Note: When there are columns with the same name in different tables it is good to dot operator to point to the particular tables data. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n14 Jun, 2021" }, { "code": null, "e": 25969, "s": 25513, "text": "In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n rows then the resulting table after selecting two tables i.e cross join of two tables contains m*n rows." }, { "code": null, "e": 26035, "s": 25969, "text": "Let us see how to select multiple tables using the MSSQL server: " }, { "code": null, "e": 26114, "s": 26035, "text": "Creating a database GeeksForGeeks by using the following SQL query as follows." }, { "code": null, "e": 26145, "s": 26114, "text": "CREATE DATABASE GeeksForGeeks;" }, { "code": null, "e": 26214, "s": 26145, "text": "Using the database student using the following SQL query as follows." }, { "code": null, "e": 26233, "s": 26214, "text": "USE GeeksForGeeks;" }, { "code": null, "e": 26323, "s": 26233, "text": "Creating three tables student, branch_details, credit_details with SQL query as follows:" }, { "code": null, "e": 26412, "s": 26323, "text": "CREATE TABLE student\n( \nstu_id varchar(10),\nstu_name varchar(20),\nbranch varchar(20)\n);" }, { "code": null, "e": 26485, "s": 26412, "text": "CREATE TABLE branch_details\n( \nbranch_name varchar(10),\nsubjects INT\n);" }, { "code": null, "e": 26583, "s": 26485, "text": "CREATE TABLE credit_details\n( \nbranch varchar(20), \nmax_credits INT,\nmin_credits_required INT\n);" }, { "code": null, "e": 26699, "s": 26583, "text": "To view the description of the three tables in the database GeeksForGeeks using the following SQL query as follows." }, { "code": null, "e": 26788, "s": 26699, "text": "EXEC sp_columns student;\nEXEC sp_columns branch_details;\nEXEC sp_columns credit_details;" }, { "code": null, "e": 26857, "s": 26788, "text": "Inserting rows into tables using the following SQL query as follows:" }, { "code": null, "e": 27203, "s": 26857, "text": "INSERT INTO student VALUES\n('1901401','DEVA','C.S'),\n('1901402','HARSH','C.S'),\n('1901403','DAVID','E.C'),\n('1901404','GAURAV','E.C');\n\nINSERT INTO branch_details VALUES\n('C.S',8),\n('E.C',7),\n('M.E',7),\n('I.C.E',9),\n('E.E.E',8);\n\nINSERT INTO credit_details VALUES\n('C.S',24, 12),\n('E.C',21, 11),\n('M.E',21, 11),\n('I.C.E',27,14),\n('E.E.E',24,12);" }, { "code": null, "e": 27294, "s": 27203, "text": "Viewing the three tables after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 27377, "s": 27294, "text": "SELECT * FROM student;\nSELECT * FROM branch_details;\nSELECT * FROM credit_details;" }, { "code": null, "e": 27451, "s": 27377, "text": "SYNTAX:\nSELECT columns\nFROM table_1, table_2,...table_n\nWHERE condition; " }, { "code": null, "e": 27513, "s": 27451, "text": "Using SELECT statements for 2 tables student, branch_details:" }, { "code": null, "e": 27552, "s": 27513, "text": "SELECT * FROM student, branch_details;" }, { "code": null, "e": 27587, "s": 27552, "text": "This table contains 4*5 = 20 rows." }, { "code": null, "e": 27665, "s": 27587, "text": "Using SELECT statements for 3 tables student, branch_details, credit_details:" }, { "code": null, "e": 27720, "s": 27665, "text": "SELECT * FROM student, branch_details, credit_details;" }, { "code": null, "e": 27767, "s": 27720, "text": "The resulting table contains 5*4*5 = 100 rows." }, { "code": null, "e": 28007, "s": 27767, "text": "We can obtain other types of join by selecting multiple tables and mentioning appropriate condition in the WHERE clause but instead of using the SELECT with multiple tables and adding conditions using the keywords of joins is more optimal." }, { "code": null, "e": 28016, "s": 28007, "text": "Example:" }, { "code": null, "e": 28095, "s": 28016, "text": "Query to display students who have enrolled in a course and their particulars." }, { "code": null, "e": 28326, "s": 28095, "text": "SELECT student.stu_id, student.stu_name,\nstudent.branch, subjects, max_credits\nFROM student, branch_details, credit_details\nWHERE student.branch = branch_details.branch_name AND \nbranch_details.branch_name = credit_details.branch;" }, { "code": null, "e": 28461, "s": 28326, "text": "Note: When there are columns with the same name in different tables it is good to dot operator to point to the particular tables data." }, { "code": null, "e": 28468, "s": 28461, "text": "Picked" }, { "code": null, "e": 28478, "s": 28468, "text": "SQL-Query" }, { "code": null, "e": 28489, "s": 28478, "text": "SQL-Server" }, { "code": null, "e": 28493, "s": 28489, "text": "SQL" }, { "code": null, "e": 28497, "s": 28493, "text": "SQL" }, { "code": null, "e": 28595, "s": 28497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28661, "s": 28595, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28676, "s": 28661, "text": "SQL | Subquery" }, { "code": null, "e": 28733, "s": 28676, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28765, "s": 28733, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28843, "s": 28765, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28860, "s": 28843, "text": "SQL using Python" }, { "code": null, "e": 28896, "s": 28860, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28962, "s": 28896, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 29024, "s": 28962, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
How to Use Dist Function in R? - GeeksforGeeks
24 Dec, 2021 In this article, we will see how to use dist() function in R programming language. R provides an inbuilt dist() function using which we can calculate six different kinds of distances between each unique pair of vectors in a two-dimensional vector. dist() method accepts a numeric matrix as an argument and a method that represent the type of distance to be measured. The method must be one of these distances – Euclidean, Maximum, Manhattan, Canberra, Binary, and Minkowski. It accepts other arguments also but they are optional. Syntax: dist(vect, method = ” “, diag = TRUE or FALSE, upper = TRUE or FALSE) Parameters: vect: A two-dimensional vector method: The distance to be measured. It must be equal to one of these, “euclidean”, “maximum”, “manhattan”, “canberra”, “binary” or “minkowski” diag: logical value (TRUE or FALSE) that conveys whether the diagonal of the distance matrix should be printed by print.dist or not. upper: logical value (TRUE or FALSE) that conveys whether the upper triangle of the distance matrix should be printed by print.dist or not. Return type: It return an object of class “dist” Now let us see how to calculate these distances using dist() function. Euclidean distance between two points in Euclidean space is basically the length of a line segment between the two points. It can be calculated from the cartesian coordinates of the points by taking the help of the Pythagorean theorem, therefore occasionally being called the Pythagorean distance. For example, In a 2-dimensional space having two points Point1 (x1,y1) and Point2 (x2,y2), the Euclidean distance is given by √(x1 – x2)2 + (y1 – y2)2. The Euclidean distance between the two vectors is given by, √Σ(vect1i - vect2i)2 where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (2, 1, 5, 8) and vect2 as (1, 2, 4, 9). Their Euclidean distance is given by, √(2 – 1)2 + (1 – 2)2 + (5 – 4)2 + (8 – 9)2 which is equal to 2. Syntax: dist(vect, method = “euclidean”, diag = TRUE or FALSE, upper = TRUE or FALSE) Example: Euclidean distance R # R program to illustrate how to calculate# euclidean distance using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Euclidean distance between each pair of vectors is: ")cat("\n\n") # Calculate Euclidean distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Euclidean distance between each unique pair of vectors# That is why we are passing Euclidean as a methoddist(twoDimensionalVect, method = "euclidean", diag = TRUE, upper = TRUE) Output: Manhattan distance is a distance metric between two points in an N-dimensional vector space. It is defined as the sum of absolute distance between coordinates in corresponding dimensions. For example, in a 2-dimensional space having two points Point1 (x1 , y1) and Point2 (x2 , y2), the Manhattan distance is given by |x1 – x2| + |y1 – y2|. In R Manhattan distance is calculated with respect to vectors. The Manhattan distance between the two vectors is given by, Σ|vect1i - vect2i| where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 7, 8, 10). Their Manhattan distance is given by, |3 – 1| + |6 – 7| + |8 – 8| + |9 – 10| which is equal to 4. Syntax: dist(vect, method = “manhattan”, diag = TRUE or FALSE, upper = TRUE or FALSE) Example: Manhattan distance R # R program to illustrate how to calculate# Manhattan distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Manhattan distance between each pair of vectors is: ")cat("\n\n") # Calculate Manhattan distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Manhattan distance between each unique pair of vectors# That is why we are passing Manhattan as a methoddist(twoDimensionalVect, method = "manhattan", diag = TRUE, upper = TRUE) Output: The maximum distance between two vectors, A and B, is calculated as the maximum difference between any pairwise elements. In R maximum distance is calculated with respect to vectors. The maximum distance between two vectors is given by, max(|vect1i - vect2i|) where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 8, 9, 10). Their Maximum distance is given by, max(|3 – 1|, |6 – 8|, |8 – 9|, |9 – 10|) which is equal to 2. Syntax: dist(vect, method = “maximum”, diag = TRUE or FALSE, upper = TRUE or FALSE) Example: Maximum distance R # R program to illustrate how to calculate Maximum distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Maximum distance between each pair of vectors is: ")cat("\n\n") # Calculate Maximum distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Maximum distance between each unique pair of vectors# That is why we are passing Maximum as a methoddist(twoDimensionalVect, method = "maximum", diag = TRUE, upper = TRUE) Output: The Canberra distance is a numerical measure of the distance between pairs of points in a vector space. In R Canberra distance is calculated with respect to vectors. The Canberra distance between two vectors is given by, ∑ |vect1i - vect2i| / (|vect1i| + |vect2i|) where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (2, 2, 7, 5) and vect2 as (3, 8, 3, 5). Their Canberra distance is given by, |2 – 3| / (2 + 3) + |2 – 8| / (2 + 8) + |7 – 3| / (7 + 3) + |5 – 5| / (5 + 5) = 0.2 + 0.6 + 0.4 + 0 which is equal to 1.2. Syntax: dist(vect, method = “canberra”, diag = TRUE or FALSE, upper = TRUE or FALSE) Example: Canberra distance R # R program to illustrate how to calculate# Canberra distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Canberra distance between each pair of vectors is: ")cat("\n\n") # Calculate Canberra distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Canberra distance between each unique pair of vectors# That is why we are passing Canberra as a methoddist(twoDimensionalVect, method = "canberra", diag = TRUE, upper = TRUE) Output: The Binary distance between two vectors, A and B, is calculated as the proportion of elements that the two vectors share. Here, vect1 is the first vector vect2 is the second vector Syntax: dist(vect, method = “binary”, diag = TRUE or FALSE, upper = TRUE or FALSE) Example: Binary distance R # R program to illustrate how to calculate# Binary distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Binary distance between each pair of vectors is: ")cat("\n\n") # Calculate Binary distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Binary distance between each unique pair of vectors# That is why we are passing Binary as a methoddist(twoDimensionalVect, method = "binary", diag = TRUE, upper = TRUE) Output: Minkowski distance is a distance measured between two points in N-dimensional space. It is a generalization of the Euclidean distance and the Manhattan distance. For example, In a 2-dimensional space having two points Point1 (x1 , y1) and Point2 (x2 , y2), the Minkowski distance is given by (|x1 – y1|p + |x2 – y2|p )1/p . In R Minkowski distance is calculated with respect to vectors. The Minkowski distance between the two vectors is given by, (Σ|vect1i - vect2i|p)1/p where, vect1 is the first vector vect2 is the second vector p is an integer R provides an inbuilt dist() method to calculate Minkowski distance between each pair of vectors in a two-dimensional vector. Syntax: dist(vect, method = “minkowski”, p = integer, diag = TRUE or FALSE, upper = TRUE or FALSE) For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (2, 7, 7, 10). Their Minkowski distance is given by, ( |3 – 2|2 + |6 – 7|2 + |8 – 7|2 + |9 – 10|2 )1/2 which is equal to 2. Example: Minkowski distance R # R program to illustrate how to calculate# Minkowski distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Minkowski distance between each pair of vectors is: ")cat("\n\n") # Calculate Minkowski distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Minkowski distance between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = "minkowski", diag = TRUE, upper = TRUE p = 2) Output: sagartomar9927 anikakapoor Picked R-Functions R-Statistics R Language 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26572, "s": 26487, "text": "In this article, we will see how to use dist() function in R programming language. " }, { "code": null, "e": 27019, "s": 26572, "text": "R provides an inbuilt dist() function using which we can calculate six different kinds of distances between each unique pair of vectors in a two-dimensional vector. dist() method accepts a numeric matrix as an argument and a method that represent the type of distance to be measured. The method must be one of these distances – Euclidean, Maximum, Manhattan, Canberra, Binary, and Minkowski. It accepts other arguments also but they are optional." }, { "code": null, "e": 27027, "s": 27019, "text": "Syntax:" }, { "code": null, "e": 27097, "s": 27027, "text": "dist(vect, method = ” “, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 27109, "s": 27097, "text": "Parameters:" }, { "code": null, "e": 27140, "s": 27109, "text": "vect: A two-dimensional vector" }, { "code": null, "e": 27284, "s": 27140, "text": "method: The distance to be measured. It must be equal to one of these, “euclidean”, “maximum”, “manhattan”, “canberra”, “binary” or “minkowski”" }, { "code": null, "e": 27417, "s": 27284, "text": "diag: logical value (TRUE or FALSE) that conveys whether the diagonal of the distance matrix should be printed by print.dist or not." }, { "code": null, "e": 27557, "s": 27417, "text": "upper: logical value (TRUE or FALSE) that conveys whether the upper triangle of the distance matrix should be printed by print.dist or not." }, { "code": null, "e": 27570, "s": 27557, "text": "Return type:" }, { "code": null, "e": 27606, "s": 27570, "text": "It return an object of class “dist”" }, { "code": null, "e": 27677, "s": 27606, "text": "Now let us see how to calculate these distances using dist() function." }, { "code": null, "e": 27976, "s": 27677, "text": "Euclidean distance between two points in Euclidean space is basically the length of a line segment between the two points. It can be calculated from the cartesian coordinates of the points by taking the help of the Pythagorean theorem, therefore occasionally being called the Pythagorean distance. " }, { "code": null, "e": 28128, "s": 27976, "text": "For example, In a 2-dimensional space having two points Point1 (x1,y1) and Point2 (x2,y2), the Euclidean distance is given by √(x1 – x2)2 + (y1 – y2)2." }, { "code": null, "e": 28190, "s": 28128, "text": "The Euclidean distance between the two vectors is given by, " }, { "code": null, "e": 28211, "s": 28190, "text": "√Σ(vect1i - vect2i)2" }, { "code": null, "e": 28218, "s": 28211, "text": "where," }, { "code": null, "e": 28244, "s": 28218, "text": "vect1 is the first vector" }, { "code": null, "e": 28271, "s": 28244, "text": "vect2 is the second vector" }, { "code": null, "e": 28463, "s": 28271, "text": "For example, we are given two vectors, vect1 as (2, 1, 5, 8) and vect2 as (1, 2, 4, 9). Their Euclidean distance is given by, √(2 – 1)2 + (1 – 2)2 + (5 – 4)2 + (8 – 9)2 which is equal to 2." }, { "code": null, "e": 28471, "s": 28463, "text": "Syntax:" }, { "code": null, "e": 28549, "s": 28471, "text": "dist(vect, method = “euclidean”, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 28578, "s": 28549, "text": "Example: Euclidean distance" }, { "code": null, "e": 28580, "s": 28578, "text": "R" }, { "code": "# R program to illustrate how to calculate# euclidean distance using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Euclidean distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Euclidean distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Euclidean distance between each unique pair of vectors# That is why we are passing Euclidean as a methoddist(twoDimensionalVect, method = \"euclidean\", diag = TRUE, upper = TRUE)", "e": 29546, "s": 28580, "text": null }, { "code": null, "e": 29554, "s": 29546, "text": "Output:" }, { "code": null, "e": 29896, "s": 29554, "text": "Manhattan distance is a distance metric between two points in an N-dimensional vector space. It is defined as the sum of absolute distance between coordinates in corresponding dimensions. For example, in a 2-dimensional space having two points Point1 (x1 , y1) and Point2 (x2 , y2), the Manhattan distance is given by |x1 – x2| + |y1 – y2|. " }, { "code": null, "e": 30021, "s": 29896, "text": "In R Manhattan distance is calculated with respect to vectors. The Manhattan distance between the two vectors is given by, " }, { "code": null, "e": 30041, "s": 30021, "text": "Σ|vect1i - vect2i| " }, { "code": null, "e": 30049, "s": 30041, "text": "where, " }, { "code": null, "e": 30075, "s": 30049, "text": "vect1 is the first vector" }, { "code": null, "e": 30102, "s": 30075, "text": "vect2 is the second vector" }, { "code": null, "e": 30290, "s": 30102, "text": "For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 7, 8, 10). Their Manhattan distance is given by, |3 – 1| + |6 – 7| + |8 – 8| + |9 – 10| which is equal to 4." }, { "code": null, "e": 30298, "s": 30290, "text": "Syntax:" }, { "code": null, "e": 30376, "s": 30298, "text": "dist(vect, method = “manhattan”, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 30404, "s": 30376, "text": "Example: Manhattan distance" }, { "code": null, "e": 30406, "s": 30404, "text": "R" }, { "code": "# R program to illustrate how to calculate# Manhattan distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Manhattan distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Manhattan distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Manhattan distance between each unique pair of vectors# That is why we are passing Manhattan as a methoddist(twoDimensionalVect, method = \"manhattan\", diag = TRUE, upper = TRUE)", "e": 31376, "s": 30406, "text": null }, { "code": null, "e": 31384, "s": 31376, "text": "Output:" }, { "code": null, "e": 31623, "s": 31384, "text": "The maximum distance between two vectors, A and B, is calculated as the maximum difference between any pairwise elements. In R maximum distance is calculated with respect to vectors. The maximum distance between two vectors is given by, " }, { "code": null, "e": 31647, "s": 31623, "text": "max(|vect1i - vect2i|) " }, { "code": null, "e": 31654, "s": 31647, "text": "where," }, { "code": null, "e": 31680, "s": 31654, "text": "vect1 is the first vector" }, { "code": null, "e": 31707, "s": 31680, "text": "vect2 is the second vector" }, { "code": null, "e": 31895, "s": 31707, "text": "For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (1, 8, 9, 10). Their Maximum distance is given by, max(|3 – 1|, |6 – 8|, |8 – 9|, |9 – 10|) which is equal to 2." }, { "code": null, "e": 31903, "s": 31895, "text": "Syntax:" }, { "code": null, "e": 31979, "s": 31903, "text": "dist(vect, method = “maximum”, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 32005, "s": 31979, "text": "Example: Maximum distance" }, { "code": null, "e": 32007, "s": 32005, "text": "R" }, { "code": "# R program to illustrate how to calculate Maximum distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Maximum distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Maximum distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Maximum distance between each unique pair of vectors# That is why we are passing Maximum as a methoddist(twoDimensionalVect, method = \"maximum\", diag = TRUE, upper = TRUE)", "e": 32937, "s": 32007, "text": null }, { "code": null, "e": 32945, "s": 32937, "text": "Output:" }, { "code": null, "e": 33169, "s": 32945, "text": "The Canberra distance is a numerical measure of the distance between pairs of points in a vector space. In R Canberra distance is calculated with respect to vectors. The Canberra distance between two vectors is given by, " }, { "code": null, "e": 33214, "s": 33169, "text": "∑ |vect1i - vect2i| / (|vect1i| + |vect2i|) " }, { "code": null, "e": 33221, "s": 33214, "text": "where," }, { "code": null, "e": 33247, "s": 33221, "text": "vect1 is the first vector" }, { "code": null, "e": 33274, "s": 33247, "text": "vect2 is the second vector" }, { "code": null, "e": 33523, "s": 33274, "text": "For example, we are given two vectors, vect1 as (2, 2, 7, 5) and vect2 as (3, 8, 3, 5). Their Canberra distance is given by, |2 – 3| / (2 + 3) + |2 – 8| / (2 + 8) + |7 – 3| / (7 + 3) + |5 – 5| / (5 + 5) = 0.2 + 0.6 + 0.4 + 0 which is equal to 1.2." }, { "code": null, "e": 33531, "s": 33523, "text": "Syntax:" }, { "code": null, "e": 33608, "s": 33531, "text": "dist(vect, method = “canberra”, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 33635, "s": 33608, "text": "Example: Canberra distance" }, { "code": null, "e": 33637, "s": 33635, "text": "R" }, { "code": "# R program to illustrate how to calculate# Canberra distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Canberra distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Canberra distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Canberra distance between each unique pair of vectors# That is why we are passing Canberra as a methoddist(twoDimensionalVect, method = \"canberra\", diag = TRUE, upper = TRUE)", "e": 34601, "s": 33637, "text": null }, { "code": null, "e": 34609, "s": 34601, "text": "Output:" }, { "code": null, "e": 34732, "s": 34609, "text": "The Binary distance between two vectors, A and B, is calculated as the proportion of elements that the two vectors share. " }, { "code": null, "e": 34738, "s": 34732, "text": "Here," }, { "code": null, "e": 34764, "s": 34738, "text": "vect1 is the first vector" }, { "code": null, "e": 34791, "s": 34764, "text": "vect2 is the second vector" }, { "code": null, "e": 34799, "s": 34791, "text": "Syntax:" }, { "code": null, "e": 34874, "s": 34799, "text": "dist(vect, method = “binary”, diag = TRUE or FALSE, upper = TRUE or FALSE)" }, { "code": null, "e": 34899, "s": 34874, "text": "Example: Binary distance" }, { "code": null, "e": 34901, "s": 34899, "text": "R" }, { "code": "# R program to illustrate how to calculate# Binary distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Binary distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Binary distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Binary distance between each unique pair of vectors# That is why we are passing Binary as a methoddist(twoDimensionalVect, method = \"binary\", diag = TRUE, upper = TRUE)", "e": 35853, "s": 34901, "text": null }, { "code": null, "e": 35861, "s": 35853, "text": "Output:" }, { "code": null, "e": 36310, "s": 35861, "text": "Minkowski distance is a distance measured between two points in N-dimensional space. It is a generalization of the Euclidean distance and the Manhattan distance. For example, In a 2-dimensional space having two points Point1 (x1 , y1) and Point2 (x2 , y2), the Minkowski distance is given by (|x1 – y1|p + |x2 – y2|p )1/p . In R Minkowski distance is calculated with respect to vectors. The Minkowski distance between the two vectors is given by, " }, { "code": null, "e": 36335, "s": 36310, "text": "(Σ|vect1i - vect2i|p)1/p" }, { "code": null, "e": 36342, "s": 36335, "text": "where," }, { "code": null, "e": 36368, "s": 36342, "text": "vect1 is the first vector" }, { "code": null, "e": 36395, "s": 36368, "text": "vect2 is the second vector" }, { "code": null, "e": 36411, "s": 36395, "text": "p is an integer" }, { "code": null, "e": 36537, "s": 36411, "text": "R provides an inbuilt dist() method to calculate Minkowski distance between each pair of vectors in a two-dimensional vector." }, { "code": null, "e": 36545, "s": 36537, "text": "Syntax:" }, { "code": null, "e": 36637, "s": 36545, "text": "dist(vect, method = “minkowski”, p = integer, diag = TRUE or FALSE, upper = TRUE or FALSE) " }, { "code": null, "e": 36835, "s": 36637, "text": "For example, we are given two vectors, vect1 as (3, 6, 8, 9) and vect2 as (2, 7, 7, 10). Their Minkowski distance is given by, ( |3 – 2|2 + |6 – 7|2 + |8 – 7|2 + |9 – 10|2 )1/2 which is equal to 2." }, { "code": null, "e": 36863, "s": 36835, "text": "Example: Minkowski distance" }, { "code": null, "e": 36865, "s": 36863, "text": "R" }, { "code": "# R program to illustrate how to calculate# Minkowski distance# using dist() function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Minkowski distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Minkowski distance between vectors using# built in dist method By passing two-dimensional# vector as a parameter Since we want to calculate# Minkowski distance between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = \"minkowski\", diag = TRUE, upper = TRUE p = 2)", "e": 37841, "s": 36865, "text": null }, { "code": null, "e": 37849, "s": 37841, "text": "Output:" }, { "code": null, "e": 37864, "s": 37849, "text": "sagartomar9927" }, { "code": null, "e": 37876, "s": 37864, "text": "anikakapoor" }, { "code": null, "e": 37883, "s": 37876, "text": "Picked" }, { "code": null, "e": 37895, "s": 37883, "text": "R-Functions" }, { "code": null, "e": 37908, "s": 37895, "text": "R-Statistics" }, { "code": null, "e": 37919, "s": 37908, "text": "R Language" }, { "code": null, "e": 38017, "s": 37919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38069, "s": 38017, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 38104, "s": 38069, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 38142, "s": 38104, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 38200, "s": 38142, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 38243, "s": 38200, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 38292, "s": 38243, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 38329, "s": 38292, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 38355, "s": 38329, "text": "Time Series Analysis in R" }, { "code": null, "e": 38372, "s": 38355, "text": "R - if statement" } ]
Find the sum of all multiples of 2 and 5 below N - GeeksforGeeks
09 Apr, 2021 Given a number N. The task is to find the sum of all multiples of 2 and 5 below N ( N may be up to 10^10). Examples: Input : N = 10 Output : 25 Explanation : 2 + 4 + 6 + 8 + 5 Input : N = 20 Output : 110 Approach : We know that multiples of 2 form an AP as: 2, 4, 6, 8, 10, 12, 14....(1) Similarly, multiples of 5 form an AP as: 5, 10, 15......(2) Now, Sum(1) + Sum(2) = 2, 4, 5, 6, 8, 10, 10, 12, 14, 15....Here, 10 is repeated. In fact, all of the multiples of 10 or 2*5 are repeated because it is counted twice, once in the series of 2 and again in the series of 5. Hence we’ll subtract the sum of the series of 10 from Sum(1) + Sum(2). The formula for the sum of an A.P is : n * ( a + l ) / 2Where is the number of terms, is the starting term, and is the last term. So, the Final answer is: S2 + S5 – S10 Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find the sum of all// multiples of 2 and 5 below N #include <bits/stdc++.h>using namespace std; // Function to find sum of AP serieslong long sumAP(long long n, long long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nlong long sumMultiples(long long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver codeint main(){ long long n = 20; cout << sumMultiples(n); return 0;} // Java program to find the sum of all// multiples of 2 and 5 below N class GFG{// Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver codepublic static void main(String[] args){ long n = 20; System.out.println(sumMultiples(n));}}// This code is contributed by mits # Python3 program to find the sum of# all multiples of 2 and 5 below N # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d); return (n) * (1 + n) * (d / 2); # Function to find the sum of all# multiples of 2 and 5 below Ndef sumMultiples(n): # Since, we need the sum of # multiples less than N n -= 1; return (int(sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10))); # Driver coden = 20; print(sumMultiples(n)); # This code is contributed by mits // C# program to find the sum of all// multiples of 2 and 5 below N using System; public class GFG{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver code static public void Main (){ long n = 20; Console.WriteLine(sumMultiples(n)); }} <?php// PHP program to find the sum of all// multiples of 2 and 5 below N// Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n /$d); return ($n) * ((1 + $n) * (int)$d / 2);} // Function to find the sum of all// multiples of 2 and 5 below Nfunction sumMultiples($n){ // Since, we need the sum of // multiples less than N $n--; return sumAP($n, 2) + sumAP($n, 5) - sumAP($n, 10);} // Driver code$n = 20; echo sumMultiples($n); // This code is contributed// by Sach_Code?> <script> // Java script program to find the sum of all// multiples of 2 and 5 below N // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * ((1 + n) * parseInt(d) / 2);} // Function to find the sum of all// multiples of 2 and 5 below Nfunction sumMultiples(n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver coden = 20; document.write( sumMultiples(n)); // This code is contributed by bobby </script> 110 Mithun Kumar Sach_Code gottumukkalabobby arithmetic progression factor series series-sum Competitive Programming Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Traversal ( BFS ) on a 2D array Prefix Sum Array - Implementation and Applications in Competitive Programming Modulo 10^9+7 (1000000007) 5 Best Languages for Competitive Programming What is Competitive Programming and How to Prepare for It? Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26538, "s": 26510, "text": "\n09 Apr, 2021" }, { "code": null, "e": 26646, "s": 26538, "text": "Given a number N. The task is to find the sum of all multiples of 2 and 5 below N ( N may be up to 10^10). " }, { "code": null, "e": 26658, "s": 26646, "text": "Examples: " }, { "code": null, "e": 26746, "s": 26658, "text": "Input : N = 10\nOutput : 25\nExplanation : 2 + 4 + 6 + 8 + 5\n\nInput : N = 20\nOutput : 110" }, { "code": null, "e": 26801, "s": 26746, "text": "Approach : We know that multiples of 2 form an AP as: " }, { "code": null, "e": 26833, "s": 26801, "text": "2, 4, 6, 8, 10, 12, 14....(1) " }, { "code": null, "e": 26875, "s": 26833, "text": "Similarly, multiples of 5 form an AP as: " }, { "code": null, "e": 26896, "s": 26875, "text": "5, 10, 15......(2) " }, { "code": null, "e": 27188, "s": 26896, "text": "Now, Sum(1) + Sum(2) = 2, 4, 5, 6, 8, 10, 10, 12, 14, 15....Here, 10 is repeated. In fact, all of the multiples of 10 or 2*5 are repeated because it is counted twice, once in the series of 2 and again in the series of 5. Hence we’ll subtract the sum of the series of 10 from Sum(1) + Sum(2)." }, { "code": null, "e": 27229, "s": 27188, "text": "The formula for the sum of an A.P is : " }, { "code": null, "e": 27322, "s": 27229, "text": "n * ( a + l ) / 2Where is the number of terms, is the starting term, and is the last term. " }, { "code": null, "e": 27349, "s": 27322, "text": "So, the Final answer is: " }, { "code": null, "e": 27365, "s": 27349, "text": "S2 + S5 – S10 " }, { "code": null, "e": 27418, "s": 27365, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27422, "s": 27418, "text": "C++" }, { "code": null, "e": 27427, "s": 27422, "text": "Java" }, { "code": null, "e": 27435, "s": 27427, "text": "Python3" }, { "code": null, "e": 27438, "s": 27435, "text": "C#" }, { "code": null, "e": 27442, "s": 27438, "text": "PHP" }, { "code": null, "e": 27453, "s": 27442, "text": "Javascript" }, { "code": "// CPP program to find the sum of all// multiples of 2 and 5 below N #include <bits/stdc++.h>using namespace std; // Function to find sum of AP serieslong long sumAP(long long n, long long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nlong long sumMultiples(long long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver codeint main(){ long long n = 20; cout << sumMultiples(n); return 0;}", "e": 28029, "s": 27453, "text": null }, { "code": "// Java program to find the sum of all// multiples of 2 and 5 below N class GFG{// Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver codepublic static void main(String[] args){ long n = 20; System.out.println(sumMultiples(n));}}// This code is contributed by mits", "e": 28617, "s": 28029, "text": null }, { "code": "# Python3 program to find the sum of# all multiples of 2 and 5 below N # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d); return (n) * (1 + n) * (d / 2); # Function to find the sum of all# multiples of 2 and 5 below Ndef sumMultiples(n): # Since, we need the sum of # multiples less than N n -= 1; return (int(sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10))); # Driver coden = 20; print(sumMultiples(n)); # This code is contributed by mits", "e": 29144, "s": 28617, "text": null }, { "code": "// C# program to find the sum of all// multiples of 2 and 5 below N using System; public class GFG{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 2 and 5 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver code static public void Main (){ long n = 20; Console.WriteLine(sumMultiples(n)); }}", "e": 29737, "s": 29144, "text": null }, { "code": "<?php// PHP program to find the sum of all// multiples of 2 and 5 below N// Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n /$d); return ($n) * ((1 + $n) * (int)$d / 2);} // Function to find the sum of all// multiples of 2 and 5 below Nfunction sumMultiples($n){ // Since, we need the sum of // multiples less than N $n--; return sumAP($n, 2) + sumAP($n, 5) - sumAP($n, 10);} // Driver code$n = 20; echo sumMultiples($n); // This code is contributed// by Sach_Code?>", "e": 30312, "s": 29737, "text": null }, { "code": "<script> // Java script program to find the sum of all// multiples of 2 and 5 below N // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * ((1 + n) * parseInt(d) / 2);} // Function to find the sum of all// multiples of 2 and 5 below Nfunction sumMultiples(n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);} // Driver coden = 20; document.write( sumMultiples(n)); // This code is contributed by bobby </script>", "e": 30893, "s": 30312, "text": null }, { "code": null, "e": 30897, "s": 30893, "text": "110" }, { "code": null, "e": 30912, "s": 30899, "text": "Mithun Kumar" }, { "code": null, "e": 30922, "s": 30912, "text": "Sach_Code" }, { "code": null, "e": 30940, "s": 30922, "text": "gottumukkalabobby" }, { "code": null, "e": 30963, "s": 30940, "text": "arithmetic progression" }, { "code": null, "e": 30970, "s": 30963, "text": "factor" }, { "code": null, "e": 30977, "s": 30970, "text": "series" }, { "code": null, "e": 30988, "s": 30977, "text": "series-sum" }, { "code": null, "e": 31012, "s": 30988, "text": "Competitive Programming" }, { "code": null, "e": 31025, "s": 31012, "text": "Mathematical" }, { "code": null, "e": 31038, "s": 31025, "text": "Mathematical" }, { "code": null, "e": 31045, "s": 31038, "text": "series" }, { "code": null, "e": 31143, "s": 31045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31189, "s": 31143, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 31267, "s": 31189, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 31294, "s": 31267, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 31339, "s": 31294, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 31398, "s": 31339, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 31428, "s": 31398, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31488, "s": 31428, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31531, "s": 31488, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31546, "s": 31531, "text": "C++ Data Types" } ]
BeautifulSoup - Modifying the tree - GeeksforGeeks
07 Sep, 2021 Prerequisites: BeautifulSoup Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to modify the parse tree. BeautifulSoup is used to search the parse tree and allow you to modify the tree. You can rename tag, change the values of its attributes, add and delete attribute. You can change the name of the tag and modify its attribute by adding or deleting them. To change tag name: Syntax: tag.name = “new_tag” To modify its attribute or to add new attribute: Syntax: tag[“attribute”] = “value” To delete any attribute: Syntax: del tag[“attribute”] A tree can also be modified by inserting new elements at required places. insert() function will insert new element at any position Syntax: tag.insert() insert_after() function will insert element after something in the parse tree. Syntax: tag.insert_after() insert_before() function will insert element before something in the parse tree. Syntax: tag.insert_before() Approach : Import module Scrap data from webpage Parse the string scraped to html Select tag within which modification has to be performed Make required changes Example 1: Python3 # importing modulefrom bs4 import BeautifulSoup markup = """<p class="para">gfg</p> """ # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # extracting a tagtag = soup.p print("Before modifying the tag name: ")print(tag)print() # modifying tag nametag.name = "div" print("After modifying the tag name: ")print(tag)print()# modifying its class attributetag['class'] = "div_class" # adding new attributetag['id'] = "div_id" print("After modifying and adding attributes: ")print(tag)print() # to delete any attributesdel tag["class"] print("After deleting class attribute: ")print(tag)print() # modifying the tags contenttag.string = "Geeks" print("After modifying tag string: ")print(tag)print() # using insert function.tag = soup.divprint("Before inserting: ")print(tag)print() # inserting contenttag.insert(1, " for Geeks")print("After inserting: ")print(tag)print() Output: Example 2: Python3 # importing modulefrom bs4 import BeautifulSoup soup = BeautifulSoup("<b>| A Computer Science portal</b>", 'html.parser') tag = soup.new_tag("p")tag.string = "Geeks" # insert beforesoup.b.string.insert_before(tag)print(soup.b)print() # insert aftersoup.b.p.insert_after(soup.new_string(" for Geeks"))print(soup.b) Output: The tree can be modified by adding a new tag at any required location. We can also wrap the element to modify it. new_tag() function will add a new tag Syntax: new_tag(“attribute”) wrap() function will enclose an element in the tag you specify and returns a new wrapper Syntax: wrap() unwrap() function unwrap the wrapped elements. Syntax: unwrap() Example: Python3 # importing modulefrom bs4 import BeautifulSoup markup = ' <p>Geeks for Geeks</p> ' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser')print(soup) # wrapping around the stringsoup.p.string.wrap(soup.new_tag("i"))print(soup) # wrapping around the tagsoup.p.wrap(soup.new_tag("div"))print(soup) # unwrapping the i tag soup.p.i.unwrap() print(soup) old_tag = soup.div # new tagnew_tag = soup.new_tag('div')new_tag.string = "| A Computer Science portal for geeks" # adding new tagold_tag.append(new_tag) print(soup) Output: replace_with() function will replace old tag or string with new tag or string in the parse tree. Syntax: replace_with() Example: Python3 # importing BeautifulSoup Modulefrom bs4 import BeautifulSoup markup = '<a href="http://gfg.com/">Geeks for Geeks <i>gfg.com</i></a>' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # tag to be replacedold_tag = soup.a # new tagnew_tag = soup.new_tag("p") # input stringnew_tag.string = "gfg.in" '''replacing tag page_element.replace_with("string")removes a tag or string from the tree, and replacesit with the tag or string of your choice.''' old_tag.i.replace_with(new_tag) print(old_tag) Output: <a href=”http://gfg.com/”>Geeks for Geeks <p>gfg.in</p></a> For adding new contents to an existing tag can be done by append() function or NavigableString() constructor. Syntax: tag.append(“content”) Example: Python3 # importing modulefrom bs4 import BeautifulSoupfrom bs4 import NavigableString markup = """<a href="https://www.geeksforgeeks.org/">Geeks for Geeks</a>""" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # extracting a tagtag = soup.a # appending contenttag.append("| A Computer Science portal")print(tag) # appending content using navigableString constructornew_str = NavigableString(" for geeks")tag.append(new_str)print(tag) Output: <a href=”https://www.geeksforgeeks.org/”>Geeks for Geeks| A Computer Science portal</a> <a href=”https://www.geeksforgeeks.org/”>Geeks for Geeks| A Computer Science portal for geeks</a> A tree can be modified by removing content from it or by removing element also. clear() removes the contents of the tag. Syntax: clear() extract() removes a tag or strings from the tree. Syntax: extract() decompose() removes the tag and delete it all content. Syntax: decompose() Example: Python3 # importing modulefrom bs4 import BeautifulSoup markup = '<a href="https://www.geeksforgeeks.org/">Geeks for Geeks <i>| A Computer Science portal</i></a>' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') tag = soup.aprint(tag)print() # clearing its all contenttag.clear()print(tag)print() # extracting i tag# parsering string to HTMLsoup2 = BeautifulSoup(markup, 'html.parser') a_tag = soup2.a print(a_tag)print()i_tag = soup2.i.extract() print(a_tag)print() # decomposing i tag# parsering string to HTMLsoup2 = BeautifulSoup(markup, 'html.parser') a_tag = soup2.a print(a_tag)print()i_tag = soup2.i.decompose() print(a_tag) Output: sweetyty singghakshay anikaseth98 kapoorsagar226 Picked Python BeautifulSoup 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": "\n07 Sep, 2021" }, { "code": null, "e": 25566, "s": 25537, "text": "Prerequisites: BeautifulSoup" }, { "code": null, "e": 25936, "s": 25566, "text": "Beautifulsoup is a Python library used for web scraping. This powerful python tool can also be used to modify html webpages. This article depicts how beautifulsoup can be employed to modify the parse tree. BeautifulSoup is used to search the parse tree and allow you to modify the tree. You can rename tag, change the values of its attributes, add and delete attribute." }, { "code": null, "e": 26024, "s": 25936, "text": "You can change the name of the tag and modify its attribute by adding or deleting them." }, { "code": null, "e": 26044, "s": 26024, "text": "To change tag name:" }, { "code": null, "e": 26073, "s": 26044, "text": "Syntax: tag.name = “new_tag”" }, { "code": null, "e": 26122, "s": 26073, "text": "To modify its attribute or to add new attribute:" }, { "code": null, "e": 26157, "s": 26122, "text": "Syntax: tag[“attribute”] = “value”" }, { "code": null, "e": 26182, "s": 26157, "text": "To delete any attribute:" }, { "code": null, "e": 26211, "s": 26182, "text": "Syntax: del tag[“attribute”]" }, { "code": null, "e": 26285, "s": 26211, "text": "A tree can also be modified by inserting new elements at required places." }, { "code": null, "e": 26343, "s": 26285, "text": "insert() function will insert new element at any position" }, { "code": null, "e": 26364, "s": 26343, "text": "Syntax: tag.insert()" }, { "code": null, "e": 26443, "s": 26364, "text": "insert_after() function will insert element after something in the parse tree." }, { "code": null, "e": 26470, "s": 26443, "text": "Syntax: tag.insert_after()" }, { "code": null, "e": 26551, "s": 26470, "text": "insert_before() function will insert element before something in the parse tree." }, { "code": null, "e": 26579, "s": 26551, "text": "Syntax: tag.insert_before()" }, { "code": null, "e": 26590, "s": 26579, "text": "Approach :" }, { "code": null, "e": 26604, "s": 26590, "text": "Import module" }, { "code": null, "e": 26628, "s": 26604, "text": "Scrap data from webpage" }, { "code": null, "e": 26661, "s": 26628, "text": "Parse the string scraped to html" }, { "code": null, "e": 26718, "s": 26661, "text": "Select tag within which modification has to be performed" }, { "code": null, "e": 26740, "s": 26718, "text": "Make required changes" }, { "code": null, "e": 26752, "s": 26740, "text": "Example 1: " }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\"<p class=\"para\">gfg</p> \"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # extracting a tagtag = soup.p print(\"Before modifying the tag name: \")print(tag)print() # modifying tag nametag.name = \"div\" print(\"After modifying the tag name: \")print(tag)print()# modifying its class attributetag['class'] = \"div_class\" # adding new attributetag['id'] = \"div_id\" print(\"After modifying and adding attributes: \")print(tag)print() # to delete any attributesdel tag[\"class\"] print(\"After deleting class attribute: \")print(tag)print() # modifying the tags contenttag.string = \"Geeks\" print(\"After modifying tag string: \")print(tag)print() # using insert function.tag = soup.divprint(\"Before inserting: \")print(tag)print() # inserting contenttag.insert(1, \" for Geeks\")print(\"After inserting: \")print(tag)print()", "e": 27649, "s": 26760, "text": null }, { "code": null, "e": 27657, "s": 27649, "text": "Output:" }, { "code": null, "e": 27668, "s": 27657, "text": "Example 2:" }, { "code": null, "e": 27676, "s": 27668, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup soup = BeautifulSoup(\"<b>| A Computer Science portal</b>\", 'html.parser') tag = soup.new_tag(\"p\")tag.string = \"Geeks\" # insert beforesoup.b.string.insert_before(tag)print(soup.b)print() # insert aftersoup.b.p.insert_after(soup.new_string(\" for Geeks\"))print(soup.b)", "e": 27991, "s": 27676, "text": null }, { "code": null, "e": 27999, "s": 27991, "text": "Output:" }, { "code": null, "e": 28113, "s": 27999, "text": "The tree can be modified by adding a new tag at any required location. We can also wrap the element to modify it." }, { "code": null, "e": 28151, "s": 28113, "text": "new_tag() function will add a new tag" }, { "code": null, "e": 28180, "s": 28151, "text": "Syntax: new_tag(“attribute”)" }, { "code": null, "e": 28269, "s": 28180, "text": "wrap() function will enclose an element in the tag you specify and returns a new wrapper" }, { "code": null, "e": 28284, "s": 28269, "text": "Syntax: wrap()" }, { "code": null, "e": 28331, "s": 28284, "text": "unwrap() function unwrap the wrapped elements." }, { "code": null, "e": 28348, "s": 28331, "text": "Syntax: unwrap()" }, { "code": null, "e": 28357, "s": 28348, "text": "Example:" }, { "code": null, "e": 28365, "s": 28357, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = ' <p>Geeks for Geeks</p> ' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser')print(soup) # wrapping around the stringsoup.p.string.wrap(soup.new_tag(\"i\"))print(soup) # wrapping around the tagsoup.p.wrap(soup.new_tag(\"div\"))print(soup) # unwrapping the i tag soup.p.i.unwrap() print(soup) old_tag = soup.div # new tagnew_tag = soup.new_tag('div')new_tag.string = \"| A Computer Science portal for geeks\" # adding new tagold_tag.append(new_tag) print(soup)", "e": 28901, "s": 28365, "text": null }, { "code": null, "e": 28909, "s": 28901, "text": "Output:" }, { "code": null, "e": 29006, "s": 28909, "text": "replace_with() function will replace old tag or string with new tag or string in the parse tree." }, { "code": null, "e": 29029, "s": 29006, "text": "Syntax: replace_with()" }, { "code": null, "e": 29038, "s": 29029, "text": "Example:" }, { "code": null, "e": 29046, "s": 29038, "text": "Python3" }, { "code": "# importing BeautifulSoup Modulefrom bs4 import BeautifulSoup markup = '<a href=\"http://gfg.com/\">Geeks for Geeks <i>gfg.com</i></a>' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # tag to be replacedold_tag = soup.a # new tagnew_tag = soup.new_tag(\"p\") # input stringnew_tag.string = \"gfg.in\" '''replacing tag page_element.replace_with(\"string\")removes a tag or string from the tree, and replacesit with the tag or string of your choice.''' old_tag.i.replace_with(new_tag) print(old_tag)", "e": 29560, "s": 29046, "text": null }, { "code": null, "e": 29568, "s": 29560, "text": "Output:" }, { "code": null, "e": 29628, "s": 29568, "text": "<a href=”http://gfg.com/”>Geeks for Geeks <p>gfg.in</p></a>" }, { "code": null, "e": 29738, "s": 29628, "text": "For adding new contents to an existing tag can be done by append() function or NavigableString() constructor." }, { "code": null, "e": 29768, "s": 29738, "text": "Syntax: tag.append(“content”)" }, { "code": null, "e": 29777, "s": 29768, "text": "Example:" }, { "code": null, "e": 29785, "s": 29777, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoupfrom bs4 import NavigableString markup = \"\"\"<a href=\"https://www.geeksforgeeks.org/\">Geeks for Geeks</a>\"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # extracting a tagtag = soup.a # appending contenttag.append(\"| A Computer Science portal\")print(tag) # appending content using navigableString constructornew_str = NavigableString(\" for geeks\")tag.append(new_str)print(tag)", "e": 30234, "s": 29785, "text": null }, { "code": null, "e": 30242, "s": 30234, "text": "Output:" }, { "code": null, "e": 30330, "s": 30242, "text": "<a href=”https://www.geeksforgeeks.org/”>Geeks for Geeks| A Computer Science portal</a>" }, { "code": null, "e": 30428, "s": 30330, "text": "<a href=”https://www.geeksforgeeks.org/”>Geeks for Geeks| A Computer Science portal for geeks</a>" }, { "code": null, "e": 30508, "s": 30428, "text": "A tree can be modified by removing content from it or by removing element also." }, { "code": null, "e": 30549, "s": 30508, "text": "clear() removes the contents of the tag." }, { "code": null, "e": 30565, "s": 30549, "text": "Syntax: clear()" }, { "code": null, "e": 30615, "s": 30565, "text": "extract() removes a tag or strings from the tree." }, { "code": null, "e": 30633, "s": 30615, "text": "Syntax: extract()" }, { "code": null, "e": 30688, "s": 30633, "text": "decompose() removes the tag and delete it all content." }, { "code": null, "e": 30708, "s": 30688, "text": "Syntax: decompose()" }, { "code": null, "e": 30717, "s": 30708, "text": "Example:" }, { "code": null, "e": 30725, "s": 30717, "text": "Python3" }, { "code": "# importing modulefrom bs4 import BeautifulSoup markup = '<a href=\"https://www.geeksforgeeks.org/\">Geeks for Geeks <i>| A Computer Science portal</i></a>' # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') tag = soup.aprint(tag)print() # clearing its all contenttag.clear()print(tag)print() # extracting i tag# parsering string to HTMLsoup2 = BeautifulSoup(markup, 'html.parser') a_tag = soup2.a print(a_tag)print()i_tag = soup2.i.extract() print(a_tag)print() # decomposing i tag# parsering string to HTMLsoup2 = BeautifulSoup(markup, 'html.parser') a_tag = soup2.a print(a_tag)print()i_tag = soup2.i.decompose() print(a_tag)", "e": 31371, "s": 30725, "text": null }, { "code": null, "e": 31379, "s": 31371, "text": "Output:" }, { "code": null, "e": 31388, "s": 31379, "text": "sweetyty" }, { "code": null, "e": 31401, "s": 31388, "text": "singghakshay" }, { "code": null, "e": 31413, "s": 31401, "text": "anikaseth98" }, { "code": null, "e": 31428, "s": 31413, "text": "kapoorsagar226" }, { "code": null, "e": 31435, "s": 31428, "text": "Picked" }, { "code": null, "e": 31456, "s": 31435, "text": "Python BeautifulSoup" }, { "code": null, "e": 31463, "s": 31456, "text": "Python" }, { "code": null, "e": 31561, "s": 31463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31593, "s": 31561, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31635, "s": 31593, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31677, "s": 31635, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31733, "s": 31677, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31760, "s": 31733, "text": "Python Classes and Objects" }, { "code": null, "e": 31799, "s": 31760, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31830, "s": 31799, "text": "Python | os.path.join() method" }, { "code": null, "e": 31859, "s": 31830, "text": "Create a directory in Python" }, { "code": null, "e": 31881, "s": 31859, "text": "Defaultdict in Python" } ]
Pretty print Linked List in Python - GeeksforGeeks
09 May, 2022 Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it looks kind of odd, right? Like it would be great to have the default print function do the same, right? Well, that’s where Python comes in. Python has some amazing methods called Dunder methods. Dunder stands for double under methods. Basically, any methods that start and end with double underscores are called Dunder methods or Magic methods. One such example of under method is __init__. One similar method is __str__, which we are going to use in this article. This method can be used for pretty-printing in Python. Pretty print is nothing but applying various kinds of styles and formatting the content to be printed. Learn more about dunder methods here. __str__ methods specify what should be returned from a class when that class is printed using the standard print function. Using this concept, we can have a lot of better representation of custom datatype. Here, below is an example of such custom representation. Note that the focus is on the Linked List implementation but more on the pythonic way of representing it. Example: Pretty print a singly linked list 10->15->20 as [10, 15, 20] Python3 class Node: def __init__(self, val=None): self.val = val self.next = None class LinkedList: def __init__(self, head=None): self.head = head def __str__(self): # defining a blank res variable res = "" # initializing ptr to head ptr = self.head # traversing and adding it to res while ptr: res += str(ptr.val) + ", " ptr = ptr.next # removing trailing commas res = res.strip(", ") # chen checking if # anything is present in res or not if len(res): return "[" + res + "]" else: return "[]" if __name__ == "__main__": # defining linked list ll = LinkedList() # defining nodes node1 = Node(10) node2 = Node(15) node3 = Node(20) # connecting the nodes ll.head = node1 node1.next = node2 node2.next = node3 # when print is called, by default #it calls the __str__ method print(ll) [10, 15, 20] Note that when printing the class, __str__ is called by default. This is the magic of Python. The main purpose of this article is to show how small little magic methods can make your lives a lot easier. adnanirshad158 Linked Lists Python DSA-exercises Python LinkedList-exercises Python-Data-Structures python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n09 May, 2022" }, { "code": null, "e": 26058, "s": 25561, "text": "Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it looks kind of odd, right? Like it would be great to have the default print function do the same, right? Well, that’s where Python comes in. Python has some amazing methods called Dunder methods. " }, { "code": null, "e": 26524, "s": 26058, "text": "Dunder stands for double under methods. Basically, any methods that start and end with double underscores are called Dunder methods or Magic methods. One such example of under method is __init__. One similar method is __str__, which we are going to use in this article. This method can be used for pretty-printing in Python. Pretty print is nothing but applying various kinds of styles and formatting the content to be printed. Learn more about dunder methods here." }, { "code": null, "e": 26894, "s": 26524, "text": "__str__ methods specify what should be returned from a class when that class is printed using the standard print function. Using this concept, we can have a lot of better representation of custom datatype. Here, below is an example of such custom representation. Note that the focus is on the Linked List implementation but more on the pythonic way of representing it. " }, { "code": null, "e": 26964, "s": 26894, "text": "Example: Pretty print a singly linked list 10->15->20 as [10, 15, 20]" }, { "code": null, "e": 26972, "s": 26964, "text": "Python3" }, { "code": "class Node: def __init__(self, val=None): self.val = val self.next = None class LinkedList: def __init__(self, head=None): self.head = head def __str__(self): # defining a blank res variable res = \"\" # initializing ptr to head ptr = self.head # traversing and adding it to res while ptr: res += str(ptr.val) + \", \" ptr = ptr.next # removing trailing commas res = res.strip(\", \") # chen checking if # anything is present in res or not if len(res): return \"[\" + res + \"]\" else: return \"[]\" if __name__ == \"__main__\": # defining linked list ll = LinkedList() # defining nodes node1 = Node(10) node2 = Node(15) node3 = Node(20) # connecting the nodes ll.head = node1 node1.next = node2 node2.next = node3 # when print is called, by default #it calls the __str__ method print(ll)", "e": 27990, "s": 26972, "text": null }, { "code": null, "e": 28003, "s": 27990, "text": "[10, 15, 20]" }, { "code": null, "e": 28207, "s": 28003, "text": "Note that when printing the class, __str__ is called by default. This is the magic of Python. The main purpose of this article is to show how small little magic methods can make your lives a lot easier. " }, { "code": null, "e": 28222, "s": 28207, "text": "adnanirshad158" }, { "code": null, "e": 28235, "s": 28222, "text": "Linked Lists" }, { "code": null, "e": 28256, "s": 28235, "text": "Python DSA-exercises" }, { "code": null, "e": 28284, "s": 28256, "text": "Python LinkedList-exercises" }, { "code": null, "e": 28307, "s": 28284, "text": "Python-Data-Structures" }, { "code": null, "e": 28322, "s": 28307, "text": "python-utility" }, { "code": null, "e": 28329, "s": 28322, "text": "Python" }, { "code": null, "e": 28427, "s": 28329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28459, "s": 28427, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28501, "s": 28459, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28543, "s": 28501, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28599, "s": 28543, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28626, "s": 28599, "text": "Python Classes and Objects" }, { "code": null, "e": 28657, "s": 28626, "text": "Python | os.path.join() method" }, { "code": null, "e": 28696, "s": 28657, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28725, "s": 28696, "text": "Create a directory in Python" }, { "code": null, "e": 28747, "s": 28725, "text": "Defaultdict in Python" } ]
PLSQL | RPAD Function - GeeksforGeeks
25 Sep, 2019 The PLSQL RPAD function is used for padding the right-side of a string with a specific set of characters. a prerequisite for this is that string shouldn’t be NULL. The RPAD function in PLSQL is useful for formatting the output of a query. The RPAD function accepts three parameters which are input_string, padded_length and the pad_string. Both input_string and pad_string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype if input_string is a character datatype. The argument padded_length must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify pad_string, then the default is a single blank. If input_string is longer than padded_length, then this function returns the portion of input_string that fits in padded_length. Syntax: RPAD( input_string, padded_length, pad_string) Parameters Used: input_string – It is used to specify the string which needs to be formatted.string_to_replace – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the RPAD function will truncate the string to the size of padded_length.pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the right-hand side of string. If this parameter is omitted, the RPAD function will pad spaces to the right-side of the input_string. input_string – It is used to specify the string which needs to be formatted. string_to_replace – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the RPAD function will truncate the string to the size of padded_length. pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the right-hand side of string. If this parameter is omitted, the RPAD function will pad spaces to the right-side of the input_string. Supported Versions of Oracle/PLSQL: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Example-1: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(RPAD(Test_String, '5')); END; Output: Geeks Example-2: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(RPAD(Test_String, '17')); END; Output: Geeksforgeeks Example-3: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(RPAD(Test_String, '17', '0')); END; Output: Geeksforgeeks0000 Example-4: DECLARE Test_String string(20) := 'Geeksforgeeks'; BEGIN dbms_output.put_line(RPAD(Test_String, '5')); END; Output: Geeksforgeek SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n25 Sep, 2019" }, { "code": null, "e": 25853, "s": 25513, "text": "The PLSQL RPAD function is used for padding the right-side of a string with a specific set of characters. a prerequisite for this is that string shouldn’t be NULL. The RPAD function in PLSQL is useful for formatting the output of a query. The RPAD function accepts three parameters which are input_string, padded_length and the pad_string." }, { "code": null, "e": 26049, "s": 25853, "text": "Both input_string and pad_string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype if input_string is a character datatype." }, { "code": null, "e": 26166, "s": 26049, "text": "The argument padded_length must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer." }, { "code": null, "e": 26365, "s": 26166, "text": "If you do not specify pad_string, then the default is a single blank. If input_string is longer than padded_length, then this function returns the portion of input_string that fits in padded_length." }, { "code": null, "e": 26373, "s": 26365, "text": "Syntax:" }, { "code": null, "e": 26420, "s": 26373, "text": "RPAD( input_string, padded_length, pad_string)" }, { "code": null, "e": 26437, "s": 26420, "text": "Parameters Used:" }, { "code": null, "e": 26961, "s": 26437, "text": "input_string – It is used to specify the string which needs to be formatted.string_to_replace – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the RPAD function will truncate the string to the size of padded_length.pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the right-hand side of string. If this parameter is omitted, the RPAD function will pad spaces to the right-side of the input_string." }, { "code": null, "e": 27038, "s": 26961, "text": "input_string – It is used to specify the string which needs to be formatted." }, { "code": null, "e": 27247, "s": 27038, "text": "string_to_replace – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the RPAD function will truncate the string to the size of padded_length." }, { "code": null, "e": 27487, "s": 27247, "text": "pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the right-hand side of string. If this parameter is omitted, the RPAD function will pad spaces to the right-side of the input_string." }, { "code": null, "e": 27523, "s": 27487, "text": "Supported Versions of Oracle/PLSQL:" }, { "code": null, "e": 27572, "s": 27523, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 27583, "s": 27572, "text": "Oracle 12c" }, { "code": null, "e": 27594, "s": 27583, "text": "Oracle 11g" }, { "code": null, "e": 27605, "s": 27594, "text": "Oracle 10g" }, { "code": null, "e": 27615, "s": 27605, "text": "Oracle 9i" }, { "code": null, "e": 27625, "s": 27615, "text": "Oracle 8i" }, { "code": null, "e": 27636, "s": 27625, "text": "Example-1:" }, { "code": null, "e": 27766, "s": 27636, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(RPAD(Test_String, '5')); \n \nEND; " }, { "code": null, "e": 27774, "s": 27766, "text": "Output:" }, { "code": null, "e": 27781, "s": 27774, "text": "Geeks " }, { "code": null, "e": 27792, "s": 27781, "text": "Example-2:" }, { "code": null, "e": 27922, "s": 27792, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(RPAD(Test_String, '17')); \n \nEND; " }, { "code": null, "e": 27930, "s": 27922, "text": "Output:" }, { "code": null, "e": 27946, "s": 27930, "text": "Geeksforgeeks " }, { "code": null, "e": 27957, "s": 27946, "text": "Example-3:" }, { "code": null, "e": 28090, "s": 27957, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(RPAD(Test_String, '17', '0')); \n \nEND; " }, { "code": null, "e": 28098, "s": 28090, "text": "Output:" }, { "code": null, "e": 28117, "s": 28098, "text": "Geeksforgeeks0000 " }, { "code": null, "e": 28128, "s": 28117, "text": "Example-4:" }, { "code": null, "e": 28258, "s": 28128, "text": "DECLARE \n Test_String string(20) := 'Geeksforgeeks';\n \nBEGIN \n dbms_output.put_line(RPAD(Test_String, '5')); \n \nEND; " }, { "code": null, "e": 28266, "s": 28258, "text": "Output:" }, { "code": null, "e": 28280, "s": 28266, "text": "Geeksforgeek " }, { "code": null, "e": 28291, "s": 28280, "text": "SQL-PL/SQL" }, { "code": null, "e": 28295, "s": 28291, "text": "SQL" }, { "code": null, "e": 28299, "s": 28295, "text": "SQL" }, { "code": null, "e": 28397, "s": 28299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28463, "s": 28397, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28478, "s": 28463, "text": "SQL | Subquery" }, { "code": null, "e": 28535, "s": 28478, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28567, "s": 28535, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28645, "s": 28567, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28681, "s": 28645, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28698, "s": 28681, "text": "SQL using Python" }, { "code": null, "e": 28764, "s": 28698, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28826, "s": 28764, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Python | Introduction to Matplotlib - GeeksforGeeks
14 May, 2018 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc. Installation :Windows, Linux and macOS distributions have matplotlib and most of its dependencies as wheel packages. Run the following command to install matplotlib package : python -mpip install -U matplotlib Importing matplotlib : from matplotlib import pyplot as plt or import matplotlib.pyplot as plt Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. Some of the sample plots are covered here. Line plot : # importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.plot(x,y) # function to show the plotplt.show() Output : Bar plot : # importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot the barplt.bar(x,y) # function to show the plotplt.show() Output : Histogram : # importing matplotlib module from matplotlib import pyplot as plt # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot histogramplt.hist(y) # Function to show the plotplt.show() Output : # importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot scatterplt.scatter(x, y) # function to show the plotplt.show() Output : Reference : Matplotlib Documentation. Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 31571, "s": 31543, "text": "\n14 May, 2018" }, { "code": null, "e": 31834, "s": 31571, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002." }, { "code": null, "e": 32046, "s": 31834, "text": "One of the greatest benefits of visualization is that it allows us visual access to huge amounts of data in easily digestible visuals. Matplotlib consists of several plots like line, bar, scatter, histogram etc." }, { "code": null, "e": 32221, "s": 32046, "text": "Installation :Windows, Linux and macOS distributions have matplotlib and most of its dependencies as wheel packages. Run the following command to install matplotlib package :" }, { "code": null, "e": 32256, "s": 32221, "text": "python -mpip install -U matplotlib" }, { "code": null, "e": 32280, "s": 32256, "text": " Importing matplotlib :" }, { "code": null, "e": 32353, "s": 32280, "text": "from matplotlib import pyplot as plt\nor\nimport matplotlib.pyplot as plt " }, { "code": null, "e": 32589, "s": 32353, "text": "Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. Some of the sample plots are covered here." }, { "code": null, "e": 32601, "s": 32589, "text": "Line plot :" }, { "code": "# importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plotplt.plot(x,y) # function to show the plotplt.show()", "e": 32813, "s": 32601, "text": null }, { "code": null, "e": 32822, "s": 32813, "text": "Output :" }, { "code": null, "e": 32834, "s": 32822, "text": " Bar plot :" }, { "code": "# importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot the barplt.bar(x,y) # function to show the plotplt.show()", "e": 33053, "s": 32834, "text": null }, { "code": null, "e": 33074, "s": 33053, "text": "Output : Histogram :" }, { "code": "# importing matplotlib module from matplotlib import pyplot as plt # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot histogramplt.hist(y) # Function to show the plotplt.show()", "e": 33258, "s": 33074, "text": null }, { "code": null, "e": 33267, "s": 33258, "text": "Output :" }, { "code": "# importing matplotlib module from matplotlib import pyplot as plt # x-axis valuesx = [5, 2, 9, 4, 7] # Y-axis valuesy = [10, 5, 8, 4, 2] # Function to plot scatterplt.scatter(x, y) # function to show the plotplt.show()", "e": 33491, "s": 33267, "text": null }, { "code": null, "e": 33500, "s": 33491, "text": "Output :" }, { "code": null, "e": 33538, "s": 33500, "text": "Reference : Matplotlib Documentation." }, { "code": null, "e": 33553, "s": 33538, "text": "Python-Library" }, { "code": null, "e": 33560, "s": 33553, "text": "Python" }, { "code": null, "e": 33658, "s": 33560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33686, "s": 33658, "text": "Read JSON file using Python" }, { "code": null, "e": 33736, "s": 33686, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 33758, "s": 33736, "text": "Python map() function" }, { "code": null, "e": 33802, "s": 33758, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 33820, "s": 33802, "text": "Python Dictionary" }, { "code": null, "e": 33843, "s": 33820, "text": "Taking input in Python" }, { "code": null, "e": 33878, "s": 33843, "text": "Read a file line by line in Python" }, { "code": null, "e": 33910, "s": 33878, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33932, "s": 33910, "text": "Enumerate() in Python" } ]
Remove Vertical or Horizontal Gridlines in ggplot2 Plot in R - GeeksforGeeks
14 Sep, 2021 In this article, we are going to learn how to remove Vertical or Horizontal Gridlines in the background of a ggplot2 Plot in R programming language. To understand how to remove Vertical or Horizontal Gridlines, first import all the required libraries to the working space and create a dataframe. Let us first create a regular plot so that the difference is apparent. Example: default plot R library("ggplot2") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Display the plotp Output: Now for removing gridlines, separate functions are added while creating a plot. In ggplot2, scales control how the data is mapped into aesthetics. When we provide some data, it takes the data and converts it into something visual for us like position, size, color, or shape. Scales toolbox can have different attributes like the following two main types: Position scales and axes Colour scales and legend In order to remove gridlines, we are going to focus on position scales. There are two position scales in a plot corresponding to x and y aesthetics. Two most common types of continuous position scales are the default scale_x_continuous() and scale_y_continuous() functions. We are going to use these functions to remove the gridlines. To remove vertical grid lines scale_x_continuous() function is passed with the breaks parameter as NULL. Syntax: scale_x_continuous(breaks =NULL ) Example: Removing vertical gridlines R library("ggplot2") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Remove Vertical Gridlines p + scale_x_continuous(breaks = NULL) Output: Similarly for removing horizontal gridlines break parameter of scale_y_continuous() is set to NULL. Example: Removing horizontal lines R library("ggplot2") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Remove Horizontal Gridlinesp + scale_y_continuous(breaks = NULL) Output: Picked R-ggplot R Language 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26636, "s": 26487, "text": "In this article, we are going to learn how to remove Vertical or Horizontal Gridlines in the background of a ggplot2 Plot in R programming language." }, { "code": null, "e": 26854, "s": 26636, "text": "To understand how to remove Vertical or Horizontal Gridlines, first import all the required libraries to the working space and create a dataframe. Let us first create a regular plot so that the difference is apparent." }, { "code": null, "e": 26876, "s": 26854, "text": "Example: default plot" }, { "code": null, "e": 26878, "s": 26876, "text": "R" }, { "code": "library(\"ggplot2\") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Display the plotp", "e": 27087, "s": 26878, "text": null }, { "code": null, "e": 27095, "s": 27087, "text": "Output:" }, { "code": null, "e": 27371, "s": 27095, "text": "Now for removing gridlines, separate functions are added while creating a plot. In ggplot2, scales control how the data is mapped into aesthetics. When we provide some data, it takes the data and converts it into something visual for us like position, size, color, or shape. " }, { "code": null, "e": 27451, "s": 27371, "text": "Scales toolbox can have different attributes like the following two main types:" }, { "code": null, "e": 27476, "s": 27451, "text": "Position scales and axes" }, { "code": null, "e": 27501, "s": 27476, "text": "Colour scales and legend" }, { "code": null, "e": 27836, "s": 27501, "text": "In order to remove gridlines, we are going to focus on position scales. There are two position scales in a plot corresponding to x and y aesthetics. Two most common types of continuous position scales are the default scale_x_continuous() and scale_y_continuous() functions. We are going to use these functions to remove the gridlines." }, { "code": null, "e": 27941, "s": 27836, "text": "To remove vertical grid lines scale_x_continuous() function is passed with the breaks parameter as NULL." }, { "code": null, "e": 27949, "s": 27941, "text": "Syntax:" }, { "code": null, "e": 27983, "s": 27949, "text": "scale_x_continuous(breaks =NULL )" }, { "code": null, "e": 28020, "s": 27983, "text": "Example: Removing vertical gridlines" }, { "code": null, "e": 28022, "s": 28020, "text": "R" }, { "code": "library(\"ggplot2\") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Remove Vertical Gridlines p + scale_x_continuous(breaks = NULL)", "e": 28277, "s": 28022, "text": null }, { "code": null, "e": 28285, "s": 28277, "text": "Output:" }, { "code": null, "e": 28385, "s": 28285, "text": "Similarly for removing horizontal gridlines break parameter of scale_y_continuous() is set to NULL." }, { "code": null, "e": 28421, "s": 28385, "text": "Example: Removing horizontal lines " }, { "code": null, "e": 28423, "s": 28421, "text": "R" }, { "code": "library(\"ggplot2\") # Store 10 entries of data in data frameA <- data.frame(x = 1:10, y = c(1,4,2,3,7,5,4,8,2,5)) # A ggplot2 plot with gridlinesp <- ggplot(A, aes(x, y)) + geom_point() # Remove Horizontal Gridlinesp + scale_y_continuous(breaks = NULL)", "e": 28679, "s": 28423, "text": null }, { "code": null, "e": 28687, "s": 28679, "text": "Output:" }, { "code": null, "e": 28694, "s": 28687, "text": "Picked" }, { "code": null, "e": 28703, "s": 28694, "text": "R-ggplot" }, { "code": null, "e": 28714, "s": 28703, "text": "R Language" }, { "code": null, "e": 28812, "s": 28714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28864, "s": 28812, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28899, "s": 28864, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28937, "s": 28899, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28995, "s": 28937, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29038, "s": 28995, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29087, "s": 29038, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29124, "s": 29087, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29141, "s": 29124, "text": "R - if statement" }, { "code": null, "e": 29167, "s": 29141, "text": "Time Series Analysis in R" } ]
java.util.Currency methods with example - GeeksforGeeks
25 Nov, 2016 This class represents currency. Here, currency is identified by their ISO 4217 currency codes. The purpose of ISO 4217 is to establish internationally recognized codes for the representation of currencies. Currencies can be represented in the code in two ways: a three-letter alphabetic code and a three-digit numeric code. util.Currency methods in Java / / | \ \ getCurrency getInstance getDisplayName getSymbol getDefaultFractionDigits Some of the Currency class methods : getCurrency() : java.util.Currency.getCurrency() method returns ISO 4217 currency code of the passed currency argument.Syntax :public String getCurrencyCode() Return : ISO 4217 currency code of the passed argument. getInstance() : java.util.Currency.getInstance() method creates currency instance for Currency code.Syntax :public static Currency getInstance(String cCode) Parameter : cCode - ISO 4217 currency code of the passed currency argument Return : currency instance for Currency code getDefaultFractionDigits() : java.util.Currency.getDefaultFractionDigits() method returns default number of argumented currency fraction digits.Syntax :public int getDefaultFractionDigits() Return : returns default number of argumented currency fraction digits. getDisplayName() : java.util.Currency.getDisplayName() method generates the currency name of the argumented currency code.Syntax :public string getDisplayName() Return : currency name of the argumented currency code getSymbol() : java.util.Currency.getSymbol() method returns Currency symbol for the argumented currency code. In case, no symbol is returned normal currency code will be returned.Syntax :public String getSymbol() Return : Symbol of the argumented currency code currency code. Java code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class// Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance("AUD"); //Australian Dollar Currency c2 = Currency.getInstance("JPY"); //Japan Yen Currency c3 = Currency.getInstance("USD"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println("Australian Dollar code : " + cCode1); System.out.println("Japan Yen code : " + cCode2); System.out.println(""); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println("AUD Fraction digits : " + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println("JPY fraction digits : " + D2); System.out.println(""); // Use of getDisplayName() method System.out.println("AUD Display : "+c1.getDisplayName()); System.out.println("JPY Display : "+c2.getSymbol()); System.out.println(""); // Use of getSymbol() method System.out.println("JPY Symbol : "+c2.getSymbol()); System.out.println("USD Symbol : "+c3.getSymbol()); }}Output:Australian Dollar code : AUD Japan Yen code : JPY AUD Fraction digits : 2 JPY fraction digits : 0 AUD Display : Australian Dollar JPY Display : JPY JPY Symbol : JPY USD Symbol : $Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.phpThis article is contributed by Mohit Gupta. 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.My Personal Notes arrow_drop_upSave getCurrency() : java.util.Currency.getCurrency() method returns ISO 4217 currency code of the passed currency argument.Syntax :public String getCurrencyCode() Return : ISO 4217 currency code of the passed argument. public String getCurrencyCode() Return : ISO 4217 currency code of the passed argument. getInstance() : java.util.Currency.getInstance() method creates currency instance for Currency code.Syntax :public static Currency getInstance(String cCode) Parameter : cCode - ISO 4217 currency code of the passed currency argument Return : currency instance for Currency code public static Currency getInstance(String cCode) Parameter : cCode - ISO 4217 currency code of the passed currency argument Return : currency instance for Currency code getDefaultFractionDigits() : java.util.Currency.getDefaultFractionDigits() method returns default number of argumented currency fraction digits.Syntax :public int getDefaultFractionDigits() Return : returns default number of argumented currency fraction digits. public int getDefaultFractionDigits() Return : returns default number of argumented currency fraction digits. getDisplayName() : java.util.Currency.getDisplayName() method generates the currency name of the argumented currency code.Syntax :public string getDisplayName() Return : currency name of the argumented currency code public string getDisplayName() Return : currency name of the argumented currency code getSymbol() : java.util.Currency.getSymbol() method returns Currency symbol for the argumented currency code. In case, no symbol is returned normal currency code will be returned.Syntax :public String getSymbol() Return : Symbol of the argumented currency code currency code. Java code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class// Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance("AUD"); //Australian Dollar Currency c2 = Currency.getInstance("JPY"); //Japan Yen Currency c3 = Currency.getInstance("USD"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println("Australian Dollar code : " + cCode1); System.out.println("Japan Yen code : " + cCode2); System.out.println(""); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println("AUD Fraction digits : " + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println("JPY fraction digits : " + D2); System.out.println(""); // Use of getDisplayName() method System.out.println("AUD Display : "+c1.getDisplayName()); System.out.println("JPY Display : "+c2.getSymbol()); System.out.println(""); // Use of getSymbol() method System.out.println("JPY Symbol : "+c2.getSymbol()); System.out.println("USD Symbol : "+c3.getSymbol()); }}Output:Australian Dollar code : AUD Japan Yen code : JPY AUD Fraction digits : 2 JPY fraction digits : 0 AUD Display : Australian Dollar JPY Display : JPY JPY Symbol : JPY USD Symbol : $Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.phpThis article is contributed by Mohit Gupta. 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.My Personal Notes arrow_drop_upSave public String getSymbol() Return : Symbol of the argumented currency code currency code. Java code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class // Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance("AUD"); //Australian Dollar Currency c2 = Currency.getInstance("JPY"); //Japan Yen Currency c3 = Currency.getInstance("USD"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println("Australian Dollar code : " + cCode1); System.out.println("Japan Yen code : " + cCode2); System.out.println(""); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println("AUD Fraction digits : " + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println("JPY fraction digits : " + D2); System.out.println(""); // Use of getDisplayName() method System.out.println("AUD Display : "+c1.getDisplayName()); System.out.println("JPY Display : "+c2.getSymbol()); System.out.println(""); // Use of getSymbol() method System.out.println("JPY Symbol : "+c2.getSymbol()); System.out.println("USD Symbol : "+c3.getSymbol()); }} Output: Australian Dollar code : AUD Japan Yen code : JPY AUD Fraction digits : 2 JPY fraction digits : 0 AUD Display : Australian Dollar JPY Display : JPY JPY Symbol : JPY USD Symbol : $ Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.php This article is contributed by Mohit Gupta. 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. Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25740, "s": 25712, "text": "\n25 Nov, 2016" }, { "code": null, "e": 26064, "s": 25740, "text": "This class represents currency. Here, currency is identified by their ISO 4217 currency codes. The purpose of ISO 4217 is to establish internationally recognized codes for the representation of currencies. Currencies can be represented in the code in two ways: a three-letter alphabetic code and a three-digit numeric code." }, { "code": null, "e": 26263, "s": 26064, "text": " util.Currency methods in Java\n / / | \\ \\\n getCurrency getInstance getDisplayName getSymbol getDefaultFractionDigits\n" }, { "code": null, "e": 26300, "s": 26263, "text": "Some of the Currency class methods :" }, { "code": null, "e": 29846, "s": 26300, "text": "getCurrency() : java.util.Currency.getCurrency() method returns ISO 4217 currency code of the passed currency argument.Syntax :public String getCurrencyCode()\nReturn : \nISO 4217 currency code of the passed argument.\ngetInstance() : java.util.Currency.getInstance() method creates currency instance for Currency code.Syntax :public static Currency getInstance(String cCode)\nParameter : \ncCode - ISO 4217 currency code of the passed currency argument\nReturn : \ncurrency instance for Currency code\ngetDefaultFractionDigits() : java.util.Currency.getDefaultFractionDigits() method returns default number of argumented currency fraction digits.Syntax :public int getDefaultFractionDigits()\nReturn : \nreturns default number of argumented currency fraction digits.\ngetDisplayName() : java.util.Currency.getDisplayName() method generates the currency name of the argumented currency code.Syntax :public string getDisplayName()\nReturn : \ncurrency name of the argumented currency code\ngetSymbol() : java.util.Currency.getSymbol() method returns Currency symbol for the argumented currency code. In case, no symbol is returned normal currency code will be returned.Syntax :public String getSymbol()\nReturn : \nSymbol of the argumented currency code currency code.\nJava code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class// Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance(\"AUD\"); //Australian Dollar Currency c2 = Currency.getInstance(\"JPY\"); //Japan Yen Currency c3 = Currency.getInstance(\"USD\"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println(\"Australian Dollar code : \" + cCode1); System.out.println(\"Japan Yen code : \" + cCode2); System.out.println(\"\"); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println(\"AUD Fraction digits : \" + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println(\"JPY fraction digits : \" + D2); System.out.println(\"\"); // Use of getDisplayName() method System.out.println(\"AUD Display : \"+c1.getDisplayName()); System.out.println(\"JPY Display : \"+c2.getSymbol()); System.out.println(\"\"); // Use of getSymbol() method System.out.println(\"JPY Symbol : \"+c2.getSymbol()); System.out.println(\"USD Symbol : \"+c3.getSymbol()); }}Output:Australian Dollar code : AUD\nJapan Yen code : JPY\n\nAUD Fraction digits : 2\nJPY fraction digits : 0\n\nAUD Display : Australian Dollar\nJPY Display : JPY\n\nJPY Symbol : JPY\nUSD Symbol : $Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.phpThis article is contributed by Mohit Gupta. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30063, "s": 29846, "text": "getCurrency() : java.util.Currency.getCurrency() method returns ISO 4217 currency code of the passed currency argument.Syntax :public String getCurrencyCode()\nReturn : \nISO 4217 currency code of the passed argument.\n" }, { "code": null, "e": 30153, "s": 30063, "text": "public String getCurrencyCode()\nReturn : \nISO 4217 currency code of the passed argument.\n" }, { "code": null, "e": 30433, "s": 30153, "text": "getInstance() : java.util.Currency.getInstance() method creates currency instance for Currency code.Syntax :public static Currency getInstance(String cCode)\nParameter : \ncCode - ISO 4217 currency code of the passed currency argument\nReturn : \ncurrency instance for Currency code\n" }, { "code": null, "e": 30605, "s": 30433, "text": "public static Currency getInstance(String cCode)\nParameter : \ncCode - ISO 4217 currency code of the passed currency argument\nReturn : \ncurrency instance for Currency code\n" }, { "code": null, "e": 30869, "s": 30605, "text": "getDefaultFractionDigits() : java.util.Currency.getDefaultFractionDigits() method returns default number of argumented currency fraction digits.Syntax :public int getDefaultFractionDigits()\nReturn : \nreturns default number of argumented currency fraction digits.\n" }, { "code": null, "e": 30981, "s": 30869, "text": "public int getDefaultFractionDigits()\nReturn : \nreturns default number of argumented currency fraction digits.\n" }, { "code": null, "e": 31199, "s": 30981, "text": "getDisplayName() : java.util.Currency.getDisplayName() method generates the currency name of the argumented currency code.Syntax :public string getDisplayName()\nReturn : \ncurrency name of the argumented currency code\n" }, { "code": null, "e": 31287, "s": 31199, "text": "public string getDisplayName()\nReturn : \ncurrency name of the argumented currency code\n" }, { "code": null, "e": 33858, "s": 31287, "text": "getSymbol() : java.util.Currency.getSymbol() method returns Currency symbol for the argumented currency code. In case, no symbol is returned normal currency code will be returned.Syntax :public String getSymbol()\nReturn : \nSymbol of the argumented currency code currency code.\nJava code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class// Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance(\"AUD\"); //Australian Dollar Currency c2 = Currency.getInstance(\"JPY\"); //Japan Yen Currency c3 = Currency.getInstance(\"USD\"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println(\"Australian Dollar code : \" + cCode1); System.out.println(\"Japan Yen code : \" + cCode2); System.out.println(\"\"); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println(\"AUD Fraction digits : \" + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println(\"JPY fraction digits : \" + D2); System.out.println(\"\"); // Use of getDisplayName() method System.out.println(\"AUD Display : \"+c1.getDisplayName()); System.out.println(\"JPY Display : \"+c2.getSymbol()); System.out.println(\"\"); // Use of getSymbol() method System.out.println(\"JPY Symbol : \"+c2.getSymbol()); System.out.println(\"USD Symbol : \"+c3.getSymbol()); }}Output:Australian Dollar code : AUD\nJapan Yen code : JPY\n\nAUD Fraction digits : 2\nJPY fraction digits : 0\n\nAUD Display : Australian Dollar\nJPY Display : JPY\n\nJPY Symbol : JPY\nUSD Symbol : $Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.phpThis article is contributed by Mohit Gupta. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33949, "s": 33858, "text": "public String getSymbol()\nReturn : \nSymbol of the argumented currency code currency code.\n" }, { "code": null, "e": 34087, "s": 33949, "text": "Java code explaining getInstance(), getCurrencyCode(),getDefaultFractionDigits(), getDisplayName(), getSymbol() methods in Currency class" }, { "code": "// Java program explaining Currency class methods// getInstance(), getCurrencyCode(),getDefaultFractionDigits()// getDisplayName(), getSymbol()import java.util.*;public class NewClass{ public static void main(String[] args) { // Use of getInstance() method to 'AUD' instance Currency c1 = Currency.getInstance(\"AUD\"); //Australian Dollar Currency c2 = Currency.getInstance(\"JPY\"); //Japan Yen Currency c3 = Currency.getInstance(\"USD\"); //Japan Yen // Use of getCurrencyCode() method String cCode1 = c1.getCurrencyCode(); String cCode2 = c2.getCurrencyCode(); System.out.println(\"Australian Dollar code : \" + cCode1); System.out.println(\"Japan Yen code : \" + cCode2); System.out.println(\"\"); // Use of getDefaultFractionDigits() method int D1 = c1.getDefaultFractionDigits(); System.out.println(\"AUD Fraction digits : \" + D1); int D2 = c2.getDefaultFractionDigits(); System.out.println(\"JPY fraction digits : \" + D2); System.out.println(\"\"); // Use of getDisplayName() method System.out.println(\"AUD Display : \"+c1.getDisplayName()); System.out.println(\"JPY Display : \"+c2.getSymbol()); System.out.println(\"\"); // Use of getSymbol() method System.out.println(\"JPY Symbol : \"+c2.getSymbol()); System.out.println(\"USD Symbol : \"+c3.getSymbol()); }}", "e": 35517, "s": 34087, "text": null }, { "code": null, "e": 35525, "s": 35517, "text": "Output:" }, { "code": null, "e": 35708, "s": 35525, "text": "Australian Dollar code : AUD\nJapan Yen code : JPY\n\nAUD Fraction digits : 2\nJPY fraction digits : 0\n\nAUD Display : Australian Dollar\nJPY Display : JPY\n\nJPY Symbol : JPY\nUSD Symbol : $" }, { "code": null, "e": 35790, "s": 35708, "text": "Refer the link for list of ISO 4217 Currency Codes :http://www.xe.com/iso4217.php" }, { "code": null, "e": 36089, "s": 35790, "text": "This article is contributed by Mohit Gupta. 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": 36214, "s": 36089, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36227, "s": 36214, "text": "Java-Library" }, { "code": null, "e": 36232, "s": 36227, "text": "Java" }, { "code": null, "e": 36237, "s": 36232, "text": "Java" }, { "code": null, "e": 36335, "s": 36237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36386, "s": 36335, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36416, "s": 36386, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36431, "s": 36416, "text": "Stream In Java" }, { "code": null, "e": 36450, "s": 36431, "text": "Interfaces in Java" }, { "code": null, "e": 36481, "s": 36450, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36499, "s": 36481, "text": "ArrayList in Java" }, { "code": null, "e": 36531, "s": 36499, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36551, "s": 36531, "text": "Stack Class in Java" }, { "code": null, "e": 36575, "s": 36551, "text": "Singleton Class in Java" } ]
Pure CSS Dropdown - GeeksforGeeks
27 Sep, 2021 Pure CSS is a CSS framework. It is a free and open-source tool collection for creating responsive websites and web applications. Pure CSS is developed by Yahoo and is used for creating faster, beautiful, and responsive websites. It can be used as an alternative to Bootstrap. Dropdowns are one of the most important parts of an interactive website. A dropdown menu is the collection of menu items that allow users to choose a value from the list. To create a dropdown menu in Pure.CSS, we use class pure-menu-has-children and pure-menu-allow-hover. This class allows us to convert any element into a dropdown item. Syntax: <div class="pure-menu-has-children pure-menu-allow-hover"></div> Example 1: The following example shows a simple dropdown menu and a drop-down with different background colors created by using the background-color property of CSS. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-LTIDeidl25h2dPxrB2Ekgc9c7sEC3CWGM6HeFmuDNUjX76Ert4Z4IY714dhZHPLd" crossorigin="anonymous"></head> <body> <center> <h2 style="color:green;"> GeeksforGeeks </h2> </center> <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-item pure-menu-selected"> <a href="#" class="pure-menu-link">Home</a> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link">Courses</a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Placement 100</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Complete Interview Preparation</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Android Bootcamp</a> </li> </ul> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover" style="background-color: green;"> <a href="#" class="pure-menu-link" style="color:white;"> Contact US </a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> At Office </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> At Headquarter </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Via mail </a> </li> </ul> </li> </ul> </div></body> </html> Output: Pure CSS Example 2: We can create a nested dropdown by nesting dropdown components inside each other. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-LTIDeidl25h2dPxrB2Ekgc9c7sEC3CWGM6HeFmuDNUjX76Ert4Z4IY714dhZHPLd" crossorigin="anonymous"></head> <body> <center> <h2 style="color:green;"> GeeksforGeeks </h2> </center> <div class="pure-menu pure-menu-horizontal"> <ul class="pure-menu-list"> <li class="pure-menu-item pure-menu-selected"> <a href="#" class="pure-menu-link">Home</a> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link">Courses</a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Placement 100</a> </li> <li class="pure-menu-item" disabled> <a href="#" class="pure-menu-link"> Complete Interview Preparation</a> </li> <li class="pure-menu-item" active> <a href="#" class="pure-menu-link"> Android Bootcamp</a> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link"> Contact US </a> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> At Office </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> At Headquarter </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Via mail </a> </li> </ul> </li> </ul> </li> </ul> </div></body> </html> Output: Reference: https://purecss.io/menus/ CSS-Questions Picked Pure CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26591, "s": 26563, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26721, "s": 26591, "text": "Pure CSS is a CSS framework. It is a free and open-source tool collection for creating responsive websites and web applications. " }, { "code": null, "e": 27040, "s": 26721, "text": "Pure CSS is developed by Yahoo and is used for creating faster, beautiful, and responsive websites. It can be used as an alternative to Bootstrap. Dropdowns are one of the most important parts of an interactive website. A dropdown menu is the collection of menu items that allow users to choose a value from the list. " }, { "code": null, "e": 27208, "s": 27040, "text": "To create a dropdown menu in Pure.CSS, we use class pure-menu-has-children and pure-menu-allow-hover. This class allows us to convert any element into a dropdown item." }, { "code": null, "e": 27216, "s": 27208, "text": "Syntax:" }, { "code": null, "e": 27281, "s": 27216, "text": "<div class=\"pure-menu-has-children pure-menu-allow-hover\"></div>" }, { "code": null, "e": 27449, "s": 27283, "text": "Example 1: The following example shows a simple dropdown menu and a drop-down with different background colors created by using the background-color property of CSS." }, { "code": null, "e": 27454, "s": 27449, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\" integrity=\"sha384-LTIDeidl25h2dPxrB2Ekgc9c7sEC3CWGM6HeFmuDNUjX76Ert4Z4IY714dhZHPLd\" crossorigin=\"anonymous\"></head> <body> <center> <h2 style=\"color:green;\"> GeeksforGeeks </h2> </center> <div class=\"pure-menu pure-menu-horizontal\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-item pure-menu-selected\"> <a href=\"#\" class=\"pure-menu-link\">Home</a> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\">Courses</a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Placement 100</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Complete Interview Preparation</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Android Bootcamp</a> </li> </ul> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\" style=\"background-color: green;\"> <a href=\"#\" class=\"pure-menu-link\" style=\"color:white;\"> Contact US </a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> At Office </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> At Headquarter </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Via mail </a> </li> </ul> </li> </ul> </div></body> </html>", "e": 29973, "s": 27454, "text": null }, { "code": null, "e": 29981, "s": 29973, "text": "Output:" }, { "code": null, "e": 29990, "s": 29981, "text": "Pure CSS" }, { "code": null, "e": 30083, "s": 29990, "text": "Example 2: We can create a nested dropdown by nesting dropdown components inside each other." }, { "code": null, "e": 30088, "s": 30083, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://unpkg.com/[email protected]/build/pure-min.css\" integrity=\"sha384-LTIDeidl25h2dPxrB2Ekgc9c7sEC3CWGM6HeFmuDNUjX76Ert4Z4IY714dhZHPLd\" crossorigin=\"anonymous\"></head> <body> <center> <h2 style=\"color:green;\"> GeeksforGeeks </h2> </center> <div class=\"pure-menu pure-menu-horizontal\"> <ul class=\"pure-menu-list\"> <li class=\"pure-menu-item pure-menu-selected\"> <a href=\"#\" class=\"pure-menu-link\">Home</a> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\">Courses</a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Placement 100</a> </li> <li class=\"pure-menu-item\" disabled> <a href=\"#\" class=\"pure-menu-link\"> Complete Interview Preparation</a> </li> <li class=\"pure-menu-item\" active> <a href=\"#\" class=\"pure-menu-link\"> Android Bootcamp</a> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\"> Contact US </a> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> At Office </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> At Headquarter </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Via mail </a> </li> </ul> </li> </ul> </li> </ul> </div></body> </html>", "e": 32838, "s": 30088, "text": null }, { "code": null, "e": 32846, "s": 32838, "text": "Output:" }, { "code": null, "e": 32883, "s": 32846, "text": "Reference: https://purecss.io/menus/" }, { "code": null, "e": 32897, "s": 32883, "text": "CSS-Questions" }, { "code": null, "e": 32904, "s": 32897, "text": "Picked" }, { "code": null, "e": 32913, "s": 32904, "text": "Pure CSS" }, { "code": null, "e": 32917, "s": 32913, "text": "CSS" }, { "code": null, "e": 32934, "s": 32917, "text": "Web Technologies" }, { "code": null, "e": 33032, "s": 32934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33082, "s": 33032, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33144, "s": 33082, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33192, "s": 33144, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33250, "s": 33192, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 33305, "s": 33250, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 33345, "s": 33305, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33378, "s": 33345, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33423, "s": 33378, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33466, "s": 33423, "text": "How to fetch data from an API in ReactJS ?" } ]
Construct Complete Binary Tree from its Linked List Representation - GeeksforGeeks
13 Apr, 2022 Given Linked List Representation of Complete Binary Tree, construct the Binary tree. A complete binary tree can be represented in an array in the following approach.If root node is stored at index i, its left, and right children are stored at indices 2*i+1, 2*i+2 respectively. Suppose tree is represented by a linked list in same way, how do we convert this into normal linked representation of binary tree where every node has data, left and right pointers? In the linked list representation, we cannot directly access the children of the current node unless we traverse the list. We are mainly given level order traversal in sequential access form. We know head of linked list is always is root of the tree. We take the first node as root and we also know that the next two nodes are left and right children of root. So we know partial Binary Tree. The idea is to do Level order traversal of the partially built Binary Tree using queue and traverse the linked list at the same time. At every step, we take the parent node from queue, make next two nodes of linked list as children of the parent node, and enqueue the next two nodes to queue.1. Create an empty queue. 2. Make the first node of the list as root, and enqueue it to the queue. 3. Until we reach the end of the list, do the following. .........a. Dequeue one node from the queue. This is the current parent. .........b. Traverse two nodes in the list, add them as children of the current parent. .........c. Enqueue the two nodes into the queue.Below is the code which implements the same in C++. C++ Java Python3 C# Javascript // C++ program to create a Complete Binary tree from its Linked List// Representation#include <iostream>#include <string>#include <queue>using namespace std; // Linked list nodestruct ListNode{ int data; ListNode* next;}; // Binary tree node structurestruct BinaryTreeNode{ int data; BinaryTreeNode *left, *right;}; // Function to insert a node at the beginning of the Linked Listvoid push(struct ListNode** head_ref, int new_data){ // allocate node and assign data struct ListNode* new_node = new ListNode; new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node;} // method to create a new binary tree node from the given dataBinaryTreeNode* newBinaryTreeNode(int data){ BinaryTreeNode *temp = new BinaryTreeNode; temp->data = data; temp->left = temp->right = NULL; return temp;} // converts a given linked list representing a complete binary tree into the// linked representation of binary tree.void convertList2Binary(ListNode *head, BinaryTreeNode* &root){ // queue to store the parent nodes queue<BinaryTreeNode *> q; // Base Case if (head == NULL) { root = NULL; // Note that root is passed by reference return; } // 1.) The first node is always the root node, and add it to the queue root = newBinaryTreeNode(head->data); q.push(root); // advance the pointer to the next node head = head->next; // until the end of linked list is reached, do the following steps while (head) { // 2.a) take the parent node from the q and remove it from q BinaryTreeNode* parent = q.front(); q.pop(); // 2.c) take next two nodes from the linked list. We will add // them as children of the current parent node in step 2.b. Push them // into the queue so that they will be parents to the future nodes BinaryTreeNode *leftChild = NULL, *rightChild = NULL; leftChild = newBinaryTreeNode(head->data); q.push(leftChild); head = head->next; if (head) { rightChild = newBinaryTreeNode(head->data); q.push(rightChild); head = head->next; } // 2.b) assign the left and right children of parent parent->left = leftChild; parent->right = rightChild; //remove current level node q.pop(); }} // Utility function to traverse the binary tree after conversionvoid inorderTraversal(BinaryTreeNode* root){ if (root) { inorderTraversal( root->left ); cout << root->data << " "; inorderTraversal( root->right ); }} // Driver program to test above functionsint main(){ // create a linked list shown in above diagram struct ListNode* head = NULL; push(&head, 36); /* Last node of Linked List */ push(&head, 30); push(&head, 25); push(&head, 15); push(&head, 12); push(&head, 10); /* First node of Linked List */ BinaryTreeNode *root; convertList2Binary(head, root); cout << "Inorder Traversal of the constructed Binary Tree is: \n"; inorderTraversal(root); return 0;} // Java program to create complete Binary Tree from its Linked List// representation // importing necessary classesimport java.util.*; // A linked list nodeclass ListNode{ int data; ListNode next; ListNode(int d) { data = d; next = null; }} // A binary tree nodeclass BinaryTreeNode{ int data; BinaryTreeNode left, right = null; BinaryTreeNode(int data) { this.data = data; left = right = null; }} class BinaryTree{ ListNode head; BinaryTreeNode root; // Function to insert a node at the beginning of // the Linked List void push(int new_data) { // allocate node and assign data ListNode new_node = new ListNode(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. BinaryTreeNode convertList2Binary(BinaryTreeNode node) { // queue to store the parent nodes Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>(); // Base Case if (head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(head.data); q.add(node); // advance the pointer to the next node head = head.next; // until the end of linked list is reached, do the // following steps while (head != null) { // 2.a) take the parent node from the q and // remove it from q BinaryTreeNode parent = q.peek(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes BinaryTreeNode leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(head.data); q.add(leftChild); head = head.next; if (head != null) { rightChild = new BinaryTreeNode(head.data); q.add(rightChild); head = head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; //remove current level node q.poll(); } return node; } // Utility function to traverse the binary tree // after conversion void inorderTraversal(BinaryTreeNode node) { if (node != null) { inorderTraversal(node.left); System.out.print(node.data + " "); inorderTraversal(node.right); } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.push(36); /* Last node of Linked List */ tree.push(30); tree.push(25); tree.push(15); tree.push(12); tree.push(10); /* First node of Linked List */ BinaryTreeNode node = tree.convertList2Binary(tree.root); System.out.println("Inorder Traversal of the"+ " constructed Binary Tree is:"); tree.inorderTraversal(node); }}// This code has been contributed by Mayank Jaiswal # Python program to create a Complete Binary Tree from# its linked list representation # Linked List nodeclass ListNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Binary Tree Node structureclass BinaryTreeNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Class to convert the linked list to Binary Treeclass Conversion: # Constructor for storing head of linked list # and root for the Binary Tree def __init__(self, data = None): self.head = None self.root = None def push(self, new_data): # Creating a new linked list node and storing data new_node = ListNode(new_data) # Make next of new node as head new_node.next = self.head # Move the head to point to new node self.head = new_node def convertList2Binary(self): # Queue to store the parent nodes q = [] # Base Case if self.head is None: self.root = None return # 1.) The first node is always the root node, # and add it to the queue self.root = BinaryTreeNode(self.head.data) q.append(self.root) # Advance the pointer to the next node self.head = self.head.next # Until the end of linked list is reached, do: while(self.head): # 2.a) Take the parent node from the q and # and remove it from q parent = q.pop(0) # Front of queue # 2.c) Take next two nodes from the linked list. # We will add them as children of the current # parent node in step 2.b. # Push them into the queue so that they will be # parent to the future node leftChild= None rightChild = None leftChild = BinaryTreeNode(self.head.data) q.append(leftChild) self.head = self.head.next if(self.head): rightChild = BinaryTreeNode(self.head.data) q.append(rightChild) self.head = self.head.next #2.b) Assign the left and right children of parent parent.left = leftChild parent.right = rightChild def inorderTraversal(self, root): if(root): self.inorderTraversal(root.left) print (root.data,end=" ") self.inorderTraversal(root.right) # Driver Program to test above function # Object of conversion classconv = Conversion()conv.push(36)conv.push(30)conv.push(25)conv.push(15)conv.push(12)conv.push(10) conv.convertList2Binary() print ("Inorder Traversal of the constructed Binary Tree is:")conv.inorderTraversal(conv.root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to create complete// Binary Tree from its Linked List// representation // importing necessary classesusing System;using System.Collections.Generic; // A linked list nodepublic class ListNode{ public int data; public ListNode next; public ListNode(int d) { data = d; next = null; }} // A binary tree nodepublic class BinaryTreeNode{ public int data; public BinaryTreeNode left, right = null; public BinaryTreeNode(int data) { this.data = data; left = right = null; }} public class BinaryTree{ ListNode head; BinaryTreeNode root; // Function to insert a node at // the beginning of the Linked List void push(int new_data) { // allocate node and assign data ListNode new_node = new ListNode(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. BinaryTreeNode convertList2Binary(BinaryTreeNode node) { // queue to store the parent nodes Queue<BinaryTreeNode> q = new Queue<BinaryTreeNode>(); // Base Case if (head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(head.data); q.Enqueue(node); // advance the pointer to the next node head = head.next; // until the end of linked list is reached, // do the following steps while (head != null) { // 2.a) take the parent node from the q and // remove it from q BinaryTreeNode parent = q.Peek(); BinaryTreeNode pp = q.Dequeue(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes BinaryTreeNode leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(head.data); q.Enqueue(leftChild); head = head.next; if (head != null) { rightChild = new BinaryTreeNode(head.data); q.Enqueue(rightChild); head = head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; } return node; } // Utility function to traverse the binary tree // after conversion void inorderTraversal(BinaryTreeNode node) { if (node != null) { inorderTraversal(node.left); Console.Write(node.data + " "); inorderTraversal(node.right); } } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); /* Last node of Linked List */ tree.push(36); tree.push(30); tree.push(25); tree.push(15); tree.push(12); /* First node of Linked List */ tree.push(10); BinaryTreeNode node = tree.convertList2Binary(tree.root); Console.WriteLine("Inorder Traversal of the"+ " constructed Binary Tree is:"); tree.inorderTraversal(node); }} /* This code is contributed PrinciRaj1992 */ <script> // JavaScript program to create complete // Binary Tree from its Linked List // representation // importing necessary classes // A linked list node class ListNode { constructor(d) { this.data = d; this.next = null; } } // A binary tree node class BinaryTreeNode { constructor(data) { this.data = data; this.left = null; this.right = null; } } class BinaryTree { constructor() { this.head = null; this.root = null; } // Function to insert a node at // the beginning of the Linked List push(new_data) { // allocate node and assign data var new_node = new ListNode(new_data); // link the old list off the new node new_node.next = this.head; // move the head to point to the new node this.head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. convertList2Binary(node) { // queue to store the parent nodes var q = []; // Base Case if (this.head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(this.head.data); q.push(node); // advance the pointer to the next node this.head = this.head.next; // until the end of linked list is reached, // do the following steps while (this.head != null) { // 2.a) take the parent node from the q and // remove it from q var parent = q.shift(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes var leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(this.head.data); q.push(leftChild); this.head = this.head.next; if (this.head != null) { rightChild = new BinaryTreeNode(this.head.data); q.push(rightChild); this.head = this.head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; } return node; } // Utility function to traverse the binary tree // after conversion inorderTraversal(node) { if (node != null) { this.inorderTraversal(node.left); document.write(node.data + " "); this.inorderTraversal(node.right); } } } // Driver code var tree = new BinaryTree(); /* Last node of Linked List */ tree.push(36); tree.push(30); tree.push(25); tree.push(15); tree.push(12); /* First node of Linked List */ tree.push(10); var node = tree.convertList2Binary(tree.root); document.write( "Inorder Traversal of the" + " constructed Binary Tree is:<br>" ); tree.inorderTraversal(node); </script> Inorder Traversal of the constructed Binary Tree is: 12 10 25 15 36 30 Time Complexity: Time complexity of the above solution is O(n) where n is the number of nodes. YouTubeGeeksforGeeks507K subscribersConstruct Complete Binary Tree from its Linked List Representation | 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 / 5:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=dGJtKxBpP00" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 rdtank mishra695047 amartyaghoshgfg simmytarika5 romioranjan Amazon Queue Tree Amazon Queue Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Level Order Binary Tree Traversal Queue Interface In Java Queue in Python Circular Queue | Set 1 (Introduction and Array Implementation) Sliding Window Maximum (Maximum of all subarrays of size k) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Write a Program to Find the Maximum Depth or Height of a Tree Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 39005, "s": 38977, "text": "\n13 Apr, 2022" }, { "code": null, "e": 39589, "s": 39005, "text": "Given Linked List Representation of Complete Binary Tree, construct the Binary tree. A complete binary tree can be represented in an array in the following approach.If root node is stored at index i, its left, and right children are stored at indices 2*i+1, 2*i+2 respectively. Suppose tree is represented by a linked list in same way, how do we convert this into normal linked representation of binary tree where every node has data, left and right pointers? In the linked list representation, we cannot directly access the children of the current node unless we traverse the list. " }, { "code": null, "e": 40571, "s": 39591, "text": "We are mainly given level order traversal in sequential access form. We know head of linked list is always is root of the tree. We take the first node as root and we also know that the next two nodes are left and right children of root. So we know partial Binary Tree. The idea is to do Level order traversal of the partially built Binary Tree using queue and traverse the linked list at the same time. At every step, we take the parent node from queue, make next two nodes of linked list as children of the parent node, and enqueue the next two nodes to queue.1. Create an empty queue. 2. Make the first node of the list as root, and enqueue it to the queue. 3. Until we reach the end of the list, do the following. .........a. Dequeue one node from the queue. This is the current parent. .........b. Traverse two nodes in the list, add them as children of the current parent. .........c. Enqueue the two nodes into the queue.Below is the code which implements the same in C++. " }, { "code": null, "e": 40575, "s": 40571, "text": "C++" }, { "code": null, "e": 40580, "s": 40575, "text": "Java" }, { "code": null, "e": 40588, "s": 40580, "text": "Python3" }, { "code": null, "e": 40591, "s": 40588, "text": "C#" }, { "code": null, "e": 40602, "s": 40591, "text": "Javascript" }, { "code": "// C++ program to create a Complete Binary tree from its Linked List// Representation#include <iostream>#include <string>#include <queue>using namespace std; // Linked list nodestruct ListNode{ int data; ListNode* next;}; // Binary tree node structurestruct BinaryTreeNode{ int data; BinaryTreeNode *left, *right;}; // Function to insert a node at the beginning of the Linked Listvoid push(struct ListNode** head_ref, int new_data){ // allocate node and assign data struct ListNode* new_node = new ListNode; new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node;} // method to create a new binary tree node from the given dataBinaryTreeNode* newBinaryTreeNode(int data){ BinaryTreeNode *temp = new BinaryTreeNode; temp->data = data; temp->left = temp->right = NULL; return temp;} // converts a given linked list representing a complete binary tree into the// linked representation of binary tree.void convertList2Binary(ListNode *head, BinaryTreeNode* &root){ // queue to store the parent nodes queue<BinaryTreeNode *> q; // Base Case if (head == NULL) { root = NULL; // Note that root is passed by reference return; } // 1.) The first node is always the root node, and add it to the queue root = newBinaryTreeNode(head->data); q.push(root); // advance the pointer to the next node head = head->next; // until the end of linked list is reached, do the following steps while (head) { // 2.a) take the parent node from the q and remove it from q BinaryTreeNode* parent = q.front(); q.pop(); // 2.c) take next two nodes from the linked list. We will add // them as children of the current parent node in step 2.b. Push them // into the queue so that they will be parents to the future nodes BinaryTreeNode *leftChild = NULL, *rightChild = NULL; leftChild = newBinaryTreeNode(head->data); q.push(leftChild); head = head->next; if (head) { rightChild = newBinaryTreeNode(head->data); q.push(rightChild); head = head->next; } // 2.b) assign the left and right children of parent parent->left = leftChild; parent->right = rightChild; //remove current level node q.pop(); }} // Utility function to traverse the binary tree after conversionvoid inorderTraversal(BinaryTreeNode* root){ if (root) { inorderTraversal( root->left ); cout << root->data << \" \"; inorderTraversal( root->right ); }} // Driver program to test above functionsint main(){ // create a linked list shown in above diagram struct ListNode* head = NULL; push(&head, 36); /* Last node of Linked List */ push(&head, 30); push(&head, 25); push(&head, 15); push(&head, 12); push(&head, 10); /* First node of Linked List */ BinaryTreeNode *root; convertList2Binary(head, root); cout << \"Inorder Traversal of the constructed Binary Tree is: \\n\"; inorderTraversal(root); return 0;}", "e": 43797, "s": 40602, "text": null }, { "code": "// Java program to create complete Binary Tree from its Linked List// representation // importing necessary classesimport java.util.*; // A linked list nodeclass ListNode{ int data; ListNode next; ListNode(int d) { data = d; next = null; }} // A binary tree nodeclass BinaryTreeNode{ int data; BinaryTreeNode left, right = null; BinaryTreeNode(int data) { this.data = data; left = right = null; }} class BinaryTree{ ListNode head; BinaryTreeNode root; // Function to insert a node at the beginning of // the Linked List void push(int new_data) { // allocate node and assign data ListNode new_node = new ListNode(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. BinaryTreeNode convertList2Binary(BinaryTreeNode node) { // queue to store the parent nodes Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>(); // Base Case if (head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(head.data); q.add(node); // advance the pointer to the next node head = head.next; // until the end of linked list is reached, do the // following steps while (head != null) { // 2.a) take the parent node from the q and // remove it from q BinaryTreeNode parent = q.peek(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes BinaryTreeNode leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(head.data); q.add(leftChild); head = head.next; if (head != null) { rightChild = new BinaryTreeNode(head.data); q.add(rightChild); head = head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; //remove current level node q.poll(); } return node; } // Utility function to traverse the binary tree // after conversion void inorderTraversal(BinaryTreeNode node) { if (node != null) { inorderTraversal(node.left); System.out.print(node.data + \" \"); inorderTraversal(node.right); } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.push(36); /* Last node of Linked List */ tree.push(30); tree.push(25); tree.push(15); tree.push(12); tree.push(10); /* First node of Linked List */ BinaryTreeNode node = tree.convertList2Binary(tree.root); System.out.println(\"Inorder Traversal of the\"+ \" constructed Binary Tree is:\"); tree.inorderTraversal(node); }}// This code has been contributed by Mayank Jaiswal", "e": 47415, "s": 43797, "text": null }, { "code": "# Python program to create a Complete Binary Tree from# its linked list representation # Linked List nodeclass ListNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Binary Tree Node structureclass BinaryTreeNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Class to convert the linked list to Binary Treeclass Conversion: # Constructor for storing head of linked list # and root for the Binary Tree def __init__(self, data = None): self.head = None self.root = None def push(self, new_data): # Creating a new linked list node and storing data new_node = ListNode(new_data) # Make next of new node as head new_node.next = self.head # Move the head to point to new node self.head = new_node def convertList2Binary(self): # Queue to store the parent nodes q = [] # Base Case if self.head is None: self.root = None return # 1.) The first node is always the root node, # and add it to the queue self.root = BinaryTreeNode(self.head.data) q.append(self.root) # Advance the pointer to the next node self.head = self.head.next # Until the end of linked list is reached, do: while(self.head): # 2.a) Take the parent node from the q and # and remove it from q parent = q.pop(0) # Front of queue # 2.c) Take next two nodes from the linked list. # We will add them as children of the current # parent node in step 2.b. # Push them into the queue so that they will be # parent to the future node leftChild= None rightChild = None leftChild = BinaryTreeNode(self.head.data) q.append(leftChild) self.head = self.head.next if(self.head): rightChild = BinaryTreeNode(self.head.data) q.append(rightChild) self.head = self.head.next #2.b) Assign the left and right children of parent parent.left = leftChild parent.right = rightChild def inorderTraversal(self, root): if(root): self.inorderTraversal(root.left) print (root.data,end=\" \") self.inorderTraversal(root.right) # Driver Program to test above function # Object of conversion classconv = Conversion()conv.push(36)conv.push(30)conv.push(25)conv.push(15)conv.push(12)conv.push(10) conv.convertList2Binary() print (\"Inorder Traversal of the constructed Binary Tree is:\")conv.inorderTraversal(conv.root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 50274, "s": 47415, "text": null }, { "code": "// C# program to create complete// Binary Tree from its Linked List// representation // importing necessary classesusing System;using System.Collections.Generic; // A linked list nodepublic class ListNode{ public int data; public ListNode next; public ListNode(int d) { data = d; next = null; }} // A binary tree nodepublic class BinaryTreeNode{ public int data; public BinaryTreeNode left, right = null; public BinaryTreeNode(int data) { this.data = data; left = right = null; }} public class BinaryTree{ ListNode head; BinaryTreeNode root; // Function to insert a node at // the beginning of the Linked List void push(int new_data) { // allocate node and assign data ListNode new_node = new ListNode(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. BinaryTreeNode convertList2Binary(BinaryTreeNode node) { // queue to store the parent nodes Queue<BinaryTreeNode> q = new Queue<BinaryTreeNode>(); // Base Case if (head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(head.data); q.Enqueue(node); // advance the pointer to the next node head = head.next; // until the end of linked list is reached, // do the following steps while (head != null) { // 2.a) take the parent node from the q and // remove it from q BinaryTreeNode parent = q.Peek(); BinaryTreeNode pp = q.Dequeue(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes BinaryTreeNode leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(head.data); q.Enqueue(leftChild); head = head.next; if (head != null) { rightChild = new BinaryTreeNode(head.data); q.Enqueue(rightChild); head = head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; } return node; } // Utility function to traverse the binary tree // after conversion void inorderTraversal(BinaryTreeNode node) { if (node != null) { inorderTraversal(node.left); Console.Write(node.data + \" \"); inorderTraversal(node.right); } } // Driver code public static void Main() { BinaryTree tree = new BinaryTree(); /* Last node of Linked List */ tree.push(36); tree.push(30); tree.push(25); tree.push(15); tree.push(12); /* First node of Linked List */ tree.push(10); BinaryTreeNode node = tree.convertList2Binary(tree.root); Console.WriteLine(\"Inorder Traversal of the\"+ \" constructed Binary Tree is:\"); tree.inorderTraversal(node); }} /* This code is contributed PrinciRaj1992 */", "e": 53944, "s": 50274, "text": null }, { "code": "<script> // JavaScript program to create complete // Binary Tree from its Linked List // representation // importing necessary classes // A linked list node class ListNode { constructor(d) { this.data = d; this.next = null; } } // A binary tree node class BinaryTreeNode { constructor(data) { this.data = data; this.left = null; this.right = null; } } class BinaryTree { constructor() { this.head = null; this.root = null; } // Function to insert a node at // the beginning of the Linked List push(new_data) { // allocate node and assign data var new_node = new ListNode(new_data); // link the old list off the new node new_node.next = this.head; // move the head to point to the new node this.head = new_node; } // converts a given linked list representing a // complete binary tree into the linked // representation of binary tree. convertList2Binary(node) { // queue to store the parent nodes var q = []; // Base Case if (this.head == null) { node = null; return null; } // 1.) The first node is always the root node, and // add it to the queue node = new BinaryTreeNode(this.head.data); q.push(node); // advance the pointer to the next node this.head = this.head.next; // until the end of linked list is reached, // do the following steps while (this.head != null) { // 2.a) take the parent node from the q and // remove it from q var parent = q.shift(); // 2.c) take next two nodes from the linked list. // We will add them as children of the current // parent node in step 2.b. Push them into the // queue so that they will be parents to the // future nodes var leftChild = null, rightChild = null; leftChild = new BinaryTreeNode(this.head.data); q.push(leftChild); this.head = this.head.next; if (this.head != null) { rightChild = new BinaryTreeNode(this.head.data); q.push(rightChild); this.head = this.head.next; } // 2.b) assign the left and right children of // parent parent.left = leftChild; parent.right = rightChild; } return node; } // Utility function to traverse the binary tree // after conversion inorderTraversal(node) { if (node != null) { this.inorderTraversal(node.left); document.write(node.data + \" \"); this.inorderTraversal(node.right); } } } // Driver code var tree = new BinaryTree(); /* Last node of Linked List */ tree.push(36); tree.push(30); tree.push(25); tree.push(15); tree.push(12); /* First node of Linked List */ tree.push(10); var node = tree.convertList2Binary(tree.root); document.write( \"Inorder Traversal of the\" + \" constructed Binary Tree is:<br>\" ); tree.inorderTraversal(node); </script>", "e": 57367, "s": 53944, "text": null }, { "code": null, "e": 57440, "s": 57367, "text": "Inorder Traversal of the constructed Binary Tree is: \n12 10 25 15 36 30 " }, { "code": null, "e": 57536, "s": 57440, "text": "Time Complexity: Time complexity of the above solution is O(n) where n is the number of nodes. " }, { "code": null, "e": 58401, "s": 57536, "text": "YouTubeGeeksforGeeks507K subscribersConstruct Complete Binary Tree from its Linked List Representation | 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 / 5:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=dGJtKxBpP00\" 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": 58578, "s": 58401, "text": "This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 58592, "s": 58578, "text": "princiraj1992" }, { "code": null, "e": 58599, "s": 58592, "text": "rdtank" }, { "code": null, "e": 58612, "s": 58599, "text": "mishra695047" }, { "code": null, "e": 58628, "s": 58612, "text": "amartyaghoshgfg" }, { "code": null, "e": 58641, "s": 58628, "text": "simmytarika5" }, { "code": null, "e": 58653, "s": 58641, "text": "romioranjan" }, { "code": null, "e": 58660, "s": 58653, "text": "Amazon" }, { "code": null, "e": 58666, "s": 58660, "text": "Queue" }, { "code": null, "e": 58671, "s": 58666, "text": "Tree" }, { "code": null, "e": 58678, "s": 58671, "text": "Amazon" }, { "code": null, "e": 58684, "s": 58678, "text": "Queue" }, { "code": null, "e": 58689, "s": 58684, "text": "Tree" }, { "code": null, "e": 58787, "s": 58689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 58821, "s": 58787, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 58845, "s": 58821, "text": "Queue Interface In Java" }, { "code": null, "e": 58861, "s": 58845, "text": "Queue in Python" }, { "code": null, "e": 58924, "s": 58861, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 58984, "s": 58924, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 59013, "s": 58984, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 59047, "s": 59013, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 59109, "s": 59047, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 59123, "s": 59109, "text": "Decision Tree" } ]
Find the count of numbers that can be formed using digits 3, 4 only and having length at max N. - GeeksforGeeks
25 Mar, 2021 Given a number N. Find the count of such numbers that can be formed using digits 3 and 4 only and having length at max N.Examples: Input : N = 2 Output : 6 Explanation : 3, 4, 33, 34, 43, 44 are numbers having length 2 and digits 3 and 4 only. Input : N = 1 Output : 2 Explanation : 3, 4 are the only such numbers. Approach : There are 2 numbers of length 1. They are 3 and 4. There are 4 numbers of length 2. They are 33, 34, 43 and 44. There are 8 such numbers of length 3. They are 333, 334, 343, 344, 433, 434, 443, 444. For each addition of 1 to the length, the number of numbers is increased times 2. It is easy to prove: to any number of the previous length one can append 3 or 4, so one number of the previous length creates two numbers of the next length.So for the length N the amount of such numbers of the length exactly N is 2*N. But in the problem, we need the number of numbers of length not greater than N. Let’s sum up them. 21 = 2, 21 + 22 = 2 + 4 = 6, 21 + 22 + 23 = 2 + 4 + 8 = 14, 21 + 22 + 23 + 24 = 2 + 4 + 8 + 16 = 30. One can notice that the sum of all previous powers of two is equal to the next power of two minus the first power of two. So the answer to the problem is 2N+1 – 2.Below is the implementation of the above approach : C++ Java Python3 C# PHP Javascript // Cpp program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.#include <bits/stdc++.h>using namespace std; // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.long long numbers(int n){ return (long long)(pow(2, n + 1)) - 2;} // Driver codeint main(){ int n = 2; cout << numbers(n); return 0;} // Java program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N. class GFG{ // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.static long numbers(int n){ return (long)(Math.pow(2, n + 1)) - 2;} // Driver codepublic static void main(String args[]){ int n = 2; System.out.println( numbers(n));}} // This code is contributed by Arnab Kundu # Python3 program to find the count of# numbers that can be formed using digits# 3, 4 only and having length at max N. # Function to find the count of numbers# that can be formed using digits 3, 4# only and having length at max N.def numbers(n): return pow(2, n + 1) - 2 # Driver coden = 2print(numbers(n)) # This code is contributed# by Shrikant13 // C# program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.using System; class GFG{ // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.static long numbers(int n){ return (long)(Math.Pow(2, n + 1)) - 2;} // Driver codestatic void Main(){ int n = 2; Console.WriteLine( numbers(n));}} // This code is contributed by mits <?php// PHP program to find the count of// numbers that can be formed using// digits 3, 4 only and having length// at max N. // Function to find the count of numbers// that can be formed using digits 3, 4 only// and having length at max N.function numbers($n){ return (pow(2, $n + 1)) - 2;} // Driver code$n = 2; echo numbers($n); // This code is contributed// by Akanksha Rai?> <script>// javascript program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N. // Function to find the count of numbers that // can be formed using digits 3, 4 only and // having length at max N. function numbers(n) { return (Math.pow(2, n + 1)) - 2; } // Driver code var n = 2; document.write(numbers(n)); // This code is contributed by Princi Singh</script> 6 andrew1234 shrikanth13 Mithun Kumar Akanksha_Rai princi singh maths-power number-digits Combinatorial Competitive Programming Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinational Sum Count ways to reach the nth stair using step 1, 2 or 3 Print all possible strings of length k that can be formed from a set of n characters Count of subsets with sum equal to X Python program to get all subsets of given size of a set Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 26571, "s": 26543, "text": "\n25 Mar, 2021" }, { "code": null, "e": 26704, "s": 26571, "text": "Given a number N. Find the count of such numbers that can be formed using digits 3 and 4 only and having length at max N.Examples: " }, { "code": null, "e": 26890, "s": 26704, "text": "Input : N = 2\nOutput : 6\nExplanation : 3, 4, 33, 34, 43, 44 \nare numbers having length 2 and digits 3 and 4 only.\n\nInput : N = 1\nOutput : 2\nExplanation : 3, 4 are the only such numbers." }, { "code": null, "e": 27837, "s": 26892, "text": "Approach : There are 2 numbers of length 1. They are 3 and 4. There are 4 numbers of length 2. They are 33, 34, 43 and 44. There are 8 such numbers of length 3. They are 333, 334, 343, 344, 433, 434, 443, 444. For each addition of 1 to the length, the number of numbers is increased times 2. It is easy to prove: to any number of the previous length one can append 3 or 4, so one number of the previous length creates two numbers of the next length.So for the length N the amount of such numbers of the length exactly N is 2*N. But in the problem, we need the number of numbers of length not greater than N. Let’s sum up them. 21 = 2, 21 + 22 = 2 + 4 = 6, 21 + 22 + 23 = 2 + 4 + 8 = 14, 21 + 22 + 23 + 24 = 2 + 4 + 8 + 16 = 30. One can notice that the sum of all previous powers of two is equal to the next power of two minus the first power of two. So the answer to the problem is 2N+1 – 2.Below is the implementation of the above approach : " }, { "code": null, "e": 27841, "s": 27837, "text": "C++" }, { "code": null, "e": 27846, "s": 27841, "text": "Java" }, { "code": null, "e": 27854, "s": 27846, "text": "Python3" }, { "code": null, "e": 27857, "s": 27854, "text": "C#" }, { "code": null, "e": 27861, "s": 27857, "text": "PHP" }, { "code": null, "e": 27872, "s": 27861, "text": "Javascript" }, { "code": "// Cpp program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.#include <bits/stdc++.h>using namespace std; // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.long long numbers(int n){ return (long long)(pow(2, n + 1)) - 2;} // Driver codeint main(){ int n = 2; cout << numbers(n); return 0;}", "e": 28296, "s": 27872, "text": null }, { "code": "// Java program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N. class GFG{ // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.static long numbers(int n){ return (long)(Math.pow(2, n + 1)) - 2;} // Driver codepublic static void main(String args[]){ int n = 2; System.out.println( numbers(n));}} // This code is contributed by Arnab Kundu", "e": 28765, "s": 28296, "text": null }, { "code": "# Python3 program to find the count of# numbers that can be formed using digits# 3, 4 only and having length at max N. # Function to find the count of numbers# that can be formed using digits 3, 4# only and having length at max N.def numbers(n): return pow(2, n + 1) - 2 # Driver coden = 2print(numbers(n)) # This code is contributed# by Shrikant13", "e": 29117, "s": 28765, "text": null }, { "code": "// C# program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.using System; class GFG{ // Function to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N.static long numbers(int n){ return (long)(Math.Pow(2, n + 1)) - 2;} // Driver codestatic void Main(){ int n = 2; Console.WriteLine( numbers(n));}} // This code is contributed by mits", "e": 29569, "s": 29117, "text": null }, { "code": "<?php// PHP program to find the count of// numbers that can be formed using// digits 3, 4 only and having length// at max N. // Function to find the count of numbers// that can be formed using digits 3, 4 only// and having length at max N.function numbers($n){ return (pow(2, $n + 1)) - 2;} // Driver code$n = 2; echo numbers($n); // This code is contributed// by Akanksha Rai?>", "e": 29951, "s": 29569, "text": null }, { "code": "<script>// javascript program to find the count of numbers that// can be formed using digits 3, 4 only and// having length at max N. // Function to find the count of numbers that // can be formed using digits 3, 4 only and // having length at max N. function numbers(n) { return (Math.pow(2, n + 1)) - 2; } // Driver code var n = 2; document.write(numbers(n)); // This code is contributed by Princi Singh</script>", "e": 30412, "s": 29951, "text": null }, { "code": null, "e": 30414, "s": 30412, "text": "6" }, { "code": null, "e": 30427, "s": 30416, "text": "andrew1234" }, { "code": null, "e": 30439, "s": 30427, "text": "shrikanth13" }, { "code": null, "e": 30452, "s": 30439, "text": "Mithun Kumar" }, { "code": null, "e": 30465, "s": 30452, "text": "Akanksha_Rai" }, { "code": null, "e": 30478, "s": 30465, "text": "princi singh" }, { "code": null, "e": 30490, "s": 30478, "text": "maths-power" }, { "code": null, "e": 30504, "s": 30490, "text": "number-digits" }, { "code": null, "e": 30518, "s": 30504, "text": "Combinatorial" }, { "code": null, "e": 30542, "s": 30518, "text": "Competitive Programming" }, { "code": null, "e": 30555, "s": 30542, "text": "Mathematical" }, { "code": null, "e": 30568, "s": 30555, "text": "Mathematical" }, { "code": null, "e": 30582, "s": 30568, "text": "Combinatorial" }, { "code": null, "e": 30680, "s": 30582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30698, "s": 30680, "text": "Combinational Sum" }, { "code": null, "e": 30753, "s": 30698, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 30838, "s": 30753, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 30875, "s": 30838, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 30932, "s": 30875, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 30975, "s": 30932, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31018, "s": 30975, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31059, "s": 31018, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31137, "s": 31059, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Logger throwing() method in Java with Examples - GeeksforGeeks
28 Mar, 2019 throwing(String sourceClass, String sourceMethod, Throwable thrown) method is used to Log throwing an exception.In many scenario method is closed by throwing an exception then this is a very helpful method to log that a method is terminating by throwing an exception. The logging is done using the FINER level logging. If the level of the logger is set to log FINER level logging then the given arguments are stored in a log record with a message THROW which is forwarded to all registered output handlers. Syntax: public void throwing(String sourceClass, String sourceMethod, Throwable thrown) Parameters: This method accepts three parameters: sourceClass is the name of the class that issued the logging request, sourceMethod is the name of the method and result is The Throwable that is being thrown. Return value: This method returns nothing. Below programs illustrate throwing(String sourceClass, String sourceMethod, Object result) method: Program 1: // Java program to demonstrate// throwing(String, String, Throwable) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call throwing method with class // name = GFG and method name = main // and IO Exception as Thrown object logger.throwing(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new IOException()); }} The output printed on log.txt is shown below.Output: Program 2: // Java program to demonstrate// throwing(String, String, Throwable) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { // Create a Logger static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String[] args) throws SecurityException, IOException { // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call throwing method with string // and ArithmeticException as Thrown object logger.throwing(String.class.getName(), String.class.getMethods()[0].getName(), new ArithmeticException()); }} The output printed on log.txt is shown below.Output: Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#throwing(java.lang.String, java.lang.String, java.lang.Throwable) Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n28 Mar, 2019" }, { "code": null, "e": 25732, "s": 25225, "text": "throwing(String sourceClass, String sourceMethod, Throwable thrown) method is used to Log throwing an exception.In many scenario method is closed by throwing an exception then this is a very helpful method to log that a method is terminating by throwing an exception. The logging is done using the FINER level logging. If the level of the logger is set to log FINER level logging then the given arguments are stored in a log record with a message THROW which is forwarded to all registered output handlers." }, { "code": null, "e": 25740, "s": 25732, "text": "Syntax:" }, { "code": null, "e": 25863, "s": 25740, "text": "public void throwing(String sourceClass,\n String sourceMethod,\n Throwable thrown)\n" }, { "code": null, "e": 25913, "s": 25863, "text": "Parameters: This method accepts three parameters:" }, { "code": null, "e": 25983, "s": 25913, "text": "sourceClass is the name of the class that issued the logging request," }, { "code": null, "e": 26026, "s": 25983, "text": "sourceMethod is the name of the method and" }, { "code": null, "e": 26072, "s": 26026, "text": "result is The Throwable that is being thrown." }, { "code": null, "e": 26115, "s": 26072, "text": "Return value: This method returns nothing." }, { "code": null, "e": 26214, "s": 26115, "text": "Below programs illustrate throwing(String sourceClass, String sourceMethod, Object result) method:" }, { "code": null, "e": 26225, "s": 26214, "text": "Program 1:" }, { "code": "// Java program to demonstrate// throwing(String, String, Throwable) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter; public class GFG { public static void main(String[] args) throws SecurityException, IOException { // Create a Logger Logger logger = Logger.getLogger( GFG.class.getName()); // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); handler.setFormatter(new SimpleFormatter()); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call throwing method with class // name = GFG and method name = main // and IO Exception as Thrown object logger.throwing(GFG.class.getName(), GFG.class.getMethods()[0].getName(), new IOException()); }}", "e": 27379, "s": 26225, "text": null }, { "code": null, "e": 27432, "s": 27379, "text": "The output printed on log.txt is shown below.Output:" }, { "code": null, "e": 27443, "s": 27432, "text": "Program 2:" }, { "code": "// Java program to demonstrate// throwing(String, String, Throwable) method import java.io.IOException;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger; public class GFG { // Create a Logger static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String[] args) throws SecurityException, IOException { // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); // Add file handler as // handler of logs logger.addHandler(handler); // set Logger level() logger.setLevel(Level.FINER); // set Logger level() logger.setLevel(Level.FINER); // call throwing method with string // and ArithmeticException as Thrown object logger.throwing(String.class.getName(), String.class.getMethods()[0].getName(), new ArithmeticException()); }}", "e": 28472, "s": 27443, "text": null }, { "code": null, "e": 28525, "s": 28472, "text": "The output printed on log.txt is shown below.Output:" }, { "code": null, "e": 28675, "s": 28525, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#throwing(java.lang.String, java.lang.String, java.lang.Throwable)" }, { "code": null, "e": 28695, "s": 28675, "text": "Java - util package" }, { "code": null, "e": 28710, "s": 28695, "text": "Java-Functions" }, { "code": null, "e": 28722, "s": 28710, "text": "Java-Logger" }, { "code": null, "e": 28727, "s": 28722, "text": "Java" }, { "code": null, "e": 28732, "s": 28727, "text": "Java" }, { "code": null, "e": 28830, "s": 28732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28845, "s": 28830, "text": "Stream In Java" }, { "code": null, "e": 28866, "s": 28845, "text": "Constructors in Java" }, { "code": null, "e": 28885, "s": 28866, "text": "Exceptions in Java" }, { "code": null, "e": 28915, "s": 28885, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28961, "s": 28915, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28978, "s": 28961, "text": "Generics in Java" }, { "code": null, "e": 28999, "s": 28978, "text": "Introduction to Java" }, { "code": null, "e": 29042, "s": 28999, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29078, "s": 29042, "text": "Internal Working of HashMap in Java" } ]
Fabric.js easeInOutCubic() Method - GeeksforGeeks
29 Jan, 2021 In games or animations, there are many moving objects which can move them from point A to B in a linear fashion, but after applying an easing, or easing function, it can make it look more natural. An easing function says an animation of how to progress. In this way, a straight motion can take an interesting shape. Easing functions specify the rate of change of a parameter over time. It is whose equations which make something move slowly at the start and speed up, or slow down near the end. The most common set of easing equations come from Robert Penner’s book and webpage. The easeInOutCubic() method is used for cubic easing in and out. Syntax: easeInOutCubic(t, b, c, d) Parameters: This method accepts four parameters as mentioned above and described below: t: This parameter holds the specified time when animation will start. For example, if value of t is 0, it means animation is just started. b: This parameter holds the specified starting position of the object on x-axis. For example, if value of b is 10, it means the starting position of the objects on x-coordinate is 10. c: This parameter holds the specified change in value for the object. For example, if value of c is 30, it means, the object has to move 30 to the right, ending at 40. d: This parameter holds the specified duration of the whole process. For example, if the value of d is 2, it means, the object has 2 second to perform this motion from 10 to 40. Return Value: This method returns the eased position of the object i.e., the position of the object at a specific time. Example 1: Javascript <!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body><script type="text/javascript"> // Initializing easeInOutCubic() function function easeInOutCubic (t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } // Calling the easeInOutCubic() function over // the specified parameter values console.log(fabric.util.ease.easeInOutCubic(1, 2, 3, 4)); </script> </body> </html> Output: 2.1875 Example 2: Javascript <!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body><script type="text/javascript"> // Initializing easeInOutCubic() function function easeInOutCubic (t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } // Initializing the parameters with its values var t = 5; var b = 10; var c = 40; var d = 12; // Calling the easeInOutCubic() function over // the specified parameter values console.log(fabric.util.ease.easeInOutCubic(t, b, c, d)); </script> </body> </html> Output: 21.574074074074076 Fabric.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26545, "s": 26517, "text": "\n29 Jan, 2021" }, { "code": null, "e": 26861, "s": 26545, "text": "In games or animations, there are many moving objects which can move them from point A to B in a linear fashion, but after applying an easing, or easing function, it can make it look more natural. An easing function says an animation of how to progress. In this way, a straight motion can take an interesting shape." }, { "code": null, "e": 27124, "s": 26861, "text": "Easing functions specify the rate of change of a parameter over time. It is whose equations which make something move slowly at the start and speed up, or slow down near the end. The most common set of easing equations come from Robert Penner’s book and webpage." }, { "code": null, "e": 27189, "s": 27124, "text": "The easeInOutCubic() method is used for cubic easing in and out." }, { "code": null, "e": 27197, "s": 27189, "text": "Syntax:" }, { "code": null, "e": 27224, "s": 27197, "text": "easeInOutCubic(t, b, c, d)" }, { "code": null, "e": 27312, "s": 27224, "text": "Parameters: This method accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 27451, "s": 27312, "text": "t: This parameter holds the specified time when animation will start. For example, if value of t is 0, it means animation is just started." }, { "code": null, "e": 27635, "s": 27451, "text": "b: This parameter holds the specified starting position of the object on x-axis. For example, if value of b is 10, it means the starting position of the objects on x-coordinate is 10." }, { "code": null, "e": 27803, "s": 27635, "text": "c: This parameter holds the specified change in value for the object. For example, if value of c is 30, it means, the object has to move 30 to the right, ending at 40." }, { "code": null, "e": 27981, "s": 27803, "text": "d: This parameter holds the specified duration of the whole process. For example, if the value of d is 2, it means, the object has 2 second to perform this motion from 10 to 40." }, { "code": null, "e": 28101, "s": 27981, "text": "Return Value: This method returns the eased position of the object i.e., the position of the object at a specific time." }, { "code": null, "e": 28112, "s": 28101, "text": "Example 1:" }, { "code": null, "e": 28123, "s": 28112, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body><script type=\"text/javascript\"> // Initializing easeInOutCubic() function function easeInOutCubic (t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } // Calling the easeInOutCubic() function over // the specified parameter values console.log(fabric.util.ease.easeInOutCubic(1, 2, 3, 4)); </script> </body> </html>", "e": 28687, "s": 28123, "text": null }, { "code": null, "e": 28695, "s": 28687, "text": "Output:" }, { "code": null, "e": 28702, "s": 28695, "text": "2.1875" }, { "code": null, "e": 28713, "s": 28702, "text": "Example 2:" }, { "code": null, "e": 28724, "s": 28713, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <!-- Adding the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body><script type=\"text/javascript\"> // Initializing easeInOutCubic() function function easeInOutCubic (t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } // Initializing the parameters with its values var t = 5; var b = 10; var c = 40; var d = 12; // Calling the easeInOutCubic() function over // the specified parameter values console.log(fabric.util.ease.easeInOutCubic(t, b, c, d)); </script> </body> </html>", "e": 29385, "s": 28724, "text": null }, { "code": null, "e": 29393, "s": 29385, "text": "Output:" }, { "code": null, "e": 29412, "s": 29393, "text": "21.574074074074076" }, { "code": null, "e": 29422, "s": 29412, "text": "Fabric.js" }, { "code": null, "e": 29433, "s": 29422, "text": "JavaScript" }, { "code": null, "e": 29450, "s": 29433, "text": "Web Technologies" }, { "code": null, "e": 29548, "s": 29450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29588, "s": 29548, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29649, "s": 29588, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29690, "s": 29649, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29712, "s": 29690, "text": "JavaScript | Promises" }, { "code": null, "e": 29766, "s": 29712, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29806, "s": 29766, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29839, "s": 29806, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29882, "s": 29839, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29944, "s": 29882, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Find the longest string that can be made up of other strings from the array - GeeksforGeeks
16 Mar, 2022 Given an array of strings arr[], the task is to find the largest string in the array which is made up of the other strings from the array after concatenating one after another. If no such string exists then print -1.Examples: Input: arr[] = {“geeks”, “for”, “geeksfor”, “geeksforgeeks”} Output: geeksforgeeks “geeksforgeeks” is made up of (“geeks” + “for” + “geeks”). Even though “geeksfor” is also made up of other strings but it is not the largest string.Input: arr[] = {“Hey”, “you”, “stop”, “right”, “there”} Output : -1 Approach: Sort all the strings based on their lengths in decreasing order.Now, starting from the longest string. Check for all possible prefix of the string whether it is present in the given array and for the remaining part of the string, recursively check whether it can be made up from other strings from the array.Map can be used to check whether a string exists in the array or not. The first string which satisfies the above conditions is the answer.If no such string exists then print -1. Sort all the strings based on their lengths in decreasing order. Now, starting from the longest string. Check for all possible prefix of the string whether it is present in the given array and for the remaining part of the string, recursively check whether it can be made up from other strings from the array. Map can be used to check whether a string exists in the array or not. The first string which satisfies the above conditions is the answer. If no such string exists then print -1. Below is the implementation of the above approach: C++ Python3 Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Comparator to sort the string by// their lengths in decreasing orderbool compare(string s1, string s2){ return s1.size() > s2.size();} // Function that returns true if string s can be// made up of by other two string from the array// after concatenating one after anotherbool canbuildword(string& s, bool isoriginalword, map<string, bool>& mp){ // If current string has been processed before if (mp.find(s) != mp.end() && mp[s] == 0) return false; // If current string is found in the map and // it is not the string under consideration if (mp.find(s) != mp.end() && mp[s] == 1 && isoriginalword == 0) { return true; } for (int i = 1; i < s.length(); i++) { // Split the string into two // contiguous sub-strings string left = s.substr(0, i); string right = s.substr(i); // If left sub-string is found in the map and // the right sub-string can be made from // the strings from the given array if (mp.find(left) != mp.end() && mp[left] == 1 && canbuildword(right, 0, mp)) { return true; } } // If everything failed, we return false mp[s] = 0; return false;} // Function to return the longest string// that can made be made up from the// other string of the given arraystring printlongestword(vector<string> listofwords){ // Put all the strings in the map map<string, bool> mp; for (string s : listofwords) { mp[s] = 1; } // Sort the string in decreasing // order of their lengths sort(listofwords.begin(), listofwords.end(), compare); // Starting from the longest string for (string s : listofwords) { // If current string can be made // up from other strings if (canbuildword(s, 1, mp)) return s; } return "-1";} // Driver codeint main(){ vector<string> listofwords = { "geeks", "for", "geeksfor", "geeksforgeeks" }; cout << printlongestword(listofwords); return 0;} # Python implementation of the approach # Function that returns true if string s can be# made up of by other two string from the array# after concatenating one after anotherdef canbuildword(s, isoriginalword, mp): # If current string has been processed before if s in mp and mp[s] == 0: return False # If current string is found in the map and # it is not the string under consideration if s in mp and mp[s] == 1 and isoriginalword == 0: return True for i in range(1, len(s)): # Split the string into two # contiguous sub-strings left = s[:i] right = s[i:] # If left sub-string is found in the map and # the right sub-string can be made from # the strings from the given array if left in mp and mp[left] == 1 and canbuildword(right, 0, mp): return True # If everything failed, we return false mp[s] = 0 return False # Function to return the longest string# that can made be made up from the# other string of the given arraydef printlongestword(listofwords): # Put all the strings in the map mp = dict() for i in listofwords: mp[i] = 1 # Sort the string in decreasing # order of their lengths listofwords.sort(key=lambda x: len(x), reverse=True) # Starting from the longest string for i in listofwords: # If current string can be made # up from other strings if canbuildword(i, 1, mp): return i return "-1" # Driver codeif __name__ == "__main__": listofwords = ["geeks", "for", "geeksfor", "geeksforgeeks"] print(printlongestword(listofwords)) # This code is contributed by# sanjeev2552 <script> // JavaScript implementation of the approach // Comparator to sort the string by// their lengths in decreasing orderfunction compare(s1, s2){ return s2.length - s1.length;} // Function that returns true if string s can be// made up of by other two string from the array// after concatenating one after anotherfunction canbuildword(s,isoriginalword,mp){ // If current string has been processed before if (mp.has(s) && mp.get(s) == 0) return false; // If current string is found in the map and // it is not the string under consideration if (mp.has(s) && mp.get(s) == 1 && isoriginalword == 0) { return true; } for (let i = 1; i < s.length; i++) { // Split the string into two // contiguous sub-strings let left = s.substring(0, i); let right = s.substring(i); // If left sub-string is found in the map and // the right sub-string can be made from // the strings from the given array if (mp.has(left) == true && mp.get(left) == 1 && canbuildword(right, 0, mp)) { return true; } } // If everything failed, we return false mp.set(s,0); return false;} // Function to return the longest string// that can made be made up from the// other string of the given arrayfunction printlongestword(listofwords){ // Put all the strings in the map let mp = new Map(); for (let s of listofwords) { mp.set(s,1); } // Sort the string in decreasing // order of their lengths listofwords.sort(compare); // Starting from the longest string for (let s of listofwords) { // If current string can be made // up from other strings if (canbuildword(s, 1, mp)) return s; } return "-1";} // Driver codelet listofwords = [ "geeks", "for", "geeksfor", "geeksforgeeks" ];document.write(printlongestword(listofwords)); // This code is contributed by shinjanpatra </script> geeksforgeeks Time complexity: O(N^3)Auxiliary Space: O(N). sanjeev2552 pankajsharmagfg shinjanpatra Amazon Arrays C++ Programs Data Structures Hash Sorting Strings Amazon Data Structures Arrays Hash Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 26327, "s": 26299, "text": "\n16 Mar, 2022" }, { "code": null, "e": 26555, "s": 26327, "text": "Given an array of strings arr[], the task is to find the largest string in the array which is made up of the other strings from the array after concatenating one after another. If no such string exists then print -1.Examples: " }, { "code": null, "e": 26856, "s": 26555, "text": "Input: arr[] = {“geeks”, “for”, “geeksfor”, “geeksforgeeks”} Output: geeksforgeeks “geeksforgeeks” is made up of (“geeks” + “for” + “geeks”). Even though “geeksfor” is also made up of other strings but it is not the largest string.Input: arr[] = {“Hey”, “you”, “stop”, “right”, “there”} Output : -1 " }, { "code": null, "e": 26870, "s": 26858, "text": "Approach: " }, { "code": null, "e": 27356, "s": 26870, "text": "Sort all the strings based on their lengths in decreasing order.Now, starting from the longest string. Check for all possible prefix of the string whether it is present in the given array and for the remaining part of the string, recursively check whether it can be made up from other strings from the array.Map can be used to check whether a string exists in the array or not. The first string which satisfies the above conditions is the answer.If no such string exists then print -1." }, { "code": null, "e": 27421, "s": 27356, "text": "Sort all the strings based on their lengths in decreasing order." }, { "code": null, "e": 27666, "s": 27421, "text": "Now, starting from the longest string. Check for all possible prefix of the string whether it is present in the given array and for the remaining part of the string, recursively check whether it can be made up from other strings from the array." }, { "code": null, "e": 27805, "s": 27666, "text": "Map can be used to check whether a string exists in the array or not. The first string which satisfies the above conditions is the answer." }, { "code": null, "e": 27845, "s": 27805, "text": "If no such string exists then print -1." }, { "code": null, "e": 27897, "s": 27845, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27901, "s": 27897, "text": "C++" }, { "code": null, "e": 27909, "s": 27901, "text": "Python3" }, { "code": null, "e": 27920, "s": 27909, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Comparator to sort the string by// their lengths in decreasing orderbool compare(string s1, string s2){ return s1.size() > s2.size();} // Function that returns true if string s can be// made up of by other two string from the array// after concatenating one after anotherbool canbuildword(string& s, bool isoriginalword, map<string, bool>& mp){ // If current string has been processed before if (mp.find(s) != mp.end() && mp[s] == 0) return false; // If current string is found in the map and // it is not the string under consideration if (mp.find(s) != mp.end() && mp[s] == 1 && isoriginalword == 0) { return true; } for (int i = 1; i < s.length(); i++) { // Split the string into two // contiguous sub-strings string left = s.substr(0, i); string right = s.substr(i); // If left sub-string is found in the map and // the right sub-string can be made from // the strings from the given array if (mp.find(left) != mp.end() && mp[left] == 1 && canbuildword(right, 0, mp)) { return true; } } // If everything failed, we return false mp[s] = 0; return false;} // Function to return the longest string// that can made be made up from the// other string of the given arraystring printlongestword(vector<string> listofwords){ // Put all the strings in the map map<string, bool> mp; for (string s : listofwords) { mp[s] = 1; } // Sort the string in decreasing // order of their lengths sort(listofwords.begin(), listofwords.end(), compare); // Starting from the longest string for (string s : listofwords) { // If current string can be made // up from other strings if (canbuildword(s, 1, mp)) return s; } return \"-1\";} // Driver codeint main(){ vector<string> listofwords = { \"geeks\", \"for\", \"geeksfor\", \"geeksforgeeks\" }; cout << printlongestword(listofwords); return 0;}", "e": 30059, "s": 27920, "text": null }, { "code": "# Python implementation of the approach # Function that returns true if string s can be# made up of by other two string from the array# after concatenating one after anotherdef canbuildword(s, isoriginalword, mp): # If current string has been processed before if s in mp and mp[s] == 0: return False # If current string is found in the map and # it is not the string under consideration if s in mp and mp[s] == 1 and isoriginalword == 0: return True for i in range(1, len(s)): # Split the string into two # contiguous sub-strings left = s[:i] right = s[i:] # If left sub-string is found in the map and # the right sub-string can be made from # the strings from the given array if left in mp and mp[left] == 1 and canbuildword(right, 0, mp): return True # If everything failed, we return false mp[s] = 0 return False # Function to return the longest string# that can made be made up from the# other string of the given arraydef printlongestword(listofwords): # Put all the strings in the map mp = dict() for i in listofwords: mp[i] = 1 # Sort the string in decreasing # order of their lengths listofwords.sort(key=lambda x: len(x), reverse=True) # Starting from the longest string for i in listofwords: # If current string can be made # up from other strings if canbuildword(i, 1, mp): return i return \"-1\" # Driver codeif __name__ == \"__main__\": listofwords = [\"geeks\", \"for\", \"geeksfor\", \"geeksforgeeks\"] print(printlongestword(listofwords)) # This code is contributed by# sanjeev2552", "e": 31752, "s": 30059, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Comparator to sort the string by// their lengths in decreasing orderfunction compare(s1, s2){ return s2.length - s1.length;} // Function that returns true if string s can be// made up of by other two string from the array// after concatenating one after anotherfunction canbuildword(s,isoriginalword,mp){ // If current string has been processed before if (mp.has(s) && mp.get(s) == 0) return false; // If current string is found in the map and // it is not the string under consideration if (mp.has(s) && mp.get(s) == 1 && isoriginalword == 0) { return true; } for (let i = 1; i < s.length; i++) { // Split the string into two // contiguous sub-strings let left = s.substring(0, i); let right = s.substring(i); // If left sub-string is found in the map and // the right sub-string can be made from // the strings from the given array if (mp.has(left) == true && mp.get(left) == 1 && canbuildword(right, 0, mp)) { return true; } } // If everything failed, we return false mp.set(s,0); return false;} // Function to return the longest string// that can made be made up from the// other string of the given arrayfunction printlongestword(listofwords){ // Put all the strings in the map let mp = new Map(); for (let s of listofwords) { mp.set(s,1); } // Sort the string in decreasing // order of their lengths listofwords.sort(compare); // Starting from the longest string for (let s of listofwords) { // If current string can be made // up from other strings if (canbuildword(s, 1, mp)) return s; } return \"-1\";} // Driver codelet listofwords = [ \"geeks\", \"for\", \"geeksfor\", \"geeksforgeeks\" ];document.write(printlongestword(listofwords)); // This code is contributed by shinjanpatra </script>", "e": 33725, "s": 31752, "text": null }, { "code": null, "e": 33739, "s": 33725, "text": "geeksforgeeks" }, { "code": null, "e": 33789, "s": 33741, "text": "Time complexity: O(N^3)Auxiliary Space: O(N). " }, { "code": null, "e": 33801, "s": 33789, "text": "sanjeev2552" }, { "code": null, "e": 33817, "s": 33801, "text": "pankajsharmagfg" }, { "code": null, "e": 33830, "s": 33817, "text": "shinjanpatra" }, { "code": null, "e": 33837, "s": 33830, "text": "Amazon" }, { "code": null, "e": 33844, "s": 33837, "text": "Arrays" }, { "code": null, "e": 33857, "s": 33844, "text": "C++ Programs" }, { "code": null, "e": 33873, "s": 33857, "text": "Data Structures" }, { "code": null, "e": 33878, "s": 33873, "text": "Hash" }, { "code": null, "e": 33886, "s": 33878, "text": "Sorting" }, { "code": null, "e": 33894, "s": 33886, "text": "Strings" }, { "code": null, "e": 33901, "s": 33894, "text": "Amazon" }, { "code": null, "e": 33917, "s": 33901, "text": "Data Structures" }, { "code": null, "e": 33924, "s": 33917, "text": "Arrays" }, { "code": null, "e": 33929, "s": 33924, "text": "Hash" }, { "code": null, "e": 33937, "s": 33929, "text": "Strings" }, { "code": null, "e": 33945, "s": 33937, "text": "Sorting" }, { "code": null, "e": 34043, "s": 33945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34111, "s": 34043, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34155, "s": 34111, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34203, "s": 34155, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34226, "s": 34203, "text": "Introduction to Arrays" }, { "code": null, "e": 34258, "s": 34226, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34293, "s": 34258, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 34337, "s": 34293, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 34363, "s": 34337, "text": "C++ Program for QuickSort" }, { "code": null, "e": 34422, "s": 34363, "text": "How to return multiple values from a function in C or C++?" } ]
What is currying in JavaScript?
Currying is a technique of evaluating function with multiple arguments, into sequence of functions with single argument.In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled. a) It helps to avoid passing same variable again and again. b) It is extremely useful in event handling. syntax: function Myfunction(a) { return (b) => { return (c) => { return a * b * c } } } In the following example,since no currying is used, all the parameters were passed at once(volume(11,2,3)) to the existing function to calculate the volume. Live Demo <html> <body> <script> function volume(length, width, height) { return length * width * height; } document.write((volume(11,2,3))); </script> </body> </html> 66 In the following example,since currying is used,parameters were passed one by one(volume(11)(2)(3)) until the last function called the last parameter . Live Demo <html> <body> <script> function volume(length) { return function(width) { return function(height) { return height * width * length; } } } document.write(volume(11)(2)(3)) </script> </body> </html> 66
[ { "code": null, "e": 1441, "s": 1062, "text": "Currying is a technique of evaluating function with multiple arguments, into sequence of functions with single argument.In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled." }, { "code": null, "e": 1503, "s": 1441, "text": " a) It helps to avoid passing same variable again and again." }, { "code": null, "e": 1551, "s": 1503, "text": " b) It is extremely useful in event handling. " }, { "code": null, "e": 1559, "s": 1551, "text": "syntax:" }, { "code": null, "e": 1710, "s": 1559, "text": " function Myfunction(a) {\n return (b) => {\n return (c) => {\n return a * b * c\n }\n }\n }" }, { "code": null, "e": 1868, "s": 1710, "text": "In the following example,since no currying is used, all the parameters were passed at once(volume(11,2,3)) to the existing function to calculate the volume." }, { "code": null, "e": 1879, "s": 1868, "text": " Live Demo" }, { "code": null, "e": 2052, "s": 1879, "text": "<html>\n<body>\n<script>\n function volume(length, width, height) {\n return length * width * height;\n }\n document.write((volume(11,2,3)));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2055, "s": 2052, "text": "66" }, { "code": null, "e": 2208, "s": 2055, "text": "In the following example,since currying is used,parameters were passed one by one(volume(11)(2)(3)) until the last function called the last parameter ." }, { "code": null, "e": 2219, "s": 2208, "text": " Live Demo" }, { "code": null, "e": 2464, "s": 2219, "text": "<html>\n<body>\n<script>\n function volume(length) {\n return function(width) {\n return function(height) {\n return height * width * length;\n }\n }\n }\ndocument.write(volume(11)(2)(3))\n</script>\n</body>\n</html>" }, { "code": null, "e": 2467, "s": 2464, "text": "66" } ]
Entity Framework - Database Operations
In the previous chapters, you learned three different ways of defining an entity data model. Two of them, Database First and Model First, depended on the Entity Framework designer combined with code generation. Two of them, Database First and Model First, depended on the Entity Framework designer combined with code generation. The third, Code First, lets you skip a visual designer and just write your own code. The third, Code First, lets you skip a visual designer and just write your own code. Regardless of which path you choose, you'll end up with domain classes and one or more Entity Framework DbContext classes allows you to retrieve and persist data relevant to those classes. Regardless of which path you choose, you'll end up with domain classes and one or more Entity Framework DbContext classes allows you to retrieve and persist data relevant to those classes. The DbContext API in your applications is used as a bridge between your classes and your database. The DbContext is one of the most important classes in the Entity Framework. It enables to express and execute queries. It enables to express and execute queries. It takes query results from the database and transforms them into instances of our model classes. It takes query results from the database and transforms them into instances of our model classes. It can keep track of changes to entities, including adding and deleting, and then triggers the creation of insert, update and delete statements that are sent to the database on demand. It can keep track of changes to entities, including adding and deleting, and then triggers the creation of insert, update and delete statements that are sent to the database on demand. Following are the domain ad context classes on which we will be performing different operations in this chapter. This is the same example which we have created in the chapater, Database First Approach. using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Core.Objects; using System.Linq; namespace DatabaseFirstDemo { public partial class UniContextEntities : DbContext { public UniContextEntities(): base("name = UniContextEntities") {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } } namespace DatabaseFirstDemo { using System; using System.Collections.Generic; public partial class Course { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Course() { this.Enrollments = new HashSet<Enrollment>(); } public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Enrollment> Enrollments { get; set; } } } namespace DatabaseFirstDemo { using System; using System.Collections.Generic; public partial class Student { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Student() { this.Enrollments = new HashSet<Enrollment>(); } public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public System.DateTime EnrollmentDate { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Enrollment> Enrollments { get; set; } } } namespace DatabaseFirstDemo { using System; using System.Collections.Generic; public partial class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Nullable<int> Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } } Adding a new object with Entity Framework is as simple as constructing a new instance of your object and registering it using the Add method on DbSet. The following code lets you add a new student to the database. class Program { static void Main(string[] args) { var newStudent = new Student(); //set student name newStudent.FirstMidName = "Bill"; newStudent.LastName = "Gates"; newStudent.EnrollmentDate = DateTime.Parse("2015-10-21"); newStudent.ID = 100; //create DBContext object using (var dbCtx = new UniContextEntities()) { //Add Student object into Students DBset dbCtx.Students.Add(newStudent); // call SaveChanges method to save student into database dbCtx.SaveChanges(); } } } Changing existing objects is as simple as updating the value assigned to the property(s) you want changed and calling SaveChanges. For example, the following code is used to change the last name of Ali from Khan to Aslam. using (var context = new UniContextEntities()) { var student = (from d in context.Students where d.FirstMidName == "Ali" select d).Single(); student.LastName = "Aslam"; context.SaveChanges(); } To delete an entity using Entity Framework, you use the Remove method on DbSet. Remove works for both existing and newly added entities. Calling Remove on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The entity is removed from the change tracker and is no longer tracked by the DbContext. Calling Remove on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example is of a code where the student is removed from the database whose first name is Ali. using (var context = new UniContextEntities()) { var bay = (from d in context.Students where d.FirstMidName == "Ali" select d).Single(); context.Students.Remove(bay); context.SaveChanges(); } Reading the existing data from the database is very simple. Following is the code in which all the data from the Student table are retrieved and then a program will be displayed with the students’ first and last name in alphabetical order. using (var db = new UniContextEntities()) { var query = from b in db.Students orderby b.FirstMidName select b; Console.WriteLine("All All student in the database:"); foreach (var item in query) { Console.WriteLine(item.FirstMidName +" "+ item.LastName); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3125, "s": 3032, "text": "In the previous chapters, you learned three different ways of defining an entity data model." }, { "code": null, "e": 3243, "s": 3125, "text": "Two of them, Database First and Model First, depended on the Entity Framework designer combined with code generation." }, { "code": null, "e": 3361, "s": 3243, "text": "Two of them, Database First and Model First, depended on the Entity Framework designer combined with code generation." }, { "code": null, "e": 3446, "s": 3361, "text": "The third, Code First, lets you skip a visual designer and just write your own code." }, { "code": null, "e": 3531, "s": 3446, "text": "The third, Code First, lets you skip a visual designer and just write your own code." }, { "code": null, "e": 3720, "s": 3531, "text": "Regardless of which path you choose, you'll end up with domain classes and one or more Entity Framework DbContext classes allows you to retrieve and persist data relevant to those classes." }, { "code": null, "e": 3909, "s": 3720, "text": "Regardless of which path you choose, you'll end up with domain classes and one or more Entity Framework DbContext classes allows you to retrieve and persist data relevant to those classes." }, { "code": null, "e": 4084, "s": 3909, "text": "The DbContext API in your applications is used as a bridge between your classes and your database. The DbContext is one of the most important classes in the Entity Framework." }, { "code": null, "e": 4127, "s": 4084, "text": "It enables to express and execute queries." }, { "code": null, "e": 4170, "s": 4127, "text": "It enables to express and execute queries." }, { "code": null, "e": 4268, "s": 4170, "text": "It takes query results from the database and transforms them into instances of our model classes." }, { "code": null, "e": 4366, "s": 4268, "text": "It takes query results from the database and transforms them into instances of our model classes." }, { "code": null, "e": 4551, "s": 4366, "text": "It can keep track of changes to entities, including adding and deleting, and then triggers the creation of insert, update and delete statements that are sent to the database on demand." }, { "code": null, "e": 4736, "s": 4551, "text": "It can keep track of changes to entities, including adding and deleting, and then triggers the creation of insert, update and delete statements that are sent to the database on demand." }, { "code": null, "e": 4938, "s": 4736, "text": "Following are the domain ad context classes on which we will be performing different operations in this chapter. This is the same example which we have created in the chapater, Database First Approach." }, { "code": null, "e": 5568, "s": 4938, "text": "using System;\nusing System.Data.Entity;\nusing System.Data.Entity.Infrastructure;\nusing System.Data.Entity.Core.Objects;\nusing System.Linq;\n\nnamespace DatabaseFirstDemo {\n\n public partial class UniContextEntities : DbContext {\n\n public UniContextEntities(): base(\"name = UniContextEntities\") {}\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder) {\n throw new UnintentionalCodeFirstException();\n }\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n }\n}" }, { "code": null, "e": 6251, "s": 5568, "text": "namespace DatabaseFirstDemo {\n\n using System;\n using System.Collections.Generic;\n\t\n public partial class Course {\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \n \"CA2214:DoNotCallOverridableMethodsInConstructors\")]\n\n public Course() {\n this.Enrollments = new HashSet<Enrollment>();\n }\n\t\n public int CourseID { get; set; }\n public string Title { get; set; }\n public int Credits { get; set; }\n\t\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \n \"CA2227:CollectionPropertiesShouldBeReadOnly\")]\n\t\t\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n }\n}" }, { "code": null, "e": 6997, "s": 6251, "text": "namespace DatabaseFirstDemo {\n\n using System;\n using System.Collections.Generic; \n\n public partial class Student {\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \n \"CA2214:DoNotCallOverridableMethodsInConstructors\")]\n\n public Student() {\n this.Enrollments = new HashSet<Enrollment>();\n }\n\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public System.DateTime EnrollmentDate { get; set; }\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \n \"CA2227:CollectionPropertiesShouldBeReadOnly\")]\n\t\t\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n }\n}" }, { "code": null, "e": 7404, "s": 6997, "text": "namespace DatabaseFirstDemo {\n\n using System;\n using System.Collections.Generic; \n\n public partial class Enrollment {\n\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Nullable<int> Grade { get; set; }\n\t\t\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n }\n}" }, { "code": null, "e": 7618, "s": 7404, "text": "Adding a new object with Entity Framework is as simple as constructing a new instance of your object and registering it using the Add method on DbSet. The following code lets you add a new student to the database." }, { "code": null, "e": 8197, "s": 7618, "text": "class Program {\n\n static void Main(string[] args) {\n\n var newStudent = new Student();\n\n //set student name\n\n newStudent.FirstMidName = \"Bill\";\n newStudent.LastName = \"Gates\";\n newStudent.EnrollmentDate = DateTime.Parse(\"2015-10-21\");\n newStudent.ID = 100;\n\n //create DBContext object\n\n using (var dbCtx = new UniContextEntities()) {\n\n //Add Student object into Students DBset\n dbCtx.Students.Add(newStudent);\n\n // call SaveChanges method to save student into database\n dbCtx.SaveChanges();\n }\n }\n}" }, { "code": null, "e": 8419, "s": 8197, "text": "Changing existing objects is as simple as updating the value assigned to the property(s) you want changed and calling SaveChanges. For example, the following code is used to change the last name of Ali from Khan to Aslam." }, { "code": null, "e": 8623, "s": 8419, "text": "using (var context = new UniContextEntities()) {\n\n var student = (from d in context.Students where d.FirstMidName == \"Ali\" select d).Single();\n student.LastName = \"Aslam\";\n context.SaveChanges();\n}" }, { "code": null, "e": 9219, "s": 8623, "text": "To delete an entity using Entity Framework, you use the Remove method on DbSet. Remove works for both existing and newly added entities. Calling Remove on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The entity is removed from the change tracker and is no longer tracked by the DbContext. Calling Remove on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example is of a code where the student is removed from the database whose first name is Ali." }, { "code": null, "e": 9420, "s": 9219, "text": "using (var context = new UniContextEntities()) {\n var bay = (from d in context.Students where d.FirstMidName == \"Ali\" select d).Single();\n context.Students.Remove(bay);\n context.SaveChanges();\n}" }, { "code": null, "e": 9660, "s": 9420, "text": "Reading the existing data from the database is very simple. Following is the code in which all the data from the Student table are retrieved and then a program will be displayed with the students’ first and last name in alphabetical order." }, { "code": null, "e": 10011, "s": 9660, "text": "using (var db = new UniContextEntities()) {\n\n var query = from b in db.Students orderby b.FirstMidName select b;\n Console.WriteLine(\"All All student in the database:\");\n\n foreach (var item in query) {\n Console.WriteLine(item.FirstMidName +\" \"+ item.LastName);\n }\n\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadKey();\n}" }, { "code": null, "e": 10044, "s": 10011, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 10062, "s": 10044, "text": " Trevoir Williams" }, { "code": null, "e": 10097, "s": 10062, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10110, "s": 10097, "text": " Nilay Mehta" }, { "code": null, "e": 10145, "s": 10110, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10161, "s": 10145, "text": " TELCOMA Global" }, { "code": null, "e": 10196, "s": 10161, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10214, "s": 10196, "text": " Mustafa Radaideh" }, { "code": null, "e": 10221, "s": 10214, "text": " Print" }, { "code": null, "e": 10232, "s": 10221, "text": " Add Notes" } ]
Python For Data Science —Bootstrap For Plotly Dash Interactive Visualizations | by Nicholas Leong | Towards Data Science
Greetings data practitioners. Welcome to 2021, where the new trend is all around Machine Learning.Most employers, even data scientists themselves, are drowning in the thought of deploying that new Machine Learning model that predicts literally everything for them. If you have ever been in the field, you would understand that most organizations nowadays don’t have the sufficient fundamentals to even venture into Machine Learning, but they still want to. They have not even scratched — Proper data warehousing practices Full understanding of data owned Utilization of cloud tools to perform Machine Learning That being said, data visualization will always stay a necessity in the data exploration stage. No one can properly understand data without some sort of help from visualizations. Thankfully, we have many libraries today that help us with that. Here are a few. towardsdatascience.com towardsdatascience.com Hence, it is utterly important that you are able to communicate your findings through clean and beautiful visualizations as a data scientist. It will, without a doubt, make you stand out from the crowd. Have you heard of Dash by Plotly? Dash is the new kid on the block. I wrote about it here. towardsdatascience.com Dash is the new open-source Python library that enables you to build amazing data visualization apps without having to know any HTML, CSS, or Javascript. Everything is in Python, giving Data Scientists who already know Python a really good time. Above all else, it’s fast, beautiful, and easy to learn. Dash can also be programmed to update its dashboards in real-time, without any interactions. It really is at the forefront of deploying and automating your dashboards, without the hassle of needing to manage deployment, mobile responsiveness, and the other stuff that comes along with SRE (Site Reliability Engineering). So what are you waiting for, pick it up now! In this article, we will go in-depth on how you can beautify your Dash Apps by implementing Bootstrap in Dash. It provides extremely useful tools like NavBars, Buttons, Forms, and many more. But first, for those who don’t know — What exactly is a ‘Bootstrap’? For those who have no knowledge of web-development — HTML and CSS make up the basic front-end skeleton of a webpage. I’m sure you’ve heard of them somewhere before. Every website needs HTML and CSS, they’re like the fundamentals in building one. Things get messy when it comes to optimizing websites for both desktop and mobile. According to Google, more than half of all web traffic comes from mobile. This situation has spawned an era where web developers start to put more priority on Mobile Sites and Apps. This is where Bootstrap comes in. Bootstrap is the most popular CSS framework right now in developing mobile responsive websites. According to BuiltWith and w3tech, Bootstrap is ranked first in the CSS Framework space and makes up about 26.8% of all websites in the world which includes popular sites like Netflix and Udemy. It makes front-end development faster and easier, saving you work during optimization for devices of all shapes. One of the amazing features of bootstrap is the Grid system. By default, Bootstrap splits your layout into 12 columns that scale with whatever device you are using, making it a mobile responsive framework. It also has predefined classes, which allows you to develop useful features like Buttons, NavBars, and Forms easily. It will save you hours of work. Now that’s out of the way, back to Dash. Dash visualizations are based on Plotly.It would help a ton if you’re smooth with Plotly already. To do that, you would also need solid fundamentals in data transformations using Pandas. I have written numerous guides on all the topics above, feel free to revise them before moving on. towardsdatascience.com You also understand basic Dash concepts like — Dash’s layout is made up of core components and HTML components Basic HTML concepts like Div and Container Installation pip install dashpip install dash-bootstrap-components Working with Jupyter Notebooks import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Output If you’re building a dashboard for whatever reason, it is important to design and organize it in a way that suits the user. Dash itself is not optimized for organizing purposes, we can use Bootstrap for that. The Grid SystemWelcome to the Grid. Bootstrap uses the Grid System to organize the elements on your website.In Bootstrap, your website is made up of rows and columns. You can split or group each row into different number of columns according to your needs. What does it look like in pure HTML+ CSS: <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> </div></div> What does it look like in Dash bootstrap: row = html.Div( [ dbc.Row( [ dbc.Col(html.Div("One of three columns")), dbc.Col(html.Div("One of three columns")), dbc.Col(html.Div("One of three columns")), ],no_gutters=True, ), ]) Both code blocks above produce the same thing, which is one row with default height that is split up into 3 columns, without any spacing in between the columns. You can then add any of your elements like Dash Graphs, Dash buttons, and Navbars into these columns to properly organize them. Important note to adjust heights and width — You can adjust the height of the row, and width of the columns Let's try that. app.layout = html.Div( [ dbc.Row(dbc.Col(html.Div("A single, half-width column"), width=6,style={"border":"2px black solid"})), dbc.Row( dbc.Col(html.Div("An automatically sized column"), width="auto",style={"border":"2px black solid"}) ), dbc.Row( [ dbc.Col(html.Div("One of three columns"), width=3,style={"border":"2px black solid"}), dbc.Col(html.Div("One of three columns"),style={"border":"2px black solid"}), dbc.Col(html.Div("One of three columns"), width=3,style={"border":"2px black solid",'height':'10rem'}), ] ),],className = 'container') By setting the width and height parameter in columns, we have complete control over how we want to organize our elements on the page. By using dash bootstrap, you can also assign classes to all your components using the className parameter. Note how I assign the container class to the main Div here just by specifying it in the last line. What are Classes?Classes are names you give to elements to assign certain design elements to them. You define these classes in a separate CSS file. Let's say you create a class called ‘BIG’ and assigned the size = ‘2px’ to it.You can now assign this class to as many elements you want easily by stating className = ‘BIG’. It is a way more efficient and clean way in designing your elements. With that, Let’s try it on actual visualizations. app.layout = html.Div([ dbc.Row([ dbc.Col(scatterplot1, width=4), dbc.Col(scatterplot2, width=8), ]) ],className = 'container' ) With the code block above, we have defined 2 scatterplots beforehand. The first scatterplot is set to be half the width of the second one. This is extremely useful in planning and displaying your graphs properly. From my experience, if the user does not find it clean to look at, your charts/graphs will often go unnoticed. People ignore designs that ignore people. — Frank Chimero, Designer Now that we understand the basics, let’s move onto more fun stuff.How about setting up a totally functional navigation bar on your dashboard? Let's set up a simple Navigation Bar that allows us to navigate to specific pages easily. The NavBar is responsive, stays on top of the page constantly, and is completely functional. PLOTLY_LOGO = "https://images.plot.ly/logo/new-branding/plotly-logomark.png"# defining navbar itemshome_button = dbc.NavItem(dbc.NavLink('Home',href="#home", external_link=True,className='navlinks'))statistic_button = dbc.NavItem(dbc.NavLink('Statistics',href="#statistics", external_link=True,className='navlinks'))trend_button = dbc.NavItem(dbc.NavLink('Trend',href="#trend", external_link=True,className='navlinks'))news_button = dbc.NavItem(dbc.NavLink('News',href="#news", external_link=True,className='navlinks'))navbar = dbc.Navbar( dbc.Container( [ html.A( dbc.Row( [ dbc.Col(html.Img(src=PLOTLY_LOGO,className = 'logo',height="30px")), ], align="center", no_gutters=True, ), href="#home", ), dbc.NavbarToggler(id="navbar-toggler"), dbc.Collapse(dbc.Nav([home_button,statistic_button,trend_button,news_button],className='ml-auto work-sans', navbar=True), id="navbar-collapse", navbar=True), ], ), color="rgb(42,62,66)", dark=True, style = {'background-color':'#191919'}, className = 'navbar-change', expand= 'lg') First, we define all the buttons to place on the NavBar. These buttons are defined in NavLink while associating it with whatever page name we want it to bring us to. For example, the Statistics button has href = ‘#Statistics’ on it.We can then set the HTML.Header(id= ‘Statistics’) on the header of a page, clicking that button will bring us here. You can clearly see that happening on the bottom left of the screen while we are clicking the buttons. All the design is done through the color, style, and className parameters.All there’s left to do now is simply pass all the buttons as a list into the dbc.NavBar. Pretty straight forward. You can read all about the dash bootstrap components here. Jumbotrons are often used nowadays to bring your attention to featured content. You surely had to stumble upon it without even noticing. In this section, we will attempt to generate a Jumbotron using Dash Bootstrap. Jumbotrons are perfect for landing pages. The landing page is the page that the user lands on when they visit your dashboard/website. It is the first thing they see, so be sure to make a good impression. Let’s try it out. jumbotron = dbc.Jumbotron( [ html.H1("Revenue Dashboard", className="display-3"), html.P( "A deep dive into revenue for the year, segmented by verticals.", className="lead", ), html.Hr(className="my-2"), html.P( "Data is updated every day at 12pm." ), html.P(dbc.Button("Overview", color="primary"), className="lead"), ]) A relatively simple landing Jumbotron consisting of a title, descriptions, and a button to bring the user to the main content of the page. Notice how we use className to design a lot of our elements here. I’ve only used default class names here. You can find them from the official CSS class names here. I hope this has shed light on how useful dash bootstrap can be. With this, you can completely design your dashboard with Python, while plotting your graphs with Pandas and Plotly. Full code for the article: Congratulations,you can now efficiently design your own dashboard completely in Python. In this article, you have learned: The Grid System Organizing/Designing using Bootstrap Navigation Bar Jumbotron Plenty for you to work on.Now go data practitioners, build something and share it with me,share it with the world. If you hit a roadblock, feel free to reach out to me. You can find my information below. We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data. As usual, I end with a quote. The goal is to turn data into information and information into insight. — Carly Fiorina You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers! I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data. Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can also view the code for previous write-ups in my Github.
[ { "code": null, "e": 202, "s": 172, "text": "Greetings data practitioners." }, { "code": null, "e": 437, "s": 202, "text": "Welcome to 2021, where the new trend is all around Machine Learning.Most employers, even data scientists themselves, are drowning in the thought of deploying that new Machine Learning model that predicts literally everything for them." }, { "code": null, "e": 629, "s": 437, "text": "If you have ever been in the field, you would understand that most organizations nowadays don’t have the sufficient fundamentals to even venture into Machine Learning, but they still want to." }, { "code": null, "e": 660, "s": 629, "text": "They have not even scratched —" }, { "code": null, "e": 694, "s": 660, "text": "Proper data warehousing practices" }, { "code": null, "e": 727, "s": 694, "text": "Full understanding of data owned" }, { "code": null, "e": 782, "s": 727, "text": "Utilization of cloud tools to perform Machine Learning" }, { "code": null, "e": 1042, "s": 782, "text": "That being said, data visualization will always stay a necessity in the data exploration stage. No one can properly understand data without some sort of help from visualizations. Thankfully, we have many libraries today that help us with that. Here are a few." }, { "code": null, "e": 1065, "s": 1042, "text": "towardsdatascience.com" }, { "code": null, "e": 1088, "s": 1065, "text": "towardsdatascience.com" }, { "code": null, "e": 1291, "s": 1088, "text": "Hence, it is utterly important that you are able to communicate your findings through clean and beautiful visualizations as a data scientist. It will, without a doubt, make you stand out from the crowd." }, { "code": null, "e": 1325, "s": 1291, "text": "Have you heard of Dash by Plotly?" }, { "code": null, "e": 1382, "s": 1325, "text": "Dash is the new kid on the block. I wrote about it here." }, { "code": null, "e": 1405, "s": 1382, "text": "towardsdatascience.com" }, { "code": null, "e": 1559, "s": 1405, "text": "Dash is the new open-source Python library that enables you to build amazing data visualization apps without having to know any HTML, CSS, or Javascript." }, { "code": null, "e": 1708, "s": 1559, "text": "Everything is in Python, giving Data Scientists who already know Python a really good time. Above all else, it’s fast, beautiful, and easy to learn." }, { "code": null, "e": 1801, "s": 1708, "text": "Dash can also be programmed to update its dashboards in real-time, without any interactions." }, { "code": null, "e": 2029, "s": 1801, "text": "It really is at the forefront of deploying and automating your dashboards, without the hassle of needing to manage deployment, mobile responsiveness, and the other stuff that comes along with SRE (Site Reliability Engineering)." }, { "code": null, "e": 2074, "s": 2029, "text": "So what are you waiting for, pick it up now!" }, { "code": null, "e": 2265, "s": 2074, "text": "In this article, we will go in-depth on how you can beautify your Dash Apps by implementing Bootstrap in Dash. It provides extremely useful tools like NavBars, Buttons, Forms, and many more." }, { "code": null, "e": 2334, "s": 2265, "text": "But first, for those who don’t know — What exactly is a ‘Bootstrap’?" }, { "code": null, "e": 2499, "s": 2334, "text": "For those who have no knowledge of web-development — HTML and CSS make up the basic front-end skeleton of a webpage. I’m sure you’ve heard of them somewhere before." }, { "code": null, "e": 2580, "s": 2499, "text": "Every website needs HTML and CSS, they’re like the fundamentals in building one." }, { "code": null, "e": 2845, "s": 2580, "text": "Things get messy when it comes to optimizing websites for both desktop and mobile. According to Google, more than half of all web traffic comes from mobile. This situation has spawned an era where web developers start to put more priority on Mobile Sites and Apps." }, { "code": null, "e": 2879, "s": 2845, "text": "This is where Bootstrap comes in." }, { "code": null, "e": 2975, "s": 2879, "text": "Bootstrap is the most popular CSS framework right now in developing mobile responsive websites." }, { "code": null, "e": 3170, "s": 2975, "text": "According to BuiltWith and w3tech, Bootstrap is ranked first in the CSS Framework space and makes up about 26.8% of all websites in the world which includes popular sites like Netflix and Udemy." }, { "code": null, "e": 3283, "s": 3170, "text": "It makes front-end development faster and easier, saving you work during optimization for devices of all shapes." }, { "code": null, "e": 3489, "s": 3283, "text": "One of the amazing features of bootstrap is the Grid system. By default, Bootstrap splits your layout into 12 columns that scale with whatever device you are using, making it a mobile responsive framework." }, { "code": null, "e": 3606, "s": 3489, "text": "It also has predefined classes, which allows you to develop useful features like Buttons, NavBars, and Forms easily." }, { "code": null, "e": 3638, "s": 3606, "text": "It will save you hours of work." }, { "code": null, "e": 3679, "s": 3638, "text": "Now that’s out of the way, back to Dash." }, { "code": null, "e": 3777, "s": 3679, "text": "Dash visualizations are based on Plotly.It would help a ton if you’re smooth with Plotly already." }, { "code": null, "e": 3965, "s": 3777, "text": "To do that, you would also need solid fundamentals in data transformations using Pandas. I have written numerous guides on all the topics above, feel free to revise them before moving on." }, { "code": null, "e": 3988, "s": 3965, "text": "towardsdatascience.com" }, { "code": null, "e": 4035, "s": 3988, "text": "You also understand basic Dash concepts like —" }, { "code": null, "e": 4099, "s": 4035, "text": "Dash’s layout is made up of core components and HTML components" }, { "code": null, "e": 4142, "s": 4099, "text": "Basic HTML concepts like Div and Container" }, { "code": null, "e": 4155, "s": 4142, "text": "Installation" }, { "code": null, "e": 4209, "s": 4155, "text": "pip install dashpip install dash-bootstrap-components" }, { "code": null, "e": 4240, "s": 4209, "text": "Working with Jupyter Notebooks" }, { "code": null, "e": 4452, "s": 4240, "text": "import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Output" }, { "code": null, "e": 4661, "s": 4452, "text": "If you’re building a dashboard for whatever reason, it is important to design and organize it in a way that suits the user. Dash itself is not optimized for organizing purposes, we can use Bootstrap for that." }, { "code": null, "e": 4697, "s": 4661, "text": "The Grid SystemWelcome to the Grid." }, { "code": null, "e": 4918, "s": 4697, "text": "Bootstrap uses the Grid System to organize the elements on your website.In Bootstrap, your website is made up of rows and columns. You can split or group each row into different number of columns according to your needs." }, { "code": null, "e": 4960, "s": 4918, "text": "What does it look like in pure HTML+ CSS:" }, { "code": null, "e": 5197, "s": 4960, "text": "<div class=\"container\"> <div class=\"row\"> <div class=\"col-sm\"> One of three columns </div> <div class=\"col-sm\"> One of three columns </div> <div class=\"col-sm\"> One of three columns </div> </div></div>" }, { "code": null, "e": 5239, "s": 5197, "text": "What does it look like in Dash bootstrap:" }, { "code": null, "e": 5509, "s": 5239, "text": "row = html.Div( [ dbc.Row( [ dbc.Col(html.Div(\"One of three columns\")), dbc.Col(html.Div(\"One of three columns\")), dbc.Col(html.Div(\"One of three columns\")), ],no_gutters=True, ), ])" }, { "code": null, "e": 5670, "s": 5509, "text": "Both code blocks above produce the same thing, which is one row with default height that is split up into 3 columns, without any spacing in between the columns." }, { "code": null, "e": 5798, "s": 5670, "text": "You can then add any of your elements like Dash Graphs, Dash buttons, and Navbars into these columns to properly organize them." }, { "code": null, "e": 5906, "s": 5798, "text": "Important note to adjust heights and width — You can adjust the height of the row, and width of the columns" }, { "code": null, "e": 5922, "s": 5906, "text": "Let's try that." }, { "code": null, "e": 6589, "s": 5922, "text": "app.layout = html.Div( [ dbc.Row(dbc.Col(html.Div(\"A single, half-width column\"), width=6,style={\"border\":\"2px black solid\"})), dbc.Row( dbc.Col(html.Div(\"An automatically sized column\"), width=\"auto\",style={\"border\":\"2px black solid\"}) ), dbc.Row( [ dbc.Col(html.Div(\"One of three columns\"), width=3,style={\"border\":\"2px black solid\"}), dbc.Col(html.Div(\"One of three columns\"),style={\"border\":\"2px black solid\"}), dbc.Col(html.Div(\"One of three columns\"), width=3,style={\"border\":\"2px black solid\",'height':'10rem'}), ] ),],className = 'container')" }, { "code": null, "e": 6723, "s": 6589, "text": "By setting the width and height parameter in columns, we have complete control over how we want to organize our elements on the page." }, { "code": null, "e": 6929, "s": 6723, "text": "By using dash bootstrap, you can also assign classes to all your components using the className parameter. Note how I assign the container class to the main Div here just by specifying it in the last line." }, { "code": null, "e": 7077, "s": 6929, "text": "What are Classes?Classes are names you give to elements to assign certain design elements to them. You define these classes in a separate CSS file." }, { "code": null, "e": 7320, "s": 7077, "text": "Let's say you create a class called ‘BIG’ and assigned the size = ‘2px’ to it.You can now assign this class to as many elements you want easily by stating className = ‘BIG’. It is a way more efficient and clean way in designing your elements." }, { "code": null, "e": 7370, "s": 7320, "text": "With that, Let’s try it on actual visualizations." }, { "code": null, "e": 7609, "s": 7370, "text": "app.layout = html.Div([ dbc.Row([ dbc.Col(scatterplot1, width=4), dbc.Col(scatterplot2, width=8), ]) ],className = 'container' )" }, { "code": null, "e": 7748, "s": 7609, "text": "With the code block above, we have defined 2 scatterplots beforehand. The first scatterplot is set to be half the width of the second one." }, { "code": null, "e": 7933, "s": 7748, "text": "This is extremely useful in planning and displaying your graphs properly. From my experience, if the user does not find it clean to look at, your charts/graphs will often go unnoticed." }, { "code": null, "e": 8001, "s": 7933, "text": "People ignore designs that ignore people. — Frank Chimero, Designer" }, { "code": null, "e": 8143, "s": 8001, "text": "Now that we understand the basics, let’s move onto more fun stuff.How about setting up a totally functional navigation bar on your dashboard?" }, { "code": null, "e": 8326, "s": 8143, "text": "Let's set up a simple Navigation Bar that allows us to navigate to specific pages easily. The NavBar is responsive, stays on top of the page constantly, and is completely functional." }, { "code": null, "e": 9515, "s": 8326, "text": "PLOTLY_LOGO = \"https://images.plot.ly/logo/new-branding/plotly-logomark.png\"# defining navbar itemshome_button = dbc.NavItem(dbc.NavLink('Home',href=\"#home\", external_link=True,className='navlinks'))statistic_button = dbc.NavItem(dbc.NavLink('Statistics',href=\"#statistics\", external_link=True,className='navlinks'))trend_button = dbc.NavItem(dbc.NavLink('Trend',href=\"#trend\", external_link=True,className='navlinks'))news_button = dbc.NavItem(dbc.NavLink('News',href=\"#news\", external_link=True,className='navlinks'))navbar = dbc.Navbar( dbc.Container( [ html.A( dbc.Row( [ dbc.Col(html.Img(src=PLOTLY_LOGO,className = 'logo',height=\"30px\")), ], align=\"center\", no_gutters=True, ), href=\"#home\", ), dbc.NavbarToggler(id=\"navbar-toggler\"), dbc.Collapse(dbc.Nav([home_button,statistic_button,trend_button,news_button],className='ml-auto work-sans', navbar=True), id=\"navbar-collapse\", navbar=True), ], ), color=\"rgb(42,62,66)\", dark=True, style = {'background-color':'#191919'}, className = 'navbar-change', expand= 'lg')" }, { "code": null, "e": 9863, "s": 9515, "text": "First, we define all the buttons to place on the NavBar. These buttons are defined in NavLink while associating it with whatever page name we want it to bring us to. For example, the Statistics button has href = ‘#Statistics’ on it.We can then set the HTML.Header(id= ‘Statistics’) on the header of a page, clicking that button will bring us here." }, { "code": null, "e": 9966, "s": 9863, "text": "You can clearly see that happening on the bottom left of the screen while we are clicking the buttons." }, { "code": null, "e": 10154, "s": 9966, "text": "All the design is done through the color, style, and className parameters.All there’s left to do now is simply pass all the buttons as a list into the dbc.NavBar. Pretty straight forward." }, { "code": null, "e": 10213, "s": 10154, "text": "You can read all about the dash bootstrap components here." }, { "code": null, "e": 10429, "s": 10213, "text": "Jumbotrons are often used nowadays to bring your attention to featured content. You surely had to stumble upon it without even noticing. In this section, we will attempt to generate a Jumbotron using Dash Bootstrap." }, { "code": null, "e": 10471, "s": 10429, "text": "Jumbotrons are perfect for landing pages." }, { "code": null, "e": 10633, "s": 10471, "text": "The landing page is the page that the user lands on when they visit your dashboard/website. It is the first thing they see, so be sure to make a good impression." }, { "code": null, "e": 10651, "s": 10633, "text": "Let’s try it out." }, { "code": null, "e": 11061, "s": 10651, "text": "jumbotron = dbc.Jumbotron( [ html.H1(\"Revenue Dashboard\", className=\"display-3\"), html.P( \"A deep dive into revenue for the year, segmented by verticals.\", className=\"lead\", ), html.Hr(className=\"my-2\"), html.P( \"Data is updated every day at 12pm.\" ), html.P(dbc.Button(\"Overview\", color=\"primary\"), className=\"lead\"), ])" }, { "code": null, "e": 11266, "s": 11061, "text": "A relatively simple landing Jumbotron consisting of a title, descriptions, and a button to bring the user to the main content of the page. Notice how we use className to design a lot of our elements here." }, { "code": null, "e": 11365, "s": 11266, "text": "I’ve only used default class names here. You can find them from the official CSS class names here." }, { "code": null, "e": 11545, "s": 11365, "text": "I hope this has shed light on how useful dash bootstrap can be. With this, you can completely design your dashboard with Python, while plotting your graphs with Pandas and Plotly." }, { "code": null, "e": 11572, "s": 11545, "text": "Full code for the article:" }, { "code": null, "e": 11660, "s": 11572, "text": "Congratulations,you can now efficiently design your own dashboard completely in Python." }, { "code": null, "e": 11695, "s": 11660, "text": "In this article, you have learned:" }, { "code": null, "e": 11711, "s": 11695, "text": "The Grid System" }, { "code": null, "e": 11748, "s": 11711, "text": "Organizing/Designing using Bootstrap" }, { "code": null, "e": 11763, "s": 11748, "text": "Navigation Bar" }, { "code": null, "e": 11773, "s": 11763, "text": "Jumbotron" }, { "code": null, "e": 11888, "s": 11773, "text": "Plenty for you to work on.Now go data practitioners, build something and share it with me,share it with the world." }, { "code": null, "e": 11977, "s": 11888, "text": "If you hit a roadblock, feel free to reach out to me. You can find my information below." }, { "code": null, "e": 12241, "s": 11977, "text": "We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data." }, { "code": null, "e": 12271, "s": 12241, "text": "As usual, I end with a quote." }, { "code": null, "e": 12359, "s": 12271, "text": "The goal is to turn data into information and information into insight. — Carly Fiorina" }, { "code": null, "e": 12532, "s": 12359, "text": "You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!" }, { "code": null, "e": 12753, "s": 12532, "text": "I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data." } ]
Scanner findInLine() method in Java with Examples - GeeksforGeeks
10 Oct, 2018 The findInLine(Pattern pattern) method of java.util.Scanner class tries to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner’s position is unchanged. Syntax: public String findInLine(Pattern pattern) Parameters: The function accepts a mandatory parameter Pattern pattern which is pattern which is scanned for. Return Value: The function returns the scanner’s delimiting pattern. Exceptions: The function throws an IllegalStateException if this scanner is closed. Below programs illustrate the above function: Program 1: // Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = "Geeksforgeeks has Scanner Class Methods"; // Print the string System.out.println("Target String:\n" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // finds a pattern of any 5 letter plus "for" System.out.println("\nAny 5 letter plus for : " + scanner.findInLine( Pattern.compile(".....for"))); // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println("Exception thrown : " + e); } }} Target String: Geeksforgeeks has Scanner Class Methods Any 5 letter plus for : Geeksfor Program 2: To demonstrate IllegalStateException // Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = "Geeksforgeeks has Scanner Class Methods"; // Print the string System.out.println("Target String:\n" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); // finds a pattern of any 5 letter plus "for" System.out.println("\nAny 5 letter plus for : " + scanner.findInLine( Pattern.compile(".....for"))); // print the next line of the string System.out.println("" + scanner.nextLine()); } catch (IllegalStateException e) { System.out.println("Exception thrown: " + e); } }} Target String: Geeksforgeeks has Scanner Class Methods Exception thrown: java.lang.IllegalStateException: Scanner closed The findInLine(String pattern) method ofjava.util.Scanner class tries to find the next occurrence of a pattern constructed from the specified string pattern, ignoring the delimiters. Syntax: public String findInLine(String pattern) Parameters: The function accepts a mandatory parameter string pattern which is scanned for. Return Value: The function returns the scanner’s delimiting pattern. Exceptions: The function throws an IllegalStateException if this scanner is closed. Below programs illustrate the above function: Program 1: // Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = "Geeksforgeeks has Scanner Class Methods"; // Print the string System.out.println("Target String:\n" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // finds a pattern of any 5 letter plus "for" System.out.println("\nAny 5 letter plus for : " + scanner.findInLine( Pattern.compile(".....for"))); // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println("Exception thrown : " + e); } }} Target String: Geeksforgeeks has Scanner Class Methods Any 5 letter plus for : Geeksfor Program 2: To demonstrate IllegalStateException // Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = "Geeksforgeeks has Scanner Class Methods"; // Print the string System.out.println("Target String:\n" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); // finds a pattern of any 5 letter plus "for" System.out.println("\nAny 5 letter plus for : " + scanner.findInLine( Pattern.compile(".....for"))); } catch (IllegalStateException e) { System.out.println("Exception thrown : " + e); } }} Target String: Geeksforgeeks has Scanner Class Methods Exception thrown : java.lang.IllegalStateException: Scanner closed Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#findInLine(java.util.regex.Pattern) Java - util package Java-Functions Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n10 Oct, 2018" }, { "code": null, "e": 25785, "s": 25347, "text": "The findInLine(Pattern pattern) method of java.util.Scanner class tries to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner’s position is unchanged." }, { "code": null, "e": 25793, "s": 25785, "text": "Syntax:" }, { "code": null, "e": 25835, "s": 25793, "text": "public String findInLine(Pattern pattern)" }, { "code": null, "e": 25945, "s": 25835, "text": "Parameters: The function accepts a mandatory parameter Pattern pattern which is pattern which is scanned for." }, { "code": null, "e": 26014, "s": 25945, "text": "Return Value: The function returns the scanner’s delimiting pattern." }, { "code": null, "e": 26098, "s": 26014, "text": "Exceptions: The function throws an IllegalStateException if this scanner is closed." }, { "code": null, "e": 26144, "s": 26098, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 26155, "s": 26144, "text": "Program 1:" }, { "code": "// Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = \"Geeksforgeeks has Scanner Class Methods\"; // Print the string System.out.println(\"Target String:\\n\" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // finds a pattern of any 5 letter plus \"for\" System.out.println(\"\\nAny 5 letter plus for : \" + scanner.findInLine( Pattern.compile(\".....for\"))); // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 27145, "s": 26155, "text": null }, { "code": null, "e": 27235, "s": 27145, "text": "Target String:\nGeeksforgeeks has Scanner Class Methods\n\nAny 5 letter plus for : Geeksfor\n" }, { "code": null, "e": 27283, "s": 27235, "text": "Program 2: To demonstrate IllegalStateException" }, { "code": "// Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = \"Geeksforgeeks has Scanner Class Methods\"; // Print the string System.out.println(\"Target String:\\n\" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); // finds a pattern of any 5 letter plus \"for\" System.out.println(\"\\nAny 5 letter plus for : \" + scanner.findInLine( Pattern.compile(\".....for\"))); // print the next line of the string System.out.println(\"\" + scanner.nextLine()); } catch (IllegalStateException e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 28378, "s": 27283, "text": null }, { "code": null, "e": 28502, "s": 28378, "text": "Target String:\nGeeksforgeeks has Scanner Class Methods\nException thrown:\n java.lang.IllegalStateException:\n Scanner closed\n" }, { "code": null, "e": 28685, "s": 28502, "text": "The findInLine(String pattern) method ofjava.util.Scanner class tries to find the next occurrence of a pattern constructed from the specified string pattern, ignoring the delimiters." }, { "code": null, "e": 28693, "s": 28685, "text": "Syntax:" }, { "code": null, "e": 28734, "s": 28693, "text": "public String findInLine(String pattern)" }, { "code": null, "e": 28826, "s": 28734, "text": "Parameters: The function accepts a mandatory parameter string pattern which is scanned for." }, { "code": null, "e": 28895, "s": 28826, "text": "Return Value: The function returns the scanner’s delimiting pattern." }, { "code": null, "e": 28979, "s": 28895, "text": "Exceptions: The function throws an IllegalStateException if this scanner is closed." }, { "code": null, "e": 29025, "s": 28979, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 29036, "s": 29025, "text": "Program 1:" }, { "code": "// Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = \"Geeksforgeeks has Scanner Class Methods\"; // Print the string System.out.println(\"Target String:\\n\" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // finds a pattern of any 5 letter plus \"for\" System.out.println(\"\\nAny 5 letter plus for : \" + scanner.findInLine( Pattern.compile(\".....for\"))); // close the scanner scanner.close(); } catch (IllegalStateException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 30028, "s": 29036, "text": null }, { "code": null, "e": 30118, "s": 30028, "text": "Target String:\nGeeksforgeeks has Scanner Class Methods\n\nAny 5 letter plus for : Geeksfor\n" }, { "code": null, "e": 30166, "s": 30118, "text": "Program 2: To demonstrate IllegalStateException" }, { "code": "// Java program to illustrate the// findInLine() method of Scanner class in Java import java.util.*;import java.util.regex.Pattern; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string to be searched String s = \"Geeksforgeeks has Scanner Class Methods\"; // Print the string System.out.println(\"Target String:\\n\" + s); // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); // finds a pattern of any 5 letter plus \"for\" System.out.println(\"\\nAny 5 letter plus for : \" + scanner.findInLine( Pattern.compile(\".....for\"))); } catch (IllegalStateException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 31158, "s": 30166, "text": null }, { "code": null, "e": 31283, "s": 31158, "text": "Target String:\nGeeksforgeeks has Scanner Class Methods\nException thrown :\n java.lang.IllegalStateException:\n Scanner closed\n" }, { "code": null, "e": 31395, "s": 31283, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#findInLine(java.util.regex.Pattern)" }, { "code": null, "e": 31415, "s": 31395, "text": "Java - util package" }, { "code": null, "e": 31430, "s": 31415, "text": "Java-Functions" }, { "code": null, "e": 31439, "s": 31430, "text": "Java-I/O" }, { "code": null, "e": 31444, "s": 31439, "text": "Java" }, { "code": null, "e": 31449, "s": 31444, "text": "Java" }, { "code": null, "e": 31547, "s": 31449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31562, "s": 31547, "text": "Stream In Java" }, { "code": null, "e": 31581, "s": 31562, "text": "Exceptions in Java" }, { "code": null, "e": 31602, "s": 31581, "text": "Constructors in Java" }, { "code": null, "e": 31632, "s": 31602, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31678, "s": 31632, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31695, "s": 31678, "text": "Generics in Java" }, { "code": null, "e": 31716, "s": 31695, "text": "Introduction to Java" }, { "code": null, "e": 31759, "s": 31716, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 31781, "s": 31759, "text": "PriorityQueue in Java" } ]
Pattern compile() method in Java with Examples
The pattern class of the java.regex package is a compiled representation of a regular expression. The compile() method of this class accepts a string value representing a regular expression and returns a Pattern object. import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CompileExample { public static void main( String args[] ) { //Reading string value Scanner sc = new Scanner(System.in); System.out.println("Enter input string"); String input = sc.nextLine(); //Regular expression to find digits String regex = "(\\d)"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Printing the regular expression System.out.println("Compiled regular expression: "+pattern.toString()); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); //verifying whether match occurred if(matcher.find()) { System.out.println("Given String contains digits"); } else { System.out.println("Given String does not contain digits"); } } } Enter input string hello my id is 1120KKA Compiled regular expression: (\d) Given String contains digits Another variant of this method accepts an integer value representing flags, where each flag specifies an optional condition, for example, CASE_INSENSITIVE ignores the case while compiling the regular expression. import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CompileExample { public static void main( String args[] ) { //Compiling the regular expression Pattern pattern = Pattern.compile("[t]", Pattern.CASE_INSENSITIVE); //Retrieving the matcher object Matcher matcher = pattern.matcher("Tutorialspoint"); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of matches: "+count); } } Enter input string Tutorialspoint Number of matches: 3
[ { "code": null, "e": 1160, "s": 1062, "text": "The pattern class of the java.regex package is a compiled representation of a regular expression." }, { "code": null, "e": 1282, "s": 1160, "text": "The compile() method of this class accepts a string value representing a regular expression and returns a Pattern object." }, { "code": null, "e": 2197, "s": 1282, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class CompileExample {\n public static void main( String args[] ) {\n //Reading string value\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string\");\n String input = sc.nextLine();\n //Regular expression to find digits\n String regex = \"(\\\\d)\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Printing the regular expression\n System.out.println(\"Compiled regular expression: \"+pattern.toString());\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n //verifying whether match occurred\n if(matcher.find()) {\n System.out.println(\"Given String contains digits\");\n } else {\n System.out.println(\"Given String does not contain digits\");\n }\n }\n}" }, { "code": null, "e": 2302, "s": 2197, "text": "Enter input string\nhello my id is 1120KKA\nCompiled regular expression: (\\d)\nGiven String contains digits" }, { "code": null, "e": 2514, "s": 2302, "text": "Another variant of this method accepts an integer value representing flags, where each flag specifies an optional condition, for example, CASE_INSENSITIVE ignores the case while compiling the regular expression." }, { "code": null, "e": 3031, "s": 2514, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class CompileExample {\n public static void main( String args[] ) {\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(\"[t]\", Pattern.CASE_INSENSITIVE);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(\"Tutorialspoint\");\n int count = 0;\n while(matcher.find()) {\n count++;\n }\n System.out.println(\"Number of matches: \"+count);\n }\n}" }, { "code": null, "e": 3086, "s": 3031, "text": "Enter input string\nTutorialspoint\nNumber of matches: 3" } ]
Angular PrimeNG Menubar Component - GeeksforGeeks
08 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Menubar component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. Menubar component: It is used to make a menu list in the form of a horizontal bar. Properties: model: It is an array of menu items. It accepts the array data type as input & the default value is null. style: It is an inline style of the component. It is of string data type & the default value is null. styleClass: It is used to set the style class of the component. It is of string data type & the default value is null. baseZIndex: It is used to set base zIndex value to use in layering. It accepts the number data type as input & the default value is 0. autoZIndex: It is used to specify whether to automatically manage the layering. It accepts the boolean data type as input & the default value is true. autoDisplay: It is used to specify whether to show a root submenu on mouseover. It accepts the boolean data type as input & the default value is false. Styling: p-menubar: It is the container element. p-menu-list: It is a list element. p-menuitem: It is the menuitem element. p-menuitem-text: It is the label of a menuitem. p-menuitem-icon: It is the icon of a menuitem. p-submenu-icon: It is the arrow icon of a submenu. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example: This is the basic example that illustrates how to use the Menubar component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG MenuBar Component</h5><p-menubar [model]="gfg"></p-menubar> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenubarModule } from 'primeng/menubar';@NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MenubarModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} Output: Reference: https://primefaces.org/primeng/showcase/#/menubar Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26743, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Menubar component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code." }, { "code": null, "e": 26826, "s": 26743, "text": "Menubar component: It is used to make a menu list in the form of a horizontal bar." }, { "code": null, "e": 26838, "s": 26826, "text": "Properties:" }, { "code": null, "e": 26944, "s": 26838, "text": "model: It is an array of menu items. It accepts the array data type as input & the default value is null." }, { "code": null, "e": 27046, "s": 26944, "text": "style: It is an inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27165, "s": 27046, "text": "styleClass: It is used to set the style class of the component. It is of string data type & the default value is null." }, { "code": null, "e": 27300, "s": 27165, "text": "baseZIndex: It is used to set base zIndex value to use in layering. It accepts the number data type as input & the default value is 0." }, { "code": null, "e": 27451, "s": 27300, "text": "autoZIndex: It is used to specify whether to automatically manage the layering. It accepts the boolean data type as input & the default value is true." }, { "code": null, "e": 27603, "s": 27451, "text": "autoDisplay: It is used to specify whether to show a root submenu on mouseover. It accepts the boolean data type as input & the default value is false." }, { "code": null, "e": 27612, "s": 27603, "text": "Styling:" }, { "code": null, "e": 27652, "s": 27612, "text": "p-menubar: It is the container element." }, { "code": null, "e": 27687, "s": 27652, "text": "p-menu-list: It is a list element." }, { "code": null, "e": 27727, "s": 27687, "text": "p-menuitem: It is the menuitem element." }, { "code": null, "e": 27775, "s": 27727, "text": "p-menuitem-text: It is the label of a menuitem." }, { "code": null, "e": 27822, "s": 27775, "text": "p-menuitem-icon: It is the icon of a menuitem." }, { "code": null, "e": 27873, "s": 27822, "text": "p-submenu-icon: It is the arrow icon of a submenu." }, { "code": null, "e": 27927, "s": 27875, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27994, "s": 27927, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28009, "s": 27994, "text": "ng new appname" }, { "code": null, "e": 28106, "s": 28009, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28117, "s": 28106, "text": "cd appname" }, { "code": null, "e": 28166, "s": 28117, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28223, "s": 28166, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28275, "s": 28223, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28361, "s": 28275, "text": "Example: This is the basic example that illustrates how to use the Menubar component." }, { "code": null, "e": 28380, "s": 28361, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG MenuBar Component</h5><p-menubar [model]=\"gfg\"></p-menubar>", "e": 28474, "s": 28380, "text": null }, { "code": null, "e": 28488, "s": 28474, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenubarModule } from 'primeng/menubar';@NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MenubarModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 28957, "s": 28488, "text": null }, { "code": null, "e": 28974, "s": 28957, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 29549, "s": 28974, "text": null }, { "code": null, "e": 29557, "s": 29549, "text": "Output:" }, { "code": null, "e": 29618, "s": 29557, "text": "Reference: https://primefaces.org/primeng/showcase/#/menubar" }, { "code": null, "e": 29634, "s": 29618, "text": "Angular-PrimeNG" }, { "code": null, "e": 29644, "s": 29634, "text": "AngularJS" }, { "code": null, "e": 29661, "s": 29644, "text": "Web Technologies" }, { "code": null, "e": 29759, "s": 29661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29794, "s": 29759, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29829, "s": 29794, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29853, "s": 29829, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29888, "s": 29853, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29941, "s": 29888, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29981, "s": 29941, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30014, "s": 29981, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30059, "s": 30014, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30102, "s": 30059, "text": "How to fetch data from an API in ReactJS ?" } ]
Find whether it is possible to finish all tasks or not from given dependencies
01 Jul, 2022 There are a total of n tasks you have to pick, labelled from 0 to n-1. Some tasks may have prerequisites, for example to pick task 0 you have to first pick task 1, which is expressed as a pair: [0, 1]Given the total number of tasks and a list of prerequisite pairs, is it possible for you to finish all tasks?Examples: Input: 2, [[1, 0]] Output: true Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0. So it is possible.Input: 2, [[1, 0], [0, 1]] Output: false Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0, and to pick task 0 you should also have finished task 1. So it is impossible.Input: 3, [[1, 0], [2, 1], [3, 2]] Output: true Explanation: There are a total of 3 tasks to pick. To pick tasks 1 you should have finished task 0, and to pick task 2 you should have finished task 1 and to pick task 3 you should have finished task 2. So it is possible. Asked In: Google, Twitter, Amazon and many more companies. Solution: We can consider this problem as a graph (related to topological sorting) problem. All tasks are nodes of the graph and if task u is a prerequisite of task v, we will add a directed edge from node u to node v. Now, this problem is equivalent to detecting a cycle in the graph represented by prerequisites. If there is a cycle in the graph, then it is not possible to finish all tasks (because in that case there is no any topological order of tasks). Both BFS and DFS can be used to solve it.Since pair is inconvenient for the implementation of graph algorithms, we first transform it to a graph. If task u is a prerequisite of task v, we will add a directed edge from node u to node v.Prerequisite : Detect Cycle in a Directed GraphUsing DFS For DFS, it will first visit a node, then one neighbor of it, then one neighbor of this neighbor... and so on. If it meets a node which was visited in the current process of DFS visit, a cycle is detected and we will return false. Otherwise it will start from another unvisited node and repeat this process till all the nodes have been visited. Note that you should make two records: one is to record all the visited nodes and the other is to record the visited nodes in the current DFS visit.The code is as follows. We use a vector visited to record all the visited nodes and another vector onpath to record the visited nodes of the current DFS visit. Once the current visit is finished, we reset the onpath value of the starting node to false. CPP Java Python3 C# // CPP program to check whether we can finish all// tasks or not from given dependencies.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation from a list// of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // A DFS based function to check if there is a cycle// in the directed graph.bool dfs_cycle(vector<unordered_set<int> >& graph, int node, vector<bool>& onpath, vector<bool>& visited){ if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph[node]) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; return onpath[node] = false;} // Main function to check whether possible to finish all tasks or notbool canFinish(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<bool> onpath(numTasks, false), visited(numTasks, false); for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); if (canFinish(numTasks, prerequisites)) { cout << "Possible to finish all tasks"; } else { cout << "Impossible to finish all tasks"; } return 0;} // Java program to check whether we can finish all// tasks or not from given dependencies.import java.util.*; public class GFG{ // class to store dependencies as a pair static class pair{ int first, second; pair(int first, int second){ this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static ArrayList<ArrayList<Integer>> make_graph(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(numTasks); for(int i=0; i<numTasks; i++){ graph.add(new ArrayList<Integer>()); } for (pair pre : prerequisites) graph.get(pre.second).add(pre.first); return graph; } // A DFS based function to check if there is a cycle // in the directed graph. static boolean dfs_cycle(ArrayList<ArrayList<Integer>> graph, int node, boolean onpath[], boolean visited[]) { if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph.get(node)) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; return onpath[node] = false; } // Main function to check whether possible to finish all tasks or not static boolean canFinish(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer>> graph = make_graph(numTasks, prerequisites); boolean onpath[] = new boolean[numTasks]; boolean visited[] = new boolean[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true; } public static void main(String args[]) { int numTasks = 4; Vector<pair> prerequisites = new Vector<pair>();; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.add(new pair(1, 0)); prerequisites.add(new pair(2, 1)); prerequisites.add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { System.out.println("Possible to finish all tasks"); } else { System.out.println("Impossible to finish all tasks"); } }} // This code is contributed by adityapande88. # Python3 program to check whether we can finish all# tasks or not from given dependencies. # class to store dependencies as a pairclass pair: def __init__(self, first, second): self.first = first self.second = second # Returns adjacency list representation from a list# of pairs.def make_graph(numTasks, prerequisites): graph = [] for i in range(numTasks): graph.append([]) for pre in prerequisites: graph[pre.second].append(pre.first) return graph # A DFS based function to check if there is a cycle# in the directed graph.def dfs_cycle(graph, node, onpath, visited): if visited[node]: return false onpath[node] = visited[node] = True for neigh in graph[node]: if (onpath[neigh] or dfs_cycle(graph, neigh, onpath, visited)): return true return False # Main function to check whether possible to finish all# tasks or notdef canFinish(numTasks, prerequisites): graph = make_graph(numTasks, prerequisites) onpath = [False]*numTasks visited = [False]*numTasks for i in range(numTasks): if (not visited[i] and dfs_cycle(graph, i, onpath, visited)): return False return True # Driver code to test above functionsnumTasks = 4prerequisites = [] prerequisites.append(pair(1, 0))prerequisites.append(pair(2, 1))prerequisites.append(pair(3, 2)) if canFinish(numTasks, prerequisites): print("Possible to finish all tasks")else: print("Impossible to finish all tasks") # This code is contributed by Abhijeet Kumar(abhijeet19403) // C# program to check whether we can finish all// tasks or not from given dependencies.using System;using System.Collections.Generic; public class GFG { // class to store dependencies as a pair public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static List<List<int> > make_graph(int numTasks, List<pair> prerequisites) { List<List<int> > graph = new List<List<int> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.Add(new List<int>()); } foreach(pair pre in prerequisites) graph[pre.second] .Add(pre.first); return graph; } // A DFS based function to check if there is a cycle // in the directed graph. static bool dfs_cycle(List<List<int> > graph, int node, bool[] onpath, bool[] visited) { if (visited[node]) return false; onpath[node] = visited[node] = true; foreach( int neigh in graph[node]) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; //onpath[node] = false; return false; } // Main function to check whether possible to finish all // tasks or not static bool canFinish(int numTasks, List<pair> prerequisites) { List<List<int> > graph = make_graph(numTasks, prerequisites); bool[] onpath = new bool[numTasks]; bool[] visited = new bool[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true; } public static void Main(String[] args) { int numTasks = 4; List<pair> prerequisites = new List<pair>(); ; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.Add(new pair(1, 0)); prerequisites.Add(new pair(2, 1)); prerequisites.Add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { Console.WriteLine( "Possible to finish all tasks"); } else { Console.WriteLine( "Impossible to finish all tasks"); } }} // This code is contributed by Abhijeet Kumar(abhijeet19403) Possible to finish all tasks Using BFS BFS can be used to solve it using the idea of topological sort. If topological sorting is possible, it means there is no cycle and it is possible to finish all the tasks.BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we have found one. We set its indegree to be -1 to prevent from visiting it again and reduce the indegrees of all its neighbors by 1. This process will be repeated for n (number of nodes) times. If we have not returned false, we will return true. CPP Java Python3 C# // A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation from a list// of pairs.vector<unordered_set<int> >make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Finds in-degree of every vertexvector<int>compute_indegree(vector<unordered_set<int> >& graph){ vector<int> degrees(graph.size(), 0); for (auto neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees;} // Main function to check whether possible to finish all// tasks or notbool canFinish(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<int> degrees = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (!degrees[j]) break; if (j == numTasks) return false; degrees[j] = -1; for (int neigh : graph[j]) degrees[neigh]--; } return true;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); if (canFinish(numTasks, prerequisites)) { cout << "Possible to finish all tasks"; } else { cout << "Impossible to finish all tasks"; } return 0;} // A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.import java.util.*; public class GFG { // class to store dependencies as a pair static class pair { int first, second; pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static ArrayList<ArrayList<Integer> > make_graph(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer> > graph = new ArrayList<ArrayList<Integer> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.add(new ArrayList<Integer>()); } for (pair pre : prerequisites) graph.get(pre.second).add(pre.first); return graph; } // Finds in-degree of every vertex static int[] compute_indegree( ArrayList<ArrayList<Integer> > graph) { int degrees[] = new int[graph.size()]; for (ArrayList<Integer> neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees; } // Main function to check whether possible to finish all // tasks or not static boolean canFinish(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer> > graph = make_graph(numTasks, prerequisites); int degrees[] = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (degrees[j] == 0) break; if (j == numTasks) return false; degrees[j] = -1; for (int neigh : graph.get(j)) degrees[neigh]--; } return true; } public static void main(String args[]) { int numTasks = 4; Vector<pair> prerequisites = new Vector<pair>(); prerequisites.add(new pair(1, 0)); prerequisites.add(new pair(2, 1)); prerequisites.add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { System.out.println( "Possible to finish all tasks"); } else { System.out.println( "Impossible to finish all tasks"); } }} // This code is contributed by adityapande88. # A BFS based solution to check if we can finish# all tasks or not. This solution is mainly based# on Kahn's algorithm. # class to store dependencies as a pair class pair: def __init__(self, first, second): self.first = first self.second = second # Returns adjacency list representation from a list# of pairs. def make_graph(numTasks, prerequisites): graph = [] for i in range(numTasks): graph.append([]) for pre in prerequisites: graph[pre.second].append(pre.first) return graph # Finds in-degree of every vertexdef compute_indegree(graph): degrees = [0]*len(graph) for neighbors in graph: for neigh in neighbors: degrees[neigh] += 1 return degrees # Main function to check whether possible to finish all tasks or notdef canFinish(numTasks, prerequisites): graph = make_graph(numTasks, prerequisites) degrees = compute_indegree(graph) for i in range(numTasks): j = 0 while(j < numTasks): if (degrees[j] == 0): break j += 1 if (j == numTasks): return False degrees[j] = -1 for neigh in graph[j]: degrees[neigh] -= 1 return True numTasks = 4prerequisites = [] prerequisites.append(pair(1, 0))prerequisites.append(pair(2, 1))prerequisites.append(pair(3, 2)) if (canFinish(numTasks, prerequisites)): print("Possible to finish all tasks")else: print("Impossible to finish all tasks") # This code is contributed by Lovely Jain // A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.using System;using System.Collections.Generic; public class GFG { // class to store dependencies as a pair public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static List<List<int> > make_graph(int numTasks, List<pair> prerequisites) { List<List<int> > graph = new List<List<int> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.Add(new List<int>()); } foreach(pair pre in prerequisites) graph[pre.second].Add(pre.first); return graph; } // Finds in-degree of every vertex static int[] compute_indegree( List<List<int> > graph) { int[] degrees = new int[graph.Count]; foreach(List<int> neighbors in graph) foreach(int neigh in neighbors) degrees[neigh]++; return degrees; } // Main function to check whether possible to finish all // tasks or not static bool canFinish(int numTasks, List<pair> prerequisites) { List<List<int> > graph = make_graph(numTasks, prerequisites); int[] degrees = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (degrees[j] == 0) break; if (j == numTasks) return false; degrees[j] = -1; foreach(int neigh in graph[j]) degrees[neigh]--; } return true; } public static void Main(String[] args) { int numTasks = 4; List<pair> prerequisites = new List<pair>(); prerequisites.Add(new pair(1, 0)); prerequisites.Add(new pair(2, 1)); prerequisites.Add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { Console.WriteLine( "Possible to finish all tasks"); } else { Console.WriteLine( "Impossible to finish all tasks"); } }} // This code is contributed by Abhijeet Kumar(abhijeet19403) Possible to finish all tasks Reference: https://leetcode.com/problems/course-schedule/ Using Union-find Another approach which is Union-find method can also be used to solve this problem. Each pair we get can be considered in a parent-child relation. As soon as we find a pair of tasks which are supposed to be in a parent-child relation, we check if they already have a common parent and hence it means there is a dependency cycle in the tasks which will never end and hence solving such set of tasks is not possible. C++14 Java Python3 C# /* * A union-find based solution for stating whether * the given set of tasks with respective prerequisites * can be finished completely or not. */#include <bits/stdc++.h>using namespace std;class Solution { // returns true/false stating whether tasks can be // finished or not vector<int> arr; public: Solution(int n) { arr.resize(n); // Initially, everyone is their own child for (int i = 0; i < n; i++) arr[i] = i; } void makeParent(int a, int b) { // find parent of b and make it a's parent arr[a] = findParent(b); } int findParent(int c) { // when an independent task is found if (c == arr) return c; // recursively find the parent of given task return findParent(arr); } bool isPossible(int N, vector<vector<int> > prerequisites) { // traverse through pre-requisites array for (int i = 0; i < prerequisites.size(); i++) { // check whether given pre-requisite pair // already have a common pre-requisite(parent) if (findParent(prerequisites[i][0]) == findParent(prerequisites[i][1])) { // tasks cannot be completed because there // was a cyclic condition in the tasks return false; } // make parent-child relation between // pre-requisite task and the task dependent on // it makeParent(prerequisites[i][0], prerequisites[i][1]); } // if there was no cycle found, tasks can be // completed return true; }}; // Driver code int main(){ vector<vector<int> > prerequisites{ { 1, 0 }, { 2, 1 }, { 3, 2 } }; Solution ob(4); if (ob.isPossible(4, prerequisites)) { cout << "Yes"; } else { cout << "No"; }} // Driver Code Ends // This code was contributed by Abhijeet Kumar(abhijeet19403) /** A union-find based solution for stating whether* the given set of tasks with respective prerequisites* can be finished completely or not.*/import java.io.*;import java.util.*; //Driver codeclass GFG { public static void main(String args[]) throws IOException { int prerequisites[][] = new int[][]{ {1,0}, {2,1}, {3,2} }; Solution ob = new Solution(); if(ob.isPossible(4, prerequisites)) { System.out.println("Yes"); } else{ System.out.println("No"); } }}//Driver Code Ends //Solution codeclass Solution { //returns true/false stating whether tasks can be finished or not public boolean isPossible(int N, int[][] prerequisites) { //make object of Union class for N tasks Union u = new Union(N); //traverse through pre-requisites array for(int i = 0; i < prerequisites.length; i++){ //check whether given pre-requisite pair //already have a common pre-requisite(parent) if(u.findParent(prerequisites[i][0]) == u.findParent(prerequisites[i][1])) { //tasks cannot be completed because there was //a cyclic condition in the tasks return false; } //make parent-child relation between pre-requisite task //and the task dependent on it u.makeParent(prerequisites[i][0], prerequisites[i][1]); } //if there was no cycle found, tasks can be completed return true; } }class Union { //to store the parents of respective tasks int[] arr; //parameterized constructor for Union class public Union(int n){ arr = new int[n]; //Initially, everyone is their own child for(int i = 0; i < n; i++){ arr[i] = i; } } public void makeParent(int a, int b){ //find parent of b and make it a's parent arr[a] = findParent(b); } public int findParent(int c){ //when an independent task is found if(c == arr) return c; //recursively find the parent of given task return findParent(arr); }} # A union-find based solution for stating whether# the given set of tasks with respective prerequisites# can be finished completely or not.class Solution: arr = [] # parameterized constructor def __init__(self,n): # Initially, everyone is their own child self.arr = [i for i in range(n)] def makeParent(self,a, b): # find parent of b and make it a's parent self.arr[a] = self.findParent(b) def findParent(self,c): # when an independent task is found if (c == self.arr): return c # recursively find the parent of given task return self.findParent(self.arr) def isPossible(self,N , prerequisites): # traverse through pre-requisites array for i in range(len(prerequisites)): # check whether given pre-requisite pair # already have a common pre-requisite(parent) if (self.findParent(prerequisites[i][0]) == self.findParent(prerequisites[i][1])): # tasks cannot be completed because there # was a cyclic condition in the tasks return false # make parent-child relation between # pre-requisite task and the task dependent on # it self.makeParent(prerequisites[i][0], prerequisites[i][1]) # if there was no cycle found, tasks can be # completed return True # Driver codeprerequisites = [[1, 0], [2, 1], [3, 2]] ob = Solution(4) if ob.isPossible(4,prerequisites ): print("Yes")else: print("No") # Driver Code Ends # This code was contributed by Abhijeet Kumar(abhijeet19403) /** A union-find based solution for stating whether* the given set of tasks with respective prerequisites* can be finished completely or not.*/using System;using System.Collections.Generic; //Solution code public class Solution { //returns true/false stating whether tasks can be finished or not public bool isPossible(int N, int[,] prerequisites) { //make object of Union class for N tasks Union u = new Union(N); //traverse through pre-requisites array for(int i = 0; i < prerequisites.Length/2; i++){ //check whether given pre-requisite pair //already have a common pre-requisite(parent) if(u.findParent(prerequisites[i,0]) == u.findParent(prerequisites[i,1])) { //tasks cannot be completed because there was //a cyclic condition in the tasks return false; } //make parent-child relation between pre-requisite task //and the task dependent on it u.makeParent(prerequisites[i,0], prerequisites[i,1]); } //if there was no cycle found, tasks can be completed return true; } } public class Union { //to store the parents of respective tasks int[] arr; //parameterized constructor for Union class public Union(int n){ arr = new int[n]; //Initially, everyone is their own child for(int i = 0; i < n; i++){ arr[i] = i; } } public void makeParent(int a, int b){ //find parent of b and make it a's parent arr[a] = findParent(b); } public int findParent(int c){ //when an independent task is found if(c == arr) return c; //recursively find the parent of given task return findParent(arr); }} //Driver code class GFG { public static void Main(String[] args) { int[,] prerequisites = new int[,]{ {1,0}, {2,1}, {3,2} }; Solution ob = new Solution(); if(ob.isPossible(4, prerequisites)) { Console.WriteLine("Yes"); } else{ Console.WriteLine("No"); } }}//Driver Code Ends // This code was contributed by Abhijeet Kumar(abhijeet19403) Yes adityapande88 anikaseth98 vishal0171cse19 rkbhola5 jainlovely450 abhijeet19403 BFS DFS graph-cycle Technical Scripter 2018 Topological Sorting Graph Technical Scripter DFS Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2022" }, { "code": null, "e": 374, "s": 54, "text": "There are a total of n tasks you have to pick, labelled from 0 to n-1. Some tasks may have prerequisites, for example to pick task 0 you have to first pick task 1, which is expressed as a pair: [0, 1]Given the total number of tasks and a list of prerequisite pairs, is it possible for you to finish all tasks?Examples: " }, { "code": null, "e": 1010, "s": 374, "text": "Input: 2, [[1, 0]] Output: true Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0. So it is possible.Input: 2, [[1, 0], [0, 1]] Output: false Explanation: There are a total of 2 tasks to pick. To pick task 1 you should have finished task 0, and to pick task 0 you should also have finished task 1. So it is impossible.Input: 3, [[1, 0], [2, 1], [3, 2]] Output: true Explanation: There are a total of 3 tasks to pick. To pick tasks 1 you should have finished task 0, and to pick task 2 you should have finished task 1 and to pick task 3 you should have finished task 2. So it is possible." }, { "code": null, "e": 1070, "s": 1010, "text": "Asked In: Google, Twitter, Amazon and many more companies. " }, { "code": null, "e": 2569, "s": 1070, "text": "Solution: We can consider this problem as a graph (related to topological sorting) problem. All tasks are nodes of the graph and if task u is a prerequisite of task v, we will add a directed edge from node u to node v. Now, this problem is equivalent to detecting a cycle in the graph represented by prerequisites. If there is a cycle in the graph, then it is not possible to finish all tasks (because in that case there is no any topological order of tasks). Both BFS and DFS can be used to solve it.Since pair is inconvenient for the implementation of graph algorithms, we first transform it to a graph. If task u is a prerequisite of task v, we will add a directed edge from node u to node v.Prerequisite : Detect Cycle in a Directed GraphUsing DFS For DFS, it will first visit a node, then one neighbor of it, then one neighbor of this neighbor... and so on. If it meets a node which was visited in the current process of DFS visit, a cycle is detected and we will return false. Otherwise it will start from another unvisited node and repeat this process till all the nodes have been visited. Note that you should make two records: one is to record all the visited nodes and the other is to record the visited nodes in the current DFS visit.The code is as follows. We use a vector visited to record all the visited nodes and another vector onpath to record the visited nodes of the current DFS visit. Once the current visit is finished, we reset the onpath value of the starting node to false. " }, { "code": null, "e": 2573, "s": 2569, "text": "CPP" }, { "code": null, "e": 2578, "s": 2573, "text": "Java" }, { "code": null, "e": 2586, "s": 2578, "text": "Python3" }, { "code": null, "e": 2589, "s": 2586, "text": "C#" }, { "code": "// CPP program to check whether we can finish all// tasks or not from given dependencies.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation from a list// of pairs.vector<unordered_set<int> > make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // A DFS based function to check if there is a cycle// in the directed graph.bool dfs_cycle(vector<unordered_set<int> >& graph, int node, vector<bool>& onpath, vector<bool>& visited){ if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph[node]) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; return onpath[node] = false;} // Main function to check whether possible to finish all tasks or notbool canFinish(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<bool> onpath(numTasks, false), visited(numTasks, false); for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); if (canFinish(numTasks, prerequisites)) { cout << \"Possible to finish all tasks\"; } else { cout << \"Impossible to finish all tasks\"; } return 0;}", "e": 4342, "s": 2589, "text": null }, { "code": "// Java program to check whether we can finish all// tasks or not from given dependencies.import java.util.*; public class GFG{ // class to store dependencies as a pair static class pair{ int first, second; pair(int first, int second){ this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static ArrayList<ArrayList<Integer>> make_graph(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(numTasks); for(int i=0; i<numTasks; i++){ graph.add(new ArrayList<Integer>()); } for (pair pre : prerequisites) graph.get(pre.second).add(pre.first); return graph; } // A DFS based function to check if there is a cycle // in the directed graph. static boolean dfs_cycle(ArrayList<ArrayList<Integer>> graph, int node, boolean onpath[], boolean visited[]) { if (visited[node]) return false; onpath[node] = visited[node] = true; for (int neigh : graph.get(node)) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; return onpath[node] = false; } // Main function to check whether possible to finish all tasks or not static boolean canFinish(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer>> graph = make_graph(numTasks, prerequisites); boolean onpath[] = new boolean[numTasks]; boolean visited[] = new boolean[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true; } public static void main(String args[]) { int numTasks = 4; Vector<pair> prerequisites = new Vector<pair>();; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.add(new pair(1, 0)); prerequisites.add(new pair(2, 1)); prerequisites.add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { System.out.println(\"Possible to finish all tasks\"); } else { System.out.println(\"Impossible to finish all tasks\"); } }} // This code is contributed by adityapande88.", "e": 6792, "s": 4342, "text": null }, { "code": "# Python3 program to check whether we can finish all# tasks or not from given dependencies. # class to store dependencies as a pairclass pair: def __init__(self, first, second): self.first = first self.second = second # Returns adjacency list representation from a list# of pairs.def make_graph(numTasks, prerequisites): graph = [] for i in range(numTasks): graph.append([]) for pre in prerequisites: graph[pre.second].append(pre.first) return graph # A DFS based function to check if there is a cycle# in the directed graph.def dfs_cycle(graph, node, onpath, visited): if visited[node]: return false onpath[node] = visited[node] = True for neigh in graph[node]: if (onpath[neigh] or dfs_cycle(graph, neigh, onpath, visited)): return true return False # Main function to check whether possible to finish all# tasks or notdef canFinish(numTasks, prerequisites): graph = make_graph(numTasks, prerequisites) onpath = [False]*numTasks visited = [False]*numTasks for i in range(numTasks): if (not visited[i] and dfs_cycle(graph, i, onpath, visited)): return False return True # Driver code to test above functionsnumTasks = 4prerequisites = [] prerequisites.append(pair(1, 0))prerequisites.append(pair(2, 1))prerequisites.append(pair(3, 2)) if canFinish(numTasks, prerequisites): print(\"Possible to finish all tasks\")else: print(\"Impossible to finish all tasks\") # This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 8332, "s": 6792, "text": null }, { "code": "// C# program to check whether we can finish all// tasks or not from given dependencies.using System;using System.Collections.Generic; public class GFG { // class to store dependencies as a pair public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static List<List<int> > make_graph(int numTasks, List<pair> prerequisites) { List<List<int> > graph = new List<List<int> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.Add(new List<int>()); } foreach(pair pre in prerequisites) graph[pre.second] .Add(pre.first); return graph; } // A DFS based function to check if there is a cycle // in the directed graph. static bool dfs_cycle(List<List<int> > graph, int node, bool[] onpath, bool[] visited) { if (visited[node]) return false; onpath[node] = visited[node] = true; foreach( int neigh in graph[node]) if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; //onpath[node] = false; return false; } // Main function to check whether possible to finish all // tasks or not static bool canFinish(int numTasks, List<pair> prerequisites) { List<List<int> > graph = make_graph(numTasks, prerequisites); bool[] onpath = new bool[numTasks]; bool[] visited = new bool[numTasks]; for (int i = 0; i < numTasks; i++) if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; return true; } public static void Main(String[] args) { int numTasks = 4; List<pair> prerequisites = new List<pair>(); ; // for prerequisites: [[1, 0], [2, 1], [3, 2]] prerequisites.Add(new pair(1, 0)); prerequisites.Add(new pair(2, 1)); prerequisites.Add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { Console.WriteLine( \"Possible to finish all tasks\"); } else { Console.WriteLine( \"Impossible to finish all tasks\"); } }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 10840, "s": 8332, "text": null }, { "code": null, "e": 10869, "s": 10840, "text": "Possible to finish all tasks" }, { "code": null, "e": 11471, "s": 10869, "text": "Using BFS BFS can be used to solve it using the idea of topological sort. If topological sorting is possible, it means there is no cycle and it is possible to finish all the tasks.BFS uses the indegrees of each node. We will first try to find a node with 0 indegree. If we fail to do so, there must be a cycle in the graph and we return false. Otherwise we have found one. We set its indegree to be -1 to prevent from visiting it again and reduce the indegrees of all its neighbors by 1. This process will be repeated for n (number of nodes) times. If we have not returned false, we will return true. " }, { "code": null, "e": 11475, "s": 11471, "text": "CPP" }, { "code": null, "e": 11480, "s": 11475, "text": "Java" }, { "code": null, "e": 11488, "s": 11480, "text": "Python3" }, { "code": null, "e": 11491, "s": 11488, "text": "C#" }, { "code": "// A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.#include <bits/stdc++.h>using namespace std; // Returns adjacency list representation from a list// of pairs.vector<unordered_set<int> >make_graph(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph(numTasks); for (auto pre : prerequisites) graph[pre.second].insert(pre.first); return graph;} // Finds in-degree of every vertexvector<int>compute_indegree(vector<unordered_set<int> >& graph){ vector<int> degrees(graph.size(), 0); for (auto neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees;} // Main function to check whether possible to finish all// tasks or notbool canFinish(int numTasks, vector<pair<int, int> >& prerequisites){ vector<unordered_set<int> > graph = make_graph(numTasks, prerequisites); vector<int> degrees = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (!degrees[j]) break; if (j == numTasks) return false; degrees[j] = -1; for (int neigh : graph[j]) degrees[neigh]--; } return true;} int main(){ int numTasks = 4; vector<pair<int, int> > prerequisites; prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(2, 1)); prerequisites.push_back(make_pair(3, 2)); if (canFinish(numTasks, prerequisites)) { cout << \"Possible to finish all tasks\"; } else { cout << \"Impossible to finish all tasks\"; } return 0;}", "e": 13200, "s": 11491, "text": null }, { "code": "// A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.import java.util.*; public class GFG { // class to store dependencies as a pair static class pair { int first, second; pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static ArrayList<ArrayList<Integer> > make_graph(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer> > graph = new ArrayList<ArrayList<Integer> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.add(new ArrayList<Integer>()); } for (pair pre : prerequisites) graph.get(pre.second).add(pre.first); return graph; } // Finds in-degree of every vertex static int[] compute_indegree( ArrayList<ArrayList<Integer> > graph) { int degrees[] = new int[graph.size()]; for (ArrayList<Integer> neighbors : graph) for (int neigh : neighbors) degrees[neigh]++; return degrees; } // Main function to check whether possible to finish all // tasks or not static boolean canFinish(int numTasks, Vector<pair> prerequisites) { ArrayList<ArrayList<Integer> > graph = make_graph(numTasks, prerequisites); int degrees[] = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (degrees[j] == 0) break; if (j == numTasks) return false; degrees[j] = -1; for (int neigh : graph.get(j)) degrees[neigh]--; } return true; } public static void main(String args[]) { int numTasks = 4; Vector<pair> prerequisites = new Vector<pair>(); prerequisites.add(new pair(1, 0)); prerequisites.add(new pair(2, 1)); prerequisites.add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { System.out.println( \"Possible to finish all tasks\"); } else { System.out.println( \"Impossible to finish all tasks\"); } }} // This code is contributed by adityapande88.", "e": 15634, "s": 13200, "text": null }, { "code": "# A BFS based solution to check if we can finish# all tasks or not. This solution is mainly based# on Kahn's algorithm. # class to store dependencies as a pair class pair: def __init__(self, first, second): self.first = first self.second = second # Returns adjacency list representation from a list# of pairs. def make_graph(numTasks, prerequisites): graph = [] for i in range(numTasks): graph.append([]) for pre in prerequisites: graph[pre.second].append(pre.first) return graph # Finds in-degree of every vertexdef compute_indegree(graph): degrees = [0]*len(graph) for neighbors in graph: for neigh in neighbors: degrees[neigh] += 1 return degrees # Main function to check whether possible to finish all tasks or notdef canFinish(numTasks, prerequisites): graph = make_graph(numTasks, prerequisites) degrees = compute_indegree(graph) for i in range(numTasks): j = 0 while(j < numTasks): if (degrees[j] == 0): break j += 1 if (j == numTasks): return False degrees[j] = -1 for neigh in graph[j]: degrees[neigh] -= 1 return True numTasks = 4prerequisites = [] prerequisites.append(pair(1, 0))prerequisites.append(pair(2, 1))prerequisites.append(pair(3, 2)) if (canFinish(numTasks, prerequisites)): print(\"Possible to finish all tasks\")else: print(\"Impossible to finish all tasks\") # This code is contributed by Lovely Jain", "e": 17150, "s": 15634, "text": null }, { "code": "// A BFS based solution to check if we can finish// all tasks or not. This solution is mainly based// on Kahn's algorithm.using System;using System.Collections.Generic; public class GFG { // class to store dependencies as a pair public class pair { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Returns adjacency list representation from a list // of pairs. static List<List<int> > make_graph(int numTasks, List<pair> prerequisites) { List<List<int> > graph = new List<List<int> >(numTasks); for (int i = 0; i < numTasks; i++) { graph.Add(new List<int>()); } foreach(pair pre in prerequisites) graph[pre.second].Add(pre.first); return graph; } // Finds in-degree of every vertex static int[] compute_indegree( List<List<int> > graph) { int[] degrees = new int[graph.Count]; foreach(List<int> neighbors in graph) foreach(int neigh in neighbors) degrees[neigh]++; return degrees; } // Main function to check whether possible to finish all // tasks or not static bool canFinish(int numTasks, List<pair> prerequisites) { List<List<int> > graph = make_graph(numTasks, prerequisites); int[] degrees = compute_indegree(graph); for (int i = 0; i < numTasks; i++) { int j = 0; for (; j < numTasks; j++) if (degrees[j] == 0) break; if (j == numTasks) return false; degrees[j] = -1; foreach(int neigh in graph[j]) degrees[neigh]--; } return true; } public static void Main(String[] args) { int numTasks = 4; List<pair> prerequisites = new List<pair>(); prerequisites.Add(new pair(1, 0)); prerequisites.Add(new pair(2, 1)); prerequisites.Add(new pair(3, 2)); if (canFinish(numTasks, prerequisites)) { Console.WriteLine( \"Possible to finish all tasks\"); } else { Console.WriteLine( \"Impossible to finish all tasks\"); } }} // This code is contributed by Abhijeet Kumar(abhijeet19403)", "e": 19545, "s": 17150, "text": null }, { "code": null, "e": 19574, "s": 19545, "text": "Possible to finish all tasks" }, { "code": null, "e": 19633, "s": 19574, "text": "Reference: https://leetcode.com/problems/course-schedule/ " }, { "code": null, "e": 19651, "s": 19633, "text": "Using Union-find " }, { "code": null, "e": 19798, "s": 19651, "text": "Another approach which is Union-find method can also be used to solve this problem. Each pair we get can be considered in a parent-child relation." }, { "code": null, "e": 20067, "s": 19798, "text": " As soon as we find a pair of tasks which are supposed to be in a parent-child relation, we check if they already have a common parent and hence it means there is a dependency cycle in the tasks which will never end and hence solving such set of tasks is not possible." }, { "code": null, "e": 20073, "s": 20067, "text": "C++14" }, { "code": null, "e": 20078, "s": 20073, "text": "Java" }, { "code": null, "e": 20086, "s": 20078, "text": "Python3" }, { "code": null, "e": 20089, "s": 20086, "text": "C#" }, { "code": "/* * A union-find based solution for stating whether * the given set of tasks with respective prerequisites * can be finished completely or not. */#include <bits/stdc++.h>using namespace std;class Solution { // returns true/false stating whether tasks can be // finished or not vector<int> arr; public: Solution(int n) { arr.resize(n); // Initially, everyone is their own child for (int i = 0; i < n; i++) arr[i] = i; } void makeParent(int a, int b) { // find parent of b and make it a's parent arr[a] = findParent(b); } int findParent(int c) { // when an independent task is found if (c == arr) return c; // recursively find the parent of given task return findParent(arr); } bool isPossible(int N, vector<vector<int> > prerequisites) { // traverse through pre-requisites array for (int i = 0; i < prerequisites.size(); i++) { // check whether given pre-requisite pair // already have a common pre-requisite(parent) if (findParent(prerequisites[i][0]) == findParent(prerequisites[i][1])) { // tasks cannot be completed because there // was a cyclic condition in the tasks return false; } // make parent-child relation between // pre-requisite task and the task dependent on // it makeParent(prerequisites[i][0], prerequisites[i][1]); } // if there was no cycle found, tasks can be // completed return true; }}; // Driver code int main(){ vector<vector<int> > prerequisites{ { 1, 0 }, { 2, 1 }, { 3, 2 } }; Solution ob(4); if (ob.isPossible(4, prerequisites)) { cout << \"Yes\"; } else { cout << \"No\"; }} // Driver Code Ends // This code was contributed by Abhijeet Kumar(abhijeet19403)", "e": 22151, "s": 20089, "text": null }, { "code": "/** A union-find based solution for stating whether* the given set of tasks with respective prerequisites* can be finished completely or not.*/import java.io.*;import java.util.*; //Driver codeclass GFG { public static void main(String args[]) throws IOException { int prerequisites[][] = new int[][]{ {1,0}, {2,1}, {3,2} }; Solution ob = new Solution(); if(ob.isPossible(4, prerequisites)) { System.out.println(\"Yes\"); } else{ System.out.println(\"No\"); } }}//Driver Code Ends //Solution codeclass Solution { //returns true/false stating whether tasks can be finished or not public boolean isPossible(int N, int[][] prerequisites) { //make object of Union class for N tasks Union u = new Union(N); //traverse through pre-requisites array for(int i = 0; i < prerequisites.length; i++){ //check whether given pre-requisite pair //already have a common pre-requisite(parent) if(u.findParent(prerequisites[i][0]) == u.findParent(prerequisites[i][1])) { //tasks cannot be completed because there was //a cyclic condition in the tasks return false; } //make parent-child relation between pre-requisite task //and the task dependent on it u.makeParent(prerequisites[i][0], prerequisites[i][1]); } //if there was no cycle found, tasks can be completed return true; } }class Union { //to store the parents of respective tasks int[] arr; //parameterized constructor for Union class public Union(int n){ arr = new int[n]; //Initially, everyone is their own child for(int i = 0; i < n; i++){ arr[i] = i; } } public void makeParent(int a, int b){ //find parent of b and make it a's parent arr[a] = findParent(b); } public int findParent(int c){ //when an independent task is found if(c == arr) return c; //recursively find the parent of given task return findParent(arr); }}", "e": 24423, "s": 22151, "text": null }, { "code": "# A union-find based solution for stating whether# the given set of tasks with respective prerequisites# can be finished completely or not.class Solution: arr = [] # parameterized constructor def __init__(self,n): # Initially, everyone is their own child self.arr = [i for i in range(n)] def makeParent(self,a, b): # find parent of b and make it a's parent self.arr[a] = self.findParent(b) def findParent(self,c): # when an independent task is found if (c == self.arr): return c # recursively find the parent of given task return self.findParent(self.arr) def isPossible(self,N , prerequisites): # traverse through pre-requisites array for i in range(len(prerequisites)): # check whether given pre-requisite pair # already have a common pre-requisite(parent) if (self.findParent(prerequisites[i][0]) == self.findParent(prerequisites[i][1])): # tasks cannot be completed because there # was a cyclic condition in the tasks return false # make parent-child relation between # pre-requisite task and the task dependent on # it self.makeParent(prerequisites[i][0], prerequisites[i][1]) # if there was no cycle found, tasks can be # completed return True # Driver codeprerequisites = [[1, 0], [2, 1], [3, 2]] ob = Solution(4) if ob.isPossible(4,prerequisites ): print(\"Yes\")else: print(\"No\") # Driver Code Ends # This code was contributed by Abhijeet Kumar(abhijeet19403)", "e": 26043, "s": 24423, "text": null }, { "code": "/** A union-find based solution for stating whether* the given set of tasks with respective prerequisites* can be finished completely or not.*/using System;using System.Collections.Generic; //Solution code public class Solution { //returns true/false stating whether tasks can be finished or not public bool isPossible(int N, int[,] prerequisites) { //make object of Union class for N tasks Union u = new Union(N); //traverse through pre-requisites array for(int i = 0; i < prerequisites.Length/2; i++){ //check whether given pre-requisite pair //already have a common pre-requisite(parent) if(u.findParent(prerequisites[i,0]) == u.findParent(prerequisites[i,1])) { //tasks cannot be completed because there was //a cyclic condition in the tasks return false; } //make parent-child relation between pre-requisite task //and the task dependent on it u.makeParent(prerequisites[i,0], prerequisites[i,1]); } //if there was no cycle found, tasks can be completed return true; } } public class Union { //to store the parents of respective tasks int[] arr; //parameterized constructor for Union class public Union(int n){ arr = new int[n]; //Initially, everyone is their own child for(int i = 0; i < n; i++){ arr[i] = i; } } public void makeParent(int a, int b){ //find parent of b and make it a's parent arr[a] = findParent(b); } public int findParent(int c){ //when an independent task is found if(c == arr) return c; //recursively find the parent of given task return findParent(arr); }} //Driver code class GFG { public static void Main(String[] args) { int[,] prerequisites = new int[,]{ {1,0}, {2,1}, {3,2} }; Solution ob = new Solution(); if(ob.isPossible(4, prerequisites)) { Console.WriteLine(\"Yes\"); } else{ Console.WriteLine(\"No\"); } }}//Driver Code Ends // This code was contributed by Abhijeet Kumar(abhijeet19403)", "e": 28374, "s": 26043, "text": null }, { "code": null, "e": 28378, "s": 28374, "text": "Yes" }, { "code": null, "e": 28392, "s": 28378, "text": "adityapande88" }, { "code": null, "e": 28404, "s": 28392, "text": "anikaseth98" }, { "code": null, "e": 28420, "s": 28404, "text": "vishal0171cse19" }, { "code": null, "e": 28429, "s": 28420, "text": "rkbhola5" }, { "code": null, "e": 28443, "s": 28429, "text": "jainlovely450" }, { "code": null, "e": 28457, "s": 28443, "text": "abhijeet19403" }, { "code": null, "e": 28461, "s": 28457, "text": "BFS" }, { "code": null, "e": 28465, "s": 28461, "text": "DFS" }, { "code": null, "e": 28477, "s": 28465, "text": "graph-cycle" }, { "code": null, "e": 28501, "s": 28477, "text": "Technical Scripter 2018" }, { "code": null, "e": 28521, "s": 28501, "text": "Topological Sorting" }, { "code": null, "e": 28527, "s": 28521, "text": "Graph" }, { "code": null, "e": 28546, "s": 28527, "text": "Technical Scripter" }, { "code": null, "e": 28550, "s": 28546, "text": "DFS" }, { "code": null, "e": 28556, "s": 28550, "text": "Graph" }, { "code": null, "e": 28560, "s": 28556, "text": "BFS" } ]
Matplotlib.figure.Figure.subplots() in Python
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The subplots() method figure module of matplotlib library is used to display the figure window. Syntax: subplots(self, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None) Parameters: This method accept the following parameters that are described below: nrows, ncols : These parameter are the number of rows/columns of the subplot grid. sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes. squeeze : This parameter is an optional parameter and it contains boolean value with default as True. num: This parameter is the pyplot.figure keyword that sets the figure number or label. subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot. gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns: This method return the following values. ax : This method return the axes.Axes object or array of Axes objects. Below examples illustrate the matplotlib.figure.Figure.subplots() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2) fig = plt.figure()ax = fig.subplots() ax.plot(x, y) fig.suptitle("""matplotlib.figure.Figure.subplots()function Example\n\n""", fontweight ="bold") fig.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2) fig = plt.figure()axs = fig.subplots(2, 2, subplot_kw = dict(polar = True)) axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y) fig.suptitle("""matplotlib.figure.Figure.subplots()function Example\n\n""", fontweight ="bold") fig.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 435, "s": 339, "text": "The subplots() method figure module of matplotlib library is used to display the figure window." }, { "code": null, "e": 553, "s": 435, "text": "Syntax: subplots(self, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)" }, { "code": null, "e": 635, "s": 553, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 718, "s": 635, "text": "nrows, ncols : These parameter are the number of rows/columns of the subplot grid." }, { "code": null, "e": 819, "s": 718, "text": "sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes." }, { "code": null, "e": 921, "s": 819, "text": "squeeze : This parameter is an optional parameter and it contains boolean value with default as True." }, { "code": null, "e": 1008, "s": 921, "text": "num: This parameter is the pyplot.figure keyword that sets the figure number or label." }, { "code": null, "e": 1122, "s": 1008, "text": "subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot." }, { "code": null, "e": 1263, "s": 1122, "text": "gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on." }, { "code": null, "e": 1313, "s": 1263, "text": "Returns: This method return the following values." }, { "code": null, "e": 1384, "s": 1313, "text": "ax : This method return the axes.Axes object or array of Axes objects." }, { "code": null, "e": 1481, "s": 1384, "text": "Below examples illustrate the matplotlib.figure.Figure.subplots() function in matplotlib.figure:" }, { "code": null, "e": 1492, "s": 1481, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2) fig = plt.figure()ax = fig.subplots() ax.plot(x, y) fig.suptitle(\"\"\"matplotlib.figure.Figure.subplots()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ", "e": 1802, "s": 1492, "text": null }, { "code": null, "e": 1810, "s": 1802, "text": "Output:" }, { "code": null, "e": 1821, "s": 1810, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2) fig = plt.figure()axs = fig.subplots(2, 2, subplot_kw = dict(polar = True)) axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y) fig.suptitle(\"\"\"matplotlib.figure.Figure.subplots()function Example\\n\\n\"\"\", fontweight =\"bold\") fig.show() ", "e": 2214, "s": 1821, "text": null }, { "code": null, "e": 2222, "s": 2214, "text": "Output:" }, { "code": null, "e": 2246, "s": 2222, "text": "Matplotlib figure-class" }, { "code": null, "e": 2264, "s": 2246, "text": "Python-matplotlib" }, { "code": null, "e": 2271, "s": 2264, "text": "Python" } ]
JavaScript SyntaxError – Unexpected token
31 Jul, 2020 This JavaScript exceptions unexpected token occur if a specific language construct was expected, but anything else is typed mistakenly. This could be a simple typing mistake. Message: SyntaxError: expected expression, got "x" SyntaxError: expected property name, got "x" SyntaxError: expected target, got "x" SyntaxError: expected rest argument name, got "x" SyntaxError: expected closing parenthesis, got "x" SyntaxError: expected '=>' after argument list, got "x" Error Type: SyntaxError Cause of Error: There is a simple typing mistake in the code. Example 1: HTML <!DOCTYPE html><html><head> <title>Unexpected Token Error</title></head><body> <script> for (let i = 0; i < 5; ++i) { document.write(i); } </script></body></html> Output: 01234 Example 2: There is a typing mistake in the code, So the error occurred. HTML <!DOCTYPE html><html><head> <title>Unexpected Token Error</title></head><body> <script> for (let i = 0; i < 5,; ++i) { document.write(i); } </script></body></html> Output(in console): SyntaxError: Unexpected token ';' javascript-basics JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2020" }, { "code": null, "e": 203, "s": 28, "text": "This JavaScript exceptions unexpected token occur if a specific language construct was expected, but anything else is typed mistakenly. This could be a simple typing mistake." }, { "code": null, "e": 212, "s": 203, "text": "Message:" }, { "code": null, "e": 497, "s": 212, "text": "SyntaxError: expected expression, got \"x\"\nSyntaxError: expected property name, got \"x\" \nSyntaxError: expected target, got \"x\"\nSyntaxError: expected rest argument name, got \"x\"\nSyntaxError: expected closing parenthesis, got \"x\"\nSyntaxError: expected '=>' after argument list, got \"x\"\n\n" }, { "code": null, "e": 509, "s": 497, "text": "Error Type:" }, { "code": null, "e": 522, "s": 509, "text": "SyntaxError\n" }, { "code": null, "e": 584, "s": 522, "text": "Cause of Error: There is a simple typing mistake in the code." }, { "code": null, "e": 595, "s": 584, "text": "Example 1:" }, { "code": null, "e": 600, "s": 595, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Unexpected Token Error</title></head><body> <script> for (let i = 0; i < 5; ++i) { document.write(i); } </script></body></html>", "e": 796, "s": 600, "text": null }, { "code": null, "e": 804, "s": 796, "text": "Output:" }, { "code": null, "e": 811, "s": 804, "text": "01234\n" }, { "code": null, "e": 884, "s": 811, "text": "Example 2: There is a typing mistake in the code, So the error occurred." }, { "code": null, "e": 889, "s": 884, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Unexpected Token Error</title></head><body> <script> for (let i = 0; i < 5,; ++i) { document.write(i); } </script></body></html>", "e": 1086, "s": 889, "text": null }, { "code": null, "e": 1106, "s": 1086, "text": "Output(in console):" }, { "code": null, "e": 1141, "s": 1106, "text": "SyntaxError: Unexpected token ';'\n" }, { "code": null, "e": 1159, "s": 1141, "text": "javascript-basics" }, { "code": null, "e": 1170, "s": 1159, "text": "JavaScript" }, { "code": null, "e": 1187, "s": 1170, "text": "Web Technologies" } ]
Python | Pandas Series.transpose()
05 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.transpose() function return the transpose, which is by definition self. Syntax: Series.transpose(*args, **kwargs) Parameter : None Returns : self Example #1: Use Series.transpose() function to find the transpose of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr) Output : Now we will use Series.transpose() function to find the transpose of the given series object. # find the transposesr.transpose() Output : As we can see in the output, the Series.transpose() function has returned the same object as the transpose of the given series object, which is by definition self. Example #2: Use Dataframe.transpose() function to find the transpose of the given Dataframe. # importing pandas as pdimport pandas as pd # Creating the Dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Print the dataframeprint(df) Output : Now we will use Dataframe.transpose() function to find the transpose of the given Dataframe. # find the transposedf.transpose() Output : As we can see in the output, the Dataframe.transpose() function has successfully returned the transpose of the given Dataframe object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 371, "s": 285, "text": "Pandas Series.transpose() function return the transpose, which is by definition self." }, { "code": null, "e": 413, "s": 371, "text": "Syntax: Series.transpose(*args, **kwargs)" }, { "code": null, "e": 430, "s": 413, "text": "Parameter : None" }, { "code": null, "e": 445, "s": 430, "text": "Returns : self" }, { "code": null, "e": 539, "s": 445, "text": "Example #1: Use Series.transpose() function to find the transpose of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)", "e": 891, "s": 539, "text": null }, { "code": null, "e": 900, "s": 891, "text": "Output :" }, { "code": null, "e": 994, "s": 900, "text": "Now we will use Series.transpose() function to find the transpose of the given series object." }, { "code": "# find the transposesr.transpose()", "e": 1029, "s": 994, "text": null }, { "code": null, "e": 1038, "s": 1029, "text": "Output :" }, { "code": null, "e": 1295, "s": 1038, "text": "As we can see in the output, the Series.transpose() function has returned the same object as the transpose of the given series object, which is by definition self. Example #2: Use Dataframe.transpose() function to find the transpose of the given Dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'], 'Event':['Music', 'Poetry', 'Theatre', 'Comedy'], 'Cost':[10000, 5000, 15000, 2000]}) # Print the dataframeprint(df)", "e": 1600, "s": 1295, "text": null }, { "code": null, "e": 1609, "s": 1600, "text": "Output :" }, { "code": null, "e": 1702, "s": 1609, "text": "Now we will use Dataframe.transpose() function to find the transpose of the given Dataframe." }, { "code": "# find the transposedf.transpose()", "e": 1737, "s": 1702, "text": null }, { "code": null, "e": 1746, "s": 1737, "text": "Output :" }, { "code": null, "e": 1881, "s": 1746, "text": "As we can see in the output, the Dataframe.transpose() function has successfully returned the transpose of the given Dataframe object." }, { "code": null, "e": 1902, "s": 1881, "text": "Python pandas-series" }, { "code": null, "e": 1931, "s": 1902, "text": "Python pandas-series-methods" }, { "code": null, "e": 1945, "s": 1931, "text": "Python-pandas" }, { "code": null, "e": 1952, "s": 1945, "text": "Python" } ]
Indexing Multi-dimensional arrays in Python using NumPy
05 Aug, 2021 NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It contains various features.Note: For more information, refer to Python NumpyExample: Python3 # numpy library importedimport numpy as np # creating single-dimensional arrayarr_s = np.arrange(5)print(arr_s) Output: [0 1 2 3 4] arrange() method in numpy creates single dimension array of length 5. Single parameter inside the arrange() method acts as the end element for the range. arrange() also takes start and end arguments with steps. Example: Python3 import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b) Output: [20 22 24 26 28] Indexing these arrays is simple. Every array element has a particular index associated with them. Indexing starts at 0 and goes on till the length of array-1. In the previous example, arr_b has 5 elements within itself. Accessing these elements can be done with: array_name[index_number] Example: Python3 import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b) print(arr_b[2]) # Slicing operation from index# 1 to 3print(arr_b[1:4]) Output [20 22 24 26 28] 24 [22 24 26] For Multidimensional array you can use reshape() method along with arrange() Python3 import numpy as np arr_m = np.arrange(12).reshape(6, 2)print(arr_m) Output: [[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9] [10 11]] Inside reshape() the parameters should be the multiple of the arrange() parameter. In our previous example, we had 6 rows and 2 columns. You can specify another parameter whereby you define the dimension of the array. By default, it is an 2d array. Example: Python3 import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3)print(arr_m) Output [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] To index a multi-dimensional array you can index with slicing operation similar to a single dimension array.Example: Python3 import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3) # Indexingprint(arr_m[0:3])print()print(arr_m[1:5:2,::3]) Output: [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] [[[6 7 8]]] saurabh1990aror Python numpy-Indexing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Aug, 2021" }, { "code": null, "e": 364, "s": 52, "text": "NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It contains various features.Note: For more information, refer to Python NumpyExample: " }, { "code": null, "e": 372, "s": 364, "text": "Python3" }, { "code": "# numpy library importedimport numpy as np # creating single-dimensional arrayarr_s = np.arrange(5)print(arr_s)", "e": 484, "s": 372, "text": null }, { "code": null, "e": 494, "s": 484, "text": "Output: " }, { "code": null, "e": 506, "s": 494, "text": "[0 1 2 3 4]" }, { "code": null, "e": 727, "s": 506, "text": "arrange() method in numpy creates single dimension array of length 5. Single parameter inside the arrange() method acts as the end element for the range. arrange() also takes start and end arguments with steps. Example: " }, { "code": null, "e": 735, "s": 727, "text": "Python3" }, { "code": "import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b)", "e": 943, "s": 735, "text": null }, { "code": null, "e": 952, "s": 943, "text": "Output: " }, { "code": null, "e": 969, "s": 952, "text": "[20 22 24 26 28]" }, { "code": null, "e": 1234, "s": 969, "text": "Indexing these arrays is simple. Every array element has a particular index associated with them. Indexing starts at 0 and goes on till the length of array-1. In the previous example, arr_b has 5 elements within itself. Accessing these elements can be done with: " }, { "code": null, "e": 1259, "s": 1234, "text": "array_name[index_number]" }, { "code": null, "e": 1270, "s": 1259, "text": "Example: " }, { "code": null, "e": 1278, "s": 1270, "text": "Python3" }, { "code": "import numpy as np # here inside arrange method we# provide start, end, step as# arguments.arr_b = np.arrange(20, 30, 2) # step argument helps in printing# every said step and skipping the# rest.print(arr_b) print(arr_b[2]) # Slicing operation from index# 1 to 3print(arr_b[1:4])", "e": 1559, "s": 1278, "text": null }, { "code": null, "e": 1567, "s": 1559, "text": "Output " }, { "code": null, "e": 1598, "s": 1567, "text": "[20 22 24 26 28]\n24\n[22 24 26]" }, { "code": null, "e": 1677, "s": 1598, "text": "For Multidimensional array you can use reshape() method along with arrange() " }, { "code": null, "e": 1685, "s": 1677, "text": "Python3" }, { "code": "import numpy as np arr_m = np.arrange(12).reshape(6, 2)print(arr_m)", "e": 1753, "s": 1685, "text": null }, { "code": null, "e": 1763, "s": 1753, "text": "Output: " }, { "code": null, "e": 1818, "s": 1763, "text": "[[ 0 1]\n [ 2 3]\n [ 4 5]\n [ 6 7]\n [ 8 9]\n [10 11]]" }, { "code": null, "e": 2077, "s": 1818, "text": "Inside reshape() the parameters should be the multiple of the arrange() parameter. In our previous example, we had 6 rows and 2 columns. You can specify another parameter whereby you define the dimension of the array. By default, it is an 2d array. Example: " }, { "code": null, "e": 2085, "s": 2077, "text": "Python3" }, { "code": "import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3)print(arr_m)", "e": 2156, "s": 2085, "text": null }, { "code": null, "e": 2165, "s": 2156, "text": "Output " }, { "code": null, "e": 2221, "s": 2165, "text": "[[[ 0 1 2]\n [ 3 4 5]]\n\n [[ 6 7 8]\n [ 9 10 11]]]" }, { "code": null, "e": 2339, "s": 2221, "text": "To index a multi-dimensional array you can index with slicing operation similar to a single dimension array.Example: " }, { "code": null, "e": 2347, "s": 2339, "text": "Python3" }, { "code": "import numpy as np arr_m = np.arrange(12).reshape(2, 2, 3) # Indexingprint(arr_m[0:3])print()print(arr_m[1:5:2,::3])", "e": 2464, "s": 2347, "text": null }, { "code": null, "e": 2473, "s": 2464, "text": "Output: " }, { "code": null, "e": 2542, "s": 2473, "text": "[[[ 0 1 2]\n [ 3 4 5]]\n\n [[ 6 7 8]\n [ 9 10 11]]]\n\n[[[6 7 8]]]" }, { "code": null, "e": 2560, "s": 2544, "text": "saurabh1990aror" }, { "code": null, "e": 2582, "s": 2560, "text": "Python numpy-Indexing" }, { "code": null, "e": 2589, "s": 2582, "text": "Python" } ]
Python | Pandas Index.intersection()
17 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.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the index and other, preserving the order of the calling index. Syntax: Index.intersection(other) Parameters :other : Index or array-like Returns : intersection : Index Example #1: Use Index.intersection() function to find the set intersection of two Indexes. # importing pandas as pdimport pandas as pd # Creating the first Indexidx1 = pd.Index(['Labrador', 'Beagle', 'Mastiff', 'Lhasa', 'Husky', 'Beagle']) # Creating the second Indexidx2 = pd.Index(['Labrador', 'Great_Dane', 'Pug', 'German_sepherd', 'Husky', 'Pitbull']) # Print the first and second Indexprint(idx1, '\n', idx2) Output : Now we find the set intersection of the two Indexes. # Find the elements common to both the Indexesidx2.intersection(idx1) Output : As we can see in the output, the Index.intersection() function has returned the intersection of the two indexes. The ordering of the labels has been maintained based on the calling Index. Example #2: Use Index.intersection() function to find the set intersection of two Indexes. The Index contains NaN values. # importing pandas as pdimport pandas as pd # Creating the first Indexidx1 = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', '2014-02-11']) # Creating the second Indexidx2 = pd.Index(['2015-10-31', '2015-10-02', '2018-01-03', '2016-02-08', '2017-06-05', '2014-07-11', None]) # Print the first and second Indexprint(idx1, '\n', idx2) Output : Now we find the intersection of idx1 and idx2. # find intersection and maintain # ordering of labels based on idx1idx1.intersection(idx2) Output :Note : The missing values in both the indexes are considered common to each other. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 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": 436, "s": 242, "text": "Pandas Index.intersection() function form the intersection of two Index objects. This returns a new Index with elements common to the index and other, preserving the order of the calling index." }, { "code": null, "e": 470, "s": 436, "text": "Syntax: Index.intersection(other)" }, { "code": null, "e": 510, "s": 470, "text": "Parameters :other : Index or array-like" }, { "code": null, "e": 541, "s": 510, "text": "Returns : intersection : Index" }, { "code": null, "e": 632, "s": 541, "text": "Example #1: Use Index.intersection() function to find the set intersection of two Indexes." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first Indexidx1 = pd.Index(['Labrador', 'Beagle', 'Mastiff', 'Lhasa', 'Husky', 'Beagle']) # Creating the second Indexidx2 = pd.Index(['Labrador', 'Great_Dane', 'Pug', 'German_sepherd', 'Husky', 'Pitbull']) # Print the first and second Indexprint(idx1, '\\n', idx2)", "e": 989, "s": 632, "text": null }, { "code": null, "e": 998, "s": 989, "text": "Output :" }, { "code": null, "e": 1051, "s": 998, "text": "Now we find the set intersection of the two Indexes." }, { "code": "# Find the elements common to both the Indexesidx2.intersection(idx1)", "e": 1121, "s": 1051, "text": null }, { "code": null, "e": 1130, "s": 1121, "text": "Output :" }, { "code": null, "e": 1440, "s": 1130, "text": "As we can see in the output, the Index.intersection() function has returned the intersection of the two indexes. The ordering of the labels has been maintained based on the calling Index. Example #2: Use Index.intersection() function to find the set intersection of two Indexes. The Index contains NaN values." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first Indexidx1 = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03', '2016-02-08', '2017-05-05', '2014-02-11']) # Creating the second Indexidx2 = pd.Index(['2015-10-31', '2015-10-02', '2018-01-03', '2016-02-08', '2017-06-05', '2014-07-11', None]) # Print the first and second Indexprint(idx1, '\\n', idx2)", "e": 1846, "s": 1440, "text": null }, { "code": null, "e": 1855, "s": 1846, "text": "Output :" }, { "code": null, "e": 1902, "s": 1855, "text": "Now we find the intersection of idx1 and idx2." }, { "code": "# find intersection and maintain # ordering of labels based on idx1idx1.intersection(idx2)", "e": 1993, "s": 1902, "text": null }, { "code": null, "e": 2084, "s": 1993, "text": "Output :Note : The missing values in both the indexes are considered common to each other." }, { "code": null, "e": 2107, "s": 2084, "text": "Python pandas-indexing" }, { "code": null, "e": 2121, "s": 2107, "text": "Python-pandas" }, { "code": null, "e": 2128, "s": 2121, "text": "Python" } ]
Unbounded Knapsack (Repetition of items allowed) | Set 2
21 Jul, 2021 Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W.Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explaination: The maximum value that can be obtained is 18, by selecting the 2nd item twice. Input: W = 50, val[] = {6, 18}, wt[] = {2, 3}Output: 294 Naive Approach: Refer to the previous post to solve the problem using traditional Unbounded Knapsack algorithm.Time Complexity: O(N * W)Auxiliary Space: O(W) Efficient Approach: The above approach can be optimized based on the following observations: Suppose the ith index gives us the maximum value per unit weight in the given data, which can be easily found in O(n). For any weight X, greater than or equal to wt[i], the maximum reachable value will be dp[X – wt[i]] + val[i]. We can calculate the values of dp[] from 0 to wt[i] using the traditional algorithm and we can also calculate the number of instances of ith item we can fit in W weight. So the required answer will be val[i] * (W/wt[i]) + dp[W%wt[i]]. Below is the implementation of new algorithm. Python3 # Python Program to implement the above approach from fractions import Fraction # Function to implement optimized# Unbounded Knapsack algorithmdef unboundedKnapsackBetter(W, val, wt): # Stores most dense item maxDenseIndex = 0 # Find the item with highest unit value # (if two items have same unit value then choose the lighter item) for i in range(1, len(val)): if Fraction(val[i], wt[i]) \ > Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \ or (Fraction(val[i], wt[i]) == Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \ and wt[i] < wt[maxDenseIndex] ): maxDenseIndex = i dp = [0 for i in range(W + 1)] counter = 0 breaked = False for i in range(W + 1): for j in range(len(wt)): if (wt[j] <= i): dp[i] = max(dp[i], dp[i - wt[j]] + val[j]) if i - wt[maxDenseIndex] >= 0 \ and dp[i] - dp[i-wt[maxDenseIndex]] == val[maxDenseIndex]: counter += 1 if counter>= wt[maxDenseIndex]: breaked = True # print(i) break else: counter = 0 if not breaked: return dp[W] else: start = i - wt[maxDenseIndex] + 1 times = (W - start) // wt[maxDenseIndex] index = (W - start) % wt[maxDenseIndex] + start return (times * val[maxDenseIndex] + dp[index]) # Driver CodeW = 100val = [10, 30, 20]wt = [5, 10, 15] print(unboundedKnapsackBetter(W, val, wt)) 300 Time Complexity: O( N + min(wt[i], W) * N)Auxiliary Space: O(W) knapsack Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jul, 2021" }, { "code": null, "e": 308, "s": 54, "text": "Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W.Note: Each weight can be included multiple times." }, { "code": null, "e": 318, "s": 308, "text": "Examples:" }, { "code": null, "e": 465, "s": 318, "text": "Input: W = 4, val[] = {6, 18}, wt[] = {2, 3}Output: 18Explaination: The maximum value that can be obtained is 18, by selecting the 2nd item twice." }, { "code": null, "e": 522, "s": 465, "text": "Input: W = 50, val[] = {6, 18}, wt[] = {2, 3}Output: 294" }, { "code": null, "e": 680, "s": 522, "text": "Naive Approach: Refer to the previous post to solve the problem using traditional Unbounded Knapsack algorithm.Time Complexity: O(N * W)Auxiliary Space: O(W)" }, { "code": null, "e": 774, "s": 680, "text": "Efficient Approach: The above approach can be optimized based on the following observations:" }, { "code": null, "e": 893, "s": 774, "text": "Suppose the ith index gives us the maximum value per unit weight in the given data, which can be easily found in O(n)." }, { "code": null, "e": 1003, "s": 893, "text": "For any weight X, greater than or equal to wt[i], the maximum reachable value will be dp[X – wt[i]] + val[i]." }, { "code": null, "e": 1173, "s": 1003, "text": "We can calculate the values of dp[] from 0 to wt[i] using the traditional algorithm and we can also calculate the number of instances of ith item we can fit in W weight." }, { "code": null, "e": 1239, "s": 1173, "text": "So the required answer will be val[i] * (W/wt[i]) + dp[W%wt[i]]. " }, { "code": null, "e": 1286, "s": 1239, "text": "Below is the implementation of new algorithm." }, { "code": null, "e": 1294, "s": 1286, "text": "Python3" }, { "code": "# Python Program to implement the above approach from fractions import Fraction # Function to implement optimized# Unbounded Knapsack algorithmdef unboundedKnapsackBetter(W, val, wt): # Stores most dense item maxDenseIndex = 0 # Find the item with highest unit value # (if two items have same unit value then choose the lighter item) for i in range(1, len(val)): if Fraction(val[i], wt[i]) \\ > Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \\ or (Fraction(val[i], wt[i]) == Fraction(val[maxDenseIndex], wt[maxDenseIndex]) \\ and wt[i] < wt[maxDenseIndex] ): maxDenseIndex = i dp = [0 for i in range(W + 1)] counter = 0 breaked = False for i in range(W + 1): for j in range(len(wt)): if (wt[j] <= i): dp[i] = max(dp[i], dp[i - wt[j]] + val[j]) if i - wt[maxDenseIndex] >= 0 \\ and dp[i] - dp[i-wt[maxDenseIndex]] == val[maxDenseIndex]: counter += 1 if counter>= wt[maxDenseIndex]: breaked = True # print(i) break else: counter = 0 if not breaked: return dp[W] else: start = i - wt[maxDenseIndex] + 1 times = (W - start) // wt[maxDenseIndex] index = (W - start) % wt[maxDenseIndex] + start return (times * val[maxDenseIndex] + dp[index]) # Driver CodeW = 100val = [10, 30, 20]wt = [5, 10, 15] print(unboundedKnapsackBetter(W, val, wt))", "e": 2922, "s": 1294, "text": null }, { "code": null, "e": 2927, "s": 2922, "text": "300\n" }, { "code": null, "e": 2991, "s": 2927, "text": "Time Complexity: O( N + min(wt[i], W) * N)Auxiliary Space: O(W)" }, { "code": null, "e": 3000, "s": 2991, "text": "knapsack" }, { "code": null, "e": 3020, "s": 3000, "text": "Dynamic Programming" }, { "code": null, "e": 3033, "s": 3020, "text": "Mathematical" }, { "code": null, "e": 3053, "s": 3033, "text": "Dynamic Programming" }, { "code": null, "e": 3066, "s": 3053, "text": "Mathematical" } ]
Enumeration vs Iterator vs ListIterator in Java
02 Sep, 2020 Enumeration is an interface. It is used in the collection framework in java to retrieve the elements one by one. Enumeration is a legacy interface that is applicable only for legacy classes like Vector, HashTable, Stack, etc. It provides a single direction iteration. By using enumeration, we can perform only read operation, and we cannot perform remove operation. Enumeration object can be created by calling elements() method present in the Vector class. // Here "v" is a vector object. enum is of // type Enumeration interface and refers to "v" Enumeration enum = v.elements(); An iterator is a universal cursor that can be applied to any collection object. It provides a single direction iteration. By using an iterator, we can perform both read and remove operation, but we cannot perform replace operation. Iterator must be used whenever we want to enumerate elements in all collection framework implemented interfaces like Set, List, Queue, DeQue, and also implemented classes of Map interface. Iterator object can be created by calling iterator() method present in the Collection interface // Here "c" is any collection object. itr is of // type Iterator interface and refers to "c" Iterator itr = c.iterator(); ListIterator is the most powerful cursor among all the three cursors. ListIterator is only applicable for list implemented classes like ArrayList, LinkedList, Stack, etc. ListIterator traverses both in the forward and backward direction. By using ListIteartor, we can perform read, remove, and replace operation. The ListIterator must be used when we want to enumerate elements of the list. ListIterator object can be created by calling listIterator() method present in the list interface. // Here "l" is any list object. ltr is of // type ListIterator interface and refers to "l" ListIterator ltr = l.listIterator(); Java // A Java program to demonstrates the // difference between Enumeration,// Iterator, and ListIterator import java.io.*;import java.util.*; class GFG { public static void main(String args[]) { // Creating a vector object Vector<Integer> v = new Vector<Integer>(); // Adding elements to the vector object v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); System.out.println("Enumeration: "); // Creating an Enumeration object Enumeration e = v.elements(); // Checking the next element availability while (e.hasMoreElements()) { // Moving cursor to the next element int i = (Integer)e.nextElement(); // Printing the element System.out.print(i + " "); } System.out.println(); System.out.println(); System.out.println("Iterator: "); // Creating Iterator object Iterator<Integer> itr = v.iterator(); // Checking the next element availability while (itr.hasNext()) { // Moving cursor to the next element int i = (Integer)itr.next(); // Checking if i == 10 then // remove the element if (i == 10) itr.remove(); } System.out.println(v); System.out.println(); System.out.println("ListIterator: "); // Creating ListIterator object ListIterator<Integer> ltr = v.listIterator(); // Checking the next element availability while (ltr.hasNext()) { // Moving cursor to the next element int i = (Integer)ltr.next(); // Performing add, remove, and // replace operation if (i == 20) ltr.remove(); else if (i == 30) ltr.add(60); else if (i == 40) ltr.set(100); } System.out.println(v); }} Enumeration: 10 20 30 40 50 Iterator: [20, 30, 40, 50] ListIterator: [30, 60, 100, 50] Table showing the Difference between Enumeration, Iterator, and ListIterator Java-Enumeration Java-Iterator Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Sep, 2020" }, { "code": null, "e": 418, "s": 52, "text": "Enumeration is an interface. It is used in the collection framework in java to retrieve the elements one by one. Enumeration is a legacy interface that is applicable only for legacy classes like Vector, HashTable, Stack, etc. It provides a single direction iteration. By using enumeration, we can perform only read operation, and we cannot perform remove operation." }, { "code": null, "e": 510, "s": 418, "text": "Enumeration object can be created by calling elements() method present in the Vector class." }, { "code": null, "e": 635, "s": 510, "text": "// Here \"v\" is a vector object. enum is of\n// type Enumeration interface and refers to \"v\"\nEnumeration enum = v.elements();\n" }, { "code": null, "e": 1056, "s": 635, "text": "An iterator is a universal cursor that can be applied to any collection object. It provides a single direction iteration. By using an iterator, we can perform both read and remove operation, but we cannot perform replace operation. Iterator must be used whenever we want to enumerate elements in all collection framework implemented interfaces like Set, List, Queue, DeQue, and also implemented classes of Map interface." }, { "code": null, "e": 1152, "s": 1056, "text": "Iterator object can be created by calling iterator() method present in the Collection interface" }, { "code": null, "e": 1275, "s": 1152, "text": "// Here \"c\" is any collection object. itr is of\n// type Iterator interface and refers to \"c\"\nIterator itr = c.iterator();\n" }, { "code": null, "e": 1666, "s": 1275, "text": "ListIterator is the most powerful cursor among all the three cursors. ListIterator is only applicable for list implemented classes like ArrayList, LinkedList, Stack, etc. ListIterator traverses both in the forward and backward direction. By using ListIteartor, we can perform read, remove, and replace operation. The ListIterator must be used when we want to enumerate elements of the list." }, { "code": null, "e": 1765, "s": 1666, "text": "ListIterator object can be created by calling listIterator() method present in the list interface." }, { "code": null, "e": 1894, "s": 1765, "text": "// Here \"l\" is any list object. ltr is of\n// type ListIterator interface and refers to \"l\"\nListIterator ltr = l.listIterator();\n" }, { "code": null, "e": 1899, "s": 1894, "text": "Java" }, { "code": "// A Java program to demonstrates the // difference between Enumeration,// Iterator, and ListIterator import java.io.*;import java.util.*; class GFG { public static void main(String args[]) { // Creating a vector object Vector<Integer> v = new Vector<Integer>(); // Adding elements to the vector object v.add(10); v.add(20); v.add(30); v.add(40); v.add(50); System.out.println(\"Enumeration: \"); // Creating an Enumeration object Enumeration e = v.elements(); // Checking the next element availability while (e.hasMoreElements()) { // Moving cursor to the next element int i = (Integer)e.nextElement(); // Printing the element System.out.print(i + \" \"); } System.out.println(); System.out.println(); System.out.println(\"Iterator: \"); // Creating Iterator object Iterator<Integer> itr = v.iterator(); // Checking the next element availability while (itr.hasNext()) { // Moving cursor to the next element int i = (Integer)itr.next(); // Checking if i == 10 then // remove the element if (i == 10) itr.remove(); } System.out.println(v); System.out.println(); System.out.println(\"ListIterator: \"); // Creating ListIterator object ListIterator<Integer> ltr = v.listIterator(); // Checking the next element availability while (ltr.hasNext()) { // Moving cursor to the next element int i = (Integer)ltr.next(); // Performing add, remove, and // replace operation if (i == 20) ltr.remove(); else if (i == 30) ltr.add(60); else if (i == 40) ltr.set(100); } System.out.println(v); }}", "e": 4075, "s": 1899, "text": null }, { "code": null, "e": 4172, "s": 4075, "text": "Enumeration: \n10 20 30 40 50 \n\nIterator: \n[20, 30, 40, 50]\n\nListIterator: \n[30, 60, 100, 50]\n\n\n\n" }, { "code": null, "e": 4249, "s": 4172, "text": "Table showing the Difference between Enumeration, Iterator, and ListIterator" }, { "code": null, "e": 4266, "s": 4249, "text": "Java-Enumeration" }, { "code": null, "e": 4280, "s": 4266, "text": "Java-Iterator" }, { "code": null, "e": 4299, "s": 4280, "text": "Difference Between" }, { "code": null, "e": 4304, "s": 4299, "text": "Java" }, { "code": null, "e": 4309, "s": 4304, "text": "Java" } ]
Some useful C++ tricks for beginners in Competitive Programming
25 May, 2022 Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data types can save a lot of time during programming contests. When a variable is defined as auto, the compiler can be determining the datatye on its own. Example: When a variable is defined as auto, the compiler can be determining the datatye on its own. Example: auto a = 100; // a will become 'int' auto b = 1LL; // b will become 'long long' auto c = 1.0; // c will become 'double' auto d = "variable"; // d will become 'string' The watch macro is one of the most useful tricks ever. #define watch(x) cout << (#x) << " is " << (x) << endl If you’re debugging your code, watch(variable); will print the name of the variable and its value. (It’s possible because it’s build in preprocessing time.) Using typedef’s can save a lot of time of yours which you might spend re-writing the same snippet again and again. Example: typedef long long ll; typedef pair w; typedef vector va; typedef vector vb; typedef vector vc; The C++ STL is a very rich library consisting of useful functions, which are super useful and time-saving during contests. For using these functions you need to include a header file. #include <algorithm> We are going to discuss the most commonly used STL algorithmic functions below:- // for binary search in containers like vector (let target element=6) binary_search(v.begin(), v.end(), 6); // return 1 or 0 as present or not // max/min of two numbers ans = max(a,b); ans = min(a,b); // max/min of three numbers ans = max(a,max(b,c)); ans = min(a, min(b,c)); // swap two numbers swap(a,b); // reverse containers like vectors, strings reverse(v.begin(), v.end()); // rotate containers like vector, strings by n position rotate(v.begin(), v.begin()+n, v.end()); // sort arrays of size n sort(arr, arr+n); // sort containers like vector, strings(based on intro sort) sort(v.begin(), v.end()); There’s an inbuilt function to evaluate the greatest common divisor of two numbers. It’s called __gcd() and it’s present in the algorithm header file. To read more about it, refer: https://www.geeksforgeeks.org/stdgcd-c-inbuilt-function-finding-gcd/ Using “\n” for adding new line breaks is much faster than using “endl”. If you use ios::sync_with_stdio(false) at the beginning of your code, you’ll make cin and cout as fast as printf and scanf, but you’ll no longer be able to use neither printf nor scanf. simranarora5sos geeky01adarsh CPP-Competitive-Programming C++ Competitive Programming 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++ std::string class in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Modulo 10^9+7 (1000000007) Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 364, "s": 52, "text": "Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. " }, { "code": null, "e": 565, "s": 366, "text": "Using the auto keyword to declare data types can save a lot of time during programming contests. When a variable is defined as auto, the compiler can be determining the datatye on its own. Example: " }, { "code": null, "e": 667, "s": 565, "text": "When a variable is defined as auto, the compiler can be determining the datatye on its own. Example: " }, { "code": null, "e": 834, "s": 667, "text": "auto a = 100; // a will become 'int'\nauto b = 1LL; // b will become 'long long'\nauto c = 1.0; // c will become 'double'\nauto d = \"variable\"; // d will become 'string'" }, { "code": null, "e": 890, "s": 834, "text": "The watch macro is one of the most useful tricks ever. " }, { "code": null, "e": 945, "s": 890, "text": "#define watch(x) cout << (#x) << \" is \" << (x) << endl" }, { "code": null, "e": 1102, "s": 945, "text": "If you’re debugging your code, watch(variable); will print the name of the variable and its value. (It’s possible because it’s build in preprocessing time.)" }, { "code": null, "e": 1226, "s": 1102, "text": "Using typedef’s can save a lot of time of yours which you might spend re-writing the same snippet again and again. Example:" }, { "code": null, "e": 1321, "s": 1226, "text": "typedef long long ll;\ntypedef pair w;\ntypedef vector va;\ntypedef vector vb;\ntypedef vector vc;" }, { "code": null, "e": 1506, "s": 1321, "text": "The C++ STL is a very rich library consisting of useful functions, which are super useful and time-saving during contests. For using these functions you need to include a header file. " }, { "code": null, "e": 1527, "s": 1506, "text": "#include <algorithm>" }, { "code": null, "e": 1608, "s": 1527, "text": "We are going to discuss the most commonly used STL algorithmic functions below:-" }, { "code": null, "e": 2223, "s": 1608, "text": "// for binary search in containers like vector (let target element=6)\nbinary_search(v.begin(), v.end(), 6); \n// return 1 or 0 as present or not\n\n// max/min of two numbers\nans = max(a,b);\nans = min(a,b);\n\n// max/min of three numbers\nans = max(a,max(b,c));\nans = min(a, min(b,c));\n\n// swap two numbers\nswap(a,b);\n\n// reverse containers like vectors, strings\nreverse(v.begin(), v.end());\n\n// rotate containers like vector, strings by n position\nrotate(v.begin(), v.begin()+n, v.end());\n\n// sort arrays of size n\nsort(arr, arr+n);\n\n// sort containers like vector, strings(based on intro sort)\nsort(v.begin(), v.end());" }, { "code": null, "e": 2473, "s": 2223, "text": "There’s an inbuilt function to evaluate the greatest common divisor of two numbers. It’s called __gcd() and it’s present in the algorithm header file. To read more about it, refer: https://www.geeksforgeeks.org/stdgcd-c-inbuilt-function-finding-gcd/" }, { "code": null, "e": 2545, "s": 2473, "text": "Using “\\n” for adding new line breaks is much faster than using “endl”." }, { "code": null, "e": 2731, "s": 2545, "text": "If you use ios::sync_with_stdio(false) at the beginning of your code, you’ll make cin and cout as fast as printf and scanf, but you’ll no longer be able to use neither printf nor scanf." }, { "code": null, "e": 2747, "s": 2731, "text": "simranarora5sos" }, { "code": null, "e": 2761, "s": 2747, "text": "geeky01adarsh" }, { "code": null, "e": 2789, "s": 2761, "text": "CPP-Competitive-Programming" }, { "code": null, "e": 2793, "s": 2789, "text": "C++" }, { "code": null, "e": 2817, "s": 2793, "text": "Competitive Programming" }, { "code": null, "e": 2821, "s": 2817, "text": "CPP" }, { "code": null, "e": 2919, "s": 2821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2943, "s": 2919, "text": "Sorting a vector in C++" }, { "code": null, "e": 2963, "s": 2943, "text": "Polymorphism in C++" }, { "code": null, "e": 2988, "s": 2963, "text": "std::string class in C++" }, { "code": null, "e": 3032, "s": 2988, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3065, "s": 3032, "text": "Friend class and function in C++" }, { "code": null, "e": 3108, "s": 3065, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 3151, "s": 3108, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 3178, "s": 3151, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 3219, "s": 3178, "text": "Arrow operator -> in C/C++ with Examples" } ]
React-Bootstrap Modal Component
30 Apr, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. Modal Component provides a way to add dialogs to our website for user notifications, displaying information, or to display completely custom information to the user. We can use the following approach in ReactJS to use the react-bootstrap Modal Component. Modal Props: animation: It is used to add a fade animation when Modal is open and closed. autoFocus: When the modal is open, it is used to automatically shift focus to itself and replace it with the last focused element when it closes when this attribute is set to true. backdrop: It is used to include a backdrop component. backdropClassName: It is used to add an optional extra class name to .modal-backdrop centered: It is used to vertically center the Dialog which is open in the window. container: It is the container attribute, and it is of type any. aria-labelledby: It is the aria-labelledby attribute, and it is of type any. contentClassName: It is used to add an optional extra class name to .modal-content dialogAs: It is a Component type that helps in providing the modal content Markup. dialogClassName: It is the className for the dialog. enforceFocus: The modal will prevent focus from leaving the Modal while open when it is set to true. keyboard: When the escape key is pressed, it closes the modal. manager: In order to track and manage the state of open Modals, a ModalManager instance is used. onEnter: It is used to trigger a callback before the Modal transitions in. onEntered: It is used to trigger a callback after the Modal finishes transitioning in. onEntering: It is used to trigger a callback when Modal begins to transition in. onEscapeKeyDown: It is used to trigger a callback when the escape key is pressed. onExit: It is used to trigger a callback before the Modal transitions out. onExited: It is used to trigger a callback after the Modal finishes transitioning out. onExiting: It is used to trigger a callback when the Modal begins to transition out. onHide: It is used to trigger a callback when the header non-static backdrop or closeButton is clicked. onShow: It is used to trigger a callback when the Modal is opening. restoreFocus: It is used to restore focus to previously focused elements when modal is hidden. restoreFocusOptions: When restoreFocus is set to true, It is the set of option which are passed to focus function. scrollable: It is used in an overflow condition, and it allows scrolling the <Modal.Body> instead of the entire modal. show: It is used to show the modal. size: It is used to render the size of our modal. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Modal.Dialog Props: centered: It is used to indicate whether the component should be vertical centered or not. contentClassName: It is used to add the content class name for styling. scrollable: It is used to allow the scrolling of <Modal.Body> instead of the complete modal. size: It is used to render the size of our modal. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Modal.Header Props: closeButton: It is used to specify whether the modal should have a close button or not. closeLabel: It is used to provide an accessible label for the close button. onHide: It is a callback that is trigger when the close button is clicked. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Modal.Title Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Modal.Body Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Modal.Footer Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Modal from 'react-bootstrap/Modal';import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Modal Component</h4> <Modal.Dialog> <Modal.Header closeButton> <Modal.Title> Sample Modal Heading </Modal.Title> </Modal.Header> <Modal.Body> <p> This is the sample text for our Modal </p> </Modal.Body> <Modal.Footer> <Button variant="primary"> Save changes </Button> <Button variant="secondary"> Close </Button> </Modal.Footer> </Modal.Dialog> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/modal/ React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Apr, 2021" }, { "code": null, "e": 390, "s": 53, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Modal Component provides a way to add dialogs to our website for user notifications, displaying information, or to display completely custom information to the user. We can use the following approach in ReactJS to use the react-bootstrap Modal Component." }, { "code": null, "e": 403, "s": 390, "text": "Modal Props:" }, { "code": null, "e": 480, "s": 403, "text": "animation: It is used to add a fade animation when Modal is open and closed." }, { "code": null, "e": 661, "s": 480, "text": "autoFocus: When the modal is open, it is used to automatically shift focus to itself and replace it with the last focused element when it closes when this attribute is set to true." }, { "code": null, "e": 715, "s": 661, "text": "backdrop: It is used to include a backdrop component." }, { "code": null, "e": 801, "s": 715, "text": "backdropClassName: It is used to add an optional extra class name to .modal-backdrop " }, { "code": null, "e": 883, "s": 801, "text": "centered: It is used to vertically center the Dialog which is open in the window." }, { "code": null, "e": 948, "s": 883, "text": "container: It is the container attribute, and it is of type any." }, { "code": null, "e": 1025, "s": 948, "text": "aria-labelledby: It is the aria-labelledby attribute, and it is of type any." }, { "code": null, "e": 1108, "s": 1025, "text": "contentClassName: It is used to add an optional extra class name to .modal-content" }, { "code": null, "e": 1191, "s": 1108, "text": "dialogAs: It is a Component type that helps in providing the modal content Markup." }, { "code": null, "e": 1244, "s": 1191, "text": "dialogClassName: It is the className for the dialog." }, { "code": null, "e": 1345, "s": 1244, "text": "enforceFocus: The modal will prevent focus from leaving the Modal while open when it is set to true." }, { "code": null, "e": 1408, "s": 1345, "text": "keyboard: When the escape key is pressed, it closes the modal." }, { "code": null, "e": 1505, "s": 1408, "text": "manager: In order to track and manage the state of open Modals, a ModalManager instance is used." }, { "code": null, "e": 1580, "s": 1505, "text": "onEnter: It is used to trigger a callback before the Modal transitions in." }, { "code": null, "e": 1667, "s": 1580, "text": "onEntered: It is used to trigger a callback after the Modal finishes transitioning in." }, { "code": null, "e": 1748, "s": 1667, "text": "onEntering: It is used to trigger a callback when Modal begins to transition in." }, { "code": null, "e": 1830, "s": 1748, "text": "onEscapeKeyDown: It is used to trigger a callback when the escape key is pressed." }, { "code": null, "e": 1905, "s": 1830, "text": "onExit: It is used to trigger a callback before the Modal transitions out." }, { "code": null, "e": 1992, "s": 1905, "text": "onExited: It is used to trigger a callback after the Modal finishes transitioning out." }, { "code": null, "e": 2077, "s": 1992, "text": "onExiting: It is used to trigger a callback when the Modal begins to transition out." }, { "code": null, "e": 2181, "s": 2077, "text": "onHide: It is used to trigger a callback when the header non-static backdrop or closeButton is clicked." }, { "code": null, "e": 2249, "s": 2181, "text": "onShow: It is used to trigger a callback when the Modal is opening." }, { "code": null, "e": 2344, "s": 2249, "text": "restoreFocus: It is used to restore focus to previously focused elements when modal is hidden." }, { "code": null, "e": 2459, "s": 2344, "text": "restoreFocusOptions: When restoreFocus is set to true, It is the set of option which are passed to focus function." }, { "code": null, "e": 2578, "s": 2459, "text": "scrollable: It is used in an overflow condition, and it allows scrolling the <Modal.Body> instead of the entire modal." }, { "code": null, "e": 2614, "s": 2578, "text": "show: It is used to show the modal." }, { "code": null, "e": 2664, "s": 2614, "text": "size: It is used to render the size of our modal." }, { "code": null, "e": 2748, "s": 2664, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2768, "s": 2748, "text": "Modal.Dialog Props:" }, { "code": null, "e": 2859, "s": 2768, "text": "centered: It is used to indicate whether the component should be vertical centered or not." }, { "code": null, "e": 2931, "s": 2859, "text": "contentClassName: It is used to add the content class name for styling." }, { "code": null, "e": 3024, "s": 2931, "text": "scrollable: It is used to allow the scrolling of <Modal.Body> instead of the complete modal." }, { "code": null, "e": 3074, "s": 3024, "text": "size: It is used to render the size of our modal." }, { "code": null, "e": 3158, "s": 3074, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3178, "s": 3158, "text": "Modal.Header Props:" }, { "code": null, "e": 3266, "s": 3178, "text": "closeButton: It is used to specify whether the modal should have a close button or not." }, { "code": null, "e": 3342, "s": 3266, "text": "closeLabel: It is used to provide an accessible label for the close button." }, { "code": null, "e": 3417, "s": 3342, "text": "onHide: It is a callback that is trigger when the close button is clicked." }, { "code": null, "e": 3501, "s": 3417, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3520, "s": 3501, "text": "Modal.Title Props:" }, { "code": null, "e": 3584, "s": 3520, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 3668, "s": 3584, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3686, "s": 3668, "text": "Modal.Body Props:" }, { "code": null, "e": 3750, "s": 3686, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 3834, "s": 3750, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3854, "s": 3834, "text": "Modal.Footer Props:" }, { "code": null, "e": 3918, "s": 3854, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 4002, "s": 3918, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 4052, "s": 4002, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 4147, "s": 4052, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 4211, "s": 4147, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 4243, "s": 4211, "text": "npx create-react-app foldername" }, { "code": null, "e": 4356, "s": 4243, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 4456, "s": 4356, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 4470, "s": 4456, "text": "cd foldername" }, { "code": null, "e": 4625, "s": 4470, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 4730, "s": 4625, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 4781, "s": 4730, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 4833, "s": 4781, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 4851, "s": 4833, "text": "Project Structure" }, { "code": null, "e": 4981, "s": 4851, "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": 4988, "s": 4981, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Modal from 'react-bootstrap/Modal';import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Modal Component</h4> <Modal.Dialog> <Modal.Header closeButton> <Modal.Title> Sample Modal Heading </Modal.Title> </Modal.Header> <Modal.Body> <p> This is the sample text for our Modal </p> </Modal.Body> <Modal.Footer> <Button variant=\"primary\"> Save changes </Button> <Button variant=\"secondary\"> Close </Button> </Modal.Footer> </Modal.Dialog> </div> );}", "e": 5833, "s": 4988, "text": null }, { "code": null, "e": 5946, "s": 5833, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 5956, "s": 5946, "text": "npm start" }, { "code": null, "e": 6055, "s": 5956, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6118, "s": 6055, "text": "Reference: https://react-bootstrap.github.io/components/modal/" }, { "code": null, "e": 6134, "s": 6118, "text": "React-Bootstrap" }, { "code": null, "e": 6142, "s": 6134, "text": "ReactJS" }, { "code": null, "e": 6159, "s": 6142, "text": "Web Technologies" } ]
Convert ArrayList to Vector in Java
10 Feb, 2022 There are several ways to convert ArrayList to Vector. We can use a vector constructor for converting ArrayList to vector. We can read ArrayList elements one by one and add them in vector. Approach 1: (Using Vector Constructor) Create an ArrayList. Add elements in ArrayList. Create a vector and pass the ArrayList in Vector Constructor. Vector(Collection c): Creates a vector that contains the elements of collection c. Vector<E> v = new Vector<E>(Collection c); Example: Java // Java program to Convert ArrayList to Vector import java.util.ArrayList;import java.util.Vector; public class GFG { public static void main(String[] args) { // create ArrayList ArrayList<Integer> ArrList = new ArrayList<Integer>(); // add elements in ArrayList ArrList.add(10); ArrList.add(20); ArrList.add(30); ArrList.add(40); ArrList.add(50); // display ArrayList System.out.println(" ArrayList : " + ArrList); // create vector and pass the ArrayList in vector // constructor Vector<Integer> vector = new Vector<Integer>(ArrList); // print vector System.out.println(" Vector : " + vector); }} ArrayList : [10, 20, 30, 40, 50] Vector : [10, 20, 30, 40, 50] Approach 2: (Using for loop) Create a ArrayList. Add some values in ArrayList. Create an Vector. Execute a loop. Traverse each element of ArrayList from the left side to the right side. Add the ArrayList elements in Vector. Example: Java // Java program to Convert ArrayList to Vector import java.util.Vector;import java.util.ArrayList;public class GFG { public static void main(String[] args) { // Create a ArrayList that contain strings ArrayList<String> Arrlist = new ArrayList<String>(); // add values in ArrayList Arrlist.add("A"); Arrlist.add("B"); Arrlist.add("C"); Arrlist.add("D"); Arrlist.add("E"); // Display the ArrayList System.out.println(" ArrayList : " + Arrlist); // create a vector Vector<String> v = new Vector<String>(); // Convert ArrayList to Vector // get the size to ArrayList int n = Arrlist.size(); // execute for loop from 0 to n for (int i = 0; i < n; i++) { // get the elements from ArrayList // and add the arrayList elements in vector v.add(Arrlist.get(i)); } // Display Vector System.out.println("\n vector : " + v); }} ArrayList : [A, B, C, D, E] vector : [A, B, C, D, E] Approach 3: (Using addAll() method) This method is used to append all the elements from the collection passed as a parameter to this function to the end of a vector keeping in mind the order of return by the collection’s iterator. Syntax: boolean addAll(Collection C) Parameters: The method accepts a mandatory parameter C which is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the vector. Return Value: The method returns True if at least one action of append is performed, else False. Example: Java // Java program to Convert ArrayList to Vector import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> listStrings = new ArrayList<>(); listStrings.add("Geeks"); listStrings.add("for"); listStrings.add("Geeks"); // create empty vector object Vector<String> vStrings = new Vector<>(); // use the addAll method vStrings.addAll(listStrings); System.out.println("Vector contains: " + vStrings); }} Vector contains: [Geeks, for, Geeks] simmytarika5 avtarkumar719 Java-ArrayList Java-Vector 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. 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": 28, "s": 0, "text": "\n10 Feb, 2022" }, { "code": null, "e": 217, "s": 28, "text": "There are several ways to convert ArrayList to Vector. We can use a vector constructor for converting ArrayList to vector. We can read ArrayList elements one by one and add them in vector." }, { "code": null, "e": 256, "s": 217, "text": "Approach 1: (Using Vector Constructor)" }, { "code": null, "e": 277, "s": 256, "text": "Create an ArrayList." }, { "code": null, "e": 304, "s": 277, "text": "Add elements in ArrayList." }, { "code": null, "e": 366, "s": 304, "text": "Create a vector and pass the ArrayList in Vector Constructor." }, { "code": null, "e": 449, "s": 366, "text": "Vector(Collection c): Creates a vector that contains the elements of collection c." }, { "code": null, "e": 492, "s": 449, "text": "Vector<E> v = new Vector<E>(Collection c);" }, { "code": null, "e": 501, "s": 492, "text": "Example:" }, { "code": null, "e": 506, "s": 501, "text": "Java" }, { "code": "// Java program to Convert ArrayList to Vector import java.util.ArrayList;import java.util.Vector; public class GFG { public static void main(String[] args) { // create ArrayList ArrayList<Integer> ArrList = new ArrayList<Integer>(); // add elements in ArrayList ArrList.add(10); ArrList.add(20); ArrList.add(30); ArrList.add(40); ArrList.add(50); // display ArrayList System.out.println(\" ArrayList : \" + ArrList); // create vector and pass the ArrayList in vector // constructor Vector<Integer> vector = new Vector<Integer>(ArrList); // print vector System.out.println(\" Vector : \" + vector); }}", "e": 1223, "s": 506, "text": null }, { "code": null, "e": 1291, "s": 1226, "text": " ArrayList : [10, 20, 30, 40, 50]\n Vector : [10, 20, 30, 40, 50]" }, { "code": null, "e": 1322, "s": 1293, "text": "Approach 2: (Using for loop)" }, { "code": null, "e": 1344, "s": 1324, "text": "Create a ArrayList." }, { "code": null, "e": 1374, "s": 1344, "text": "Add some values in ArrayList." }, { "code": null, "e": 1392, "s": 1374, "text": "Create an Vector." }, { "code": null, "e": 1408, "s": 1392, "text": "Execute a loop." }, { "code": null, "e": 1481, "s": 1408, "text": "Traverse each element of ArrayList from the left side to the right side." }, { "code": null, "e": 1519, "s": 1481, "text": "Add the ArrayList elements in Vector." }, { "code": null, "e": 1530, "s": 1521, "text": "Example:" }, { "code": null, "e": 1537, "s": 1532, "text": "Java" }, { "code": "// Java program to Convert ArrayList to Vector import java.util.Vector;import java.util.ArrayList;public class GFG { public static void main(String[] args) { // Create a ArrayList that contain strings ArrayList<String> Arrlist = new ArrayList<String>(); // add values in ArrayList Arrlist.add(\"A\"); Arrlist.add(\"B\"); Arrlist.add(\"C\"); Arrlist.add(\"D\"); Arrlist.add(\"E\"); // Display the ArrayList System.out.println(\" ArrayList : \" + Arrlist); // create a vector Vector<String> v = new Vector<String>(); // Convert ArrayList to Vector // get the size to ArrayList int n = Arrlist.size(); // execute for loop from 0 to n for (int i = 0; i < n; i++) { // get the elements from ArrayList // and add the arrayList elements in vector v.add(Arrlist.get(i)); } // Display Vector System.out.println(\"\\n vector : \" + v); }}", "e": 2552, "s": 1537, "text": null }, { "code": null, "e": 2612, "s": 2555, "text": " ArrayList : [A, B, C, D, E]\n\n vector : [A, B, C, D, E]" }, { "code": null, "e": 2650, "s": 2614, "text": "Approach 3: (Using addAll() method)" }, { "code": null, "e": 2847, "s": 2652, "text": "This method is used to append all the elements from the collection passed as a parameter to this function to the end of a vector keeping in mind the order of return by the collection’s iterator." }, { "code": null, "e": 2857, "s": 2849, "text": "Syntax:" }, { "code": null, "e": 2888, "s": 2859, "text": "boolean addAll(Collection C)" }, { "code": null, "e": 3069, "s": 2890, "text": "Parameters: The method accepts a mandatory parameter C which is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the vector." }, { "code": null, "e": 3168, "s": 3071, "text": "Return Value: The method returns True if at least one action of append is performed, else False." }, { "code": null, "e": 3179, "s": 3170, "text": "Example:" }, { "code": null, "e": 3186, "s": 3181, "text": "Java" }, { "code": "// Java program to Convert ArrayList to Vector import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> listStrings = new ArrayList<>(); listStrings.add(\"Geeks\"); listStrings.add(\"for\"); listStrings.add(\"Geeks\"); // create empty vector object Vector<String> vStrings = new Vector<>(); // use the addAll method vStrings.addAll(listStrings); System.out.println(\"Vector contains: \" + vStrings); }}", "e": 3708, "s": 3186, "text": null }, { "code": null, "e": 3748, "s": 3711, "text": "Vector contains: [Geeks, for, Geeks]" }, { "code": null, "e": 3763, "s": 3750, "text": "simmytarika5" }, { "code": null, "e": 3777, "s": 3763, "text": "avtarkumar719" }, { "code": null, "e": 3792, "s": 3777, "text": "Java-ArrayList" }, { "code": null, "e": 3804, "s": 3792, "text": "Java-Vector" }, { "code": null, "e": 3811, "s": 3804, "text": "Picked" }, { "code": null, "e": 3835, "s": 3811, "text": "Technical Scripter 2020" }, { "code": null, "e": 3840, "s": 3835, "text": "Java" }, { "code": null, "e": 3854, "s": 3840, "text": "Java Programs" }, { "code": null, "e": 3873, "s": 3854, "text": "Technical Scripter" }, { "code": null, "e": 3878, "s": 3873, "text": "Java" }, { "code": null, "e": 3976, "s": 3878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3991, "s": 3976, "text": "Stream In Java" }, { "code": null, "e": 4012, "s": 3991, "text": "Introduction to Java" }, { "code": null, "e": 4033, "s": 4012, "text": "Constructors in Java" }, { "code": null, "e": 4052, "s": 4033, "text": "Exceptions in Java" }, { "code": null, "e": 4069, "s": 4052, "text": "Generics in Java" }, { "code": null, "e": 4095, "s": 4069, "text": "Java Programming Examples" }, { "code": null, "e": 4129, "s": 4095, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4176, "s": 4129, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4214, "s": 4176, "text": "Factory method design pattern in Java" } ]
JavaScript | Adding days in milliseconds to Date object
23 May, 2019 Given a date, the task is to add days in milliseconds to it. To add days in milliseconds to date object in JavaScript, some methods are used which are listed below: JavaScript getMilliseconds() Method: This method returns the milliseconds (from 0 to 999) of the provided date and time.Syntax:Date.getMilliseconds() Return value: It returns a number, from 0 to 009, representing the milliseconds. Syntax: Date.getMilliseconds() Return value: It returns a number, from 0 to 009, representing the milliseconds. JavaScript setMilliseconds() Method: This method sets the milliseconds of a date object.Syntax:Date.setMilliseconds(millisec) Parameters: It accepts single parameter millisec which is required. It specifies the integer value representing the milliseconds. The expected values are 0-999, but other values are allowed.Note: The parameter accepts values apart from their range and these values works like:millisec = -1, it means the last millisecond of the previous second and same for the other parameters.If millisec passed as 1000, it means the first millisecond of the next second and same for the other parameters.Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970. JavaScript setMilliseconds() Method: This method sets the milliseconds of a date object.Syntax: Date.setMilliseconds(millisec) Parameters: It accepts single parameter millisec which is required. It specifies the integer value representing the milliseconds. The expected values are 0-999, but other values are allowed. Note: The parameter accepts values apart from their range and these values works like: millisec = -1, it means the last millisecond of the previous second and same for the other parameters. If millisec passed as 1000, it means the first millisecond of the next second and same for the other parameters. Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970. JavaScript getTime() method: This method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime()Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970. Syntax: Date.getTime() Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970. JavaScript setTime() method: This method sets the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)Parameters: It accepts single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, in midnight January 1, 1970Return value: It returns the number of milliseconds between the date object and midnight January 1 1970. JavaScript setTime() method: This method sets the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970. Syntax: Date.setTime(millisec) Parameters: It accepts single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, in midnight January 1, 1970 Return value: It returns the number of milliseconds between the date object and midnight January 1 1970. Example 1: This example added 1 day in milliseconds to the var today by using setTime() and getTime() method. <!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding days in milliseconds to Date object </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> addMilliseconds </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMillisecs = function(d) { this.setTime(this.getTime() + (d)); return this; } function gfg_Run() { var a = new Date(); var d = 1; a.addMillisecs(d*24*60*60*1000); el_down.innerHTML = a; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example added 5 days in milliseconds to the var today by using setMilliseconds() and getMilliseconds() method. <!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding days in milliseconds to Date object </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> addMilliseconds </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMillisecs= function(s) { this.setMilliseconds(this.getMilliseconds()+s); return this; } function gfg_Run() { var a = new Date(); var d = 5; a.addMillisecs(d*24*60*60*1000); el_down.innerHTML = a; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 193, "s": 28, "text": "Given a date, the task is to add days in milliseconds to it. To add days in milliseconds to date object in JavaScript, some methods are used which are listed below:" }, { "code": null, "e": 424, "s": 193, "text": "JavaScript getMilliseconds() Method: This method returns the milliseconds (from 0 to 999) of the provided date and time.Syntax:Date.getMilliseconds()\nReturn value: It returns a number, from 0 to 009, representing the milliseconds." }, { "code": null, "e": 432, "s": 424, "text": "Syntax:" }, { "code": null, "e": 456, "s": 432, "text": "Date.getMilliseconds()\n" }, { "code": null, "e": 537, "s": 456, "text": "Return value: It returns a number, from 0 to 009, representing the milliseconds." }, { "code": null, "e": 1277, "s": 537, "text": "JavaScript setMilliseconds() Method: This method sets the milliseconds of a date object.Syntax:Date.setMilliseconds(millisec)\nParameters: It accepts single parameter millisec which is required. It specifies the integer value representing the milliseconds. The expected values are 0-999, but other values are allowed.Note: The parameter accepts values apart from their range and these values works like:millisec = -1, it means the last millisecond of the previous second and same for the other parameters.If millisec passed as 1000, it means the first millisecond of the next second and same for the other parameters.Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 1373, "s": 1277, "text": "JavaScript setMilliseconds() Method: This method sets the milliseconds of a date object.Syntax:" }, { "code": null, "e": 1405, "s": 1373, "text": "Date.setMilliseconds(millisec)\n" }, { "code": null, "e": 1596, "s": 1405, "text": "Parameters: It accepts single parameter millisec which is required. It specifies the integer value representing the milliseconds. The expected values are 0-999, but other values are allowed." }, { "code": null, "e": 1683, "s": 1596, "text": "Note: The parameter accepts values apart from their range and these values works like:" }, { "code": null, "e": 1786, "s": 1683, "text": "millisec = -1, it means the last millisecond of the previous second and same for the other parameters." }, { "code": null, "e": 1899, "s": 1786, "text": "If millisec passed as 1000, it means the first millisecond of the next second and same for the other parameters." }, { "code": null, "e": 2023, "s": 1899, "text": "Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 2287, "s": 2023, "text": "JavaScript getTime() method: This method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime()Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 2295, "s": 2287, "text": "Syntax:" }, { "code": null, "e": 2310, "s": 2295, "text": "Date.getTime()" }, { "code": null, "e": 2417, "s": 2310, "text": "Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 2862, "s": 2417, "text": "JavaScript setTime() method: This method sets the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)Parameters: It accepts single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, in midnight January 1, 1970Return value: It returns the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 3015, "s": 2862, "text": "JavaScript setTime() method: This method sets the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970." }, { "code": null, "e": 3023, "s": 3015, "text": "Syntax:" }, { "code": null, "e": 3046, "s": 3023, "text": "Date.setTime(millisec)" }, { "code": null, "e": 3206, "s": 3046, "text": "Parameters: It accepts single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, in midnight January 1, 1970" }, { "code": null, "e": 3311, "s": 3206, "text": "Return value: It returns the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 3421, "s": 3311, "text": "Example 1: This example added 1 day in milliseconds to the var today by using setTime() and getTime() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding days in milliseconds to Date object </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> addMilliseconds </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMillisecs = function(d) { this.setTime(this.getTime() + (d)); return this; } function gfg_Run() { var a = new Date(); var d = 1; a.addMillisecs(d*24*60*60*1000); el_down.innerHTML = a; } </script> </body> </html> ", "e": 4670, "s": 3421, "text": null }, { "code": null, "e": 4678, "s": 4670, "text": "Output:" }, { "code": null, "e": 4709, "s": 4678, "text": "Before clicking on the button:" }, { "code": null, "e": 4739, "s": 4709, "text": "After clicking on the button:" }, { "code": null, "e": 4866, "s": 4739, "text": "Example 2: This example added 5 days in milliseconds to the var today by using setMilliseconds() and getMilliseconds() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding days in milliseconds to Date object </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> addMilliseconds </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMillisecs= function(s) { this.setMilliseconds(this.getMilliseconds()+s); return this; } function gfg_Run() { var a = new Date(); var d = 5; a.addMillisecs(d*24*60*60*1000); el_down.innerHTML = a; } </script> </body> </html> ", "e": 6118, "s": 4866, "text": null }, { "code": null, "e": 6126, "s": 6118, "text": "Output:" }, { "code": null, "e": 6157, "s": 6126, "text": "Before clicking on the button:" }, { "code": null, "e": 6187, "s": 6157, "text": "After clicking on the button:" }, { "code": null, "e": 6203, "s": 6187, "text": "javascript-date" }, { "code": null, "e": 6214, "s": 6203, "text": "JavaScript" }, { "code": null, "e": 6231, "s": 6214, "text": "Web Technologies" }, { "code": null, "e": 6258, "s": 6231, "text": "Web technologies Questions" }, { "code": null, "e": 6356, "s": 6258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6417, "s": 6356, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6457, "s": 6417, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6499, "s": 6457, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 6540, "s": 6499, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6562, "s": 6540, "text": "JavaScript | Promises" }, { "code": null, "e": 6595, "s": 6562, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6657, "s": 6595, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6718, "s": 6657, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6768, "s": 6718, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Replace NaN with Blank or Empty String in Pandas?
22 Nov, 2021 In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas. For this, we will create dataframe using pandas dataframe() object. Python3 # import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ "name": ['sravan', np.nan, 'harsha', 'ramya'], "subjects": [np.nan, 'java', np.nan, 'html/php'], "marks": [98, np.nan, np.nan, np.nan]}) # displaydata Output: We can replace the NaN with an empty string using replace() function. This function will replace an empty string inplace of the NaN value Syntax: dataframe.replace(np.nan, ”) where dataframe is the input dataframe first parameter takes Nan value second parameter replace the NaN with empty string Example: Python3 # import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ "name": ['sravan', np.nan, 'harsha', 'ramya'], "subjects": [np.nan, 'java', np.nan, 'html/php'], "marks": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using replace() functiondata.replace(np.nan, '') Output: This is used to replace multiple columns NaN values with an empty string. Syntax: dataframe[[‘columns’ ]].fillna(”) where dataframe is the input dataframe columns are the multiple columns in the dataframe Example: Python3 # import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ "name": ['sravan', np.nan, 'harsha', 'ramya'], "subjects": [np.nan, 'java', np.nan, 'html/php'], "marks": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using fillna() functiondata[['name', 'subjects', 'marks']].fillna('') Output: dataframe.fillna('') Example: Python3 # import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ "name": ['sravan', np.nan, 'harsha', 'ramya'], "subjects": [np.nan, 'java', np.nan, 'html/php'], "marks": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using fillna() functiondata.fillna('') Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 118, "s": 28, "text": "In this article, we will discuss how to replace NaN with Blank or Empty string in Pandas." }, { "code": null, "e": 186, "s": 118, "text": "For this, we will create dataframe using pandas dataframe() object." }, { "code": null, "e": 194, "s": 186, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ \"name\": ['sravan', np.nan, 'harsha', 'ramya'], \"subjects\": [np.nan, 'java', np.nan, 'html/php'], \"marks\": [98, np.nan, np.nan, np.nan]}) # displaydata", "e": 496, "s": 194, "text": null }, { "code": null, "e": 504, "s": 496, "text": "Output:" }, { "code": null, "e": 642, "s": 504, "text": "We can replace the NaN with an empty string using replace() function. This function will replace an empty string inplace of the NaN value" }, { "code": null, "e": 679, "s": 642, "text": "Syntax: dataframe.replace(np.nan, ”)" }, { "code": null, "e": 685, "s": 679, "text": "where" }, { "code": null, "e": 718, "s": 685, "text": "dataframe is the input dataframe" }, { "code": null, "e": 750, "s": 718, "text": "first parameter takes Nan value" }, { "code": null, "e": 801, "s": 750, "text": "second parameter replace the NaN with empty string" }, { "code": null, "e": 810, "s": 801, "text": "Example:" }, { "code": null, "e": 818, "s": 810, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ \"name\": ['sravan', np.nan, 'harsha', 'ramya'], \"subjects\": [np.nan, 'java', np.nan, 'html/php'], \"marks\": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using replace() functiondata.replace(np.nan, '')", "e": 1188, "s": 818, "text": null }, { "code": null, "e": 1196, "s": 1188, "text": "Output:" }, { "code": null, "e": 1270, "s": 1196, "text": "This is used to replace multiple columns NaN values with an empty string." }, { "code": null, "e": 1312, "s": 1270, "text": "Syntax: dataframe[[‘columns’ ]].fillna(”)" }, { "code": null, "e": 1318, "s": 1312, "text": "where" }, { "code": null, "e": 1351, "s": 1318, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1401, "s": 1351, "text": "columns are the multiple columns in the dataframe" }, { "code": null, "e": 1410, "s": 1401, "text": "Example:" }, { "code": null, "e": 1418, "s": 1410, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ \"name\": ['sravan', np.nan, 'harsha', 'ramya'], \"subjects\": [np.nan, 'java', np.nan, 'html/php'], \"marks\": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using fillna() functiondata[['name', 'subjects', 'marks']].fillna('')", "e": 1809, "s": 1418, "text": null }, { "code": null, "e": 1817, "s": 1809, "text": "Output:" }, { "code": null, "e": 1838, "s": 1817, "text": "dataframe.fillna('')" }, { "code": null, "e": 1847, "s": 1838, "text": "Example:" }, { "code": null, "e": 1855, "s": 1847, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # import numpy moduleimport numpy as np # create dataframe with 3 columnsdata = pd.DataFrame({ \"name\": ['sravan', np.nan, 'harsha', 'ramya'], \"subjects\": [np.nan, 'java', np.nan, 'html/php'], \"marks\": [98, np.nan, np.nan, np.nan]}) # replace nan with empty string# using fillna() functiondata.fillna('')", "e": 2215, "s": 1855, "text": null }, { "code": null, "e": 2223, "s": 2215, "text": "Output:" }, { "code": null, "e": 2248, "s": 2223, "text": "pandas-dataframe-program" }, { "code": null, "e": 2255, "s": 2248, "text": "Picked" }, { "code": null, "e": 2279, "s": 2255, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2293, "s": 2279, "text": "Python-pandas" }, { "code": null, "e": 2300, "s": 2293, "text": "Python" } ]
Python | Indices list of matching element from other list
10 Oct, 2019 Sometimes, while working with Python list, we have a problem in which we have to search for a element in list. But this can be extended to a list and need to find the exact places where elements occur in other list. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + count()This is the brute method to perform this task. In this we can just count the occurrence of an element in other list and if we find it, then we add it’s index to the result list. # Python3 code to demonstrate working of# Indices list of matching element from other list# Using loop + count() # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Indices list of matching element from other list# Using loop + count()res = []i = 0while (i < len(test_list1)): if (test_list2.count(test_list1[i]) > 0): res.append(i) i += 1 # printing result print("The matching element Indices list : " + str(res)) The original list 1 is : [5, 7, 8, 9, 10, 11] The original list 2 is : [8, 10, 11] The matching element Indices list : [2, 4, 5] Method #2 : Using list comprehension + set() + enumerate()The combination of above functions can be used to perform the task. In these we just convert the list to set and then check for index and value together for existence using enumerate() and append the index if found. # Python3 code to demonstrate working of# Indices list of matching element from other list# Using list comprehension + set() + enumerate() # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Indices list of matching element from other list# Using list comprehension + set() + enumerate()temp = set(test_list2)res = [i for i, val in enumerate(test_list1) if val in temp] # printing result print("The matching element Indices list : " + str(res)) The original list 1 is : [5, 7, 8, 9, 10, 11] The original list 2 is : [8, 10, 11] The matching element Indices list : [2, 4, 5] Akanksha_Rai Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2019" }, { "code": null, "e": 308, "s": 28, "text": "Sometimes, while working with Python list, we have a problem in which we have to search for a element in list. But this can be extended to a list and need to find the exact places where elements occur in other list. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 518, "s": 308, "text": "Method #1 : Using loop + count()This is the brute method to perform this task. In this we can just count the occurrence of an element in other list and if we find it, then we add it’s index to the result list." }, { "code": "# Python3 code to demonstrate working of# Indices list of matching element from other list# Using loop + count() # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Indices list of matching element from other list# Using loop + count()res = []i = 0while (i < len(test_list1)): if (test_list2.count(test_list1[i]) > 0): res.append(i) i += 1 # printing result print(\"The matching element Indices list : \" + str(res))", "e": 1108, "s": 518, "text": null }, { "code": null, "e": 1238, "s": 1108, "text": "The original list 1 is : [5, 7, 8, 9, 10, 11]\nThe original list 2 is : [8, 10, 11]\nThe matching element Indices list : [2, 4, 5]\n" }, { "code": null, "e": 1514, "s": 1240, "text": "Method #2 : Using list comprehension + set() + enumerate()The combination of above functions can be used to perform the task. In these we just convert the list to set and then check for index and value together for existence using enumerate() and append the index if found." }, { "code": "# Python3 code to demonstrate working of# Indices list of matching element from other list# Using list comprehension + set() + enumerate() # initializing liststest_list1 = [5, 7, 8, 9, 10, 11]test_list2 = [8, 10, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Indices list of matching element from other list# Using list comprehension + set() + enumerate()temp = set(test_list2)res = [i for i, val in enumerate(test_list1) if val in temp] # printing result print(\"The matching element Indices list : \" + str(res))", "e": 2121, "s": 1514, "text": null }, { "code": null, "e": 2251, "s": 2121, "text": "The original list 1 is : [5, 7, 8, 9, 10, 11]\nThe original list 2 is : [8, 10, 11]\nThe matching element Indices list : [2, 4, 5]\n" }, { "code": null, "e": 2264, "s": 2251, "text": "Akanksha_Rai" }, { "code": null, "e": 2285, "s": 2264, "text": "Python list-programs" }, { "code": null, "e": 2292, "s": 2285, "text": "Python" }, { "code": null, "e": 2308, "s": 2292, "text": "Python Programs" } ]
How to Make Histograms with Density Plots with Seaborn histplot?
29 Oct, 2021 Histograms are visualization tools that represent the distribution of a set of continuous data. In a histogram, the data is divided into a set of intervals or bins (usually on the x-axis) and the count of data points that fall into each bin corresponding to the height of the bar above that bin. These bins may or may not be equal in width but are adjacent (with no gaps). A density plot (also known as kernel density plot) is another visualization tool for evaluating data distributions. It can be considered as a smoothed histogram. The peaks of a density plot help display where values are concentrated over the interval. There are a variety of smoothing techniques. Kernel Density Estimation (KDE) is one of the techniques used to smooth a histogram. Seaborn is a data visualization library based on matplotlib in Python. In this article, we will use seaborn.histplot() to plot a histogram with a density plot. Syntax: seaborn.histplot(data, x, y, hue, stat, bins, binwidth, discrete, kde, log_scale) Parameters:- data: input data in the form of Dataframe or Numpy array x, y (optional): key of the data to be positioned on the x and y axes respectively hue (optional): semantic data key which is mapped to determine the color of plot elements stat (optional): count, frequency, density or probability Return: This method returns the matplotlib axes with the plot drawn on it. Example 1: We will generate the data using the random.randn() method. Python3 # Import necessary librariesimport seaborn as snsimport numpy as npimport pandas as pd # Generating dataset of random numbersnp.random.seed(1)num_var = np.random.randn(1000)num_var = pd.Series(num_var, name = "Numerical Variable") # Plot histogramsns.histplot(data = num_var, kde = True) Output: By default kde parameter of seaborn.histplot is set to false. So, by setting the kde to true, a kernel density estimate is computed to smooth the distribution and a density plotline is drawn. Example 2: Let us use the sample dataset, Penguins, from the Seaborn library in this example. This dataset shows the characteristics (body mass, flipper length, bill length gender) of different penguin species on different islands. Python3 # Import necessary librariesimport numpy as npimport pandas as pdimport seaborn as sns # Load datasetpenguins = sns.load_dataset("penguins") # Plot histogramsns.histplot(data = penguins, x = "body_mass_g", kde = True) Output: We can also visualize the distribution of body mass for multiple species in a single plot. The hue parameter maps the semantic variable ‘species’. Python3 # Plot Histogramsns.histplot(data = penguins, x = "body_mass_g", kde = True, hue = "species") Output: Example 3: This example uses the sample dataset, Tips, from the Seaborn library which records the tips received by a restaurant server. It consists of the tip received total bill or cost of the meal, gender of the customer, size of the customer party, day, time and whether a smoker is present at the party or not. Instead of the count of data points, the histogram in this example is normalized so that each bar’s height shows a probability. Python3 # Import necessary librariesimport numpy as npimport pandas as pdimport seaborn as sns # Load datasettips = sns.load_dataset("tips") # Plot histogramsns.histplot(data = tips, x = "size", stat = "probability", discrete = True) Output: rajeev0719singh Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe Taking input in Python Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2021" }, { "code": null, "e": 429, "s": 54, "text": "Histograms are visualization tools that represent the distribution of a set of continuous data. In a histogram, the data is divided into a set of intervals or bins (usually on the x-axis) and the count of data points that fall into each bin corresponding to the height of the bar above that bin. These bins may or may not be equal in width but are adjacent (with no gaps). " }, { "code": null, "e": 811, "s": 429, "text": "A density plot (also known as kernel density plot) is another visualization tool for evaluating data distributions. It can be considered as a smoothed histogram. The peaks of a density plot help display where values are concentrated over the interval. There are a variety of smoothing techniques. Kernel Density Estimation (KDE) is one of the techniques used to smooth a histogram." }, { "code": null, "e": 971, "s": 811, "text": "Seaborn is a data visualization library based on matplotlib in Python. In this article, we will use seaborn.histplot() to plot a histogram with a density plot." }, { "code": null, "e": 1061, "s": 971, "text": "Syntax: seaborn.histplot(data, x, y, hue, stat, bins, binwidth, discrete, kde, log_scale)" }, { "code": null, "e": 1074, "s": 1061, "text": "Parameters:-" }, { "code": null, "e": 1131, "s": 1074, "text": "data: input data in the form of Dataframe or Numpy array" }, { "code": null, "e": 1214, "s": 1131, "text": "x, y (optional): key of the data to be positioned on the x and y axes respectively" }, { "code": null, "e": 1304, "s": 1214, "text": "hue (optional): semantic data key which is mapped to determine the color of plot elements" }, { "code": null, "e": 1362, "s": 1304, "text": "stat (optional): count, frequency, density or probability" }, { "code": null, "e": 1437, "s": 1362, "text": "Return: This method returns the matplotlib axes with the plot drawn on it." }, { "code": null, "e": 1507, "s": 1437, "text": "Example 1: We will generate the data using the random.randn() method." }, { "code": null, "e": 1515, "s": 1507, "text": "Python3" }, { "code": "# Import necessary librariesimport seaborn as snsimport numpy as npimport pandas as pd # Generating dataset of random numbersnp.random.seed(1)num_var = np.random.randn(1000)num_var = pd.Series(num_var, name = \"Numerical Variable\") # Plot histogramsns.histplot(data = num_var, kde = True)", "e": 1803, "s": 1515, "text": null }, { "code": null, "e": 1811, "s": 1803, "text": "Output:" }, { "code": null, "e": 2003, "s": 1811, "text": "By default kde parameter of seaborn.histplot is set to false. So, by setting the kde to true, a kernel density estimate is computed to smooth the distribution and a density plotline is drawn." }, { "code": null, "e": 2235, "s": 2003, "text": "Example 2: Let us use the sample dataset, Penguins, from the Seaborn library in this example. This dataset shows the characteristics (body mass, flipper length, bill length gender) of different penguin species on different islands." }, { "code": null, "e": 2243, "s": 2235, "text": "Python3" }, { "code": "# Import necessary librariesimport numpy as npimport pandas as pdimport seaborn as sns # Load datasetpenguins = sns.load_dataset(\"penguins\") # Plot histogramsns.histplot(data = penguins, x = \"body_mass_g\", kde = True)", "e": 2461, "s": 2243, "text": null }, { "code": null, "e": 2469, "s": 2461, "text": "Output:" }, { "code": null, "e": 2617, "s": 2469, "text": "We can also visualize the distribution of body mass for multiple species in a single plot. The hue parameter maps the semantic variable ‘species’. " }, { "code": null, "e": 2625, "s": 2617, "text": "Python3" }, { "code": "# Plot Histogramsns.histplot(data = penguins, x = \"body_mass_g\", kde = True, hue = \"species\")", "e": 2719, "s": 2625, "text": null }, { "code": null, "e": 2727, "s": 2719, "text": "Output:" }, { "code": null, "e": 3171, "s": 2727, "text": "Example 3: This example uses the sample dataset, Tips, from the Seaborn library which records the tips received by a restaurant server. It consists of the tip received total bill or cost of the meal, gender of the customer, size of the customer party, day, time and whether a smoker is present at the party or not. Instead of the count of data points, the histogram in this example is normalized so that each bar’s height shows a probability. " }, { "code": null, "e": 3179, "s": 3171, "text": "Python3" }, { "code": "# Import necessary librariesimport numpy as npimport pandas as pdimport seaborn as sns # Load datasettips = sns.load_dataset(\"tips\") # Plot histogramsns.histplot(data = tips, x = \"size\", stat = \"probability\", discrete = True)", "e": 3405, "s": 3179, "text": null }, { "code": null, "e": 3413, "s": 3405, "text": "Output:" }, { "code": null, "e": 3429, "s": 3413, "text": "rajeev0719singh" }, { "code": null, "e": 3444, "s": 3429, "text": "Python-Seaborn" }, { "code": null, "e": 3451, "s": 3444, "text": "Python" }, { "code": null, "e": 3549, "s": 3451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3577, "s": 3549, "text": "Read JSON file using Python" }, { "code": null, "e": 3599, "s": 3577, "text": "Python map() function" }, { "code": null, "e": 3649, "s": 3599, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3667, "s": 3649, "text": "Python Dictionary" }, { "code": null, "e": 3711, "s": 3667, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3734, "s": 3711, "text": "Taking input in Python" }, { "code": null, "e": 3776, "s": 3734, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3798, "s": 3776, "text": "Enumerate() in Python" }, { "code": null, "e": 3833, "s": 3798, "text": "Read a file line by line in Python" } ]
Sort list of tuples by specific ordering in Python
When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used. The 'sorted' method is used to sort the elements of a list. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list. Below is a demonstration for the same − Live Demo def tuple_sort(my_tup): return(sorted(my_tup, key = lambda x: x[1])) my_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)] print("The list of tuple is : ") print(my_tuple) print("The tuple after placing in a specific order is : ") print(tuple_sort(my_tuple)) The list of tuple is : [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)] The tuple after placing in a specific order is : [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)] A method named 'tuple_sort' is defined that takes a list of tuple as parameter. It uses the 'sorted' method to sort the list of tuple in the order based on the first element in every tuple inside the list of tuple. A list of tuple is defined, and is displayed on the console. The function is called by passing this list of tuple as parameter. This operation's data is stored in a variable. This variable is the output that is displayed on the console.
[ { "code": null, "e": 1288, "s": 1187, "text": "When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used." }, { "code": null, "e": 1348, "s": 1288, "text": "The 'sorted' method is used to sort the elements of a list." }, { "code": null, "e": 1537, "s": 1348, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list." }, { "code": null, "e": 1577, "s": 1537, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1587, "s": 1577, "text": "Live Demo" }, { "code": null, "e": 1866, "s": 1587, "text": "def tuple_sort(my_tup):\n return(sorted(my_tup, key = lambda x: x[1]))\n\nmy_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]\n\nprint(\"The list of tuple is : \")\nprint(my_tuple)\nprint(\"The tuple after placing in a specific order is : \")\nprint(tuple_sort(my_tuple))" }, { "code": null, "e": 2054, "s": 1866, "text": "The list of tuple is :\n[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]\nThe tuple after placing in a specific order is :\n[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]" }, { "code": null, "e": 2134, "s": 2054, "text": "A method named 'tuple_sort' is defined that takes a list of tuple as parameter." }, { "code": null, "e": 2269, "s": 2134, "text": "It uses the 'sorted' method to sort the list of tuple in the order based on the first element in every tuple inside the list of tuple." }, { "code": null, "e": 2330, "s": 2269, "text": "A list of tuple is defined, and is displayed on the console." }, { "code": null, "e": 2397, "s": 2330, "text": "The function is called by passing this list of tuple as parameter." }, { "code": null, "e": 2444, "s": 2397, "text": "This operation's data is stored in a variable." }, { "code": null, "e": 2506, "s": 2444, "text": "This variable is the output that is displayed on the console." } ]
SAP Labs Interview Experience
22 Oct, 2020 Online Assessment Round: 15 MCQ questions and 2 coding questions were asked. In MCQ, questions were from Aptitude, DS, CN, and DBMS. Coding 1: Count the distinct pairs with a difference equal to k. Coding 2: I don’t remember exactly this. To solve coding 1, either use a sorting algorithm or just use two-loop. Interview Rounds: Two coding round(tech round), managerial round, and HR round. Coding, round-1 was on hacker rank, and the remaining rounds were on Microsoft Teams meeting. Tech Round-1: [ 30 mins] Introduce yourself.DBMS query question: two tables were given candidate(id, name, gender, age) and results(candidate_id, votes,....) find the sum of votes of those candidates whose age<50 and gender is female. (select sum(votes) from candidates inner join results on candidate.id=results.candidate_id where candidate.age<50 and candidate.gender=’F’;String question: Three strings are given concatenate them in alphabetical order.Pattern Matching Approach. (I explained two approaches, Naive and KMP)Explain your project, and problems encountered, and how did you fix them. Introduce yourself. DBMS query question: two tables were given candidate(id, name, gender, age) and results(candidate_id, votes,....) find the sum of votes of those candidates whose age<50 and gender is female. (select sum(votes) from candidates inner join results on candidate.id=results.candidate_id where candidate.age<50 and candidate.gender=’F’; String question: Three strings are given concatenate them in alphabetical order. Pattern Matching Approach. (I explained two approaches, Naive and KMP) Explain your project, and problems encountered, and how did you fix them. Tech Round-2: [ 40 mins ] Introduce yourself. Coding question: A string is given containing chars p,c,m,b (physics, chemistry, maths, biology), and these four chars form a group. Find out how many groups are possible in the given input. i/p: “pcmppcmb”, “ppccmmbb”, pmppc”, etc. [ Just count the all occurrences of p,c,m,b, and return min]. Oops concept: Inheritance, friend function/class, virtual function/abstarct class, etc. DBMS query: two tables were given i.e, student, course. One query was based on join, and 2nd one was on GROUP BY and LIMIT clause. Binary tree traversal: Find preorder, postorder, and explain recursive behavior. Write the code to find min element, height, level order traversal, print leaf node, and insert an element, for binary search tree. Project-related questions. Managerial Round: [ 30 mins ] Introduce yourself. Strength and weakness and why? Why did you choose to engineer? Explain your project, and what are some major factors of your project. Whether you get the desired result or not? were you stuck at any point during implementation and how did you fix that? Puzzle: a dataset is given(from 2000-2020) in which two columns are there i.e, noOfDOB, noOfDeath, then find out max population year?, and How do you implement this? Suppose SAP has three posts vacancies for ML, IoT and PROGRAMMER then which one will you choose and why? if you didn’t get your desired post then what will you do? In my resume I had written reading practical and proven books as a hobby then he asked those books name/writer and what did you find most interesting? I was rejected after the managerial round. I was shocked, what went wrong, which results in rejection. Suggestions: Since I was able to solve all the questions of both the technical rounds, then also I was rejected. It may be because of the managerial round, and Vipin sir(managerial round interviewer) may not be satisfied with my answers. In the managerial round: Personal questions answer must be related to your professional life, and you should also explain with one incident which makes you realize. For example, if you explained your weakness then you should also explain that you are working on that to improve.If they asked, why did you choose to engineer then you should say something logical. Don’t say like I had no other option, my father suggested to me, my relative suggested to me, etc. I said I read a book that inclined my interest in engineering. Personal questions answer must be related to your professional life, and you should also explain with one incident which makes you realize. For example, if you explained your weakness then you should also explain that you are working on that to improve. If they asked, why did you choose to engineer then you should say something logical. Don’t say like I had no other option, my father suggested to me, my relative suggested to me, etc. I said I read a book that inclined my interest in engineering. Marketing SAP Labs Interview Experiences SAP Labs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Oct, 2020" }, { "code": null, "e": 161, "s": 28, "text": "Online Assessment Round: 15 MCQ questions and 2 coding questions were asked. In MCQ, questions were from Aptitude, DS, CN, and DBMS." }, { "code": null, "e": 226, "s": 161, "text": "Coding 1: Count the distinct pairs with a difference equal to k." }, { "code": null, "e": 267, "s": 226, "text": "Coding 2: I don’t remember exactly this." }, { "code": null, "e": 339, "s": 267, "text": "To solve coding 1, either use a sorting algorithm or just use two-loop." }, { "code": null, "e": 513, "s": 339, "text": "Interview Rounds: Two coding round(tech round), managerial round, and HR round. Coding, round-1 was on hacker rank, and the remaining rounds were on Microsoft Teams meeting." }, { "code": null, "e": 538, "s": 513, "text": "Tech Round-1: [ 30 mins]" }, { "code": null, "e": 1111, "s": 538, "text": "Introduce yourself.DBMS query question: two tables were given candidate(id, name, gender, age) and results(candidate_id, votes,....) find the sum of votes of those candidates whose age<50 and gender is female. (select sum(votes) from candidates inner join results on candidate.id=results.candidate_id where candidate.age<50 and candidate.gender=’F’;String question: Three strings are given concatenate them in alphabetical order.Pattern Matching Approach. (I explained two approaches, Naive and KMP)Explain your project, and problems encountered, and how did you fix them." }, { "code": null, "e": 1131, "s": 1111, "text": "Introduce yourself." }, { "code": null, "e": 1462, "s": 1131, "text": "DBMS query question: two tables were given candidate(id, name, gender, age) and results(candidate_id, votes,....) find the sum of votes of those candidates whose age<50 and gender is female. (select sum(votes) from candidates inner join results on candidate.id=results.candidate_id where candidate.age<50 and candidate.gender=’F’;" }, { "code": null, "e": 1543, "s": 1462, "text": "String question: Three strings are given concatenate them in alphabetical order." }, { "code": null, "e": 1614, "s": 1543, "text": "Pattern Matching Approach. (I explained two approaches, Naive and KMP)" }, { "code": null, "e": 1688, "s": 1614, "text": "Explain your project, and problems encountered, and how did you fix them." }, { "code": null, "e": 1714, "s": 1688, "text": "Tech Round-2: [ 40 mins ]" }, { "code": null, "e": 1734, "s": 1714, "text": "Introduce yourself." }, { "code": null, "e": 2029, "s": 1734, "text": "Coding question: A string is given containing chars p,c,m,b (physics, chemistry, maths, biology), and these four chars form a group. Find out how many groups are possible in the given input. i/p: “pcmppcmb”, “ppccmmbb”, pmppc”, etc. [ Just count the all occurrences of p,c,m,b, and return min]." }, { "code": null, "e": 2117, "s": 2029, "text": "Oops concept: Inheritance, friend function/class, virtual function/abstarct class, etc." }, { "code": null, "e": 2250, "s": 2119, "text": "DBMS query: two tables were given i.e, student, course. One query was based on join, and 2nd one was on GROUP BY and LIMIT clause." }, { "code": null, "e": 2331, "s": 2250, "text": "Binary tree traversal: Find preorder, postorder, and explain recursive behavior." }, { "code": null, "e": 2462, "s": 2331, "text": "Write the code to find min element, height, level order traversal, print leaf node, and insert an element, for binary search tree." }, { "code": null, "e": 2489, "s": 2462, "text": "Project-related questions." }, { "code": null, "e": 2519, "s": 2489, "text": "Managerial Round: [ 30 mins ]" }, { "code": null, "e": 2539, "s": 2519, "text": "Introduce yourself." }, { "code": null, "e": 2570, "s": 2539, "text": "Strength and weakness and why?" }, { "code": null, "e": 2602, "s": 2570, "text": "Why did you choose to engineer?" }, { "code": null, "e": 2792, "s": 2602, "text": "Explain your project, and what are some major factors of your project. Whether you get the desired result or not? were you stuck at any point during implementation and how did you fix that?" }, { "code": null, "e": 2958, "s": 2792, "text": "Puzzle: a dataset is given(from 2000-2020) in which two columns are there i.e, noOfDOB, noOfDeath, then find out max population year?, and How do you implement this?" }, { "code": null, "e": 3122, "s": 2958, "text": "Suppose SAP has three posts vacancies for ML, IoT and PROGRAMMER then which one will you choose and why? if you didn’t get your desired post then what will you do?" }, { "code": null, "e": 3273, "s": 3122, "text": "In my resume I had written reading practical and proven books as a hobby then he asked those books name/writer and what did you find most interesting?" }, { "code": null, "e": 3376, "s": 3273, "text": "I was rejected after the managerial round. I was shocked, what went wrong, which results in rejection." }, { "code": null, "e": 3615, "s": 3376, "text": "Suggestions: Since I was able to solve all the questions of both the technical rounds, then also I was rejected. It may be because of the managerial round, and Vipin sir(managerial round interviewer) may not be satisfied with my answers. " }, { "code": null, "e": 3640, "s": 3615, "text": "In the managerial round:" }, { "code": null, "e": 4140, "s": 3640, "text": "Personal questions answer must be related to your professional life, and you should also explain with one incident which makes you realize. For example, if you explained your weakness then you should also explain that you are working on that to improve.If they asked, why did you choose to engineer then you should say something logical. Don’t say like I had no other option, my father suggested to me, my relative suggested to me, etc. I said I read a book that inclined my interest in engineering." }, { "code": null, "e": 4394, "s": 4140, "text": "Personal questions answer must be related to your professional life, and you should also explain with one incident which makes you realize. For example, if you explained your weakness then you should also explain that you are working on that to improve." }, { "code": null, "e": 4641, "s": 4394, "text": "If they asked, why did you choose to engineer then you should say something logical. Don’t say like I had no other option, my father suggested to me, my relative suggested to me, etc. I said I read a book that inclined my interest in engineering." }, { "code": null, "e": 4651, "s": 4641, "text": "Marketing" }, { "code": null, "e": 4660, "s": 4651, "text": "SAP Labs" }, { "code": null, "e": 4682, "s": 4660, "text": "Interview Experiences" }, { "code": null, "e": 4691, "s": 4682, "text": "SAP Labs" } ]
Readers-Writers Problem | Writers Preference Solution
31 Jan, 2022 Prerequisites — Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution), Semaphores in Process Synchronization In Process-synchronization, there is a very classical synchronization problem named as Readers-writers problem. The problem has several sub-problems or variations all involving priorities, one of which is discussed in the above post. The second variation goes by the name Writer-priority readers-writers problem. The set of variables used to solve the problem are:- The readers, which keeps the track of how many readers are there at a time. Mutex, protects the shared variables.Idle, is used to indicate the number of threads(reader or writer) in the critical section. If they’re no threads, then it should be 1, otherwise 0. The readers, which keeps the track of how many readers are there at a time. Mutex, protects the shared variables. Idle, is used to indicate the number of threads(reader or writer) in the critical section. If they’re no threads, then it should be 1, otherwise 0. int readers = 0 //Keeps the count of readers idle = Semaphore (1) // 1 if no threads are present, else 0 mutex = Semaphore (1) //Mutex protects the shared counter For the Semaphore variable,wait() means “wait until a condition is true” andsignal() means that “signal that the condition is true” readSwitch = Lightswitch () writeSwitch = Lightswitch () noReaders = Semaphore (1) noWriters = Semaphore (1) First, let’s explore the scenario when Reader has priority over writer. The problem statement: It states that, once a reader is ready, then readers may read the file. In other words, no reader should wait if the reader has access to the object, while the writer waits till the reader to complete it. Solution when reader has priority over writer Writers Solution: Writer requests entry to the critical section If allowed then, it holds noReaders, and writes. Else it waits in the queue, till wait() is true It exits the critical section Here is the writer code: idle.wait() //Waits till the critical section is empty. //Critical Section for the Writer idle.signal() //Signals that the critical section is empty. Here, when the writer was in the critical section, no other thread( i.e. reader or writer) was present in the Critical section. First, a reader checks whether the critical section is empty or not. If empty, it proceeds there and bars the writer from entering. Reader Solution: Reader requests for entry in the critical section. if allowed, then It holds noWriters, Since it holds the mutex, any subsequent readers queue on mutex. Subsequent readers can still enter Reader exits the critical section. Here is the reader code : readSwitch.lock ( noWriters ) //Locks the writer noReaders.wait () signaling // Waits till the reader exits the critical section //critical section for readers noReaders.signal () //Signals that reader has exited from the Critical section readSwitch.unlock (noWriters) // Unlocks the reader. The problem statement: It requires that, once a writer is ready, that writer performs its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading. Solution when Writer has the Priority over Reader Readers Solution: Reader requests the entry to the critical section If allowed, then, It holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue.Once the last reader exits, it signals noWriters, which allows the writers in the queue to proceed. It holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue. Once the last reader exits, it signals noWriters, which allows the writers in the queue to proceed. Here is the reader code: noReaders.wait () readSwitch.lock ( noWriters ) // Locks the writers when readers enter the critical section noReaders.signal () //Signals that reader is in critical section //critical section for readers readSwitch . unlock ( noWriters ) //Once the reader exits the critical section, then the writer is unlocked. Writers Solution: Writer requests the entry to the critical section. If allowed, then It holds both noReaders as well as noWriters. This ensures that no reader and no writer are in the critical section.If a reader is in the critical section, it holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue.Moreover, writeSwitch allows multiple writers to queue on noWriters, while locking the noReaders. Hence, many writers pass through the critical section without even signaling the noReaders It holds both noReaders as well as noWriters. This ensures that no reader and no writer are in the critical section. If a reader is in the critical section, it holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue. Moreover, writeSwitch allows multiple writers to queue on noWriters, while locking the noReaders. Hence, many writers pass through the critical section without even signaling the noReaders Once the last writer leaves the critical section, then the only reader can enter the critical section Here is the writer code: writeSwitch . lock ( noReaders ) //Locks the reader noWriters . wait () // Waits till the writer is complete. //critical section for writers noWriters . signal () //Signals that writer has exited from the Critical section writeSwitch . unlock ( noReaders ) // Unlocks the reader. But this implementation has a drawback, i.e. the readers may starve or may face long delays. To avoid starvation, monitors are used. rs1686740 surinderdawra388 rkbhola5 Process Synchronization GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Jan, 2022" }, { "code": null, "e": 186, "s": 52, "text": "Prerequisites — Readers-Writers Problem | Set 1 (Introduction and Readers Preference Solution), Semaphores in Process Synchronization" }, { "code": null, "e": 500, "s": 186, "text": "In Process-synchronization, there is a very classical synchronization problem named as Readers-writers problem. The problem has several sub-problems or variations all involving priorities, one of which is discussed in the above post. The second variation goes by the name Writer-priority readers-writers problem. " }, { "code": null, "e": 553, "s": 500, "text": "The set of variables used to solve the problem are:-" }, { "code": null, "e": 815, "s": 553, "text": "The readers, which keeps the track of how many readers are there at a time. Mutex, protects the shared variables.Idle, is used to indicate the number of threads(reader or writer) in the critical section. If they’re no threads, then it should be 1, otherwise 0." }, { "code": null, "e": 891, "s": 815, "text": "The readers, which keeps the track of how many readers are there at a time." }, { "code": null, "e": 931, "s": 891, "text": " Mutex, protects the shared variables." }, { "code": null, "e": 1079, "s": 931, "text": "Idle, is used to indicate the number of threads(reader or writer) in the critical section. If they’re no threads, then it should be 1, otherwise 0." }, { "code": null, "e": 1276, "s": 1079, "text": "int readers = 0 //Keeps the count of readers\nidle = Semaphore (1) // 1 if no threads are present, else 0\nmutex = Semaphore (1) //Mutex protects the shared counter" }, { "code": null, "e": 1409, "s": 1276, "text": "For the Semaphore variable,wait() means “wait until a condition is true” andsignal() means that “signal that the condition is true”" }, { "code": null, "e": 1518, "s": 1409, "text": "readSwitch = Lightswitch ()\nwriteSwitch = Lightswitch ()\nnoReaders = Semaphore (1)\nnoWriters = Semaphore (1)" }, { "code": null, "e": 1591, "s": 1518, "text": "First, let’s explore the scenario when Reader has priority over writer. " }, { "code": null, "e": 1820, "s": 1591, "text": "The problem statement: It states that, once a reader is ready, then readers may read the file. In other words, no reader should wait if the reader has access to the object, while the writer waits till the reader to complete it." }, { "code": null, "e": 1866, "s": 1820, "text": "Solution when reader has priority over writer" }, { "code": null, "e": 1884, "s": 1866, "text": "Writers Solution:" }, { "code": null, "e": 1930, "s": 1884, "text": "Writer requests entry to the critical section" }, { "code": null, "e": 2027, "s": 1930, "text": "If allowed then, it holds noReaders, and writes. Else it waits in the queue, till wait() is true" }, { "code": null, "e": 2057, "s": 2027, "text": "It exits the critical section" }, { "code": null, "e": 2082, "s": 2057, "text": "Here is the writer code:" }, { "code": null, "e": 2262, "s": 2082, "text": "idle.wait() //Waits till the critical section is empty.\n //Critical Section for the Writer\nidle.signal() //Signals that the critical section is empty." }, { "code": null, "e": 2522, "s": 2262, "text": "Here, when the writer was in the critical section, no other thread( i.e. reader or writer) was present in the Critical section. First, a reader checks whether the critical section is empty or not. If empty, it proceeds there and bars the writer from entering." }, { "code": null, "e": 2539, "s": 2522, "text": "Reader Solution:" }, { "code": null, "e": 2590, "s": 2539, "text": "Reader requests for entry in the critical section." }, { "code": null, "e": 2727, "s": 2590, "text": "if allowed, then It holds noWriters, Since it holds the mutex, any subsequent readers queue on mutex. Subsequent readers can still enter" }, { "code": null, "e": 2762, "s": 2727, "text": "Reader exits the critical section." }, { "code": null, "e": 2789, "s": 2762, "text": "Here is the reader code :" }, { "code": null, "e": 3137, "s": 2789, "text": "readSwitch.lock ( noWriters ) //Locks the writer\n noReaders.wait () signaling // Waits till the reader exits the critical section\n //critical section for readers\n noReaders.signal () //Signals that reader has exited from the Critical section\nreadSwitch.unlock (noWriters) // Unlocks the reader." }, { "code": null, "e": 3350, "s": 3137, "text": "The problem statement: It requires that, once a writer is ready, that writer performs its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading." }, { "code": null, "e": 3400, "s": 3350, "text": "Solution when Writer has the Priority over Reader" }, { "code": null, "e": 3418, "s": 3400, "text": "Readers Solution:" }, { "code": null, "e": 3468, "s": 3418, "text": "Reader requests the entry to the critical section" }, { "code": null, "e": 3486, "s": 3468, "text": "If allowed, then," }, { "code": null, "e": 3730, "s": 3486, "text": "It holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue.Once the last reader exits, it signals noWriters, which allows the writers in the queue to proceed." }, { "code": null, "e": 3875, "s": 3730, "text": "It holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue." }, { "code": null, "e": 3975, "s": 3875, "text": "Once the last reader exits, it signals noWriters, which allows the writers in the queue to proceed." }, { "code": null, "e": 4001, "s": 3975, "text": "Here is the reader code:" }, { "code": null, "e": 4346, "s": 4001, "text": "noReaders.wait ()\n readSwitch.lock ( noWriters ) // Locks the writers when readers enter the critical section\nnoReaders.signal () //Signals that reader is in critical section\n //critical section for readers\nreadSwitch . unlock ( noWriters ) //Once the reader exits the critical section, then the writer is unlocked." }, { "code": null, "e": 4365, "s": 4346, "text": "Writers Solution:" }, { "code": null, "e": 4416, "s": 4365, "text": "Writer requests the entry to the critical section." }, { "code": null, "e": 4433, "s": 4416, "text": "If allowed, then" }, { "code": null, "e": 4923, "s": 4433, "text": "It holds both noReaders as well as noWriters. This ensures that no reader and no writer are in the critical section.If a reader is in the critical section, it holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue.Moreover, writeSwitch allows multiple writers to queue on noWriters, while locking the noReaders. Hence, many writers pass through the critical section without even signaling the noReaders" }, { "code": null, "e": 5041, "s": 4923, "text": "It holds both noReaders as well as noWriters. This ensures that no reader and no writer are in the critical section." }, { "code": null, "e": 5226, "s": 5041, "text": "If a reader is in the critical section, it holds noWriters, but it doesn’t hold noReaders. Thus if a writer arrives it can lock noReaders, which will cause subsequent readers to queue." }, { "code": null, "e": 5415, "s": 5226, "text": "Moreover, writeSwitch allows multiple writers to queue on noWriters, while locking the noReaders. Hence, many writers pass through the critical section without even signaling the noReaders" }, { "code": null, "e": 5520, "s": 5415, "text": " Once the last writer leaves the critical section, then the only reader can enter the critical section" }, { "code": null, "e": 5545, "s": 5520, "text": "Here is the writer code:" }, { "code": null, "e": 5902, "s": 5545, "text": "writeSwitch . lock ( noReaders ) //Locks the reader\n noWriters . wait () // Waits till the writer is complete.\n //critical section for writers\n noWriters . signal () //Signals that writer has exited from the Critical section\nwriteSwitch . unlock ( noReaders ) // Unlocks the reader." }, { "code": null, "e": 6035, "s": 5902, "text": "But this implementation has a drawback, i.e. the readers may starve or may face long delays. To avoid starvation, monitors are used." }, { "code": null, "e": 6045, "s": 6035, "text": "rs1686740" }, { "code": null, "e": 6062, "s": 6045, "text": "surinderdawra388" }, { "code": null, "e": 6071, "s": 6062, "text": "rkbhola5" }, { "code": null, "e": 6095, "s": 6071, "text": "Process Synchronization" }, { "code": null, "e": 6103, "s": 6095, "text": "GATE CS" }, { "code": null, "e": 6121, "s": 6103, "text": "Operating Systems" }, { "code": null, "e": 6139, "s": 6121, "text": "Operating Systems" } ]
Print a Formatted string in R Programming – sprintf() Function
03 Jun, 2020 sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list. Syntax: sprintf(format, values) Parameter:format: Format of printing the valuesvalues: to be passed into format Example 1: # R program to illustrate # the use of sprintf() function # Initializing valuesx1 <- "Welcome"x2 <- "GeeksforGeeks" # Calling sprintf() functionsprintf("% s to % s", x1, x2) Output: [1] "Welcome to GeeksforGeeks" Example 2: # R program to illustrate # the use of sprintf() function # Initializing valuesx1 <- "GeeksforGeeks"x2 <- 100x3 <- "success" # Calling sprintf() functionsprintf("% s gives %.0f percent % s", x1, x2, x3) Output: [1] "GeeksforGeeks gives 100 percent success" R String-Functions R-basics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 165, "s": 28, "text": "sprintf() function in R Language uses Format provided by the user to return the formatted string with the use of the values in the list." }, { "code": null, "e": 197, "s": 165, "text": "Syntax: sprintf(format, values)" }, { "code": null, "e": 277, "s": 197, "text": "Parameter:format: Format of printing the valuesvalues: to be passed into format" }, { "code": null, "e": 288, "s": 277, "text": "Example 1:" }, { "code": "# R program to illustrate # the use of sprintf() function # Initializing valuesx1 <- \"Welcome\"x2 <- \"GeeksforGeeks\" # Calling sprintf() functionsprintf(\"% s to % s\", x1, x2)", "e": 464, "s": 288, "text": null }, { "code": null, "e": 472, "s": 464, "text": "Output:" }, { "code": null, "e": 504, "s": 472, "text": "[1] \"Welcome to GeeksforGeeks\"\n" }, { "code": null, "e": 515, "s": 504, "text": "Example 2:" }, { "code": "# R program to illustrate # the use of sprintf() function # Initializing valuesx1 <- \"GeeksforGeeks\"x2 <- 100x3 <- \"success\" # Calling sprintf() functionsprintf(\"% s gives %.0f percent % s\", x1, x2, x3)", "e": 720, "s": 515, "text": null }, { "code": null, "e": 728, "s": 720, "text": "Output:" }, { "code": null, "e": 775, "s": 728, "text": "[1] \"GeeksforGeeks gives 100 percent success\"\n" }, { "code": null, "e": 794, "s": 775, "text": "R String-Functions" }, { "code": null, "e": 803, "s": 794, "text": "R-basics" }, { "code": null, "e": 814, "s": 803, "text": "R Language" } ]
Difference Between Single and Double Square Brackets in R - GeeksforGeeks
18 Nov, 2021 The single and double square brackets are used as indexing operators in R Programming Language. Both of these operators are used for referencing the components of R storage objects either as a subset belonging to the same data type or as an element. The table illustrates some key differences among both the types of operators : [] [[]] Example 1: Accessing the elements of the singular lists Singular lists contain a single level of indexing for the elements. On the application of either of the bracket operator, the elements at the specified index position of the list is returned. In case of double square brackets, the same result is obtained, because the list at jth specified index also consist of that particular element itself. Therefore, the type of brackets can be used interchangeably. The only difference here is, in case we specify an index which is greater than the length of the list, then singular brackets return NA, because the value is missing. However, double brackets try to access the list present at this missing index, and thereby throws an error. R # declaring a numeric vectorvec <- c(1:10)print ("Original Vector")print (vec) # using single bracketprint ("Singular brackets")print(vec[5]) # using dual bracketprint ("Double brackets")print (vec[[5]]) Output: [1] "Original Vector" [1] 1 2 3 4 5 6 7 8 9 10 [1] "Singular brackets" [1] 5 [1] "Double brackets" [1] 5 Example 2: Accessing the elements of the nested lists Nested lists contain lists and other objects (either vectors) as its elements. Retrieval in the nested lists is performed based on multiple and recursive indexing. The number of index subscripts used for reference depends on the number of levels to explore to access the element. The element at the index can be accessed using double brackets and lists’ subset can be accessed using single brackets. R # declaring a nested listnested_list <- list(list(letters[1:8],"secondele"), 5:15, FALSE) print("Original list")print(nested_list) print ("Accessing first sub-list of the list")print(nested_list[1]) print ("Accessing first component of the list")print(nested_list[[1]]) print ("Accessing components inside component of the list")print(nested_list[[1]][[2]]) Output: [1] "Original list" [[1]] [[1]][[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" [[1]][[2]] [1] "secondele" [[2]] [1] 5 6 7 8 9 10 11 12 13 14 15 [[3]] [1] FALSE [1] "Accessing first sub-list of the list" [[1]] [[1]][[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" [[1]][[2]] [1] "secondele" [1] "Accessing first component of the list" [[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" [[2]] [1] "secondele" [1] "Accessing components inside component of the list" [1] "secondele" Example 3: Accessing the elements of the vectors or arrays In case of uni-dimensional arrays, there is no major differences in the working of both the operators. Both the operators attempt to return the element present at the specified index of the array. However, like singular lists, in case any element outside the range is accessed, in case of singular brackets NA is returned, while double brackets throw a subscript out of bounds exception, while terminating the execution. R # declaring a numeric vectorarr <- 1:15print ("Original Vector")print (arr) print ("Singular brackets")print(arr[8]) print ("Double brackets")print(arr[[8]]) Output [1] "Original Vector" [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [1] "Singular brackets" [1] 10 [1] "Singular brackets" [1] 10 Example 4: Accessing the elements of the dataframes The single brackets in a dataframe are used to access a subset of the dataframe, that is a sub-dataframe is only accessed. The column corresponding to the specified index and all the rows are returned as an output. In case of double brackets in a dataframe, the same output is returned to the form of an element vector. R # declaring a dataframedata_frame <- data.frame(col1=letters[1:6], col2 = c(7:12), col3 = c(1:6))print ("Original dataframe")print (data_frame) print ("Sub dataframe")print (data_frame[2]) print ("Element dataframe")print (data_frame[[2]]) Output: [1] "Original dataframe" col1 col2 col3 1 a 7 1 2 b 8 2 3 c 9 3 4 d 10 4 5 e 11 5 6 f 12 6 [1] "Sub dataframe" col2 1 7 2 8 3 9 4 10 5 11 6 12 [1] "Element dataframe" [1] 7 8 9 10 11 12 prachisoda1234 Picked R-basics Difference Between R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method
[ { "code": null, "e": 24858, "s": 24830, "text": "\n18 Nov, 2021" }, { "code": null, "e": 25109, "s": 24858, "text": "The single and double square brackets are used as indexing operators in R Programming Language. Both of these operators are used for referencing the components of R storage objects either as a subset belonging to the same data type or as an element. " }, { "code": null, "e": 25189, "s": 25109, "text": "The table illustrates some key differences among both the types of operators : " }, { "code": null, "e": 25192, "s": 25189, "text": "[]" }, { "code": null, "e": 25197, "s": 25192, "text": "[[]]" }, { "code": null, "e": 25253, "s": 25197, "text": "Example 1: Accessing the elements of the singular lists" }, { "code": null, "e": 25933, "s": 25253, "text": "Singular lists contain a single level of indexing for the elements. On the application of either of the bracket operator, the elements at the specified index position of the list is returned. In case of double square brackets, the same result is obtained, because the list at jth specified index also consist of that particular element itself. Therefore, the type of brackets can be used interchangeably. The only difference here is, in case we specify an index which is greater than the length of the list, then singular brackets return NA, because the value is missing. However, double brackets try to access the list present at this missing index, and thereby throws an error." }, { "code": null, "e": 25935, "s": 25933, "text": "R" }, { "code": "# declaring a numeric vectorvec <- c(1:10)print (\"Original Vector\")print (vec) # using single bracketprint (\"Singular brackets\")print(vec[5]) # using dual bracketprint (\"Double brackets\")print (vec[[5]])", "e": 26139, "s": 25935, "text": null }, { "code": null, "e": 26147, "s": 26139, "text": "Output:" }, { "code": null, "e": 26261, "s": 26147, "text": "[1] \"Original Vector\"\n[1] 1 2 3 4 5 6 7 8 9 10\n[1] \"Singular brackets\"\n[1] 5\n[1] \"Double brackets\"\n[1] 5" }, { "code": null, "e": 26315, "s": 26261, "text": "Example 2: Accessing the elements of the nested lists" }, { "code": null, "e": 26716, "s": 26315, "text": "Nested lists contain lists and other objects (either vectors) as its elements. Retrieval in the nested lists is performed based on multiple and recursive indexing. The number of index subscripts used for reference depends on the number of levels to explore to access the element. The element at the index can be accessed using double brackets and lists’ subset can be accessed using single brackets. " }, { "code": null, "e": 26718, "s": 26716, "text": "R" }, { "code": "# declaring a nested listnested_list <- list(list(letters[1:8],\"secondele\"), 5:15, FALSE) print(\"Original list\")print(nested_list) print (\"Accessing first sub-list of the list\")print(nested_list[1]) print (\"Accessing first component of the list\")print(nested_list[[1]]) print (\"Accessing components inside component of the list\")print(nested_list[[1]][[2]])", "e": 27119, "s": 26718, "text": null }, { "code": null, "e": 27127, "s": 27119, "text": "Output:" }, { "code": null, "e": 27600, "s": 27127, "text": "[1] \"Original list\"\n[[1]]\n[[1]][[1]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n[[1]][[2]]\n[1] \"secondele\"\n\n\n[[2]]\n [1] 5 6 7 8 9 10 11 12 13 14 15\n\n[[3]]\n[1] FALSE\n\n[1] \"Accessing first sub-list of the list\"\n[[1]]\n[[1]][[1]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n[[1]][[2]]\n[1] \"secondele\"\n\n\n[1] \"Accessing first component of the list\"\n[[1]]\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\"\n\n[[2]]\n[1] \"secondele\"\n\n[1] \"Accessing components inside component of the list\"\n[1] \"secondele\"" }, { "code": null, "e": 27659, "s": 27600, "text": "Example 3: Accessing the elements of the vectors or arrays" }, { "code": null, "e": 28081, "s": 27659, "text": "In case of uni-dimensional arrays, there is no major differences in the working of both the operators. Both the operators attempt to return the element present at the specified index of the array. However, like singular lists, in case any element outside the range is accessed, in case of singular brackets NA is returned, while double brackets throw a subscript out of bounds exception, while terminating the execution. " }, { "code": null, "e": 28083, "s": 28081, "text": "R" }, { "code": "# declaring a numeric vectorarr <- 1:15print (\"Original Vector\")print (arr) print (\"Singular brackets\")print(arr[8]) print (\"Double brackets\")print(arr[[8]])", "e": 28241, "s": 28083, "text": null }, { "code": null, "e": 28248, "s": 28241, "text": "Output" }, { "code": null, "e": 28381, "s": 28248, "text": "[1] \"Original Vector\"\n[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n[1] \"Singular brackets\"\n[1] 10\n[1] \"Singular brackets\"\n[1] 10" }, { "code": null, "e": 28433, "s": 28381, "text": "Example 4: Accessing the elements of the dataframes" }, { "code": null, "e": 28754, "s": 28433, "text": "The single brackets in a dataframe are used to access a subset of the dataframe, that is a sub-dataframe is only accessed. The column corresponding to the specified index and all the rows are returned as an output. In case of double brackets in a dataframe, the same output is returned to the form of an element vector. " }, { "code": null, "e": 28756, "s": 28754, "text": "R" }, { "code": "# declaring a dataframedata_frame <- data.frame(col1=letters[1:6], col2 = c(7:12), col3 = c(1:6))print (\"Original dataframe\")print (data_frame) print (\"Sub dataframe\")print (data_frame[2]) print (\"Element dataframe\")print (data_frame[[2]])", "e": 29023, "s": 28756, "text": null }, { "code": null, "e": 29031, "s": 29023, "text": "Output:" }, { "code": null, "e": 29288, "s": 29031, "text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 a 7 1\n2 b 8 2\n3 c 9 3\n4 d 10 4\n5 e 11 5\n6 f 12 6\n[1] \"Sub dataframe\"\n col2\n1 7\n2 8\n3 9\n4 10\n5 11\n6 12\n[1] \"Element dataframe\"\n[1] 7 8 9 10 11 12" }, { "code": null, "e": 29303, "s": 29288, "text": "prachisoda1234" }, { "code": null, "e": 29310, "s": 29303, "text": "Picked" }, { "code": null, "e": 29319, "s": 29310, "text": "R-basics" }, { "code": null, "e": 29338, "s": 29319, "text": "Difference Between" }, { "code": null, "e": 29349, "s": 29338, "text": "R Language" }, { "code": null, "e": 29447, "s": 29349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29508, "s": 29447, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29576, "s": 29508, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 29634, "s": 29576, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 29689, "s": 29634, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 29763, "s": 29689, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 29808, "s": 29763, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 29866, "s": 29808, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 29918, "s": 29866, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 29950, "s": 29918, "text": "Loops in R (for, while, repeat)" } ]
How to filter two-dimensional NumPy array based on condition ? - GeeksforGeeks
05 Apr, 2021 In this article, we are going to see how to apply the filter by the given condition in NumPy two-dimensional array. We have to obtain the output of required elements i.e., whatever we want to filter the elements from the existing array or new array. Here we are going to create a two-dimensional array in numpy. Python3 import numpy as np # 2-D Array also called as arrays # with rank 2np_2d_arr = np.array([[1, 2, 3], [4, 5, 6]]) # View the 2-D Array A2print(np_2d_arr) Output: [[1 2 3] [4 5 6]] Now let see some example for applying the filter by the given condition in NumPy two-dimensional array. Example 1: Using np.asarray() method In this example, we are using the np.asarray() method which is explained below: Syntax : numpy.asarray(arr, dtype=None, order=None) Parameters : arr : [array_like] Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtype : [data-type, optional] By default, the data-type is inferred from the input data. order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’. Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is returned. Here, we first create a numpy array and a filter with its values to be filtered. To filter we used this fltr in numpy.in1d() method and stored as its values in the original array that return True if condition fulfills. Python3 import numpy as np arr = np.asarray([[1, 'one'], [2, 'two'], [3, 'three'], [4, 'four'], [5, 'five']]) fltr = np.asarray(['two', 'four'])arr[np.in1d(arr[:, 1], fltr)] Output: array([['2', 'two'], ['4', 'four']], dtype='<U21') Example 2: Using numpy.all() method In this example, we are using the np.all() method which is explained below: The numpy.all() function tests whether all array elements along the mentioned axis evaluate to True. Syntax: numpy.all(array, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Parameters : Array :[array_like]Input array or object whose elements, we need to test. axis : [int or tuple of ints, optional]Axis along which array elements are evaluated. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result keepdmis : [boolean, optional]If this is set to True. Return : A new Boolean array as per ‘out’ parameter Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.all() method return True if all the values fulfills the condition. This return value maps with the original array to give the filtered values. Python3 import numpy as np a = np.arange(12).reshape((3, 4))print(a[:, np.all(a < 10, axis = 0)]) Output: [[0 1] [4 5] [8 9]] Example 3: Using numpy.any() method In this example, we are using the np.any() method which is explained below: The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True.Syntax : numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c) Parameters : array :[array_like]Input array or object whose elements, we need to test. axis : [int or tuple of ints, optional]Axis along which array elements are evaluated. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result keepdmis : [boolean, optional]If this is set to True. Return : A new Boolean array as per ‘out’ parameter Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.any() method return true if any of the values fulfill the condition. This return value maps with the original array to give the filtered values. Python3 import numpy as np a = np.arange(12).reshape((3, 4))print(a[:, np.any(a < 2, axis = 0)]) Output: [[0 1] [4 5] [8 9]] Picked Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24105, "s": 24077, "text": "\n05 Apr, 2021" }, { "code": null, "e": 24355, "s": 24105, "text": "In this article, we are going to see how to apply the filter by the given condition in NumPy two-dimensional array. We have to obtain the output of required elements i.e., whatever we want to filter the elements from the existing array or new array." }, { "code": null, "e": 24417, "s": 24355, "text": "Here we are going to create a two-dimensional array in numpy." }, { "code": null, "e": 24425, "s": 24417, "text": "Python3" }, { "code": "import numpy as np # 2-D Array also called as arrays # with rank 2np_2d_arr = np.array([[1, 2, 3], [4, 5, 6]]) # View the 2-D Array A2print(np_2d_arr)", "e": 24580, "s": 24425, "text": null }, { "code": null, "e": 24588, "s": 24580, "text": "Output:" }, { "code": null, "e": 24607, "s": 24588, "text": "[[1 2 3]\n [4 5 6]]" }, { "code": null, "e": 24711, "s": 24607, "text": "Now let see some example for applying the filter by the given condition in NumPy two-dimensional array." }, { "code": null, "e": 24748, "s": 24711, "text": "Example 1: Using np.asarray() method" }, { "code": null, "e": 24828, "s": 24748, "text": "In this example, we are using the np.asarray() method which is explained below:" }, { "code": null, "e": 24880, "s": 24828, "text": "Syntax : numpy.asarray(arr, dtype=None, order=None)" }, { "code": null, "e": 24893, "s": 24880, "text": "Parameters :" }, { "code": null, "e": 25065, "s": 24893, "text": "arr : [array_like] Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays." }, { "code": null, "e": 25154, "s": 25065, "text": "dtype : [data-type, optional] By default, the data-type is inferred from the input data." }, { "code": null, "e": 25269, "s": 25154, "text": "order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’." }, { "code": null, "e": 25468, "s": 25269, "text": "Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is returned." }, { "code": null, "e": 25687, "s": 25468, "text": "Here, we first create a numpy array and a filter with its values to be filtered. To filter we used this fltr in numpy.in1d() method and stored as its values in the original array that return True if condition fulfills." }, { "code": null, "e": 25695, "s": 25687, "text": "Python3" }, { "code": "import numpy as np arr = np.asarray([[1, 'one'], [2, 'two'], [3, 'three'], [4, 'four'], [5, 'five']]) fltr = np.asarray(['two', 'four'])arr[np.in1d(arr[:, 1], fltr)]", "e": 25882, "s": 25695, "text": null }, { "code": null, "e": 25890, "s": 25882, "text": "Output:" }, { "code": null, "e": 25948, "s": 25890, "text": "array([['2', 'two'],\n ['4', 'four']], dtype='<U21')" }, { "code": null, "e": 25984, "s": 25948, "text": "Example 2: Using numpy.all() method" }, { "code": null, "e": 26060, "s": 25984, "text": "In this example, we are using the np.all() method which is explained below:" }, { "code": null, "e": 26161, "s": 26060, "text": "The numpy.all() function tests whether all array elements along the mentioned axis evaluate to True." }, { "code": null, "e": 26267, "s": 26161, "text": "Syntax: numpy.all(array, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)" }, { "code": null, "e": 26280, "s": 26267, "text": "Parameters :" }, { "code": null, "e": 26354, "s": 26280, "text": "Array :[array_like]Input array or object whose elements, we need to test." }, { "code": null, "e": 26440, "s": 26354, "text": "axis : [int or tuple of ints, optional]Axis along which array elements are evaluated." }, { "code": null, "e": 26534, "s": 26440, "text": "out : [ndarray, optional]Output array with same dimensions as Input array, placed with result" }, { "code": null, "e": 26588, "s": 26534, "text": "keepdmis : [boolean, optional]If this is set to True." }, { "code": null, "e": 26640, "s": 26588, "text": "Return : A new Boolean array as per ‘out’ parameter" }, { "code": null, "e": 26935, "s": 26640, "text": "Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.all() method return True if all the values fulfills the condition. This return value maps with the original array to give the filtered values." }, { "code": null, "e": 26943, "s": 26935, "text": "Python3" }, { "code": "import numpy as np a = np.arange(12).reshape((3, 4))print(a[:, np.all(a < 10, axis = 0)])", "e": 27036, "s": 26943, "text": null }, { "code": null, "e": 27044, "s": 27036, "text": "Output:" }, { "code": null, "e": 27066, "s": 27044, "text": "[[0 1]\n [4 5]\n [8 9]]" }, { "code": null, "e": 27102, "s": 27066, "text": "Example 3: Using numpy.any() method" }, { "code": null, "e": 27178, "s": 27102, "text": "In this example, we are using the np.any() method which is explained below:" }, { "code": null, "e": 27381, "s": 27178, "text": "The numpy.any() function tests whether any array elements along the mentioned axis evaluate to True.Syntax : numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)" }, { "code": null, "e": 27394, "s": 27381, "text": "Parameters :" }, { "code": null, "e": 27468, "s": 27394, "text": "array :[array_like]Input array or object whose elements, we need to test." }, { "code": null, "e": 27554, "s": 27468, "text": "axis : [int or tuple of ints, optional]Axis along which array elements are evaluated." }, { "code": null, "e": 27648, "s": 27554, "text": "out : [ndarray, optional]Output array with same dimensions as Input array, placed with result" }, { "code": null, "e": 27702, "s": 27648, "text": "keepdmis : [boolean, optional]If this is set to True." }, { "code": null, "e": 27754, "s": 27702, "text": "Return : A new Boolean array as per ‘out’ parameter" }, { "code": null, "e": 28051, "s": 27754, "text": "Here, we first create a numpy array by using np.arrange() and reshape() methods. To filter we used conditions in the index place to be filtered. The np.any() method return true if any of the values fulfill the condition. This return value maps with the original array to give the filtered values." }, { "code": null, "e": 28059, "s": 28051, "text": "Python3" }, { "code": "import numpy as np a = np.arange(12).reshape((3, 4))print(a[:, np.any(a < 2, axis = 0)])", "e": 28151, "s": 28059, "text": null }, { "code": null, "e": 28159, "s": 28151, "text": "Output:" }, { "code": null, "e": 28181, "s": 28159, "text": "[[0 1]\n [4 5]\n [8 9]]" }, { "code": null, "e": 28188, "s": 28181, "text": "Picked" }, { "code": null, "e": 28219, "s": 28188, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 28232, "s": 28219, "text": "Python-numpy" }, { "code": null, "e": 28239, "s": 28232, "text": "Python" }, { "code": null, "e": 28337, "s": 28239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28346, "s": 28337, "text": "Comments" }, { "code": null, "e": 28359, "s": 28346, "text": "Old Comments" }, { "code": null, "e": 28377, "s": 28359, "text": "Python Dictionary" }, { "code": null, "e": 28399, "s": 28377, "text": "Enumerate() in Python" }, { "code": null, "e": 28431, "s": 28399, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28473, "s": 28431, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28499, "s": 28473, "text": "Python String | replace()" }, { "code": null, "e": 28543, "s": 28499, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28580, "s": 28543, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28636, "s": 28580, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28665, "s": 28636, "text": "*args and **kwargs in Python" } ]
C++ Program to Implement Vector
A vector is a dynamic array that can resize itself if an element is inserted or deleted. The vector elements are contained in a contiguous storage and the container handles the storage automatically. A program that implements vectors is given as follows − #include <iostream> #include <vector> #include <string> #include <cstdlib> using namespace std; int main() { int ch, val; vector<int> vec; cout<<"1)Insert Element into the Vector"<<endl; cout<<"2)Delete Last Element of the Vector"<<endl; cout<<"3)Print size of the Vector"<<endl; cout<<"4)Display Vector elements"<<endl; cout<<"5)Clear the Vector"<<endl; cout<<"6)Exit"<<endl; do { cout<<"Enter your Choice: "<<endl; cin>>ch; switch(ch) { case 1: cout<<"Enter value to be inserted: "<<endl; cin>>val; vec.push_back(val); break; case 2: cout<<"Last Element is deleted."<<endl; vec.pop_back(); break; case 3: cout<<"Size of Vector: "; cout<<vec.size()<<endl; break; case 4: cout<<"Displaying Vector Elements: "; for (int i = 0; i < vec.size(); i++) cout<<vec[i]<<" "; cout<<endl; break; case 5: vec.clear(); cout<<"Vector Cleared"<<endl; break; case 6: cout<<"Exit"<<endl; break; default: cout<<"Error....Wrong Choice Entered"<<endl; } } while (ch!=6); return 0; } The output of the above program is as follows 1)Insert Element into the Vector 2)Delete Last Element of the Vector 3)Print size of the Vector 4)Display Vector elements 5)Clear the Vector 6)Exit Enter your Choice: 1 Enter value to be inserted: 5 Enter your Choice: 1 Enter value to be inserted: 2 Enter your Choice: 1 Enter value to be inserted: 8 Enter your Choice: 1 Enter value to be inserted: 6 Enter your Choice: 3 Size of Vector: 4 Enter your Choice: 4 Displaying Vector Elements: 5 2 8 6 Enter your Choice: 2 Last Element is deleted. Enter your Choice: 3 Size of Vector: 3 Enter your Choice: 4 Displaying Vector Elements: 5 2 8 Enter your Choice: 5 Vector Cleared Enter your Choice: 3 Size of Vector: 0 Enter your Choice: 4 Displaying Vector Elements: Enter your Choice: 9 Error....Wrong Choice Entered Enter your Choice: 6 Exit In the above program, first the vector is defined and then a menu is provided to the user to choose the vector operations. This is given below − vector<int> vec; cout<<"1)Insert Element into the Vector"<<endl; cout<<"2)Delete Last Element of the Vector"<<endl; cout<<"3)Print size of the Vector"<<endl; cout<<"4)Display Vector elements"<<endl; cout<<"5)Clear the Vector"<<endl; cout<<"6)Exit"<<endl; A do while loop is used to enter the user choice and a switch statement is used to implement the operations according to the choice. The different operations are insert element into vector, delete element from vector, print size of vector, display elements of vector, clear vector and exit. The code snippet for this is given below − do { cout<<"Enter your Choice: "<<endl; cin>>ch; switch(ch) { case 1: cout<<"Enter value to be inserted: "<<endl; cin>>val; vec.push_back(val); break; case 2: cout<<"Last Element is deleted."<<endl; vec.pop_back(); break; case 3: cout<<"Size of Vector: "; cout<<vec.size()<<endl; break; case 4: cout<<"Displaying Vector Elements: "; for (int i = 0; i < vec.size(); i++) cout<<vec[i]<<" "; cout<<endl; break; case 5: vec.clear(); cout<<"Vector Cleared"<<endl; break; case 6: cout<<"Exit"<<endl; break; default: cout<<"Error....Wrong Choice Entered"<<endl; } } while (ch!=6);
[ { "code": null, "e": 1262, "s": 1062, "text": "A vector is a dynamic array that can resize itself if an element is inserted or deleted. The vector elements are contained in a contiguous storage and the container handles the storage automatically." }, { "code": null, "e": 1318, "s": 1262, "text": "A program that implements vectors is given as follows −" }, { "code": null, "e": 2592, "s": 1318, "text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <cstdlib>\n\nusing namespace std;\nint main() {\n int ch, val;\n vector<int> vec;\n cout<<\"1)Insert Element into the Vector\"<<endl;\n cout<<\"2)Delete Last Element of the Vector\"<<endl;\n cout<<\"3)Print size of the Vector\"<<endl;\n cout<<\"4)Display Vector elements\"<<endl;\n cout<<\"5)Clear the Vector\"<<endl;\n cout<<\"6)Exit\"<<endl;\n\n do {\n cout<<\"Enter your Choice: \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1:\n cout<<\"Enter value to be inserted: \"<<endl;\n cin>>val;\n vec.push_back(val);\n break;\n case 2:\n cout<<\"Last Element is deleted.\"<<endl;\n vec.pop_back();\n break;\n case 3:\n cout<<\"Size of Vector: \";\n cout<<vec.size()<<endl;\n break;\n case 4:\n cout<<\"Displaying Vector Elements: \";\n for (int i = 0; i < vec.size(); i++)\n cout<<vec[i]<<\" \";\n cout<<endl;\n break;\n case 5:\n vec.clear();\n cout<<\"Vector Cleared\"<<endl;\n break;\n case 6:\n cout<<\"Exit\"<<endl;\n break;\n default:\n cout<<\"Error....Wrong Choice Entered\"<<endl;\n }\n } while (ch!=6);\n return 0;\n}" }, { "code": null, "e": 2638, "s": 2592, "text": "The output of the above program is as follows" }, { "code": null, "e": 3428, "s": 2638, "text": "1)Insert Element into the Vector\n2)Delete Last Element of the Vector\n3)Print size of the Vector\n4)Display Vector elements\n5)Clear the Vector\n6)Exit\n\nEnter your Choice: 1\nEnter value to be inserted: 5\nEnter your Choice: 1\nEnter value to be inserted: 2\nEnter your Choice: 1\nEnter value to be inserted: 8\nEnter your Choice: 1\nEnter value to be inserted: 6\nEnter your Choice: 3\nSize of Vector: 4\nEnter your Choice: 4\nDisplaying Vector Elements: 5 2 8 6\nEnter your Choice: 2\nLast Element is deleted.\nEnter your Choice: 3\nSize of Vector: 3\nEnter your Choice: 4\nDisplaying Vector Elements: 5 2 8\nEnter your Choice: 5\nVector Cleared\nEnter your Choice: 3\nSize of Vector: 0\nEnter your Choice: 4\nDisplaying Vector Elements:\nEnter your Choice: 9\nError....Wrong Choice Entered\nEnter your Choice: 6\nExit" }, { "code": null, "e": 3573, "s": 3428, "text": "In the above program, first the vector is defined and then a menu is provided to the user to choose the vector operations. This is given below −" }, { "code": null, "e": 3828, "s": 3573, "text": "vector<int> vec;\ncout<<\"1)Insert Element into the Vector\"<<endl;\ncout<<\"2)Delete Last Element of the Vector\"<<endl;\ncout<<\"3)Print size of the Vector\"<<endl;\ncout<<\"4)Display Vector elements\"<<endl;\ncout<<\"5)Clear the Vector\"<<endl;\ncout<<\"6)Exit\"<<endl;" }, { "code": null, "e": 4162, "s": 3828, "text": "A do while loop is used to enter the user choice and a switch statement is used to implement the operations according to the choice. The different operations are insert element into vector, delete element from vector, print size of vector, display elements of vector, clear vector and exit. The code snippet for this is given below −" }, { "code": null, "e": 4916, "s": 4162, "text": "do {\n cout<<\"Enter your Choice: \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1:\n cout<<\"Enter value to be inserted: \"<<endl;\n cin>>val;\n vec.push_back(val);\n break;\n case 2:\n cout<<\"Last Element is deleted.\"<<endl;\n vec.pop_back();\n break;\n case 3:\n cout<<\"Size of Vector: \";\n cout<<vec.size()<<endl;\n break;\n case 4:\n cout<<\"Displaying Vector Elements: \";\n for (int i = 0; i < vec.size(); i++)\n cout<<vec[i]<<\" \";\n cout<<endl;\n break;\n case 5:\n vec.clear();\n cout<<\"Vector Cleared\"<<endl;\n break;\n case 6:\n cout<<\"Exit\"<<endl;\n break;\n default:\n cout<<\"Error....Wrong Choice Entered\"<<endl;\n }\n} while (ch!=6);" } ]
Count items common to both the lists but with different prices - GeeksforGeeks
07 Mar, 2022 Given two lists list1 and list2 containing m and n items respectively. Each item is associated with two fields: name and price. The problem is to count items that are in both the lists but with different prices. Examples: Input : list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}} list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}} Output : 2 bread and wheat are the two items common to both the lists but with different prices. Source: Cognizant Interview Experience | Set 5. Method 1 (Naive Approach): Using two nested loops compare each item of list1 with all the items of list2. If a match is found with a different price then increment the count. C++ Java Python3 C# Javascript // C++ implementation to count items common to both// the lists but with different prices#include <bits/stdc++.h> using namespace std; // details of an itemstruct item{ string name; int price;}; // function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compare(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver program to test aboveint main(){ item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; } // Java implementation to count items common to both// the lists but with different pricesclass GFG{ // details of an itemstatic class item{ String name; int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compareTo(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver codepublic static void main(String[] args){ item list1[] = {new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)}; item list2[] = {new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)}; int m = list1.length; int n = list2.length; System.out.print("Count = " + countItems(list1, m, list2, n)); } } // This code is contributed by 29AjayKumar # Python implementation to# count items common to both# the lists but with different# prices # function to count items# common to both# the lists but with different pricesdef countItems(list1, list2): count = 0 # for each item of 'list1' # check if it is in 'list2' # but with a different price for i in list1: for j in list2: if i[0] == j[0] and i[1] != j[1]: count += 1 # required count of items return count # Driver program to test abovelist1 = [("apple", 60), ("bread", 20), ("wheat", 50), ("oil", 30)]list2 = [("milk", 20), ("bread", 15), ("wheat", 40), ("apple", 60)] print("Count = ", countItems(list1, list2)) # This code is contributed by Ansu Kumari. // C# implementation to count items common to both// the lists but with different pricesusing System; class GFG{ // details of an itemclass item{ public String name; public int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item []list1, int m, item []list2, int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.CompareTo(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver codepublic static void Main(String[] args){ item []list1 = {new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)}; item []list2 = {new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)}; int m = list1.Length; int n = list2.Length; Console.Write("Count = " + countItems(list1, m, list2, n)); } }// This code is contributed by PrinciRaj1992 <script> // Javascript implementation to// count items common to both// the lists but with different prices // function to count items common to both// the lists but with different pricesfunction countItems(list1, m, list2, n){ var count = 0; // for each item of 'list1' // check if it is in 'list2' // but with a different price for (var i = 0; i < m; i++) for (var j = 0; j < n; j++) if (list1[i][0] === list2[j][0] && (list1[i][1] != list2[j][1])) count++; // required count of items return count;} // Driver program to test abovevar list1 = [["apple", 60], ["bread", 20], ["wheat", 50], ["oil", 30]];var list2 = [["milk", 20], ["bread", 15], ["wheat", 40], ["apple", 60]]; var m = list1.length;var n = list2.length; document.write( "Count = " + countItems(list1, m, list2, n)); </script> Output: Count = 2 Time Complexity: O(m*n). Auxiliary Space: O(1). Method 2 (Binary Search): Sort the list2 in alphabetical order of its items name. Now, for each item of list1 check whether it in present in list2 using the binary search technique and get its price from list2. If prices are different then increment the count. C++ Java Python3 Javascript // C++ implementation to count// items common to both the lists// but with different prices#include <bits/stdc++.h>using namespace std; // Details of an itemstruct item{ string name; int price;}; // comparator function// used for sortingbool compare(struct item a, struct item b){ return (a.name.compare (b.name) <= 0); } // Function to search 'str'// in 'list2[]'. If it exists then// price associated with 'str'// in 'list2[]' is being returned// else -1 is returned. Here binary// search technique is being applied// for searchingint binary_search(item list2[], int low, int high, string str){ while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' // is in 'list2' if (list2[mid].name.compare(str) == 0) return list2[mid].price; else if (list2[mid].name.compare(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ // sort 'list2' in alphabetical // order of items name sort(list2, list2 + n, compare); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then // -1 is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver codeint main(){ item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; } // Java implementation to count// items common to both the lists// but with different pricesimport java.util.*;class GFG{ // Details of an itemstatic class item{ String name; int price; item(String name, int price) { this.name = name; this.price = price; }}; // comparator function used for sortingstatic class Com implements Comparator<item>{ public int compare(item a, item b) { return a.name.compareTo(b.name); } } // Function to search 'str' in 'list2[]'.// If it exists then price associated// with 'str' in 'list2[]' is being// returned else -1 is returned. Here// binary search technique is being // applied for searchingstatic int binary_search(item list2[], int low, int high, String str){ while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' is in 'list2' if (list2[mid].name.compareTo(str) == 0) return list2[mid].price; else if (list2[mid].name.compareTo(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not // in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ // sort 'list2' in alphabetical // order of items name Arrays.sort(list2, new Com()); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then -1 // is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver codepublic static void main(String[] args){ item[] list1 = {new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)}; item list2[] = {new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)}; int m = list1.length; int n = list2.length; System.out.print("Count = " + countItems(list1, m, list2, n));}} // This code is contributed by 29AjayKumar # Python3 implementation to count# items common to both the lists# but with different prices # Details of an itemfrom ast import Strfrom functools import cmp_to_key class item: def __init__(self, name, price): self.name = name self.price = price # Function to search 'str' in 'list2[]'.# If it exists then price associated# with 'str' in 'list2[]' is being# returned else -1 is returned. Here# binary search technique is being# applied for searchingdef binary_search(list2, low, high, str): while (low <= high): mid = ((low + high) // 2) # if true the item 'str' is in 'list2' # print(list2[mid].name,str) if (list2[mid].name == str): return list2[mid].price elif (list2[mid].name < str): low = mid + 1 else: high = mid - 1 # item 'str' is not # in 'list2' return -1 # Function to count items common to both# the lists but with different pricesdef custom_logic(a, b): return a.name == b.name def countItems(list1, m, list2, n): # sort 'list2' in alphabetical # order of items name sorted(list2,key=cmp_to_key(custom_logic)) # initial count count = 0 for i in range(m): # get the price of item 'list1[i]' # from 'list2' if item in not # present in second list then -1 # is being obtained r = binary_search(list2, 0, n - 1, list1[i].name) # if item is present in list2 # with a different price if ((r != -1) and (r != list1[i].price)): count += 1 # Required count of items return count # Driver code list1=[item("apple", 60), item("bread", 20), item("wheat", 50), item("oil", 30)]list2=[item("milk", 20), item("bread", 15), item("wheat", 40), item("apple", 60)]m = len(list1)n = len(list2)print(f"Count = {countItems(list1, m,list2, n)}") # This code is contributed by shinjanpatra <script>// Javascript implementation to count// items common to both the lists// but with different prices // Details of an itemclass item{ constructor(name,price) { this.name = name; this.price = price; }} // Function to search 'str' in 'list2[]'.// If it exists then price associated// with 'str' in 'list2[]' is being// returned else -1 is returned. Here// binary search technique is being// applied for searchingfunction binary_search(list2,low,high,str){ while (low <= high) { let mid = Math.floor((low + high) / 2); // if true the item 'str' is in 'list2' if (list2[mid].name == (str)) return list2[mid].price; else if (list2[mid].name < (str)) low = mid + 1; else high = mid - 1; } // item 'str' is not // in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesfunction countItems(list1, m, list2, n){ // sort 'list2' in alphabetical // order of items name list2.sort(function(a,b){return a.name==b.name;}); // initial count let count = 0; for (let i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then -1 // is being obtained let r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver code let list1=[new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)];let list2=[new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)];let m = list1.length;let n = list2.length;document.write("Count = " + countItems(list1, m, list2, n)); // This code is contributed by patel2127</script> Output: Count = 2 Time Complexity: (m*log2n). Auxiliary Space: O(1). For efficiency, the list with the maximum number of elements should be sorted and used for binary search. Method 3 (Efficient Approach): Create a hash table with (key, value) tuple as (item name, price). Insert the elements of list1 in the hash table. Now, for each element of list2 check if it is the hash table or not. If it is present, then check if its price is different from the value from the hash table. If so then increment the count. C++ Java C# Javascript // C++ implementation to count items common to both// the lists but with different prices#include <bits/stdc++.h> using namespace std; // details of an itemstruct item{ string name; int price;}; // function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key unordered_map<string, int> um; int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um[list1[i].name] = list1[i].price; // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.find(list2[i].name) != um.end()) && (um[list2[i].name] != list2[i].price)) count++; // required count of items return count; } // Driver program to test aboveint main(){ item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; } // Java implementation to count// items common to both the lists// but with different pricesimport java.util.*;class GFG{ // details of an itemstatic class item{ String name; int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key HashMap<String, Integer> um = new HashMap<>(); int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um.put(list1[i].name, list1[i].price); // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.containsKey(list2[i].name)) && (um.get(list2[i].name) != list2[i].price)) count++; // required count of items return count; } // Driver program to test abovepublic static void main(String[] args){ item list1[] = {new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)}; item list2[] = {new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)}; int m = list1.length; int n = list2.length; System.out.print("Count = " + countItems(list1, m, clist2, n));} } // This code is contributed by gauravrajput1 // C# implementation to count// items common to both the lists// but with different pricesusing System;using System.Collections.Generic;class GFG{ // Details of an itempublic class item{ public String name; public int price; public item(String name, int price) { this.name = name; this.price = price; }}; // Function to count items common to// both the lists but with different pricesstatic int countItems(item []list1, int m, item []list2, int n){ // 'um' implemented as hash table // that contains item name as the // key and price as the value // associated with the key Dictionary<String, int> um = new Dictionary<String, int>(); int count = 0; // Insert elements of 'list1' // in 'um' for (int i = 0; i < m; i++) um.Add(list1[i].name, list1[i].price); // For each element of 'list2' // check if it is present in // 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.ContainsKey(list2[i].name)) && (um[list2[i].name] != list2[i].price)) count++; // Required count of items return count; } // Driver codepublic static void Main(String[] args){ item []list1 = {new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)}; item []list2 = {new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)}; int m = list1.Length; int n = list2.Length; Console.Write("Count = " + countItems(list1, m, list2, n));} } // This code is contributed by shikhasingrajput <script> // JavaScript implementation to count// items common to both the lists// but with different prices // details of an itemclass item{ constructor(name,price) { this.name = name; this.price = price; }} // function to count items common to both// the lists but with different pricesfunction countItems(list1,m,list2,n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key let um = new Map(); let count = 0; // insert elements of 'list1' in 'um' for (let i = 0; i < m; i++) um.set(list1[i].name, list1[i].price); // for each element of 'list2' check if it is // present in 'um' with a different price // value for (let i = 0; i < n; i++) if ((um.has(list2[i].name)) && (um.get(list2[i].name) != list2[i].price)) count++; // required count of items return count; } // Driver program to test abovelet list1=[new item("apple", 60), new item("bread", 20), new item("wheat", 50), new item("oil", 30)];let list2=[new item("milk", 20), new item("bread", 15), new item("wheat", 40), new item("apple", 60)];let m = list1.length;let n = list2.length; document.write("Count = " + countItems(list1, m, list2, n)); // This code is contributed by unknown2108 </script> Output: Count = 2 Time Complexity: O(m + n). Auxiliary Space: O(m). For efficiency, the list having a minimum number of elements should be inserted in the hash table. 29AjayKumar princiraj1992 GauravRajput1 shikhasingrajput itsok rajeev0719singh patel2127 unknown2108 ruhelaa48 shinjanpatra Binary Search Hash Searching Searching Hash Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most frequent element in an array Sorting a Map by value in C++ STL Double Hashing C++ program for hashing with chaining Quadratic Probing in Hashing 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": 25420, "s": 25392, "text": "\n07 Mar, 2022" }, { "code": null, "e": 25632, "s": 25420, "text": "Given two lists list1 and list2 containing m and n items respectively. Each item is associated with two fields: name and price. The problem is to count items that are in both the lists but with different prices." }, { "code": null, "e": 25643, "s": 25632, "text": "Examples: " }, { "code": null, "e": 25931, "s": 25643, "text": "Input : list1[] = {{\"apple\", 60}, {\"bread\", 20}, \n {\"wheat\", 50}, {\"oil\", 30}}\n list2[] = {{\"milk\", 20}, {\"bread\", 15}, \n {\"wheat\", 40}, {\"apple\", 60}}\nOutput : 2\nbread and wheat are the two items common to both the\nlists but with different prices." }, { "code": null, "e": 25979, "s": 25931, "text": "Source: Cognizant Interview Experience | Set 5." }, { "code": null, "e": 26155, "s": 25979, "text": "Method 1 (Naive Approach): Using two nested loops compare each item of list1 with all the items of list2. If a match is found with a different price then increment the count. " }, { "code": null, "e": 26159, "s": 26155, "text": "C++" }, { "code": null, "e": 26164, "s": 26159, "text": "Java" }, { "code": null, "e": 26172, "s": 26164, "text": "Python3" }, { "code": null, "e": 26175, "s": 26172, "text": "C#" }, { "code": null, "e": 26186, "s": 26175, "text": "Javascript" }, { "code": "// C++ implementation to count items common to both// the lists but with different prices#include <bits/stdc++.h> using namespace std; // details of an itemstruct item{ string name; int price;}; // function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compare(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver program to test aboveint main(){ item list1[] = {{\"apple\", 60}, {\"bread\", 20}, {\"wheat\", 50}, {\"oil\", 30}}; item list2[] = {{\"milk\", 20}, {\"bread\", 15}, {\"wheat\", 40}, {\"apple\", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << \"Count = \" << countItems(list1, m, list2, n); return 0; }", "e": 27355, "s": 26186, "text": null }, { "code": "// Java implementation to count items common to both// the lists but with different pricesclass GFG{ // details of an itemstatic class item{ String name; int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compareTo(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver codepublic static void main(String[] args){ item list1[] = {new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)}; item list2[] = {new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)}; int m = list1.length; int n = list2.length; System.out.print(\"Count = \" + countItems(list1, m, list2, n)); } } // This code is contributed by 29AjayKumar", "e": 28657, "s": 27355, "text": null }, { "code": "# Python implementation to# count items common to both# the lists but with different# prices # function to count items# common to both# the lists but with different pricesdef countItems(list1, list2): count = 0 # for each item of 'list1' # check if it is in 'list2' # but with a different price for i in list1: for j in list2: if i[0] == j[0] and i[1] != j[1]: count += 1 # required count of items return count # Driver program to test abovelist1 = [(\"apple\", 60), (\"bread\", 20), (\"wheat\", 50), (\"oil\", 30)]list2 = [(\"milk\", 20), (\"bread\", 15), (\"wheat\", 40), (\"apple\", 60)] print(\"Count = \", countItems(list1, list2)) # This code is contributed by Ansu Kumari.", "e": 29414, "s": 28657, "text": null }, { "code": "// C# implementation to count items common to both// the lists but with different pricesusing System; class GFG{ // details of an itemclass item{ public String name; public int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item []list1, int m, item []list2, int n){ int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.CompareTo(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count;} // Driver codepublic static void Main(String[] args){ item []list1 = {new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)}; item []list2 = {new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)}; int m = list1.Length; int n = list2.Length; Console.Write(\"Count = \" + countItems(list1, m, list2, n)); } }// This code is contributed by PrinciRaj1992", "e": 30742, "s": 29414, "text": null }, { "code": "<script> // Javascript implementation to// count items common to both// the lists but with different prices // function to count items common to both// the lists but with different pricesfunction countItems(list1, m, list2, n){ var count = 0; // for each item of 'list1' // check if it is in 'list2' // but with a different price for (var i = 0; i < m; i++) for (var j = 0; j < n; j++) if (list1[i][0] === list2[j][0] && (list1[i][1] != list2[j][1])) count++; // required count of items return count;} // Driver program to test abovevar list1 = [[\"apple\", 60], [\"bread\", 20], [\"wheat\", 50], [\"oil\", 30]];var list2 = [[\"milk\", 20], [\"bread\", 15], [\"wheat\", 40], [\"apple\", 60]]; var m = list1.length;var n = list2.length; document.write( \"Count = \" + countItems(list1, m, list2, n)); </script>", "e": 31660, "s": 30742, "text": null }, { "code": null, "e": 31670, "s": 31660, "text": "Output: " }, { "code": null, "e": 31680, "s": 31670, "text": "Count = 2" }, { "code": null, "e": 31728, "s": 31680, "text": "Time Complexity: O(m*n). Auxiliary Space: O(1)." }, { "code": null, "e": 31989, "s": 31728, "text": "Method 2 (Binary Search): Sort the list2 in alphabetical order of its items name. Now, for each item of list1 check whether it in present in list2 using the binary search technique and get its price from list2. If prices are different then increment the count." }, { "code": null, "e": 31993, "s": 31989, "text": "C++" }, { "code": null, "e": 31998, "s": 31993, "text": "Java" }, { "code": null, "e": 32006, "s": 31998, "text": "Python3" }, { "code": null, "e": 32017, "s": 32006, "text": "Javascript" }, { "code": "// C++ implementation to count// items common to both the lists// but with different prices#include <bits/stdc++.h>using namespace std; // Details of an itemstruct item{ string name; int price;}; // comparator function// used for sortingbool compare(struct item a, struct item b){ return (a.name.compare (b.name) <= 0); } // Function to search 'str'// in 'list2[]'. If it exists then// price associated with 'str'// in 'list2[]' is being returned// else -1 is returned. Here binary// search technique is being applied// for searchingint binary_search(item list2[], int low, int high, string str){ while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' // is in 'list2' if (list2[mid].name.compare(str) == 0) return list2[mid].price; else if (list2[mid].name.compare(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ // sort 'list2' in alphabetical // order of items name sort(list2, list2 + n, compare); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then // -1 is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver codeint main(){ item list1[] = {{\"apple\", 60}, {\"bread\", 20}, {\"wheat\", 50}, {\"oil\", 30}}; item list2[] = {{\"milk\", 20}, {\"bread\", 15}, {\"wheat\", 40}, {\"apple\", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << \"Count = \" << countItems(list1, m, list2, n); return 0; }", "e": 34205, "s": 32017, "text": null }, { "code": "// Java implementation to count// items common to both the lists// but with different pricesimport java.util.*;class GFG{ // Details of an itemstatic class item{ String name; int price; item(String name, int price) { this.name = name; this.price = price; }}; // comparator function used for sortingstatic class Com implements Comparator<item>{ public int compare(item a, item b) { return a.name.compareTo(b.name); } } // Function to search 'str' in 'list2[]'.// If it exists then price associated// with 'str' in 'list2[]' is being// returned else -1 is returned. Here// binary search technique is being // applied for searchingstatic int binary_search(item list2[], int low, int high, String str){ while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' is in 'list2' if (list2[mid].name.compareTo(str) == 0) return list2[mid].price; else if (list2[mid].name.compareTo(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not // in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ // sort 'list2' in alphabetical // order of items name Arrays.sort(list2, new Com()); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then -1 // is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver codepublic static void main(String[] args){ item[] list1 = {new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)}; item list2[] = {new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)}; int m = list1.length; int n = list2.length; System.out.print(\"Count = \" + countItems(list1, m, list2, n));}} // This code is contributed by 29AjayKumar", "e": 36637, "s": 34205, "text": null }, { "code": "# Python3 implementation to count# items common to both the lists# but with different prices # Details of an itemfrom ast import Strfrom functools import cmp_to_key class item: def __init__(self, name, price): self.name = name self.price = price # Function to search 'str' in 'list2[]'.# If it exists then price associated# with 'str' in 'list2[]' is being# returned else -1 is returned. Here# binary search technique is being# applied for searchingdef binary_search(list2, low, high, str): while (low <= high): mid = ((low + high) // 2) # if true the item 'str' is in 'list2' # print(list2[mid].name,str) if (list2[mid].name == str): return list2[mid].price elif (list2[mid].name < str): low = mid + 1 else: high = mid - 1 # item 'str' is not # in 'list2' return -1 # Function to count items common to both# the lists but with different pricesdef custom_logic(a, b): return a.name == b.name def countItems(list1, m, list2, n): # sort 'list2' in alphabetical # order of items name sorted(list2,key=cmp_to_key(custom_logic)) # initial count count = 0 for i in range(m): # get the price of item 'list1[i]' # from 'list2' if item in not # present in second list then -1 # is being obtained r = binary_search(list2, 0, n - 1, list1[i].name) # if item is present in list2 # with a different price if ((r != -1) and (r != list1[i].price)): count += 1 # Required count of items return count # Driver code list1=[item(\"apple\", 60), item(\"bread\", 20), item(\"wheat\", 50), item(\"oil\", 30)]list2=[item(\"milk\", 20), item(\"bread\", 15), item(\"wheat\", 40), item(\"apple\", 60)]m = len(list1)n = len(list2)print(f\"Count = {countItems(list1, m,list2, n)}\") # This code is contributed by shinjanpatra", "e": 38682, "s": 36637, "text": null }, { "code": "<script>// Javascript implementation to count// items common to both the lists// but with different prices // Details of an itemclass item{ constructor(name,price) { this.name = name; this.price = price; }} // Function to search 'str' in 'list2[]'.// If it exists then price associated// with 'str' in 'list2[]' is being// returned else -1 is returned. Here// binary search technique is being// applied for searchingfunction binary_search(list2,low,high,str){ while (low <= high) { let mid = Math.floor((low + high) / 2); // if true the item 'str' is in 'list2' if (list2[mid].name == (str)) return list2[mid].price; else if (list2[mid].name < (str)) low = mid + 1; else high = mid - 1; } // item 'str' is not // in 'list2' return -1;} // Function to count items common to both// the lists but with different pricesfunction countItems(list1, m, list2, n){ // sort 'list2' in alphabetical // order of items name list2.sort(function(a,b){return a.name==b.name;}); // initial count let count = 0; for (let i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then -1 // is being obtained let r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count;} // Driver code let list1=[new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)];let list2=[new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)];let m = list1.length;let n = list2.length;document.write(\"Count = \" + countItems(list1, m, list2, n)); // This code is contributed by patel2127</script>", "e": 40732, "s": 38682, "text": null }, { "code": null, "e": 40742, "s": 40732, "text": "Output: " }, { "code": null, "e": 40752, "s": 40742, "text": "Count = 2" }, { "code": null, "e": 40909, "s": 40752, "text": "Time Complexity: (m*log2n). Auxiliary Space: O(1). For efficiency, the list with the maximum number of elements should be sorted and used for binary search." }, { "code": null, "e": 41248, "s": 40909, "text": "Method 3 (Efficient Approach): Create a hash table with (key, value) tuple as (item name, price). Insert the elements of list1 in the hash table. Now, for each element of list2 check if it is the hash table or not. If it is present, then check if its price is different from the value from the hash table. If so then increment the count. " }, { "code": null, "e": 41252, "s": 41248, "text": "C++" }, { "code": null, "e": 41257, "s": 41252, "text": "Java" }, { "code": null, "e": 41260, "s": 41257, "text": "C#" }, { "code": null, "e": 41271, "s": 41260, "text": "Javascript" }, { "code": "// C++ implementation to count items common to both// the lists but with different prices#include <bits/stdc++.h> using namespace std; // details of an itemstruct item{ string name; int price;}; // function to count items common to both// the lists but with different pricesint countItems(item list1[], int m, item list2[], int n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key unordered_map<string, int> um; int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um[list1[i].name] = list1[i].price; // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.find(list2[i].name) != um.end()) && (um[list2[i].name] != list2[i].price)) count++; // required count of items return count; } // Driver program to test aboveint main(){ item list1[] = {{\"apple\", 60}, {\"bread\", 20}, {\"wheat\", 50}, {\"oil\", 30}}; item list2[] = {{\"milk\", 20}, {\"bread\", 15}, {\"wheat\", 40}, {\"apple\", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << \"Count = \" << countItems(list1, m, list2, n); return 0; }", "e": 42696, "s": 41271, "text": null }, { "code": "// Java implementation to count// items common to both the lists// but with different pricesimport java.util.*;class GFG{ // details of an itemstatic class item{ String name; int price; public item(String name, int price) { this.name = name; this.price = price; }}; // function to count items common to both// the lists but with different pricesstatic int countItems(item list1[], int m, item list2[], int n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key HashMap<String, Integer> um = new HashMap<>(); int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um.put(list1[i].name, list1[i].price); // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.containsKey(list2[i].name)) && (um.get(list2[i].name) != list2[i].price)) count++; // required count of items return count; } // Driver program to test abovepublic static void main(String[] args){ item list1[] = {new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)}; item list2[] = {new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)}; int m = list1.length; int n = list2.length; System.out.print(\"Count = \" + countItems(list1, m, clist2, n));} } // This code is contributed by gauravrajput1", "e": 44347, "s": 42696, "text": null }, { "code": "// C# implementation to count// items common to both the lists// but with different pricesusing System;using System.Collections.Generic;class GFG{ // Details of an itempublic class item{ public String name; public int price; public item(String name, int price) { this.name = name; this.price = price; }}; // Function to count items common to// both the lists but with different pricesstatic int countItems(item []list1, int m, item []list2, int n){ // 'um' implemented as hash table // that contains item name as the // key and price as the value // associated with the key Dictionary<String, int> um = new Dictionary<String, int>(); int count = 0; // Insert elements of 'list1' // in 'um' for (int i = 0; i < m; i++) um.Add(list1[i].name, list1[i].price); // For each element of 'list2' // check if it is present in // 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.ContainsKey(list2[i].name)) && (um[list2[i].name] != list2[i].price)) count++; // Required count of items return count; } // Driver codepublic static void Main(String[] args){ item []list1 = {new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)}; item []list2 = {new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)}; int m = list1.Length; int n = list2.Length; Console.Write(\"Count = \" + countItems(list1, m, list2, n));} } // This code is contributed by shikhasingrajput", "e": 46095, "s": 44347, "text": null }, { "code": "<script> // JavaScript implementation to count// items common to both the lists// but with different prices // details of an itemclass item{ constructor(name,price) { this.name = name; this.price = price; }} // function to count items common to both// the lists but with different pricesfunction countItems(list1,m,list2,n){ // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key let um = new Map(); let count = 0; // insert elements of 'list1' in 'um' for (let i = 0; i < m; i++) um.set(list1[i].name, list1[i].price); // for each element of 'list2' check if it is // present in 'um' with a different price // value for (let i = 0; i < n; i++) if ((um.has(list2[i].name)) && (um.get(list2[i].name) != list2[i].price)) count++; // required count of items return count; } // Driver program to test abovelet list1=[new item(\"apple\", 60), new item(\"bread\", 20), new item(\"wheat\", 50), new item(\"oil\", 30)];let list2=[new item(\"milk\", 20), new item(\"bread\", 15), new item(\"wheat\", 40), new item(\"apple\", 60)];let m = list1.length;let n = list2.length; document.write(\"Count = \" + countItems(list1, m, list2, n)); // This code is contributed by unknown2108 </script>", "e": 47545, "s": 46095, "text": null }, { "code": null, "e": 47555, "s": 47545, "text": "Output: " }, { "code": null, "e": 47565, "s": 47555, "text": "Count = 2" }, { "code": null, "e": 47715, "s": 47565, "text": "Time Complexity: O(m + n). Auxiliary Space: O(m). For efficiency, the list having a minimum number of elements should be inserted in the hash table. " }, { "code": null, "e": 47727, "s": 47715, "text": "29AjayKumar" }, { "code": null, "e": 47741, "s": 47727, "text": "princiraj1992" }, { "code": null, "e": 47755, "s": 47741, "text": "GauravRajput1" }, { "code": null, "e": 47772, "s": 47755, "text": "shikhasingrajput" }, { "code": null, "e": 47778, "s": 47772, "text": "itsok" }, { "code": null, "e": 47794, "s": 47778, "text": "rajeev0719singh" }, { "code": null, "e": 47804, "s": 47794, "text": "patel2127" }, { "code": null, "e": 47816, "s": 47804, "text": "unknown2108" }, { "code": null, "e": 47826, "s": 47816, "text": "ruhelaa48" }, { "code": null, "e": 47839, "s": 47826, "text": "shinjanpatra" }, { "code": null, "e": 47853, "s": 47839, "text": "Binary Search" }, { "code": null, "e": 47858, "s": 47853, "text": "Hash" }, { "code": null, "e": 47868, "s": 47858, "text": "Searching" }, { "code": null, "e": 47878, "s": 47868, "text": "Searching" }, { "code": null, "e": 47883, "s": 47878, "text": "Hash" }, { "code": null, "e": 47897, "s": 47883, "text": "Binary Search" }, { "code": null, "e": 47995, "s": 47897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48029, "s": 47995, "text": "Most frequent element in an array" }, { "code": null, "e": 48063, "s": 48029, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 48078, "s": 48063, "text": "Double Hashing" }, { "code": null, "e": 48116, "s": 48078, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 48145, "s": 48116, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 48159, "s": 48145, "text": "Binary Search" }, { "code": null, "e": 48227, "s": 48159, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 48241, "s": 48227, "text": "Linear Search" }, { "code": null, "e": 48265, "s": 48241, "text": "Find the Missing Number" } ]
SentencePiece Tokenizer Demystified | by Jonathan Kernes | Towards Data Science
I’ll be the first to admit that learning about tokenization schemes can be boring, if not downright painful. Often, when training a natural language, choosing and implementing a tokenization scheme is just one more added layer of complexity. It can complicate your production pipelines, kill the mood with a poorly timed [OOV] or [UNK], or maybe just send you into the depths of unicode hell, where you wonder why “string” != “string”. However, like your first truly good glass of wine, or your first experience with high quality sushi, once you’ve had a taste of the good stuff, you’ll see the rest in a totally different light. This post is meant to discuss SentencePiece, and show how painless it makes the tokenization process. Along the way you might just decide that tokenization isn’t so bad after all. Surprisingly, it’s not actually a tokenizer, I know, misleading. It’s actually a method for selecting tokens from a precompiled list, optimizing the tokenization process based on a supplied corpus. SentencePiece [1], is the name for a package (available here [2]) which implements the Subword Regularization algorithm [3] (all by the same author, Kudo, Taku). For the duration of the post, I will continue to use SentencePiece to refer to both the algorithm and its package, as that will hopefully be less confusing. If you want instructions on how to use the actual software, take a look at the colab link at the end of the article or in Reference [18]. It’s implemented in C++ and blazingly fast. You can train a tokenizer on a corpus of 105 characters in seconds.It’s also blazingly fast to tokenize. This means you can use it directly on raw text data, without the need to store your tokenized data to disk.Subword regularization is like a text version of data augmentation, and can greatly improve the quality of your model.It’s whitespace agnostic. You can train non-whitespace delineated languages like Chinese and Japanese with the same ease as you would English or French.It can work at the byte level, so you **almost** never need to use [UNK] or [OOV] tokens. This is not specific only to SentencePiece.This paper [17]: Byte Pair Encoding is Suboptimal for Language Model Pretraining — https://arxiv.org/pdf/2004.03720.pdf It’s implemented in C++ and blazingly fast. You can train a tokenizer on a corpus of 105 characters in seconds. It’s also blazingly fast to tokenize. This means you can use it directly on raw text data, without the need to store your tokenized data to disk. Subword regularization is like a text version of data augmentation, and can greatly improve the quality of your model. It’s whitespace agnostic. You can train non-whitespace delineated languages like Chinese and Japanese with the same ease as you would English or French. It can work at the byte level, so you **almost** never need to use [UNK] or [OOV] tokens. This is not specific only to SentencePiece. This paper [17]: Byte Pair Encoding is Suboptimal for Language Model Pretraining — https://arxiv.org/pdf/2004.03720.pdf SentencePiece is powerful, but what exactly is its purpose? Alluding to point (3), it enables us to train the subword regularization task, which we now explain. Our goal in this subsection is to explicitly develop the learning objective for subword regularization. To begin, let’s consider how we might assign probabilities to sequences. In general, we like to think of sequences as containing a direction, meaning there is a forward and backward direction. You speak words in an order. Stocks rise and fall over time. We can thus specify the distribution of a sequence in terms of its conditional distributions at earlier times. Given a sequence of unigrams X = (x_1, ... , x_n), from repeated application of Bayes’ rule we rewrite its probability as Readers familiar with the Naive Bayes method [5] should recognize this formula. In Naive Bayes, we make a conditional independence assumption (a strong assumption) that if X is conditioned on some variable y, i.e. P(X|y), then we can assume that p(x_2|x_1, y) = p(x_2 | y), p(x_3|x_2, x_1, y) = p(x_3|y) and so on. Meaning if we are given information about this other thing y, we can totally forget about all the variables x_{j<i} that x_i depends on. To prep ourselves for such a simplification, we consider the problem of Nerual Machine Translation (NMT). There, we want to assess the probability P(Y|X) of a target sentence Y given an input sentence X. As both Y and X are sequences, we can write the probability [3] Here, the lower case variables indicate the actual tokens, and the uppercase the sequence of such tokens. Theta represents our model parameters (the weights of a neural network). As it stands, this formula is not quite correct. In reality, X and Y can be formed by an exponentially large number of possible subword sequences. Think breaking down the word “hello”. We could tokenize in a large number of ways: So in reality, we should replace X and Y on the left with a specific sequence representation x and y. SentencePiece acknowledges this reality, and uses it to its advantage. We can then write the full segmentation-averaged cost function for our NMT task as This formula is slightly intimidating, but you don’t need to think too hard about it. What we can do in practice, is remove the expectation E[...] and just replace x and y with a single randomized segmentation. That’s it. Everything else we would normally do for training an NMT model is unchanged (this includes a short length penalty and any other model hacks). The “use one sample” approximation should be familiar to anyone who has worked with Variational Autoencoders [6], where the expectation value over hidden states is similarly approximated by a sample size of one. Now that we’ve defined the training task, we have to answer the practical question; yeah cool, but how in the world do we build a probability distribution over an exponential number of states?! Like everything else in science, we cheat and approximate like hell until someone tells us we can’t. At its heart, SentencePiece is just another plain old a unigram model. What this means is that it’s too hard to consider even a joint distribution P(x_1, x_2) of just two tokens, let alone the n needed to specify P(X). So, we just make the approximation: subject to the normalization constraint: where every subword (known as a unigram here) occurs with probability independent of every other subword. Yes, a drastic assumption, but empirically not too harmful. Unigram language models are quite common, and have been around for a while. A popular method called Byte Pair Encoding (BPE), first introduced in the information literature by Gage [7] and later used in the context of NMT by Sennrich et. al. [8] (a very readable paper btw) is a simple method generating based on encoding the text with the fewest required bits of information. A slight variant of BPE called WordPiece is another popular tokenizer, and we refer the reader to other digestible summary articles like [9] for a better overview. In principle, SentencePiece can be built on any unigram model. The only things we need to feed it are The unigram probabilitiesThe training corpus The unigram probabilities The training corpus We then just train the SentencePiece tokenizer on the corpus, and we are free to perform the subword regularized (or not) NMT training. The beauty is we don’t even need to use subword regularization if we don’t want to. We could also just use SentencePiece as a fast tokenizer that let’s us handle raw text on the fly. Despite making the drastic unigram assumption, how to train the tokenizer is not at all obvious, and one of the reasons for this post. We explain this in detail after the next section. In order to actually do something concrete though, eventually we have to pick a unigram model. In this post, we will use BPE, as it’s straightforward and simple enough that we can make a homecooked version on the spot. The general idea is to do the following: Go through your corpus and find all the “bytes” i.e. the irreducible characters from which all others can be built. This is our base. It ensures we can almost always reconstruct any unseen input.Run a sliding window over the entire corpus (the actual code is slightly different) and find the most frequent bigram. Bigrams are formed from consecutive subwords in the current list of seen subwords. So, “hello” would have the counts {“he”: 1, “el”:1, “ll”:1, “lo”: 1}.Choose the most frequent bigram, add it to the list of subwords, then merge all instances of this bigram in the corpus.Repeat until you reach your desired vocabulary size. Go through your corpus and find all the “bytes” i.e. the irreducible characters from which all others can be built. This is our base. It ensures we can almost always reconstruct any unseen input. Run a sliding window over the entire corpus (the actual code is slightly different) and find the most frequent bigram. Bigrams are formed from consecutive subwords in the current list of seen subwords. So, “hello” would have the counts {“he”: 1, “el”:1, “ll”:1, “lo”: 1}. Choose the most frequent bigram, add it to the list of subwords, then merge all instances of this bigram in the corpus. Repeat until you reach your desired vocabulary size. By always picking the most frequent bigram (i.e. byte-pair) we in essence minimizing the coding length needed to encode our corpus, hence the whole “minimizing information” thing. In practice, it’s not efficient to loop over the entire corpus every time we want to find a new byte-pair. Instead, we loop once at the start to find all words (not subwords, actual words) and create vocabulary, which is a dictionary matching words to their word count. We then only need to loop over words in the dictionary each time, and if a word appears 20 times, then any of its subwords will also appear at least 20 times. BPE is an incremental and deterministic method. We can always tokenize by following the same order of merges. I want to pause and emphasize the importance of this point. If we don’t follow the same order, all hell breaks loose. In BPE we first preprocess words to be space separated, with a special </w> token to indicate a word break. Consider the word Boat → B o a t </w> Suppose our corpus talks alot about snakes (boa constrictors), breakfast and sailing, so we might see the words “boa”, “oat”, and “boat”. If we talk more about snakes than breakfast, we might get the tokenization (For snake enthusiasts) Boat → Boa t </w> (For breakfast enthusiasts) Boats -> B oat </w> If we never talk about boats, then the tokenizers will never line up. One will have a Boa where the other has an Oat and they won’t agree. With that digression out of the way, let’s dive right into the BPE code, since it’s not our main focus, and it’s actually semi-written out in the original paper [8] The standard BPE format is how we wrote Boat above. Subwords separated by spaces, with an end of word token </w>. We choose the token “_” instead of </w> to align better with SentencePiece. First, in the `initialize_vocab` method, we initialize the vocabulary by getting all the words and their counts, then initialize the tokens by finding all irreducible characters. The get_bigrams method is auxiliary method to determine the most frequent bigram. The merge vocab takes care of updating the vocab to use the new bigram, and returns the bigram → bytepair merge, so that we can store the operation in a list. Finally, the find_merges function does the work of actually finding bigrams, and the fit function just coordinates all of the helper methods. Great! Now that we have our byte-pair encoder ready to manufacture subwords on the spot, we can turn to training SentencePiece. We assume that we have a large collection of bigrams, greater than whatever desired vocab size we ultimately want. To train, we want to maximize the log-probability of obtaining a particular tokenization X=(x_1, ..., x_n) of the corpus, given the unigram probabilities p(x_1),...,p(x_n). Since only the full un-tokenized sequence X is observed, the actual tokenization (x_1, ..., x_n) is unobserved. This is a classic setup for using the EM algorithm [10] So it should be easy right? Just turn to any old ML textbook and copy/paste the EM result. Well,... no. The problem is that the x_i are all of different sizes! It turns out that the code implementation of sentence piece uses a Bayesian method of training, whereas the paper description uses a maximum likelihood EM method. If this is confusing, just know generally Bayesian=harder. To see what I’m talking about you either have to really dig into the C++ code, or just look where I tell you in references [11] and [12]. Since this point will come up, we need to show how to solve the basic Bayesian EM problem for Dirichlet processes. As it is a little off the main topic, please see Appendix I for details. For now, we’ll keep moving along. The SentencePiece training objective is the following. We wish to maximize the log-likelihood Where the x are the unigram sequences, and S(x) denotes the set of all possible sequences. Again, these are hidden variables, we only see the un-tokenized corpus! To solve this, we incorporate an EM type algorithm. If you’re familiar with EM, you’ll notice the steps are actually backwards, we do an ME-method. Despite the fancy name, it’s actually quite intuitive and straightforward. The steps are: Initialize the unigram probabilities. Remember P(x) = P(x_1)...P(x_n) so once we have the unigrams, we have the probability of any sequence. In our code, we just use the BPE frequency counts to get closer to the objective.M-step: compute the most probable unigram sequence given the current probabilities. This defines a single tokenization. Implementing this requires some thought.E-step: given the current tokenization, recompute the unigram probabilities by counting the occurrence of all subwords in the tokenization. The frequentist unigram probability is just the frequency with which that unigram occurs. In practice, it is of no more difficulty to Bayesian-ify this (see the Appendix) and instead compute Initialize the unigram probabilities. Remember P(x) = P(x_1)...P(x_n) so once we have the unigrams, we have the probability of any sequence. In our code, we just use the BPE frequency counts to get closer to the objective. M-step: compute the most probable unigram sequence given the current probabilities. This defines a single tokenization. Implementing this requires some thought. E-step: given the current tokenization, recompute the unigram probabilities by counting the occurrence of all subwords in the tokenization. The frequentist unigram probability is just the frequency with which that unigram occurs. In practice, it is of no more difficulty to Bayesian-ify this (see the Appendix) and instead compute 4. Repeat steps 2 and 3 until convergence. The log-likelihood is theoretically guaranteed to monotonically increase, so if it doesn’t you’ve got a bug. We’re almost there, the final piece we need is how to compute step 2. If all of the subwords were of the same length, this would be a classic application of the Viterbi algorithm [13]. But alas, life is not so simple. The Viterbi algorithm applies to the following problem You have some hidden states z_1, ..., z_n, and you want to transition from z_1 →z_2 →... →z_n, and you know the transition matrix A_ij, giving the probability to go from z_i^{(1)} → z_j^{(2)}, where i and j are the hidden state dimension, and the superscript is the sequence order. All transitions get the same A matrix. You can use Viterbi to construct an optimal path The issue is that A is not between adjacent states. To understand how this may be a problem, let us represent a simple tokenization procedure diagrammatically. Consider tokenizing the word “hello”. Let’s say we have the subwords: {“he”, “h”, “ll”, “e”, “o”, “hell”}. Then, we can generate the following “trellis-like” figure (it’s not a trellis since we don’t show transitions to all possible hidden states i.e. characters, and transitions are not restricted to nearest neighbors, we can jump more than one box to the right.): Each arrow represents a transition, and we can think of it as carrying a probability as well, given by the unigram probability of the token created from the arrow’s tail (not inclusive) to its head (inclusive). The goal is to now pick arrows such that we arrive at <eos> — end of sequence — with as high a probability as possible. This problem has optimal substructure and can be solved with dynamic programming. Let’s say we are sitting at state (4). There are three arrows feeding into it, a red, a blue, and a green. The max probability at (4) is just the best path out of the three possible choices: coming from red, from blue, or from green. In equations: We’re almost ready to code it up, but there’s one issue. How do we actually find those arrows we drew? And how do we do it efficiently? For this, we need to make use of the Trie data structure [14]. It’s bit a bit difficult to explain in words (pun intended!) so let’s just show what the trie looks like for our current problem: The root node is the start-of-sequence token <sos>. Any time we encounter and <end> node, it signifies that everything in the path from <sos> to <end> is a valid subword. The root <sos> will begin with exactly one branch for every unique character in our subword list. As we grow the available subwords, we create more branches in our trie. The Trie is going to be the fundamental data structure that our tokenizer uses to store and retrieve subwords. Here’s a basic Trie implementation in python that will fit all of our needs: We’ve now got everything we need. The actual algorithm for computing sequences can vary depending on if we want just the best sequence (Viterbi) or the n_best, so we will keep two separate functions for this. The dynamic programming solution to this type of problem is old and so it has other names; it is referred to as a forwards-backwards algorithm, and is a special subset of the sum-product algorithm for training directed graphical models [13, pg. 613]. More sophisticated algorithms include the Forward-DP Backward-A* algorithm [15] and Forward-Filtering and Backward-Sampling algorithm (FFBS) [16]. Our solution will be closer to the latter. There’s one final note before showing the code. When performing the max over p_{i<j}, we brute force search p_{T<i<j}, where T is the length of the longest subword. That’s probably going to be a small number and shouldn’t harm our O(N) algorithm. Ok, below is our full sentencepiece trainer. For the moment, you only need to pay attention to the methods 1) forward_step 2) backward_step The forward and backward steps implement the algorithm we just talked about. The backward step hasn’t been discussed yet though. While we compute the forward step, we also store the length of the max token ending at any given index. This way, we can retrace all of the arrows that led to our max probability, since the length of the arrow fully specifies the transition! This is because the tokenized text isn’t changing, meaning the hidden states are set. We really are just choosing how many steps to jump at every character. The full EM step is easy to put together now. We follow the steps outlined earlier, and use the Bayesian-ified EM step, which is why we had to import the digamma function from scipy. There’s one more piece (pun intended again) to make this complete. In general, we want to be able to fix our vocab size. What sentencepiece does is first aggregate more subword tokens than it really needs. We then perform pruning “rounds” whereby we optimize the EM algorithm, then remove or prune off the least probable 20% tokens (probabilities were computed in the E-step). We repeat this procedure until we reach our desired vocab size. The fit method now takes care of running the EM steps, pruning after each round, then continuing if further reductions are needed. And that’s the trainer. The final part is subword sampling. Disclaimer, we don’t use the same algorithm, but it’s enough to generate randomized tokenizations and provide a proof of concept. In the forward-backward pass, we only stored the optimal sequence. To find alternative tokenizations, at each index instead of saving only the optimal ending subword, we save the n_best number of ending subwords. Now, we can tokenize by randomly sampling each final subword from the provided list. This gives us subword regularization! Why the disclaimer? Well, if you think about it, we actually still have the same problem as before, where randomly sampling ending subwords locally does not guarantee that the full tokenization will be 2nd, 3rd, 4th, or whatever best. To properly do that, please see the actual sentencepiece implementation [2] or the FFBS algorithm [16]. The random sampler is provided by the generalized_forward_step and generalized_backward_step methods. Here’s an example output Sample 1: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'or', 'l', 'd']Sample 2: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'o', 'r', 'l', 'd'] Sample 3: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'or', 'l', 'd'] This was a long dive into SentencePiece, but I hope it has been worth the effort. Now that you know more about how it works, you can promptly forget everything and just piece together what you need from the bullet points at the top of the article (pun still intended!!): Speed speed speed. Can directly handle text data during training.Subword regularization → better models, data augmentation, improved Language Modeling pretrainingCan easily tokenize non-whitespace languages like Japanese and ChineseNo more [UNK] tokens (well...almost no more [UNK] tokens) Speed speed speed. Can directly handle text data during training. Subword regularization → better models, data augmentation, improved Language Modeling pretraining Can easily tokenize non-whitespace languages like Japanese and Chinese No more [UNK] tokens (well...almost no more [UNK] tokens) If you have any NLP tasks, please strongly considering using SentencePiece as your tokenizer. For using the actual software, I’ve found the following google colab tutorial to be really useful [18] colab.research.google.com Thanks, and happy tokenizing! Here, we discuss how to Bayesian-ify your EM algorithm. You can also read along with Reference [12]. The discussion is based on the mean field theory. We will simply use its main result, i.e. the coupled equations for determining posterior distributions over hidden parameters/states. See Chapter 10 of [13] for further reading. The goal of variational inference is to determine the posterior distributions of our model’s unobserved parameters and/or states. We begin by writing the model’s log evidence: Which is a repeat of our earlier definition; nothing new yet. Recall, X is the un-tokenized corpus, S(x) represents all possible sequences, and the boldface lowercase x denotes a particular tokenization. Due to the summation inside the log, this model is intractable. To make headway, we first introduce hidden variables pi, denoting the unigram probabilities. We further condition these probabilities on a Dirichlet prior, creating a Bayesian model. We write: The probability p(pi|alpha) is a symmetric Dirichlet distribution: and the probability of any particular sequence is the product of its unigram probabilities The x_{nk} binary-valued (can only be 0 or 1) and represent whether the nth position in the sequence is given by the kth subword in the vocabulary. We now make the mean field approximation for the posterior distribution the subscripts are purely labels; they don’t represent dimensions or anything like that, they’re just names. From here, we can make use of the general formulae for computing posteriors: and similarly for pi Inserting our definitions for the log model evidence into the expectation values and pulling out all the terms not averaged over, we find the two equations Now we make the following observation. The top equation is precisely in the form of a Dirichlet distribution, with a modified prior. Furthermore, since the z_nk are binary variables we can perform their expectation as just the count of various unigrams. We define this with the variable which again is just the unigram count. Now that we know the distribution over pi, we can compute its expectation value using the known result [13, page 687, Eq. B.21 OR go to wikipedia — way faster] Putting this into the equation for log q_z(z), we find the distribution This is exactly our categorical distribution over the weights pi! In other words, we immediately recognize that the thing inside the parenthesis are indeed our weights pi. The only thing we need to mention, is that when applying the Bayesian-ified method, we set alpha=0. This has the effect of enhancing high count unigrams and diminishing low counts. [1] Kudo, Taku, and John Richardson. “Sentencepiece: A simple and language independent subword tokenizer and detokenizer for neural text processing.” arXiv preprint arXiv:1808.06226 (2018). [2] https://github.com/google/sentencepiece/ [3] Kudo, Taku. “Subword regularization: Improving neural network translation models with multiple subword candidates.” arXiv preprint arXiv:1804.10959 (2018). [4] Steven L Scott. 2002. “Bayesian methods for hidden markov models: Recursive computing in the 21st century.” Journal of the American Statistical Association . [5] http://cs229.stanford.edu/notes-spring2019/cs229-notes2.pdf [6] Kingma, Diederik P., and Max Welling. “Auto-encoding variational bayes.” arXiv preprint arXiv:1312.6114 (2013). [7] Philip Gage. “A new algorithm for data compression.” C Users J. 12(2):23–38 (1994). [8] Rico Sennrich, Barry Haddow, and Alexandra Birch. “Neural machine translation of rare words with subword units.” In Proc. of ACL (2016). [9] https://huggingface.co/transformers/tokenizer_summary.html [10] http://cs229.stanford.edu/notes-spring2019/cs229-notes8.pdf [11] Specifically, go to Line 271 https://github.com/google/sentencepiece/blob/master/src/unigram_model_trainer.cc [12] If you looked at [11] you will find the link, page 178 in particular: https://cs.stanford.edu/~pliang/papers/tutorial-acl2007-talk.pdf [13] Bishop, Christopher M. “Pattern recognition and machine learning.” springer, (2006). Look at page 629 [14] https://en.wikipedia.org/wiki/Trie — Sorry I don’t have a better reference, I’m really not even sure how I know this anymore. [15] Masaaki Nagata. “A stochastic japanese morphological analyzer using a forward-dp backward-a* nbest search algorithm.” In Proc. of COLING (1994). [16] Steven L Scott. “Bayesian methods for hidden markov models: Recursive computing in the 21st century.” Journal of the American Statistical Association (2002). [17] Bostrom, Kaj, and Greg Durrett. “Byte pair encoding is suboptimal for language model pretraining.” arXiv preprint arXiv:2004.03720 (2020). [18] https://colab.research.google.com/github/google/sentencepiece/blob/master/python/sentencepiece_python_module_example.ipynb [19] Murphy, Kevin P. Machine learning: a probabilistic perspective. MIT press, (2012).
[ { "code": null, "e": 607, "s": 171, "text": "I’ll be the first to admit that learning about tokenization schemes can be boring, if not downright painful. Often, when training a natural language, choosing and implementing a tokenization scheme is just one more added layer of complexity. It can complicate your production pipelines, kill the mood with a poorly timed [OOV] or [UNK], or maybe just send you into the depths of unicode hell, where you wonder why “string” != “string”." }, { "code": null, "e": 981, "s": 607, "text": "However, like your first truly good glass of wine, or your first experience with high quality sushi, once you’ve had a taste of the good stuff, you’ll see the rest in a totally different light. This post is meant to discuss SentencePiece, and show how painless it makes the tokenization process. Along the way you might just decide that tokenization isn’t so bad after all." }, { "code": null, "e": 1498, "s": 981, "text": "Surprisingly, it’s not actually a tokenizer, I know, misleading. It’s actually a method for selecting tokens from a precompiled list, optimizing the tokenization process based on a supplied corpus. SentencePiece [1], is the name for a package (available here [2]) which implements the Subword Regularization algorithm [3] (all by the same author, Kudo, Taku). For the duration of the post, I will continue to use SentencePiece to refer to both the algorithm and its package, as that will hopefully be less confusing." }, { "code": null, "e": 1636, "s": 1498, "text": "If you want instructions on how to use the actual software, take a look at the colab link at the end of the article or in Reference [18]." }, { "code": null, "e": 2415, "s": 1636, "text": "It’s implemented in C++ and blazingly fast. You can train a tokenizer on a corpus of 105 characters in seconds.It’s also blazingly fast to tokenize. This means you can use it directly on raw text data, without the need to store your tokenized data to disk.Subword regularization is like a text version of data augmentation, and can greatly improve the quality of your model.It’s whitespace agnostic. You can train non-whitespace delineated languages like Chinese and Japanese with the same ease as you would English or French.It can work at the byte level, so you **almost** never need to use [UNK] or [OOV] tokens. This is not specific only to SentencePiece.This paper [17]: Byte Pair Encoding is Suboptimal for Language Model Pretraining — https://arxiv.org/pdf/2004.03720.pdf" }, { "code": null, "e": 2527, "s": 2415, "text": "It’s implemented in C++ and blazingly fast. You can train a tokenizer on a corpus of 105 characters in seconds." }, { "code": null, "e": 2673, "s": 2527, "text": "It’s also blazingly fast to tokenize. This means you can use it directly on raw text data, without the need to store your tokenized data to disk." }, { "code": null, "e": 2792, "s": 2673, "text": "Subword regularization is like a text version of data augmentation, and can greatly improve the quality of your model." }, { "code": null, "e": 2945, "s": 2792, "text": "It’s whitespace agnostic. You can train non-whitespace delineated languages like Chinese and Japanese with the same ease as you would English or French." }, { "code": null, "e": 3079, "s": 2945, "text": "It can work at the byte level, so you **almost** never need to use [UNK] or [OOV] tokens. This is not specific only to SentencePiece." }, { "code": null, "e": 3199, "s": 3079, "text": "This paper [17]: Byte Pair Encoding is Suboptimal for Language Model Pretraining — https://arxiv.org/pdf/2004.03720.pdf" }, { "code": null, "e": 3360, "s": 3199, "text": "SentencePiece is powerful, but what exactly is its purpose? Alluding to point (3), it enables us to train the subword regularization task, which we now explain." }, { "code": null, "e": 3951, "s": 3360, "text": "Our goal in this subsection is to explicitly develop the learning objective for subword regularization. To begin, let’s consider how we might assign probabilities to sequences. In general, we like to think of sequences as containing a direction, meaning there is a forward and backward direction. You speak words in an order. Stocks rise and fall over time. We can thus specify the distribution of a sequence in terms of its conditional distributions at earlier times. Given a sequence of unigrams X = (x_1, ... , x_n), from repeated application of Bayes’ rule we rewrite its probability as" }, { "code": null, "e": 4403, "s": 3951, "text": "Readers familiar with the Naive Bayes method [5] should recognize this formula. In Naive Bayes, we make a conditional independence assumption (a strong assumption) that if X is conditioned on some variable y, i.e. P(X|y), then we can assume that p(x_2|x_1, y) = p(x_2 | y), p(x_3|x_2, x_1, y) = p(x_3|y) and so on. Meaning if we are given information about this other thing y, we can totally forget about all the variables x_{j<i} that x_i depends on." }, { "code": null, "e": 4671, "s": 4403, "text": "To prep ourselves for such a simplification, we consider the problem of Nerual Machine Translation (NMT). There, we want to assess the probability P(Y|X) of a target sentence Y given an input sentence X. As both Y and X are sequences, we can write the probability [3]" }, { "code": null, "e": 5080, "s": 4671, "text": "Here, the lower case variables indicate the actual tokens, and the uppercase the sequence of such tokens. Theta represents our model parameters (the weights of a neural network). As it stands, this formula is not quite correct. In reality, X and Y can be formed by an exponentially large number of possible subword sequences. Think breaking down the word “hello”. We could tokenize in a large number of ways:" }, { "code": null, "e": 5336, "s": 5080, "text": "So in reality, we should replace X and Y on the left with a specific sequence representation x and y. SentencePiece acknowledges this reality, and uses it to its advantage. We can then write the full segmentation-averaged cost function for our NMT task as" }, { "code": null, "e": 5700, "s": 5336, "text": "This formula is slightly intimidating, but you don’t need to think too hard about it. What we can do in practice, is remove the expectation E[...] and just replace x and y with a single randomized segmentation. That’s it. Everything else we would normally do for training an NMT model is unchanged (this includes a short length penalty and any other model hacks)." }, { "code": null, "e": 5912, "s": 5700, "text": "The “use one sample” approximation should be familiar to anyone who has worked with Variational Autoencoders [6], where the expectation value over hidden states is similarly approximated by a sample size of one." }, { "code": null, "e": 6207, "s": 5912, "text": "Now that we’ve defined the training task, we have to answer the practical question; yeah cool, but how in the world do we build a probability distribution over an exponential number of states?! Like everything else in science, we cheat and approximate like hell until someone tells us we can’t." }, { "code": null, "e": 6462, "s": 6207, "text": "At its heart, SentencePiece is just another plain old a unigram model. What this means is that it’s too hard to consider even a joint distribution P(x_1, x_2) of just two tokens, let alone the n needed to specify P(X). So, we just make the approximation:" }, { "code": null, "e": 6503, "s": 6462, "text": "subject to the normalization constraint:" }, { "code": null, "e": 6669, "s": 6503, "text": "where every subword (known as a unigram here) occurs with probability independent of every other subword. Yes, a drastic assumption, but empirically not too harmful." }, { "code": null, "e": 7210, "s": 6669, "text": "Unigram language models are quite common, and have been around for a while. A popular method called Byte Pair Encoding (BPE), first introduced in the information literature by Gage [7] and later used in the context of NMT by Sennrich et. al. [8] (a very readable paper btw) is a simple method generating based on encoding the text with the fewest required bits of information. A slight variant of BPE called WordPiece is another popular tokenizer, and we refer the reader to other digestible summary articles like [9] for a better overview." }, { "code": null, "e": 7312, "s": 7210, "text": "In principle, SentencePiece can be built on any unigram model. The only things we need to feed it are" }, { "code": null, "e": 7357, "s": 7312, "text": "The unigram probabilitiesThe training corpus" }, { "code": null, "e": 7383, "s": 7357, "text": "The unigram probabilities" }, { "code": null, "e": 7403, "s": 7383, "text": "The training corpus" }, { "code": null, "e": 7722, "s": 7403, "text": "We then just train the SentencePiece tokenizer on the corpus, and we are free to perform the subword regularized (or not) NMT training. The beauty is we don’t even need to use subword regularization if we don’t want to. We could also just use SentencePiece as a fast tokenizer that let’s us handle raw text on the fly." }, { "code": null, "e": 7907, "s": 7722, "text": "Despite making the drastic unigram assumption, how to train the tokenizer is not at all obvious, and one of the reasons for this post. We explain this in detail after the next section." }, { "code": null, "e": 8126, "s": 7907, "text": "In order to actually do something concrete though, eventually we have to pick a unigram model. In this post, we will use BPE, as it’s straightforward and simple enough that we can make a homecooked version on the spot." }, { "code": null, "e": 8167, "s": 8126, "text": "The general idea is to do the following:" }, { "code": null, "e": 8805, "s": 8167, "text": "Go through your corpus and find all the “bytes” i.e. the irreducible characters from which all others can be built. This is our base. It ensures we can almost always reconstruct any unseen input.Run a sliding window over the entire corpus (the actual code is slightly different) and find the most frequent bigram. Bigrams are formed from consecutive subwords in the current list of seen subwords. So, “hello” would have the counts {“he”: 1, “el”:1, “ll”:1, “lo”: 1}.Choose the most frequent bigram, add it to the list of subwords, then merge all instances of this bigram in the corpus.Repeat until you reach your desired vocabulary size." }, { "code": null, "e": 9001, "s": 8805, "text": "Go through your corpus and find all the “bytes” i.e. the irreducible characters from which all others can be built. This is our base. It ensures we can almost always reconstruct any unseen input." }, { "code": null, "e": 9273, "s": 9001, "text": "Run a sliding window over the entire corpus (the actual code is slightly different) and find the most frequent bigram. Bigrams are formed from consecutive subwords in the current list of seen subwords. So, “hello” would have the counts {“he”: 1, “el”:1, “ll”:1, “lo”: 1}." }, { "code": null, "e": 9393, "s": 9273, "text": "Choose the most frequent bigram, add it to the list of subwords, then merge all instances of this bigram in the corpus." }, { "code": null, "e": 9446, "s": 9393, "text": "Repeat until you reach your desired vocabulary size." }, { "code": null, "e": 9626, "s": 9446, "text": "By always picking the most frequent bigram (i.e. byte-pair) we in essence minimizing the coding length needed to encode our corpus, hence the whole “minimizing information” thing." }, { "code": null, "e": 10055, "s": 9626, "text": "In practice, it’s not efficient to loop over the entire corpus every time we want to find a new byte-pair. Instead, we loop once at the start to find all words (not subwords, actual words) and create vocabulary, which is a dictionary matching words to their word count. We then only need to loop over words in the dictionary each time, and if a word appears 20 times, then any of its subwords will also appear at least 20 times." }, { "code": null, "e": 10409, "s": 10055, "text": "BPE is an incremental and deterministic method. We can always tokenize by following the same order of merges. I want to pause and emphasize the importance of this point. If we don’t follow the same order, all hell breaks loose. In BPE we first preprocess words to be space separated, with a special </w> token to indicate a word break. Consider the word" }, { "code": null, "e": 10429, "s": 10409, "text": "Boat → B o a t </w>" }, { "code": null, "e": 10642, "s": 10429, "text": "Suppose our corpus talks alot about snakes (boa constrictors), breakfast and sailing, so we might see the words “boa”, “oat”, and “boat”. If we talk more about snakes than breakfast, we might get the tokenization" }, { "code": null, "e": 10684, "s": 10642, "text": "(For snake enthusiasts) Boat → Boa t </w>" }, { "code": null, "e": 10732, "s": 10684, "text": "(For breakfast enthusiasts) Boats -> B oat </w>" }, { "code": null, "e": 10871, "s": 10732, "text": "If we never talk about boats, then the tokenizers will never line up. One will have a Boa where the other has an Oat and they won’t agree." }, { "code": null, "e": 11036, "s": 10871, "text": "With that digression out of the way, let’s dive right into the BPE code, since it’s not our main focus, and it’s actually semi-written out in the original paper [8]" }, { "code": null, "e": 11226, "s": 11036, "text": "The standard BPE format is how we wrote Boat above. Subwords separated by spaces, with an end of word token </w>. We choose the token “_” instead of </w> to align better with SentencePiece." }, { "code": null, "e": 11405, "s": 11226, "text": "First, in the `initialize_vocab` method, we initialize the vocabulary by getting all the words and their counts, then initialize the tokens by finding all irreducible characters." }, { "code": null, "e": 11646, "s": 11405, "text": "The get_bigrams method is auxiliary method to determine the most frequent bigram. The merge vocab takes care of updating the vocab to use the new bigram, and returns the bigram → bytepair merge, so that we can store the operation in a list." }, { "code": null, "e": 11788, "s": 11646, "text": "Finally, the find_merges function does the work of actually finding bigrams, and the fit function just coordinates all of the helper methods." }, { "code": null, "e": 12372, "s": 11788, "text": "Great! Now that we have our byte-pair encoder ready to manufacture subwords on the spot, we can turn to training SentencePiece. We assume that we have a large collection of bigrams, greater than whatever desired vocab size we ultimately want. To train, we want to maximize the log-probability of obtaining a particular tokenization X=(x_1, ..., x_n) of the corpus, given the unigram probabilities p(x_1),...,p(x_n). Since only the full un-tokenized sequence X is observed, the actual tokenization (x_1, ..., x_n) is unobserved. This is a classic setup for using the EM algorithm [10]" }, { "code": null, "e": 12532, "s": 12372, "text": "So it should be easy right? Just turn to any old ML textbook and copy/paste the EM result. Well,... no. The problem is that the x_i are all of different sizes!" }, { "code": null, "e": 12892, "s": 12532, "text": "It turns out that the code implementation of sentence piece uses a Bayesian method of training, whereas the paper description uses a maximum likelihood EM method. If this is confusing, just know generally Bayesian=harder. To see what I’m talking about you either have to really dig into the C++ code, or just look where I tell you in references [11] and [12]." }, { "code": null, "e": 13114, "s": 12892, "text": "Since this point will come up, we need to show how to solve the basic Bayesian EM problem for Dirichlet processes. As it is a little off the main topic, please see Appendix I for details. For now, we’ll keep moving along." }, { "code": null, "e": 13208, "s": 13114, "text": "The SentencePiece training objective is the following. We wish to maximize the log-likelihood" }, { "code": null, "e": 13609, "s": 13208, "text": "Where the x are the unigram sequences, and S(x) denotes the set of all possible sequences. Again, these are hidden variables, we only see the un-tokenized corpus! To solve this, we incorporate an EM type algorithm. If you’re familiar with EM, you’ll notice the steps are actually backwards, we do an ME-method. Despite the fancy name, it’s actually quite intuitive and straightforward. The steps are:" }, { "code": null, "e": 14322, "s": 13609, "text": "Initialize the unigram probabilities. Remember P(x) = P(x_1)...P(x_n) so once we have the unigrams, we have the probability of any sequence. In our code, we just use the BPE frequency counts to get closer to the objective.M-step: compute the most probable unigram sequence given the current probabilities. This defines a single tokenization. Implementing this requires some thought.E-step: given the current tokenization, recompute the unigram probabilities by counting the occurrence of all subwords in the tokenization. The frequentist unigram probability is just the frequency with which that unigram occurs. In practice, it is of no more difficulty to Bayesian-ify this (see the Appendix) and instead compute" }, { "code": null, "e": 14545, "s": 14322, "text": "Initialize the unigram probabilities. Remember P(x) = P(x_1)...P(x_n) so once we have the unigrams, we have the probability of any sequence. In our code, we just use the BPE frequency counts to get closer to the objective." }, { "code": null, "e": 14706, "s": 14545, "text": "M-step: compute the most probable unigram sequence given the current probabilities. This defines a single tokenization. Implementing this requires some thought." }, { "code": null, "e": 15037, "s": 14706, "text": "E-step: given the current tokenization, recompute the unigram probabilities by counting the occurrence of all subwords in the tokenization. The frequentist unigram probability is just the frequency with which that unigram occurs. In practice, it is of no more difficulty to Bayesian-ify this (see the Appendix) and instead compute" }, { "code": null, "e": 15189, "s": 15037, "text": "4. Repeat steps 2 and 3 until convergence. The log-likelihood is theoretically guaranteed to monotonically increase, so if it doesn’t you’ve got a bug." }, { "code": null, "e": 15259, "s": 15189, "text": "We’re almost there, the final piece we need is how to compute step 2." }, { "code": null, "e": 15462, "s": 15259, "text": "If all of the subwords were of the same length, this would be a classic application of the Viterbi algorithm [13]. But alas, life is not so simple. The Viterbi algorithm applies to the following problem" }, { "code": null, "e": 15832, "s": 15462, "text": "You have some hidden states z_1, ..., z_n, and you want to transition from z_1 →z_2 →... →z_n, and you know the transition matrix A_ij, giving the probability to go from z_i^{(1)} → z_j^{(2)}, where i and j are the hidden state dimension, and the superscript is the sequence order. All transitions get the same A matrix. You can use Viterbi to construct an optimal path" }, { "code": null, "e": 15992, "s": 15832, "text": "The issue is that A is not between adjacent states. To understand how this may be a problem, let us represent a simple tokenization procedure diagrammatically." }, { "code": null, "e": 16062, "s": 15992, "text": "Consider tokenizing the word “hello”. Let’s say we have the subwords:" }, { "code": null, "e": 16099, "s": 16062, "text": "{“he”, “h”, “ll”, “e”, “o”, “hell”}." }, { "code": null, "e": 16359, "s": 16099, "text": "Then, we can generate the following “trellis-like” figure (it’s not a trellis since we don’t show transitions to all possible hidden states i.e. characters, and transitions are not restricted to nearest neighbors, we can jump more than one box to the right.):" }, { "code": null, "e": 16690, "s": 16359, "text": "Each arrow represents a transition, and we can think of it as carrying a probability as well, given by the unigram probability of the token created from the arrow’s tail (not inclusive) to its head (inclusive). The goal is to now pick arrows such that we arrive at <eos> — end of sequence — with as high a probability as possible." }, { "code": null, "e": 17020, "s": 16690, "text": "This problem has optimal substructure and can be solved with dynamic programming. Let’s say we are sitting at state (4). There are three arrows feeding into it, a red, a blue, and a green. The max probability at (4) is just the best path out of the three possible choices: coming from red, from blue, or from green. In equations:" }, { "code": null, "e": 17349, "s": 17020, "text": "We’re almost ready to code it up, but there’s one issue. How do we actually find those arrows we drew? And how do we do it efficiently? For this, we need to make use of the Trie data structure [14]. It’s bit a bit difficult to explain in words (pun intended!) so let’s just show what the trie looks like for our current problem:" }, { "code": null, "e": 17801, "s": 17349, "text": "The root node is the start-of-sequence token <sos>. Any time we encounter and <end> node, it signifies that everything in the path from <sos> to <end> is a valid subword. The root <sos> will begin with exactly one branch for every unique character in our subword list. As we grow the available subwords, we create more branches in our trie. The Trie is going to be the fundamental data structure that our tokenizer uses to store and retrieve subwords." }, { "code": null, "e": 17878, "s": 17801, "text": "Here’s a basic Trie implementation in python that will fit all of our needs:" }, { "code": null, "e": 18528, "s": 17878, "text": "We’ve now got everything we need. The actual algorithm for computing sequences can vary depending on if we want just the best sequence (Viterbi) or the n_best, so we will keep two separate functions for this. The dynamic programming solution to this type of problem is old and so it has other names; it is referred to as a forwards-backwards algorithm, and is a special subset of the sum-product algorithm for training directed graphical models [13, pg. 613]. More sophisticated algorithms include the Forward-DP Backward-A* algorithm [15] and Forward-Filtering and Backward-Sampling algorithm (FFBS) [16]. Our solution will be closer to the latter." }, { "code": null, "e": 18775, "s": 18528, "text": "There’s one final note before showing the code. When performing the max over p_{i<j}, we brute force search p_{T<i<j}, where T is the length of the longest subword. That’s probably going to be a small number and shouldn’t harm our O(N) algorithm." }, { "code": null, "e": 18915, "s": 18775, "text": "Ok, below is our full sentencepiece trainer. For the moment, you only need to pay attention to the methods 1) forward_step 2) backward_step" }, { "code": null, "e": 19443, "s": 18915, "text": "The forward and backward steps implement the algorithm we just talked about. The backward step hasn’t been discussed yet though. While we compute the forward step, we also store the length of the max token ending at any given index. This way, we can retrace all of the arrows that led to our max probability, since the length of the arrow fully specifies the transition! This is because the tokenized text isn’t changing, meaning the hidden states are set. We really are just choosing how many steps to jump at every character." }, { "code": null, "e": 19626, "s": 19443, "text": "The full EM step is easy to put together now. We follow the steps outlined earlier, and use the Bayesian-ified EM step, which is why we had to import the digamma function from scipy." }, { "code": null, "e": 20067, "s": 19626, "text": "There’s one more piece (pun intended again) to make this complete. In general, we want to be able to fix our vocab size. What sentencepiece does is first aggregate more subword tokens than it really needs. We then perform pruning “rounds” whereby we optimize the EM algorithm, then remove or prune off the least probable 20% tokens (probabilities were computed in the E-step). We repeat this procedure until we reach our desired vocab size." }, { "code": null, "e": 20222, "s": 20067, "text": "The fit method now takes care of running the EM steps, pruning after each round, then continuing if further reductions are needed. And that’s the trainer." }, { "code": null, "e": 20388, "s": 20222, "text": "The final part is subword sampling. Disclaimer, we don’t use the same algorithm, but it’s enough to generate randomized tokenizations and provide a proof of concept." }, { "code": null, "e": 20724, "s": 20388, "text": "In the forward-backward pass, we only stored the optimal sequence. To find alternative tokenizations, at each index instead of saving only the optimal ending subword, we save the n_best number of ending subwords. Now, we can tokenize by randomly sampling each final subword from the provided list. This gives us subword regularization!" }, { "code": null, "e": 21063, "s": 20724, "text": "Why the disclaimer? Well, if you think about it, we actually still have the same problem as before, where randomly sampling ending subwords locally does not guarantee that the full tokenization will be 2nd, 3rd, 4th, or whatever best. To properly do that, please see the actual sentencepiece implementation [2] or the FFBS algorithm [16]." }, { "code": null, "e": 21190, "s": 21063, "text": "The random sampler is provided by the generalized_forward_step and generalized_backward_step methods. Here’s an example output" }, { "code": null, "e": 21379, "s": 21190, "text": "Sample 1: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'or', 'l', 'd']Sample 2: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'o', 'r', 'l', 'd'] Sample 3: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'or', 'l', 'd']" }, { "code": null, "e": 21650, "s": 21379, "text": "This was a long dive into SentencePiece, but I hope it has been worth the effort. Now that you know more about how it works, you can promptly forget everything and just piece together what you need from the bullet points at the top of the article (pun still intended!!):" }, { "code": null, "e": 21940, "s": 21650, "text": "Speed speed speed. Can directly handle text data during training.Subword regularization → better models, data augmentation, improved Language Modeling pretrainingCan easily tokenize non-whitespace languages like Japanese and ChineseNo more [UNK] tokens (well...almost no more [UNK] tokens)" }, { "code": null, "e": 22006, "s": 21940, "text": "Speed speed speed. Can directly handle text data during training." }, { "code": null, "e": 22104, "s": 22006, "text": "Subword regularization → better models, data augmentation, improved Language Modeling pretraining" }, { "code": null, "e": 22175, "s": 22104, "text": "Can easily tokenize non-whitespace languages like Japanese and Chinese" }, { "code": null, "e": 22233, "s": 22175, "text": "No more [UNK] tokens (well...almost no more [UNK] tokens)" }, { "code": null, "e": 22430, "s": 22233, "text": "If you have any NLP tasks, please strongly considering using SentencePiece as your tokenizer. For using the actual software, I’ve found the following google colab tutorial to be really useful [18]" }, { "code": null, "e": 22456, "s": 22430, "text": "colab.research.google.com" }, { "code": null, "e": 22486, "s": 22456, "text": "Thanks, and happy tokenizing!" }, { "code": null, "e": 22587, "s": 22486, "text": "Here, we discuss how to Bayesian-ify your EM algorithm. You can also read along with Reference [12]." }, { "code": null, "e": 22815, "s": 22587, "text": "The discussion is based on the mean field theory. We will simply use its main result, i.e. the coupled equations for determining posterior distributions over hidden parameters/states. See Chapter 10 of [13] for further reading." }, { "code": null, "e": 22991, "s": 22815, "text": "The goal of variational inference is to determine the posterior distributions of our model’s unobserved parameters and/or states. We begin by writing the model’s log evidence:" }, { "code": null, "e": 23452, "s": 22991, "text": "Which is a repeat of our earlier definition; nothing new yet. Recall, X is the un-tokenized corpus, S(x) represents all possible sequences, and the boldface lowercase x denotes a particular tokenization. Due to the summation inside the log, this model is intractable. To make headway, we first introduce hidden variables pi, denoting the unigram probabilities. We further condition these probabilities on a Dirichlet prior, creating a Bayesian model. We write:" }, { "code": null, "e": 23519, "s": 23452, "text": "The probability p(pi|alpha) is a symmetric Dirichlet distribution:" }, { "code": null, "e": 23610, "s": 23519, "text": "and the probability of any particular sequence is the product of its unigram probabilities" }, { "code": null, "e": 23830, "s": 23610, "text": "The x_{nk} binary-valued (can only be 0 or 1) and represent whether the nth position in the sequence is given by the kth subword in the vocabulary. We now make the mean field approximation for the posterior distribution" }, { "code": null, "e": 24016, "s": 23830, "text": "the subscripts are purely labels; they don’t represent dimensions or anything like that, they’re just names. From here, we can make use of the general formulae for computing posteriors:" }, { "code": null, "e": 24037, "s": 24016, "text": "and similarly for pi" }, { "code": null, "e": 24193, "s": 24037, "text": "Inserting our definitions for the log model evidence into the expectation values and pulling out all the terms not averaged over, we find the two equations" }, { "code": null, "e": 24480, "s": 24193, "text": "Now we make the following observation. The top equation is precisely in the form of a Dirichlet distribution, with a modified prior. Furthermore, since the z_nk are binary variables we can perform their expectation as just the count of various unigrams. We define this with the variable" }, { "code": null, "e": 24679, "s": 24480, "text": "which again is just the unigram count. Now that we know the distribution over pi, we can compute its expectation value using the known result [13, page 687, Eq. B.21 OR go to wikipedia — way faster]" }, { "code": null, "e": 24751, "s": 24679, "text": "Putting this into the equation for log q_z(z), we find the distribution" }, { "code": null, "e": 25104, "s": 24751, "text": "This is exactly our categorical distribution over the weights pi! In other words, we immediately recognize that the thing inside the parenthesis are indeed our weights pi. The only thing we need to mention, is that when applying the Bayesian-ified method, we set alpha=0. This has the effect of enhancing high count unigrams and diminishing low counts." }, { "code": null, "e": 25294, "s": 25104, "text": "[1] Kudo, Taku, and John Richardson. “Sentencepiece: A simple and language independent subword tokenizer and detokenizer for neural text processing.” arXiv preprint arXiv:1808.06226 (2018)." }, { "code": null, "e": 25339, "s": 25294, "text": "[2] https://github.com/google/sentencepiece/" }, { "code": null, "e": 25499, "s": 25339, "text": "[3] Kudo, Taku. “Subword regularization: Improving neural network translation models with multiple subword candidates.” arXiv preprint arXiv:1804.10959 (2018)." }, { "code": null, "e": 25661, "s": 25499, "text": "[4] Steven L Scott. 2002. “Bayesian methods for hidden markov models: Recursive computing in the 21st century.” Journal of the American Statistical Association ." }, { "code": null, "e": 25725, "s": 25661, "text": "[5] http://cs229.stanford.edu/notes-spring2019/cs229-notes2.pdf" }, { "code": null, "e": 25841, "s": 25725, "text": "[6] Kingma, Diederik P., and Max Welling. “Auto-encoding variational bayes.” arXiv preprint arXiv:1312.6114 (2013)." }, { "code": null, "e": 25929, "s": 25841, "text": "[7] Philip Gage. “A new algorithm for data compression.” C Users J. 12(2):23–38 (1994)." }, { "code": null, "e": 26070, "s": 25929, "text": "[8] Rico Sennrich, Barry Haddow, and Alexandra Birch. “Neural machine translation of rare words with subword units.” In Proc. of ACL (2016)." }, { "code": null, "e": 26133, "s": 26070, "text": "[9] https://huggingface.co/transformers/tokenizer_summary.html" }, { "code": null, "e": 26198, "s": 26133, "text": "[10] http://cs229.stanford.edu/notes-spring2019/cs229-notes8.pdf" }, { "code": null, "e": 26313, "s": 26198, "text": "[11] Specifically, go to Line 271 https://github.com/google/sentencepiece/blob/master/src/unigram_model_trainer.cc" }, { "code": null, "e": 26453, "s": 26313, "text": "[12] If you looked at [11] you will find the link, page 178 in particular: https://cs.stanford.edu/~pliang/papers/tutorial-acl2007-talk.pdf" }, { "code": null, "e": 26560, "s": 26453, "text": "[13] Bishop, Christopher M. “Pattern recognition and machine learning.” springer, (2006). Look at page 629" }, { "code": null, "e": 26691, "s": 26560, "text": "[14] https://en.wikipedia.org/wiki/Trie — Sorry I don’t have a better reference, I’m really not even sure how I know this anymore." }, { "code": null, "e": 26841, "s": 26691, "text": "[15] Masaaki Nagata. “A stochastic japanese morphological analyzer using a forward-dp backward-a* nbest search algorithm.” In Proc. of COLING (1994)." }, { "code": null, "e": 27004, "s": 26841, "text": "[16] Steven L Scott. “Bayesian methods for hidden markov models: Recursive computing in the 21st century.” Journal of the American Statistical Association (2002)." }, { "code": null, "e": 27148, "s": 27004, "text": "[17] Bostrom, Kaj, and Greg Durrett. “Byte pair encoding is suboptimal for language model pretraining.” arXiv preprint arXiv:2004.03720 (2020)." }, { "code": null, "e": 27276, "s": 27148, "text": "[18] https://colab.research.google.com/github/google/sentencepiece/blob/master/python/sentencepiece_python_module_example.ipynb" } ]
Create variables in MySQL stored procedure with DECLARE keyword
Use MySQL DECLARE for variables in stored procedure − DECLARE anyVariableName int DEFAULT anyValue; Let us implement the above syntax in order to create variables in stored procedure − mysql> DELIMITER // mysql> CREATE PROCEDURE variable_Demo() -> BEGIN -> DECLARE lastInsertedId int DEFAULT -1; -> select lastInsertedId; -> set @providedLastId=10001; -> select @providedLastId; -> END -> // Query OK, 0 rows affected (0.32 sec) mysql> DELIMITER ; Now you can call the above stored procedure using CALL command − mysql> call variable_Demo(); This will produce the following output − +----------------+ | lastInsertedId | +----------------+ | -1 | +----------------+ 1 row in set (0.00 sec) +-----------------+ | @providedLastId | +-----------------+ | 10001 | +-----------------+ 1 row in set (0.02 sec) Query OK, 0 rows affected (0.04 sec)
[ { "code": null, "e": 1116, "s": 1062, "text": "Use MySQL DECLARE for variables in stored procedure −" }, { "code": null, "e": 1162, "s": 1116, "text": "DECLARE anyVariableName int DEFAULT anyValue;" }, { "code": null, "e": 1247, "s": 1162, "text": "Let us implement the above syntax in order to create variables in stored procedure −" }, { "code": null, "e": 1538, "s": 1247, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE variable_Demo()\n -> BEGIN\n -> DECLARE lastInsertedId int DEFAULT -1;\n -> select lastInsertedId;\n -> set @providedLastId=10001;\n -> select @providedLastId;\n -> END\n -> //\nQuery OK, 0 rows affected (0.32 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1603, "s": 1538, "text": "Now you can call the above stored procedure using CALL command −" }, { "code": null, "e": 1632, "s": 1603, "text": "mysql> call variable_Demo();" }, { "code": null, "e": 1673, "s": 1632, "text": "This will produce the following output −" }, { "code": null, "e": 1954, "s": 1673, "text": "+----------------+\n| lastInsertedId |\n+----------------+\n| -1 |\n+----------------+\n1 row in set (0.00 sec)\n\n+-----------------+\n| @providedLastId |\n+-----------------+\n| 10001 |\n+-----------------+\n1 row in set (0.02 sec)\nQuery OK, 0 rows affected (0.04 sec)" } ]
Feature selection with Random Forest | by Gianluca Malato | Towards Data Science
Feature selection has always been a great problem in machine learning. According to my experience, I can say it’s the most important part of a data science project, because it helps us reduce the dimensions of a dataset and remove the useless variables. Fortunately, there are some models that help us calculate the importance of the features, which helps us neglecting the less useful. Random forest is one such model. Random Forest is a supervised model that implements both decision trees and the bagging method. The idea is that the training dataset is resampled according to a procedure called “bootstrap”. Each sample contains a random subset of the original columns and is used to fit a decision tree. The number of models and the number of columns are hyperparameters to be optimized. Finally, the predictions of the trees are mixed together calculating the mean value (for regression) or using soft voting (for classification). The idea of bagging is that, by averaging the outputs of the single decision trees, the standard error decreases and so does the variance of the model according to bias-variance tradeoff. That’s why Random Forest has become very famous in the last years. Each tree of the random forest can calculate the importance of a feature according to its ability to increase the pureness of the leaves. It’s a topic related to how Classification And Regression Trees (CART) work. The higher the increment in leaves purity, the higher the importance of the feature. This is done for each tree, then is averaged among all the trees and, finally, normalized to 1. So, the sum of the importance scores calculated by a Random Forest is 1. Once we have the importance of each feature, we perform feature selection using a procedure called Recursive Feature Elimination. In this article, I’ll talk about the version that makes use of the k-fold cross-validation. The idea is to fit the model, then remove the less relevant feature and calculate the average value of some performance metric in CV. Then we remove the second last important feature, fit the model again and calculate the average performance. We keep doing this approach until there are no features left. The set of features that maximize the performance in CV is the set of features we have to work with. Please note that the entire procedure needs to work with the same values for the hyperparameters. Now that the theory is clear, let’s apply it in Python using sklearn. For this example, I’ll use the Boston dataset, which is a regression dataset. Let’s first import all the objects we need, that are our dataset, the Random Forest regressor and the object that will perform the RFE with CV. Finally, matplotlib for visualizing our results. import numpy as np from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.feature_selection import RFECV import matplotlib.pyplot as plt First, let’s load our dataset. X,y = load_boston(return_X_y=True) features = load_boston()['feature_names'] Now we can split it into training and test. X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) Now we can fit our Random Forest regressor. In a real project, we must optimize the values of the hyperparameters. For this example, I’ll use the default values. I’ll only set the random state to make the results reproducible. rf = RandomForestRegressor(random_state=0) rf.fit(X_train,y_train) Once the regressor is fitted, the importance of the features is stored inside the feature_importances_ property of the estimator instance. Let’s, for example, draw a bar chart with the features sorted from the most important to the less important. We’ll have to create a list of tuples. The first element of the tuple is the feature name, the second element is the importance. Then we order our list for importance value and plot a horizontal bar plot. f_i = list(zip(features,rf.feature_importances_)) f_i.sort(key = lambda x : x[1]) plt.barh([x[0] for x in f_i],[x[1] for x in f_i]) plt.show() As we can see, LSTAT feature is the most important one, followed by RM, DIS and the other features. A horizontal bar plot is a very useful chart for representing feature importance. Now, let’s use feature importance to select the best set of features according to RFE with Cross-Validation. For this example, the metric we try to optimize is the negative mean squared error. We’re going to work with 5 folds for the cross-validation, which is a quite good value. rfe = RFECV(rf,cv=5,scoring="neg_mean_squared_error") rfe.fit(X_train,y_train) The complete set of features is: The selected features are: selected_features = np.array(features)[rfe.get_support()] As we can see, RFE has neglected the less relevant feature (CHAS). Random Forest is a very powerful model both for regression and classification. It can give its own interpretation of feature importance as well, which can be plotted and used for selecting the most informative set of features according, for example, to a Recursive Feature Elimination procedure. Properly used, feature importance can give us very good and easy-to-understand deliverables (the bar plot) and efficient optimization (feature selection). That’s why I think that feature importance is a necessary part of every machine learning project. Gianluca Malato is a Data Scientist who teaches machine learning and data science on www.yourdatateacher.com. Originally published at https://www.yourdatateacher.com on October 11, 2021.
[ { "code": null, "e": 592, "s": 172, "text": "Feature selection has always been a great problem in machine learning. According to my experience, I can say it’s the most important part of a data science project, because it helps us reduce the dimensions of a dataset and remove the useless variables. Fortunately, there are some models that help us calculate the importance of the features, which helps us neglecting the less useful. Random forest is one such model." }, { "code": null, "e": 965, "s": 592, "text": "Random Forest is a supervised model that implements both decision trees and the bagging method. The idea is that the training dataset is resampled according to a procedure called “bootstrap”. Each sample contains a random subset of the original columns and is used to fit a decision tree. The number of models and the number of columns are hyperparameters to be optimized." }, { "code": null, "e": 1109, "s": 965, "text": "Finally, the predictions of the trees are mixed together calculating the mean value (for regression) or using soft voting (for classification)." }, { "code": null, "e": 1364, "s": 1109, "text": "The idea of bagging is that, by averaging the outputs of the single decision trees, the standard error decreases and so does the variance of the model according to bias-variance tradeoff. That’s why Random Forest has become very famous in the last years." }, { "code": null, "e": 1833, "s": 1364, "text": "Each tree of the random forest can calculate the importance of a feature according to its ability to increase the pureness of the leaves. It’s a topic related to how Classification And Regression Trees (CART) work. The higher the increment in leaves purity, the higher the importance of the feature. This is done for each tree, then is averaged among all the trees and, finally, normalized to 1. So, the sum of the importance scores calculated by a Random Forest is 1." }, { "code": null, "e": 2055, "s": 1833, "text": "Once we have the importance of each feature, we perform feature selection using a procedure called Recursive Feature Elimination. In this article, I’ll talk about the version that makes use of the k-fold cross-validation." }, { "code": null, "e": 2559, "s": 2055, "text": "The idea is to fit the model, then remove the less relevant feature and calculate the average value of some performance metric in CV. Then we remove the second last important feature, fit the model again and calculate the average performance. We keep doing this approach until there are no features left. The set of features that maximize the performance in CV is the set of features we have to work with. Please note that the entire procedure needs to work with the same values for the hyperparameters." }, { "code": null, "e": 2707, "s": 2559, "text": "Now that the theory is clear, let’s apply it in Python using sklearn. For this example, I’ll use the Boston dataset, which is a regression dataset." }, { "code": null, "e": 2900, "s": 2707, "text": "Let’s first import all the objects we need, that are our dataset, the Random Forest regressor and the object that will perform the RFE with CV. Finally, matplotlib for visualizing our results." }, { "code": null, "e": 3140, "s": 2900, "text": "import numpy as np from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.feature_selection import RFECV import matplotlib.pyplot as plt" }, { "code": null, "e": 3171, "s": 3140, "text": "First, let’s load our dataset." }, { "code": null, "e": 3248, "s": 3171, "text": "X,y = load_boston(return_X_y=True) features = load_boston()['feature_names']" }, { "code": null, "e": 3292, "s": 3248, "text": "Now we can split it into training and test." }, { "code": null, "e": 3384, "s": 3292, "text": "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)" }, { "code": null, "e": 3611, "s": 3384, "text": "Now we can fit our Random Forest regressor. In a real project, we must optimize the values of the hyperparameters. For this example, I’ll use the default values. I’ll only set the random state to make the results reproducible." }, { "code": null, "e": 3678, "s": 3611, "text": "rf = RandomForestRegressor(random_state=0) rf.fit(X_train,y_train)" }, { "code": null, "e": 3817, "s": 3678, "text": "Once the regressor is fitted, the importance of the features is stored inside the feature_importances_ property of the estimator instance." }, { "code": null, "e": 4131, "s": 3817, "text": "Let’s, for example, draw a bar chart with the features sorted from the most important to the less important. We’ll have to create a list of tuples. The first element of the tuple is the feature name, the second element is the importance. Then we order our list for importance value and plot a horizontal bar plot." }, { "code": null, "e": 4274, "s": 4131, "text": "f_i = list(zip(features,rf.feature_importances_)) f_i.sort(key = lambda x : x[1]) plt.barh([x[0] for x in f_i],[x[1] for x in f_i]) plt.show()" }, { "code": null, "e": 4456, "s": 4274, "text": "As we can see, LSTAT feature is the most important one, followed by RM, DIS and the other features. A horizontal bar plot is a very useful chart for representing feature importance." }, { "code": null, "e": 4737, "s": 4456, "text": "Now, let’s use feature importance to select the best set of features according to RFE with Cross-Validation. For this example, the metric we try to optimize is the negative mean squared error. We’re going to work with 5 folds for the cross-validation, which is a quite good value." }, { "code": null, "e": 4816, "s": 4737, "text": "rfe = RFECV(rf,cv=5,scoring=\"neg_mean_squared_error\") rfe.fit(X_train,y_train)" }, { "code": null, "e": 4849, "s": 4816, "text": "The complete set of features is:" }, { "code": null, "e": 4876, "s": 4849, "text": "The selected features are:" }, { "code": null, "e": 4934, "s": 4876, "text": "selected_features = np.array(features)[rfe.get_support()]" }, { "code": null, "e": 5001, "s": 4934, "text": "As we can see, RFE has neglected the less relevant feature (CHAS)." }, { "code": null, "e": 5550, "s": 5001, "text": "Random Forest is a very powerful model both for regression and classification. It can give its own interpretation of feature importance as well, which can be plotted and used for selecting the most informative set of features according, for example, to a Recursive Feature Elimination procedure. Properly used, feature importance can give us very good and easy-to-understand deliverables (the bar plot) and efficient optimization (feature selection). That’s why I think that feature importance is a necessary part of every machine learning project." }, { "code": null, "e": 5660, "s": 5550, "text": "Gianluca Malato is a Data Scientist who teaches machine learning and data science on www.yourdatateacher.com." } ]
Tryit Editor v3.6 - Show Python
import matplotlib.pyplot as plt numpy.random.seed(2) ​ x = numpy.random.normal(3, 1, 100) y = numpy.random.normal(150, 40, 100) / x
[ { "code": null, "e": 45, "s": 13, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 66, "s": 45, "text": "numpy.random.seed(2)" }, { "code": null, "e": 68, "s": 66, "text": "​" }, { "code": null, "e": 103, "s": 68, "text": "x = numpy.random.normal(3, 1, 100)" } ]
How to create a data frame in R with list elements?
If a list has the same length of elements (not sub-elements) as the length of each vector for which we want to create the data frame then we first need to create the data frame of vectors then we can easily add the list into the data frame. But if we have a list and other vectors then data frame cannot be created as data.frame function will read each value of the list separately. Live Demo > df1<-data.frame(x=rpois(20,5),y=rpois(20,1)) > df1 x y 1 6 1 2 8 1 3 6 2 4 8 1 5 5 1 6 3 1 7 6 1 8 7 1 9 7 1 10 7 2 11 5 0 12 5 2 13 2 2 14 4 0 15 2 1 16 3 1 17 4 0 18 6 4 19 6 2 20 4 1 > df1$z<-list(1:3,4:5,6:10,12:15,16:17,18:20,21:22,23:25,26:27,28:30,31:35,36:38,39:42,43:45,46:48,49:55,56:60,61:62,63:65,66:70) > df1 x y z 1 6 1 1, 2, 3 2 8 1 4, 5 3 6 2 6, 7, 8, 9, 10 4 8 1 12, 13, 14, 15 5 5 1 16, 17 6 3 1 18, 19, 20 7 6 1 21, 22 8 7 1 23, 24, 25 9 7 1 26, 27 10 7 2 28, 29, 30 11 5 0 31, 32, 33, 34, 35 12 5 2 36, 37, 38 13 2 2 39, 40, 41, 42 14 4 0 43, 44, 45 15 2 1 46, 47, 48 16 3 1 49, 50, 51, 52, 53, 54, 55 17 4 0 56, 57, 58, 59, 60 18 6 4 61, 62 19 6 2 63, 64, 65 20 4 1 66, 67, 68, 69, 70 Let’s have a look at another example: > df2<-data.frame(F1=sample(LETTERS[1:4],20,replace=TRUE),F2=sample(LETTERS[21:26],20,replace=TRUE)) > df2 F1 F2 1 C W 2 B Z 3 A V 4 D W 5 D V 6 A X 7 C X 8 D Y 9 C Y 10 B V 11 D X 12 B W 13 D V 14 A U 15 A X 16 C X 17 C Z 18 B X 19 C Z 20 A V > df2$F3<-list(rep(c("A","B"))) > df2 F1 F2 F3 1 C W A, B 2 B Z A, B 3 A V A, B 4 D W A, B 5 D V A, B 6 A X A, B 7 C X A, B 8 D Y A, B 9 C Y A, B 10 B V A, B 11 D X A, B 12 B W A, B 13 D V A, B 14 A U A, B 15 A X A, B 16 C X A, B 17 C Z A, B 18 B X A, B 19 C Z A, B 20 A V A, B
[ { "code": null, "e": 1445, "s": 1062, "text": "If a list has the same length of elements (not sub-elements) as the length of each vector for which we want to create the data frame then we first need to create the data frame of vectors then we can easily add the list into the data frame. But if we have a list and other vectors then data frame cannot be created as data.frame function will read each value of the list separately." }, { "code": null, "e": 1455, "s": 1445, "text": "Live Demo" }, { "code": null, "e": 1508, "s": 1455, "text": "> df1<-data.frame(x=rpois(20,5),y=rpois(20,1))\n> df1" }, { "code": null, "e": 1655, "s": 1508, "text": " x y\n1 6 1\n2 8 1\n3 6 2\n4 8 1\n5 5 1\n6 3 1\n7 6 1\n8 7 1\n9 7 1\n10 7 2\n11 5 0\n12 5 2\n13 2 2\n14 4 0\n15 2 1\n16 3 1\n17 4 0\n18 6 4\n19 6 2\n20 4 1" }, { "code": null, "e": 1791, "s": 1655, "text": "> df1$z<-list(1:3,4:5,6:10,12:15,16:17,18:20,21:22,23:25,26:27,28:30,31:35,36:38,39:42,43:45,46:48,49:55,56:60,61:62,63:65,66:70)\n> df1" }, { "code": null, "e": 2318, "s": 1791, "text": " x y z\n1 6 1 1, 2, 3\n2 8 1 4, 5\n3 6 2 6, 7, 8, 9, 10\n4 8 1 12, 13, 14, 15\n5 5 1 16, 17\n6 3 1 18, 19, 20\n7 6 1 21, 22\n8 7 1 23, 24, 25\n9 7 1 26, 27\n10 7 2 28, 29, 30\n11 5 0 31, 32, 33, 34, 35\n12 5 2 36, 37, 38\n13 2 2 39, 40, 41, 42\n14 4 0 43, 44, 45\n15 2 1 46, 47, 48\n16 3 1 49, 50, 51, 52, 53, 54, 55\n17 4 0 56, 57, 58, 59, 60\n18 6 4 61, 62\n19 6 2 63, 64, 65\n20 4 1 66, 67, 68, 69, 70" }, { "code": null, "e": 2356, "s": 2318, "text": "Let’s have a look at another example:" }, { "code": null, "e": 2463, "s": 2356, "text": "> df2<-data.frame(F1=sample(LETTERS[1:4],20,replace=TRUE),F2=sample(LETTERS[21:26],20,replace=TRUE))\n> df2" }, { "code": null, "e": 2600, "s": 2463, "text": "F1 F2\n1 C W\n2 B Z\n3 A V\n4 D W\n5 D V\n6 A X\n7 C X\n8 D Y\n9 C Y\n10 B V\n11 D X\n12 B W\n13 D V\n14 A U\n15 A X\n16 C X\n17 C Z\n18 B X\n19 C Z\n20 A V" }, { "code": null, "e": 2638, "s": 2600, "text": "> df2$F3<-list(rep(c(\"A\",\"B\")))\n> df2" }, { "code": null, "e": 2880, "s": 2638, "text": " F1 F2 F3\n1 C W A, B\n2 B Z A, B\n3 A V A, B\n4 D W A, B\n5 D V A, B\n6 A X A, B\n7 C X A, B\n8 D Y A, B\n9 C Y A, B\n10 B V A, B\n11 D X A, B\n12 B W A, B\n13 D V A, B\n14 A U A, B\n15 A X A, B\n16 C X A, B\n17 C Z A, B\n18 B X A, B\n19 C Z A, B\n20 A V A, B" } ]
Levenshtein Distance in JavaScript
The Levenshtein distance is a string metric for measuring the difference between two sequences. It is the minimum number of single-character edits required to change one word into the other. For example − Consider, we have these two strings − const str1 = 'hitting'; const str2 = 'kitten'; The Levenshtein distance between these two strings is 3 because we are required to make these three edits − kitten → hitten (substitution of "h" for "k") kitten → hitten (substitution of "h" for "k") hitten → hittin (substitution of "i" for "e") hitten → hittin (substitution of "i" for "e") hittin → hitting (insertion of "g" at the end) hittin → hitting (insertion of "g" at the end) We are required to write a JavaScript function that takes in two strings and calculates the Levenshtein distance between them. Following is the code − const str1 = 'hitting'; const str2 = 'kitten'; const levenshteinDistance = (str1 = '', str2 = '') => { const track = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null)); for (let i = 0; i <= str1.length; i += 1) { track[0][i] = i; } for (let j = 0; j <= str2.length; j += 1) { track[j][0] = j; } for (let j = 1; j <= str2.length; j += 1) { for (let i = 1; i <= str1.length; i += 1) { const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1; track[j][i] = Math.min( track[j][i - 1] + 1, // deletion track[j - 1][i] + 1, // insertion track[j - 1][i - 1] + indicator, // substitution ); } } return track[str2.length][str1.length]; }; console.log(levenshteinDistance(str1, str2)); Following is the output on console − 3
[ { "code": null, "e": 1253, "s": 1062, "text": "The Levenshtein distance is a string metric for measuring the difference between two sequences. It is the minimum number of single-character edits required to change one word into the other." }, { "code": null, "e": 1267, "s": 1253, "text": "For example −" }, { "code": null, "e": 1305, "s": 1267, "text": "Consider, we have these two strings −" }, { "code": null, "e": 1352, "s": 1305, "text": "const str1 = 'hitting';\nconst str2 = 'kitten';" }, { "code": null, "e": 1460, "s": 1352, "text": "The Levenshtein distance between these two strings is 3 because we are required to make these three edits −" }, { "code": null, "e": 1506, "s": 1460, "text": "kitten → hitten (substitution of \"h\" for \"k\")" }, { "code": null, "e": 1552, "s": 1506, "text": "kitten → hitten (substitution of \"h\" for \"k\")" }, { "code": null, "e": 1598, "s": 1552, "text": "hitten → hittin (substitution of \"i\" for \"e\")" }, { "code": null, "e": 1644, "s": 1598, "text": "hitten → hittin (substitution of \"i\" for \"e\")" }, { "code": null, "e": 1691, "s": 1644, "text": "hittin → hitting (insertion of \"g\" at the end)" }, { "code": null, "e": 1738, "s": 1691, "text": "hittin → hitting (insertion of \"g\" at the end)" }, { "code": null, "e": 1865, "s": 1738, "text": "We are required to write a JavaScript function that takes in two strings and calculates the Levenshtein distance between them." }, { "code": null, "e": 1889, "s": 1865, "text": "Following is the code −" }, { "code": null, "e": 2705, "s": 1889, "text": "const str1 = 'hitting';\nconst str2 = 'kitten';\nconst levenshteinDistance = (str1 = '', str2 = '') => {\n const track = Array(str2.length + 1).fill(null).map(() =>\n Array(str1.length + 1).fill(null));\n for (let i = 0; i <= str1.length; i += 1) {\n track[0][i] = i;\n }\n for (let j = 0; j <= str2.length; j += 1) {\n track[j][0] = j;\n }\n for (let j = 1; j <= str2.length; j += 1) {\n for (let i = 1; i <= str1.length; i += 1) {\n const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;\n track[j][i] = Math.min(\n track[j][i - 1] + 1, // deletion\n track[j - 1][i] + 1, // insertion\n track[j - 1][i - 1] + indicator, // substitution\n );\n }\n }\n return track[str2.length][str1.length];\n};\nconsole.log(levenshteinDistance(str1, str2));" }, { "code": null, "e": 2742, "s": 2705, "text": "Following is the output on console −" }, { "code": null, "e": 2744, "s": 2742, "text": "3" } ]
D3.js axisBottom() Function - GeeksforGeeks
28 Jul, 2020 Axes can be drawn using built-in D3 functions. This is made of Lines, Ticks and Labels. The d3.axisBottom() function in D3.js is used to create a bottom horizontal axis. This function will construct a new bottom-oriented axis generator for the given scale, with empty tick arguments, a tick size of 6 and padding of 3. Axis API can be configured using the following script. <script src = "https://d3js.org/d3-axis.v1.min.js"></script> Syntax: d3.axisBottom(scale) Parameters: This function accepts only one parameter as mentioned above and described below: scale: This parameter holds the used scale. Return Value: This function returns the created bottom horizontal axis. Below programs illustrate the d3.axisBottom() function in D3.js: Example 1: HTML <!DOCTYPE html><html> <head> <title> D3.js | d3.axisBottom() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, 100]) .range([0, width - 50]); var x_axis = d3.axisBottom(xscale); svg.append("g") .attr("transform", "translate(20,100)") .call(x_axis) </script></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <title> D3.js | d3.axisBottom() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style></head> <body> <script> var width = 400, height = 400; var data = [10, 12, 14, 16, 18, 20]; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([d3.min(data), d3.max(data)]) .range([0, width - 60]); var x_axis = d3.axisBottom(xscale); var xAxisTranslate = height / 2; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate + ")") .call(x_axis) </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 24222, "s": 24194, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24541, "s": 24222, "text": "Axes can be drawn using built-in D3 functions. This is made of Lines, Ticks and Labels. The d3.axisBottom() function in D3.js is used to create a bottom horizontal axis. This function will construct a new bottom-oriented axis generator for the given scale, with empty tick arguments, a tick size of 6 and padding of 3." }, { "code": null, "e": 24596, "s": 24541, "text": "Axis API can be configured using the following script." }, { "code": null, "e": 24658, "s": 24596, "text": "<script src = \"https://d3js.org/d3-axis.v1.min.js\"></script>\n" }, { "code": null, "e": 24666, "s": 24658, "text": "Syntax:" }, { "code": null, "e": 24688, "s": 24666, "text": "d3.axisBottom(scale)\n" }, { "code": null, "e": 24781, "s": 24688, "text": "Parameters: This function accepts only one parameter as mentioned above and described below:" }, { "code": null, "e": 24825, "s": 24781, "text": "scale: This parameter holds the used scale." }, { "code": null, "e": 24897, "s": 24825, "text": "Return Value: This function returns the created bottom horizontal axis." }, { "code": null, "e": 24962, "s": 24897, "text": "Below programs illustrate the d3.axisBottom() function in D3.js:" }, { "code": null, "e": 24973, "s": 24962, "text": "Example 1:" }, { "code": null, "e": 24978, "s": 24973, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.axisBottom() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([0, 100]) .range([0, width - 50]); var x_axis = d3.axisBottom(xscale); svg.append(\"g\") .attr(\"transform\", \"translate(20,100)\") .call(x_axis) </script></body> </html>", "e": 25637, "s": 24978, "text": null }, { "code": null, "e": 25645, "s": 25637, "text": "Output:" }, { "code": null, "e": 25656, "s": 25645, "text": "Example 2:" }, { "code": null, "e": 25661, "s": 25656, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.axisBottom() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style></head> <body> <script> var width = 400, height = 400; var data = [10, 12, 14, 16, 18, 20]; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([d3.min(data), d3.max(data)]) .range([0, width - 60]); var x_axis = d3.axisBottom(xscale); var xAxisTranslate = height / 2; svg.append(\"g\") .attr(\"transform\", \"translate(50, \" + xAxisTranslate + \")\") .call(x_axis) </script></body> </html>", "e": 26603, "s": 25661, "text": null }, { "code": null, "e": 26611, "s": 26603, "text": "Output:" }, { "code": null, "e": 26617, "s": 26611, "text": "D3.js" }, { "code": null, "e": 26628, "s": 26617, "text": "JavaScript" }, { "code": null, "e": 26645, "s": 26628, "text": "Web Technologies" }, { "code": null, "e": 26743, "s": 26645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26788, "s": 26743, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26849, "s": 26788, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26921, "s": 26849, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26967, "s": 26921, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27007, "s": 26967, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27049, "s": 27007, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27111, "s": 27049, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27154, "s": 27111, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27187, "s": 27154, "text": "Installation of Node.js on Linux" } ]
How to delete a column from a table in MySQL?
We can delete a column from a table with the help of ALTER command. Let’s say we have create a table and have a requirement to deleted some columns in it. We can achieve this using the ALTER and DRO[ command. Let us see an example. First, we will create a table. mysql> create table DeleteColumnNameDemo -> ( -> Id int, -> Name varchar(200), -> Age int, -> Address varchar(200) -> ); Query OK, 0 rows affected (0.59 sec) Above, we have created a table with four columns. Here is the query through which we can see all the details about the table. mysql> desc DeleteColumnNameDemo; The following is the output. +---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Id | int(11) | YES | | NULL | | | Name | varchar(200) | YES | | NULL | | | Age | int(11) | YES | | NULL | | | Address | varchar(200) | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ 4 rows in set (0.00 sec) Now we have 4 columns in our table. Now let us see the syntax to delete a column. The syntax is as follows. alter table yourTableName drop column yourColumnName1, drop column yourColumnName2, . . . drop column yourColumnNameN, Now, let us delete the column “Age” and “Address” from “DeleteColumnNameDemo” table. Apply the above syntax to delete the columns. The query is as follows. mysql> ALTER table DeleteColumnNameDemo -> drop column Age, -> drop column Address; Query OK, 0 rows affected (3.11 sec) Records: 0 Duplicates: 0 Warnings: 0 We have deleted both the columns, Age and Address from the table. Let us now check the columns have been deleted or not with the help of DESC command. mysql> desc DeleteColumnNameDemo; The following is the output. We cannot see the two columns “Age’ and “Address” because we have deleted the before. +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Id | int(11) | YES | | NULL | | | Name | varchar(200) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ 2 rows in set (0.05 sec)
[ { "code": null, "e": 1271, "s": 1062, "text": "We can delete a column from a table with the help of ALTER command. Let’s say we have create a table and have a requirement to deleted some columns in it. We can achieve this using the ALTER and DRO[ command." }, { "code": null, "e": 1325, "s": 1271, "text": "Let us see an example. First, we will create a table." }, { "code": null, "e": 1501, "s": 1325, "text": "mysql> create table DeleteColumnNameDemo\n -> (\n -> Id int,\n -> Name varchar(200),\n -> Age int,\n -> Address varchar(200)\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1627, "s": 1501, "text": "Above, we have created a table with four columns. Here is the query through which we can see all the details about the table." }, { "code": null, "e": 1661, "s": 1627, "text": "mysql> desc DeleteColumnNameDemo;" }, { "code": null, "e": 1690, "s": 1661, "text": "The following is the output." }, { "code": null, "e": 2180, "s": 1690, "text": "+---------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+--------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| Name | varchar(200) | YES | | NULL | |\n| Age | int(11) | YES | | NULL | |\n| Address | varchar(200) | YES | | NULL | |\n+---------+--------------+------+-----+---------+-------+\n4 rows in set (0.00 sec)\n" }, { "code": null, "e": 2288, "s": 2180, "text": "Now we have 4 columns in our table. Now let us see the syntax to delete a column. The syntax is as follows." }, { "code": null, "e": 2407, "s": 2288, "text": "alter table yourTableName\ndrop column yourColumnName1,\ndrop column yourColumnName2,\n.\n.\n.\ndrop column yourColumnNameN," }, { "code": null, "e": 2563, "s": 2407, "text": "Now, let us delete the column “Age” and “Address” from “DeleteColumnNameDemo” table. Apply the above syntax to delete the columns. The query is as follows." }, { "code": null, "e": 2729, "s": 2563, "text": "mysql> ALTER table DeleteColumnNameDemo\n -> drop column Age,\n -> drop column Address;\nQuery OK, 0 rows affected (3.11 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2880, "s": 2729, "text": "We have deleted both the columns, Age and Address from the table. Let us now check the columns have been deleted or not with the help of DESC command." }, { "code": null, "e": 2914, "s": 2880, "text": "mysql> desc DeleteColumnNameDemo;" }, { "code": null, "e": 3029, "s": 2914, "text": "The following is the output. We cannot see the two columns “Age’ and “Address” because we have deleted the before." }, { "code": null, "e": 3391, "s": 3029, "text": "+-------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| Name | varchar(200) | YES | | NULL | |\n+-------+--------------+------+-----+---------+-------+\n2 rows in set (0.05 sec)\n" } ]
Heap Sort in C#
Heap Sort is a sorting algorithm that makes use of the heap data structure. Each time the root element of the heap i.e. the largest element is removed and stored in an array. It is replaced by the rightmost leaf element and then the heap is reestablished. This is done until there are no more elements left in the heap and the array is sorted. A program that demonstrates heap sort in C# is given as follows. Live Demo using System; namespace HeapSortDemo { public class example { static void heapSort(int[] arr, int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n-1; i>=0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } } static void heapify(int[] arr, int n, int i) { int largest = i; int left = 2*i + 1; int right = 2*i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } public static void Main() { int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100}; int n = 10, i; Console.WriteLine("Heap Sort"); Console.Write("Initial array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } heapSort(arr, 10); Console.Write("\nSorted Array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } } } } The output of the above program is as follows. Heap Sort Initial array is: 55 25 89 34 12 19 78 95 1 100 Sorted Array is: 1 12 19 25 34 55 78 89 95 100 Now, let us understand the above program. The function main() contains the array arr. It prints the initial array and then calls the function heapSort() that will sort the array. This can be seen in the following code snippet. int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100}; int n = 10, i; Console.WriteLine("Heap Sort"); Console.Write("Initial array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } heapSort(arr, 10); The function heapSort() first converts the given elements into a heap. This is done by using the for loop and calling the function heapify() for all the non-leaf elements of the heap. This can be seen in the following code snippet. for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); After the heap is created, a for loop is used to remove the root element of the heap i.e. the largest element. It is replaced by the rightmost leaf element and then heapify() is called again to reestablish the heap. This can be seen in the following code snippet. for (int i = n-1; i>=0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } The function heapify() creates a heap structure by arranging the elements as required. This process starts from the element at index i for this is considered the root element for the heapify() function. This can be seen in the following code snippet. int largest = i; int left = 2*i + 1; int right = 2*i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } Finally, the sorted array is displayed in the main() function. This can be seen in the following code snippet. Console.Write("\nSorted Array is: "); for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); }
[ { "code": null, "e": 1406, "s": 1062, "text": "Heap Sort is a sorting algorithm that makes use of the heap data structure. Each time the root element of the heap i.e. the largest element is removed and stored in an array. It is replaced by the rightmost leaf element and then the heap is reestablished. This is done until there are no more elements left in the heap and the array is sorted." }, { "code": null, "e": 1471, "s": 1406, "text": "A program that demonstrates heap sort in C# is given as follows." }, { "code": null, "e": 1482, "s": 1471, "text": " Live Demo" }, { "code": null, "e": 2797, "s": 1482, "text": "using System;\nnamespace HeapSortDemo {\n public class example {\n static void heapSort(int[] arr, int n) {\n for (int i = n / 2 - 1; i >= 0; i--)\n heapify(arr, n, i);\n for (int i = n-1; i>=0; i--) {\n int temp = arr[0];\n arr[0] = arr[i];\n arr[i] = temp;\n heapify(arr, i, 0);\n }\n }\n static void heapify(int[] arr, int n, int i) {\n int largest = i;\n int left = 2*i + 1;\n int right = 2*i + 2;\n if (left < n && arr[left] > arr[largest])\n largest = left;\n if (right < n && arr[right] > arr[largest])\n largest = right;\n if (largest != i) {\n int swap = arr[i];\n arr[i] = arr[largest];\n arr[largest] = swap;\n heapify(arr, n, largest);\n }\n }\n public static void Main() {\n int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100};\n int n = 10, i;\n Console.WriteLine(\"Heap Sort\");\n Console.Write(\"Initial array is: \");\n for (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n heapSort(arr, 10);\n Console.Write(\"\\nSorted Array is: \");\n for (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 2844, "s": 2797, "text": "The output of the above program is as follows." }, { "code": null, "e": 2949, "s": 2844, "text": "Heap Sort\nInitial array is: 55 25 89 34 12 19 78 95 1 100\nSorted Array is: 1 12 19 25 34 55 78 89 95 100" }, { "code": null, "e": 2991, "s": 2949, "text": "Now, let us understand the above program." }, { "code": null, "e": 3176, "s": 2991, "text": "The function main() contains the array arr. It prints the initial array and then calls the function heapSort() that will sort the array. This can be seen in the following code snippet." }, { "code": null, "e": 3393, "s": 3176, "text": "int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100};\nint n = 10, i;\nConsole.WriteLine(\"Heap Sort\");\nConsole.Write(\"Initial array is: \");\nfor (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n}\nheapSort(arr, 10);" }, { "code": null, "e": 3625, "s": 3393, "text": "The function heapSort() first converts the given elements into a heap. This is done by using the for loop and calling the function heapify() for all the non-leaf elements of the heap. This can be seen in the following code snippet." }, { "code": null, "e": 3682, "s": 3625, "text": "for (int i = n / 2 - 1; i >= 0; i--)\nheapify(arr, n, i);" }, { "code": null, "e": 3946, "s": 3682, "text": "After the heap is created, a for loop is used to remove the root element of the heap i.e. the largest element. It is replaced by the rightmost leaf element and then heapify() is called again to reestablish the heap. This can be seen in the following code snippet." }, { "code": null, "e": 4062, "s": 3946, "text": "for (int i = n-1; i>=0; i--) {\n int temp = arr[0];\n arr[0] = arr[i];\n arr[i] = temp;\n heapify(arr, i, 0);\n}" }, { "code": null, "e": 4313, "s": 4062, "text": "The function heapify() creates a heap structure by arranging the elements as required. This process starts from the element at index i for this is considered the root element for the heapify() function. This can be seen in the following code snippet." }, { "code": null, "e": 4613, "s": 4313, "text": "int largest = i;\nint left = 2*i + 1;\nint right = 2*i + 2;\nif (left < n && arr[left] > arr[largest])\nlargest = left;\nif (right < n && arr[right] > arr[largest])\nlargest = right;\nif (largest != i) {\n int swap = arr[i];\n arr[i] = arr[largest];\n arr[largest] = swap;\n heapify(arr, n, largest);\n}" }, { "code": null, "e": 4724, "s": 4613, "text": "Finally, the sorted array is displayed in the main() function. This can be seen in the following code snippet." }, { "code": null, "e": 4822, "s": 4724, "text": "Console.Write(\"\\nSorted Array is: \");\nfor (i = 0; i < n; i++) {\n Console.Write(arr[i] + \" \");\n}" } ]
How to Create Interactive Plots with Altair | by Khuyen Tran | Towards Data Science
Have you ever wanted to take a closer look at your data by zooming in, highlight points of interest, or see how the data change over time with a slider bar? By having more control over your static graph, you figure you might get much more insights into the data. But you imagine it must be challenging to create an interactive plot. So you decide not to bother with the interactive part. What if there is a python library that enables you to do exactly that with several lines of Python codes? The graph above is created with Altair. Altair is a statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar for quickly building a wide range of statistical graphics. You just need to declare links between data fields, color, size, etc, while letting the rest of the plot details handled automatically. With Altair, you can spend more time understanding your data and its meaning than figuring out the codes. Install Altair $ pip install altair Altair can be installed along with the example datasets in vega_datasets: $ pip install altair vega_datasets Import Altair on your Jupyter Notebook import altair as altimport pandas as pd Some datasets in Altair are built around Pandas DataFrame. What does this mean? It means that you can manipulate data in Altair just like how you deal with Pandas DataFrame. We will use gapminder data in vega_data to visualize global health and population data for some countries over the time period of 1995 to 2005. from vega_datasets import data as vega_datagap = pd.read_json(vega_data.gapminder.url)gap.head(10) Find out how many unique years are in this data: >>> gap.year.unique()array([1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005]) Since we are mostly interested in the latest data, let’s take a look at data in 2005. gap2005 = gap.loc[gap['year'] == 2005] We are curious about the correlation between fertility and life expectancy. So we specify the kind of plot we want to make with mark_point() to show data as points. We can also present the data with other geometric shapes using mark_* alt.Chart(gap2005).mark_point().encode( alt.X('fertility'), alt.Y('life_expect')) Look like the data is not in the center of the graph. Normally we would need to specify the scale with matplotlib but with Altair, you just need to use scale method Nice! But what if we want to see how the population size is related to fertility and life expectancy? We could utilize another dimension: Size Awesome. The legend on the left-hand side gives us the meaning of each circle’s size. Can we add another dimension? Absolutely! x-axis, y-axis, size, what are we missing? Color! As you can see above, we could also specify the type of data: N-Nominal (categories name), Q-Quantitative (numerical data), O-Ordinal (ordered data), or T-Temporal (time points or intervals). In the code above, since I want to cluster to be interpreted as categories data, I use :N To make our circles look nicer, we fill the point with color using filled=True. Add some opacity to see the smaller points behind the big points using alt.OpacityValue(0.5) But there are many points in the graph. Is there a way that when we click on each point to show the information about the country, fertility and life expectancy? Yes of course. That can be done with adding Tooltip Being able to see the information on each point is nice. But what if we want to see the information about multiple points at once? Without further waiting, let’s jump on how to create an interactive plot with Altair! Selection_single() enables us to click one point to highlight it. As we click on the point, we want other points to become non-relevant with gray color. This could be done with alt.condition() Now we can look at the information of the point of interest without being distracted by other points But we might be interested in several points at once. Or better, to select an interval of points. Both could be done with selection_multi() and selection_interval() Since we want to try out with different selection tools at once, let’s create a function to do it. Now use alt.hconcat() to try out with different selections and concatenate the graphs of those selections We have been seeing the data for the year 2005. What if we want to see the change of data over time? That could be easily done by adding some more conditions for alt.selection_single such as name=’select’, fields = [‘year’], the initial year init={‘year’: 1955} and range bind=alt.binding_range(min=1955, max=2005, step=5) Nice! Now we can easily see the change of the data over time by dragging the mouse on the select-year bar What is the last function that we want from our graph after creating it? Save our graph to show our websites or social media! And this can be easily done by clicking on the button in the left corner of the graph. Congratulations! You have learned how to utilize Altair for efficient data analysis. This article does not exhaustively cover everything you can do with Altair such as creating a stacked bar chart, heatmap, area chart, map or other interactive functions. You can find out more about Altair Libary here or follow the Github tutorial. What I hope you to get out the most of this article is that: creating an interesting and beautiful graph with Python can be incredibly easy and fun! Feel free to fork and play with the code for this article in this Github repo. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Heer, Jeffrey. Github: https://github.com/uwdata/visualization-curriculum. Jan 2017.
[ { "code": null, "e": 435, "s": 172, "text": "Have you ever wanted to take a closer look at your data by zooming in, highlight points of interest, or see how the data change over time with a slider bar? By having more control over your static graph, you figure you might get much more insights into the data." }, { "code": null, "e": 666, "s": 435, "text": "But you imagine it must be challenging to create an interactive plot. So you decide not to bother with the interactive part. What if there is a python library that enables you to do exactly that with several lines of Python codes?" }, { "code": null, "e": 1153, "s": 666, "text": "The graph above is created with Altair. Altair is a statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar for quickly building a wide range of statistical graphics. You just need to declare links between data fields, color, size, etc, while letting the rest of the plot details handled automatically. With Altair, you can spend more time understanding your data and its meaning than figuring out the codes." }, { "code": null, "e": 1168, "s": 1153, "text": "Install Altair" }, { "code": null, "e": 1189, "s": 1168, "text": "$ pip install altair" }, { "code": null, "e": 1263, "s": 1189, "text": "Altair can be installed along with the example datasets in vega_datasets:" }, { "code": null, "e": 1298, "s": 1263, "text": "$ pip install altair vega_datasets" }, { "code": null, "e": 1337, "s": 1298, "text": "Import Altair on your Jupyter Notebook" }, { "code": null, "e": 1377, "s": 1337, "text": "import altair as altimport pandas as pd" }, { "code": null, "e": 1551, "s": 1377, "text": "Some datasets in Altair are built around Pandas DataFrame. What does this mean? It means that you can manipulate data in Altair just like how you deal with Pandas DataFrame." }, { "code": null, "e": 1695, "s": 1551, "text": "We will use gapminder data in vega_data to visualize global health and population data for some countries over the time period of 1995 to 2005." }, { "code": null, "e": 1794, "s": 1695, "text": "from vega_datasets import data as vega_datagap = pd.read_json(vega_data.gapminder.url)gap.head(10)" }, { "code": null, "e": 1843, "s": 1794, "text": "Find out how many unique years are in this data:" }, { "code": null, "e": 1938, "s": 1843, "text": ">>> gap.year.unique()array([1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005])" }, { "code": null, "e": 2024, "s": 1938, "text": "Since we are mostly interested in the latest data, let’s take a look at data in 2005." }, { "code": null, "e": 2063, "s": 2024, "text": "gap2005 = gap.loc[gap['year'] == 2005]" }, { "code": null, "e": 2298, "s": 2063, "text": "We are curious about the correlation between fertility and life expectancy. So we specify the kind of plot we want to make with mark_point() to show data as points. We can also present the data with other geometric shapes using mark_*" }, { "code": null, "e": 2386, "s": 2298, "text": "alt.Chart(gap2005).mark_point().encode( alt.X('fertility'), alt.Y('life_expect'))" }, { "code": null, "e": 2551, "s": 2386, "text": "Look like the data is not in the center of the graph. Normally we would need to specify the scale with matplotlib but with Altair, you just need to use scale method" }, { "code": null, "e": 2694, "s": 2551, "text": "Nice! But what if we want to see how the population size is related to fertility and life expectancy? We could utilize another dimension: Size" }, { "code": null, "e": 2872, "s": 2694, "text": "Awesome. The legend on the left-hand side gives us the meaning of each circle’s size. Can we add another dimension? Absolutely! x-axis, y-axis, size, what are we missing? Color!" }, { "code": null, "e": 3154, "s": 2872, "text": "As you can see above, we could also specify the type of data: N-Nominal (categories name), Q-Quantitative (numerical data), O-Ordinal (ordered data), or T-Temporal (time points or intervals). In the code above, since I want to cluster to be interpreted as categories data, I use :N" }, { "code": null, "e": 3327, "s": 3154, "text": "To make our circles look nicer, we fill the point with color using filled=True. Add some opacity to see the smaller points behind the big points using alt.OpacityValue(0.5)" }, { "code": null, "e": 3541, "s": 3327, "text": "But there are many points in the graph. Is there a way that when we click on each point to show the information about the country, fertility and life expectancy? Yes of course. That can be done with adding Tooltip" }, { "code": null, "e": 3758, "s": 3541, "text": "Being able to see the information on each point is nice. But what if we want to see the information about multiple points at once? Without further waiting, let’s jump on how to create an interactive plot with Altair!" }, { "code": null, "e": 3951, "s": 3758, "text": "Selection_single() enables us to click one point to highlight it. As we click on the point, we want other points to become non-relevant with gray color. This could be done with alt.condition()" }, { "code": null, "e": 4052, "s": 3951, "text": "Now we can look at the information of the point of interest without being distracted by other points" }, { "code": null, "e": 4217, "s": 4052, "text": "But we might be interested in several points at once. Or better, to select an interval of points. Both could be done with selection_multi() and selection_interval()" }, { "code": null, "e": 4316, "s": 4217, "text": "Since we want to try out with different selection tools at once, let’s create a function to do it." }, { "code": null, "e": 4422, "s": 4316, "text": "Now use alt.hconcat() to try out with different selections and concatenate the graphs of those selections" }, { "code": null, "e": 4745, "s": 4422, "text": "We have been seeing the data for the year 2005. What if we want to see the change of data over time? That could be easily done by adding some more conditions for alt.selection_single such as name=’select’, fields = [‘year’], the initial year init={‘year’: 1955} and range bind=alt.binding_range(min=1955, max=2005, step=5)" }, { "code": null, "e": 4851, "s": 4745, "text": "Nice! Now we can easily see the change of the data over time by dragging the mouse on the select-year bar" }, { "code": null, "e": 5064, "s": 4851, "text": "What is the last function that we want from our graph after creating it? Save our graph to show our websites or social media! And this can be easily done by clicking on the button in the left corner of the graph." }, { "code": null, "e": 5546, "s": 5064, "text": "Congratulations! You have learned how to utilize Altair for efficient data analysis. This article does not exhaustively cover everything you can do with Altair such as creating a stacked bar chart, heatmap, area chart, map or other interactive functions. You can find out more about Altair Libary here or follow the Github tutorial. What I hope you to get out the most of this article is that: creating an interesting and beautiful graph with Python can be incredibly easy and fun!" }, { "code": null, "e": 5625, "s": 5546, "text": "Feel free to fork and play with the code for this article in this Github repo." }, { "code": null, "e": 5785, "s": 5625, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." }, { "code": null, "e": 5961, "s": 5785, "text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:" }, { "code": null, "e": 5984, "s": 5961, "text": "towardsdatascience.com" }, { "code": null, "e": 6007, "s": 5984, "text": "towardsdatascience.com" }, { "code": null, "e": 6030, "s": 6007, "text": "towardsdatascience.com" }, { "code": null, "e": 6053, "s": 6030, "text": "towardsdatascience.com" }, { "code": null, "e": 6076, "s": 6053, "text": "towardsdatascience.com" } ]
An example of predicting ratings with SVD in a collaborative filtering recommendation system | by Xue Wang | Towards Data Science
We know that there are cons with SVD to make a prediction in reality, for example, it can’t predict if there is even a NaN in the dataset, but as this is the starting point of collaborative filtering and I want to reproduce the procedure with SVD to see how it works, with some compromisation of the dataset. This story will focus on code realization with SVD, have no offline testing (no splitting of train test dataset), and include some basic linear algebra-related terminologies. Linear algebra basic SVD is singular value decomposition. Detail explanation can be found in Wiki. Here, I prefer this explanation for the recommendation system (RS): it is a k-rank approximation to the original SVD. Latent features: corresponding, the sigma in SVD. Values that are not directly observable in data but maybe recognized when looking at relationships and trends that exist between observed data values[2]. The number of the latest features is the rank of sigma in SVD. Euclidean Distance: Euclidean distance can just be considered as a straight-line distance between two vectors. For two vectors x and y, we can compute this as[2]: The hard point I want to emphasize(at least from my learning experience) is how to convert original SVD into k dimension spaces once we know the U, sigma, and Vt, and how to link them with prediction. Example is always efficient way to learn. Code Example Compromise of dataset The target of RS in collaborative filtering, here user-item based, is to predict the ratings and make the recommendation if the user hasn’t made the rating. But SVD can’t predict if there is a NaN value in the matrix, and the user has to exist in the currently known rates system and gives rates. I think there is a contradiction, but maybe I am wrong here (if you find the reason, will be appreciated to point it out). To create the dataset, the compromise here: if the user hasn’t given a rating to a movie, then fill it with 0 (there will have a conflict if 0 is in the ratings ). Please don’t recommend Funk SVD here. As I want to learn the pro and cons of the SVD process in this story. Let’s get started. The referenced code is here (In Chinese)[1]. I made some changes to it. The code consists of the below steps: Create datasetCalculate the similarityDecide kConvert the original SVD to k dimensionsMake recommendation for a specific user through the predicted rating (which are zero in original rating) Create dataset Calculate the similarity Decide k Convert the original SVD to k dimensions Make recommendation for a specific user through the predicted rating (which are zero in original rating) Import library: Create dataset: Calculate the similarity Use Euclidean Distance to measure similarity: Decide k: The value of k is determined by the percentage of the sum of squares of the first k singular values to the sum of squares of the total singular values. For example, if the percentage is 0.9, then when the square sum of the previous k single values to the total square sum of the sigma is greater than 0.9, we have accounted for more than 90% weight and can reduce the matrix to k dimensions. Convert the original SVD to k dimensions spaces: How converting the original SVD to k dimensions, below is the key: The dimension of original decomposition is: u:11x11,sigma: diagonal matrix 11, vt: 11x11 The result is k=3, then the dimension is: u:11x3, sigma: diagonal matrix 3, vt: 3x11 Below code can construct the k dimension matrix: formed_items=np.around(np.dot(np.dot(u[:,:k], sigma_K),vt[:k, :]),decimals=3) Predicted ratings: Run the below command to get the result: testdata=loadExData()recommend(testdata,0,sim_meas=ecludSim,est_method=svdEst, percentage=0.9) Using testdata, with Euclidean Distance, if the percentage of the sum of squares of the first k singular values to the sum of squares of the total singular values is greater or equal than 0.9, predict the ratings for a non-rated movie for the user 0. The predicted ratings for user 0: For user 1: The first column shows the column index and the second column is the predicted ratings. In original data for user 0, the position 0,1,2,3,4,6,7,8,9 are zero as below: [0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5] To make it easy, the complete code is as below, and you can run it with the last two commends above: In today’s story, I introduce an example that shows how to convert the SVD to k dimensions spaces to predict ratings after getting SVD, especially focus how to convert SVD to k-dimension spaces and make predicted ratings. Thanks for your reading. References: https://blog.csdn.net/weixin_41988628/article/details/83217255 (In Chinese)Udacity Data Scientist Nanodegree — Experimental Design & Recommendationshttps://stats.stackexchange.com/questions/33142/what-happens-when-you-apply-svd-to-a-collaborative-filtering-problem-what-is-th/35460#35460https://en.wikipedia.org/wiki/Singular_value_decomposition https://blog.csdn.net/weixin_41988628/article/details/83217255 (In Chinese) Udacity Data Scientist Nanodegree — Experimental Design & Recommendations
[ { "code": null, "e": 481, "s": 172, "text": "We know that there are cons with SVD to make a prediction in reality, for example, it can’t predict if there is even a NaN in the dataset, but as this is the starting point of collaborative filtering and I want to reproduce the procedure with SVD to see how it works, with some compromisation of the dataset." }, { "code": null, "e": 656, "s": 481, "text": "This story will focus on code realization with SVD, have no offline testing (no splitting of train test dataset), and include some basic linear algebra-related terminologies." }, { "code": null, "e": 677, "s": 656, "text": "Linear algebra basic" }, { "code": null, "e": 873, "s": 677, "text": "SVD is singular value decomposition. Detail explanation can be found in Wiki. Here, I prefer this explanation for the recommendation system (RS): it is a k-rank approximation to the original SVD." }, { "code": null, "e": 1140, "s": 873, "text": "Latent features: corresponding, the sigma in SVD. Values that are not directly observable in data but maybe recognized when looking at relationships and trends that exist between observed data values[2]. The number of the latest features is the rank of sigma in SVD." }, { "code": null, "e": 1160, "s": 1140, "text": "Euclidean Distance:" }, { "code": null, "e": 1303, "s": 1160, "text": "Euclidean distance can just be considered as a straight-line distance between two vectors. For two vectors x and y, we can compute this as[2]:" }, { "code": null, "e": 1546, "s": 1303, "text": "The hard point I want to emphasize(at least from my learning experience) is how to convert original SVD into k dimension spaces once we know the U, sigma, and Vt, and how to link them with prediction. Example is always efficient way to learn." }, { "code": null, "e": 1559, "s": 1546, "text": "Code Example" }, { "code": null, "e": 1581, "s": 1559, "text": "Compromise of dataset" }, { "code": null, "e": 1738, "s": 1581, "text": "The target of RS in collaborative filtering, here user-item based, is to predict the ratings and make the recommendation if the user hasn’t made the rating." }, { "code": null, "e": 1878, "s": 1738, "text": "But SVD can’t predict if there is a NaN value in the matrix, and the user has to exist in the currently known rates system and gives rates." }, { "code": null, "e": 2001, "s": 1878, "text": "I think there is a contradiction, but maybe I am wrong here (if you find the reason, will be appreciated to point it out)." }, { "code": null, "e": 2165, "s": 2001, "text": "To create the dataset, the compromise here: if the user hasn’t given a rating to a movie, then fill it with 0 (there will have a conflict if 0 is in the ratings )." }, { "code": null, "e": 2273, "s": 2165, "text": "Please don’t recommend Funk SVD here. As I want to learn the pro and cons of the SVD process in this story." }, { "code": null, "e": 2364, "s": 2273, "text": "Let’s get started. The referenced code is here (In Chinese)[1]. I made some changes to it." }, { "code": null, "e": 2402, "s": 2364, "text": "The code consists of the below steps:" }, { "code": null, "e": 2593, "s": 2402, "text": "Create datasetCalculate the similarityDecide kConvert the original SVD to k dimensionsMake recommendation for a specific user through the predicted rating (which are zero in original rating)" }, { "code": null, "e": 2608, "s": 2593, "text": "Create dataset" }, { "code": null, "e": 2633, "s": 2608, "text": "Calculate the similarity" }, { "code": null, "e": 2642, "s": 2633, "text": "Decide k" }, { "code": null, "e": 2683, "s": 2642, "text": "Convert the original SVD to k dimensions" }, { "code": null, "e": 2788, "s": 2683, "text": "Make recommendation for a specific user through the predicted rating (which are zero in original rating)" }, { "code": null, "e": 2804, "s": 2788, "text": "Import library:" }, { "code": null, "e": 2820, "s": 2804, "text": "Create dataset:" }, { "code": null, "e": 2845, "s": 2820, "text": "Calculate the similarity" }, { "code": null, "e": 2891, "s": 2845, "text": "Use Euclidean Distance to measure similarity:" }, { "code": null, "e": 3053, "s": 2891, "text": "Decide k: The value of k is determined by the percentage of the sum of squares of the first k singular values to the sum of squares of the total singular values." }, { "code": null, "e": 3293, "s": 3053, "text": "For example, if the percentage is 0.9, then when the square sum of the previous k single values to the total square sum of the sigma is greater than 0.9, we have accounted for more than 90% weight and can reduce the matrix to k dimensions." }, { "code": null, "e": 3342, "s": 3293, "text": "Convert the original SVD to k dimensions spaces:" }, { "code": null, "e": 3409, "s": 3342, "text": "How converting the original SVD to k dimensions, below is the key:" }, { "code": null, "e": 3453, "s": 3409, "text": "The dimension of original decomposition is:" }, { "code": null, "e": 3498, "s": 3453, "text": "u:11x11,sigma: diagonal matrix 11, vt: 11x11" }, { "code": null, "e": 3540, "s": 3498, "text": "The result is k=3, then the dimension is:" }, { "code": null, "e": 3583, "s": 3540, "text": "u:11x3, sigma: diagonal matrix 3, vt: 3x11" }, { "code": null, "e": 3632, "s": 3583, "text": "Below code can construct the k dimension matrix:" }, { "code": null, "e": 3710, "s": 3632, "text": "formed_items=np.around(np.dot(np.dot(u[:,:k], sigma_K),vt[:k, :]),decimals=3)" }, { "code": null, "e": 3729, "s": 3710, "text": "Predicted ratings:" }, { "code": null, "e": 3770, "s": 3729, "text": "Run the below command to get the result:" }, { "code": null, "e": 3865, "s": 3770, "text": "testdata=loadExData()recommend(testdata,0,sim_meas=ecludSim,est_method=svdEst, percentage=0.9)" }, { "code": null, "e": 4116, "s": 3865, "text": "Using testdata, with Euclidean Distance, if the percentage of the sum of squares of the first k singular values to the sum of squares of the total singular values is greater or equal than 0.9, predict the ratings for a non-rated movie for the user 0." }, { "code": null, "e": 4150, "s": 4116, "text": "The predicted ratings for user 0:" }, { "code": null, "e": 4162, "s": 4150, "text": "For user 1:" }, { "code": null, "e": 4250, "s": 4162, "text": "The first column shows the column index and the second column is the predicted ratings." }, { "code": null, "e": 4329, "s": 4250, "text": "In original data for user 0, the position 0,1,2,3,4,6,7,8,9 are zero as below:" }, { "code": null, "e": 4363, "s": 4329, "text": "[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5]" }, { "code": null, "e": 4464, "s": 4363, "text": "To make it easy, the complete code is as below, and you can run it with the last two commends above:" }, { "code": null, "e": 4686, "s": 4464, "text": "In today’s story, I introduce an example that shows how to convert the SVD to k dimensions spaces to predict ratings after getting SVD, especially focus how to convert SVD to k-dimension spaces and make predicted ratings." }, { "code": null, "e": 4711, "s": 4686, "text": "Thanks for your reading." }, { "code": null, "e": 4723, "s": 4711, "text": "References:" }, { "code": null, "e": 5069, "s": 4723, "text": "https://blog.csdn.net/weixin_41988628/article/details/83217255 (In Chinese)Udacity Data Scientist Nanodegree — Experimental Design & Recommendationshttps://stats.stackexchange.com/questions/33142/what-happens-when-you-apply-svd-to-a-collaborative-filtering-problem-what-is-th/35460#35460https://en.wikipedia.org/wiki/Singular_value_decomposition" }, { "code": null, "e": 5145, "s": 5069, "text": "https://blog.csdn.net/weixin_41988628/article/details/83217255 (In Chinese)" } ]
NDArray — — a Java based N-Dim array toolkit | by Qing Lan | Towards Data Science
Within many development languages, there is a popular paradigm of using N-Dimensional arrays. They allow you to write numerical code that would otherwise require many levels of nested loops in only a few simple operations. Because of the ability to parallelize, it often runs even faster than the standard looping as well. This is now standard practice in many fields such as data science, graphics, and deep learning, but can be used in applications far beyond this. In Python, the standard library for NDArrays is called NumPy. However, there is no equivalent standard library in Java. One offering for Java developers interested in working with NDArrays is AWS’s Deep Java Library (DJL). Although it also contains Deep Learning, the core is a powerful NDArray system that can be used on its own to bring this paradigm into Java. With support for several Deep Learning Frameworks (PyTorch, TensorFlow, MXNet), DJL can allow the NDArray operations to run at a large-scale and across multiple platforms. No matter whether you are running on CPU or GPU, PC or Android, it simply works. In this tutorial, we will walk through how you can leverage the NDArray from DJL to write your NumPy code in Java and apply NDArray into a real-world application. You can use the following configuration in a gradle project. Or, you can skip the setup and try it directly in our interactive online console. plugins { id 'java'}repositories { jcenter()}dependencies { implementation "ai.djl:api:0.6.0" // PyTorch runtimeOnly "ai.djl.pytorch:pytorch-engine:0.6.0" runtimeOnly "ai.djl.pytorch:pytorch-native-auto:1.5.0"} That’s it, now we can start our implementation. Let’s first create a try block to create a scope for our code (If you are using the interactive console, you can skip this step): try(NDManager manager = NDManager.newBaseManager()) {} NDManager helps manage the memory usage of the NDArrays. It creates them and helps clear them as well. Once you finish using an NDManager, it will clear all of the NDArrays that were created within it’s scope as well. NDManager helps the overall system utilize memory efficiently by tracking the NDArray usage. For comparison, let’s see how the code looks in Python’s NumPy as well. We will start by importing the NumPy library with the standard alias. import NumPy as np In the following sections, we are going to compare the implementation and result between NumPy and DJL’s NDArray. ones is an operation to generate N-dim array filled with 1. NumPy nd = np.ones((2, 3))```[[1. 1. 1.] [1. 1. 1.]]``` NDArray NDArray nd = manager.ones(new Shape(2, 3));/*ND: (2, 3) cpu() float32[[1., 1., 1.], [1., 1., 1.],]*/ You can also try out random generation. For example, we will generate random uniform data from 0 to 1. NumPy nd = np.random.uniform(0, 1, (1, 1, 4))# [[[0.7034806 0.85115891 0.63903668 0.39386125]]] NDArray NDArray nd = manager.randomUniform(0, 1, new Shape(1, 1, 4));/*ND: (1, 1, 4) cpu() float32[[[0.932 , 0.7686, 0.2031, 0.7468], ],]*/ This is just a quick demo of some commonly used functions. The NDManager now offers more than 20 NDArray creation methods that cover most of the methods available in NumPy. We can also try some math operations using NDArrays. Assume we are trying to do a transpose and add a number to each element of the NDArray. We can achieve this by doing the following: NumPy nd = np.arange(1, 10).reshape(3, 3)nd = nd.transpose()nd = nd + 10```[[11 14 17] [12 15 18] [13 16 19]]``` NDArray NDArray nd = manager.arange(1, 10).reshape(3, 3);nd = nd.transpose();nd = nd.add(10);/*ND: (3, 3) cpu() int32[[11, 14, 17], [12, 15, 18], [13, 16, 19],]*/ DJL now supports more than 60 different NumPy math methods covering most of the basic and advanced math functions. One of the most powerful features of NDArray is its flexible data indexing inspired by a similar feature in NumPy. Let’s assume we would like to filter all values in a matrix that are smaller than 10. NumPy nd = np.arange(5, 14)nd = nd[nd >= 10]# [10 11 12 13] NDArray: NDArray nd = manager.arange(5, 14);nd = nd.get(nd.gte(10));/*ND: (4) cpu() int32[10, 11, 12, 13]*/ Now let’s try to do something more complicated. Assume we have 3x3 matrix and we would like to multiply the second column by 2. NumPy nd = np.arange(1, 10).reshape(3, 3)nd[:, 1] *= 2```[[ 1 4 3] [ 4 10 6] [ 7 16 9]]``` NDArray NDArray nd = manager.arange(1, 10).reshape(3, 3);nd.set(new NDIndex(":, 1"), array -> array.mul(2));/*ND: (3, 3) cpu() int32[[ 1, 4, 3], [ 4, 10, 6], [ 7, 16, 9],]*/ In the above example, we introduce a concept in Java called NDIndex. It mirrors most of the NDArray get/set functionalities that NumPy supports. By simply passing a String representation, developers can do all kinds of array manipulations seamlessly in Java. These operations are really helpful when we need to manipulate a huge dataset. Let’s walk through a specific use case: Token Classification. In this case, developers were trying to do Sentiment Analysis on the text information they gathered from the users through applying a Deep Learning algorithm to it. NDArray operations were applied in the preprocessing and post-processing to encode and decode information. Before we feed the data into an NDArray, we tokenize the input text into numbers. The tokenizer in the code block below is a Map<String, Integer> that serves as a vocabulary to convert text into a corresponding vector. String text = "The rabbit cross the street and kick the fox";String[] tokens = text.toLowerCase().split(" ");int[] vector = new int[tokens.length];/*String[9] { "the", "rabbit", "cross", "the", "street","and", "kick", "the", "fox" }*/for (int i = 0; i < tokens.length; i++) { vector[i] = tokenizer.get(tokens[i]);}vector/*int[9] { 1, 6, 5, 1, 3, 2, 8, 1, 12 }*/ After that, we create an NDArray. To proceed further, we need to create a batch of tokens and apply some transformations to them. NDArray array = manager.create(vector);array = array.reshape(new Shape(vector.length, 1)); // form a batcharray = array.div(10.0);/*ND: (9, 1) cpu() float64[[0.1], [0.6], [0.5], [0.1], [0.3], [0.2], [0.8], [0.1], [1.2],]*/ Then, we can send this data to a deep learning model. To achieve the same thing in pure Java would require far more work. If we are trying to implement the reshape function above, we need to create an N-dimensional array in Java that looks like: List<List<List<...List<Float>...>>> to cover all the different dimensions. We would then have to dynamically insert a new List<Float> containing the elements to build resulting data structure. With the previous walkthrough, you should have a basic experience using NDArray in Java. To summarize, here is the three key advantages using it: Easy: Access to 60+ operators in Java with a simple input and the same output. Fast: Full support for the most used deep learning frameworks including TensorFlow, PyTorch, and MXNet. Now, you can get your computation accelerated by MKLDNN on CPU, CUDA on GPU and lots more. Deep Learning ready: It supports high dimensional arrays and sparse NDArray inputs*. You can apply this toolkit on all platforms including Apache Spark and Apache Beam for large-scale data processing. It’s a perfect tool for data preprocessing and post-processing. *Sparse currently only covers COO in PyTorch and CSR/Row_Sparse in MXNet. After trying NDArray creation and operation, you might wonder how DJL implement NDArray to achieve these behaviors. In this section, we will briefly walkthrough the architecture of NDArray. As shown above, there are three key layers to the NDArray. The Interface layer contains NDArray, it is a Java Interface that defines what the NDArray should look like. We carefully evaluated it and made all functions’ signature general enough and easy to use. In the EngineProvider layer, there are different engine’s implementation to the NDArray. This layer served as an interpretation layer that maps Engine specific behavior to NumPy behavior. As a result, all engines implementation are behaved the same way as NumPy have. In the C++ Layer, we built JNI and JNA that expose C++ methods for Java to call. It would ensure we have enough methods to build the entire NDArray stack. Also it ensures the best performance by calling directly from Java to C++ since all Engines are implemented in C/C++. Deep Java Library (DJL) is a Deep Learning Framework written in Java, supporting both training and inference. DJL is built on top of modern Deep Learning frameworks (TenserFlow, PyTorch, MXNet, etc). You can easily use DJL to train your model or deploy your favorite models from a variety of engines without any additional conversion. It contains a powerful ModelZoo design that allows you to manage trained models and load them in a single line. The built-in ModelZoo currently supports more than 70 pre-trained and ready to use models from GluonCV, HuggingFace, TorchHub and Keras. The addition of the NDArray makes DJL the best toolkit in Java to run your Deep Learning application. It can automatically identify the platform you are running on and figure out whether to leverage GPU to run your application. From the most recent release, DJL 0.6.0 officially supports MXNet 1.7.0, PyTorch 1.5.0 and TensorFlow 2.2.0. We also have experimental support for PyTorch on Android. Follow our GitHub, demo repository, Slack channel and twitter for more documentation and examples of DJL!
[ { "code": null, "e": 1298, "s": 47, "text": "Within many development languages, there is a popular paradigm of using N-Dimensional arrays. They allow you to write numerical code that would otherwise require many levels of nested loops in only a few simple operations. Because of the ability to parallelize, it often runs even faster than the standard looping as well. This is now standard practice in many fields such as data science, graphics, and deep learning, but can be used in applications far beyond this. In Python, the standard library for NDArrays is called NumPy. However, there is no equivalent standard library in Java. One offering for Java developers interested in working with NDArrays is AWS’s Deep Java Library (DJL). Although it also contains Deep Learning, the core is a powerful NDArray system that can be used on its own to bring this paradigm into Java. With support for several Deep Learning Frameworks (PyTorch, TensorFlow, MXNet), DJL can allow the NDArray operations to run at a large-scale and across multiple platforms. No matter whether you are running on CPU or GPU, PC or Android, it simply works. In this tutorial, we will walk through how you can leverage the NDArray from DJL to write your NumPy code in Java and apply NDArray into a real-world application." }, { "code": null, "e": 1441, "s": 1298, "text": "You can use the following configuration in a gradle project. Or, you can skip the setup and try it directly in our interactive online console." }, { "code": null, "e": 1697, "s": 1441, "text": "plugins { id 'java'}repositories { jcenter()}dependencies { implementation \"ai.djl:api:0.6.0\" // PyTorch runtimeOnly \"ai.djl.pytorch:pytorch-engine:0.6.0\" runtimeOnly \"ai.djl.pytorch:pytorch-native-auto:1.5.0\"}" }, { "code": null, "e": 1745, "s": 1697, "text": "That’s it, now we can start our implementation." }, { "code": null, "e": 1875, "s": 1745, "text": "Let’s first create a try block to create a scope for our code (If you are using the interactive console, you can skip this step):" }, { "code": null, "e": 1930, "s": 1875, "text": "try(NDManager manager = NDManager.newBaseManager()) {}" }, { "code": null, "e": 2384, "s": 1930, "text": "NDManager helps manage the memory usage of the NDArrays. It creates them and helps clear them as well. Once you finish using an NDManager, it will clear all of the NDArrays that were created within it’s scope as well. NDManager helps the overall system utilize memory efficiently by tracking the NDArray usage. For comparison, let’s see how the code looks in Python’s NumPy as well. We will start by importing the NumPy library with the standard alias." }, { "code": null, "e": 2403, "s": 2384, "text": "import NumPy as np" }, { "code": null, "e": 2517, "s": 2403, "text": "In the following sections, we are going to compare the implementation and result between NumPy and DJL’s NDArray." }, { "code": null, "e": 2583, "s": 2517, "text": "ones is an operation to generate N-dim array filled with 1. NumPy" }, { "code": null, "e": 2633, "s": 2583, "text": "nd = np.ones((2, 3))```[[1. 1. 1.] [1. 1. 1.]]```" }, { "code": null, "e": 2641, "s": 2633, "text": "NDArray" }, { "code": null, "e": 2742, "s": 2641, "text": "NDArray nd = manager.ones(new Shape(2, 3));/*ND: (2, 3) cpu() float32[[1., 1., 1.], [1., 1., 1.],]*/" }, { "code": null, "e": 2852, "s": 2742, "text": "You can also try out random generation. For example, we will generate random uniform data from 0 to 1. NumPy" }, { "code": null, "e": 2943, "s": 2852, "text": "nd = np.random.uniform(0, 1, (1, 1, 4))# [[[0.7034806 0.85115891 0.63903668 0.39386125]]]" }, { "code": null, "e": 2951, "s": 2943, "text": "NDArray" }, { "code": null, "e": 3083, "s": 2951, "text": "NDArray nd = manager.randomUniform(0, 1, new Shape(1, 1, 4));/*ND: (1, 1, 4) cpu() float32[[[0.932 , 0.7686, 0.2031, 0.7468], ],]*/" }, { "code": null, "e": 3256, "s": 3083, "text": "This is just a quick demo of some commonly used functions. The NDManager now offers more than 20 NDArray creation methods that cover most of the methods available in NumPy." }, { "code": null, "e": 3448, "s": 3256, "text": "We can also try some math operations using NDArrays. Assume we are trying to do a transpose and add a number to each element of the NDArray. We can achieve this by doing the following: NumPy" }, { "code": null, "e": 3555, "s": 3448, "text": "nd = np.arange(1, 10).reshape(3, 3)nd = nd.transpose()nd = nd + 10```[[11 14 17] [12 15 18] [13 16 19]]```" }, { "code": null, "e": 3563, "s": 3555, "text": "NDArray" }, { "code": null, "e": 3718, "s": 3563, "text": "NDArray nd = manager.arange(1, 10).reshape(3, 3);nd = nd.transpose();nd = nd.add(10);/*ND: (3, 3) cpu() int32[[11, 14, 17], [12, 15, 18], [13, 16, 19],]*/" }, { "code": null, "e": 3833, "s": 3718, "text": "DJL now supports more than 60 different NumPy math methods covering most of the basic and advanced math functions." }, { "code": null, "e": 4042, "s": 3833, "text": "One of the most powerful features of NDArray is its flexible data indexing inspired by a similar feature in NumPy. Let’s assume we would like to filter all values in a matrix that are smaller than 10. NumPy" }, { "code": null, "e": 4096, "s": 4042, "text": "nd = np.arange(5, 14)nd = nd[nd >= 10]# [10 11 12 13]" }, { "code": null, "e": 4105, "s": 4096, "text": "NDArray:" }, { "code": null, "e": 4204, "s": 4105, "text": "NDArray nd = manager.arange(5, 14);nd = nd.get(nd.gte(10));/*ND: (4) cpu() int32[10, 11, 12, 13]*/" }, { "code": null, "e": 4339, "s": 4204, "text": "Now let’s try to do something more complicated. Assume we have 3x3 matrix and we would like to multiply the second column by 2. NumPy" }, { "code": null, "e": 4428, "s": 4339, "text": "nd = np.arange(1, 10).reshape(3, 3)nd[:, 1] *= 2```[[ 1 4 3] [ 4 10 6] [ 7 16 9]]```" }, { "code": null, "e": 4436, "s": 4428, "text": "NDArray" }, { "code": null, "e": 4606, "s": 4436, "text": "NDArray nd = manager.arange(1, 10).reshape(3, 3);nd.set(new NDIndex(\":, 1\"), array -> array.mul(2));/*ND: (3, 3) cpu() int32[[ 1, 4, 3], [ 4, 10, 6], [ 7, 16, 9],]*/" }, { "code": null, "e": 4865, "s": 4606, "text": "In the above example, we introduce a concept in Java called NDIndex. It mirrors most of the NDArray get/set functionalities that NumPy supports. By simply passing a String representation, developers can do all kinds of array manipulations seamlessly in Java." }, { "code": null, "e": 5278, "s": 4865, "text": "These operations are really helpful when we need to manipulate a huge dataset. Let’s walk through a specific use case: Token Classification. In this case, developers were trying to do Sentiment Analysis on the text information they gathered from the users through applying a Deep Learning algorithm to it. NDArray operations were applied in the preprocessing and post-processing to encode and decode information." }, { "code": null, "e": 5497, "s": 5278, "text": "Before we feed the data into an NDArray, we tokenize the input text into numbers. The tokenizer in the code block below is a Map<String, Integer> that serves as a vocabulary to convert text into a corresponding vector." }, { "code": null, "e": 5862, "s": 5497, "text": "String text = \"The rabbit cross the street and kick the fox\";String[] tokens = text.toLowerCase().split(\" \");int[] vector = new int[tokens.length];/*String[9] { \"the\", \"rabbit\", \"cross\", \"the\", \"street\",\"and\", \"kick\", \"the\", \"fox\" }*/for (int i = 0; i < tokens.length; i++) { vector[i] = tokenizer.get(tokens[i]);}vector/*int[9] { 1, 6, 5, 1, 3, 2, 8, 1, 12 }*/" }, { "code": null, "e": 5992, "s": 5862, "text": "After that, we create an NDArray. To proceed further, we need to create a batch of tokens and apply some transformations to them." }, { "code": null, "e": 6215, "s": 5992, "text": "NDArray array = manager.create(vector);array = array.reshape(new Shape(vector.length, 1)); // form a batcharray = array.div(10.0);/*ND: (9, 1) cpu() float64[[0.1], [0.6], [0.5], [0.1], [0.3], [0.2], [0.8], [0.1], [1.2],]*/" }, { "code": null, "e": 6654, "s": 6215, "text": "Then, we can send this data to a deep learning model. To achieve the same thing in pure Java would require far more work. If we are trying to implement the reshape function above, we need to create an N-dimensional array in Java that looks like: List<List<List<...List<Float>...>>> to cover all the different dimensions. We would then have to dynamically insert a new List<Float> containing the elements to build resulting data structure." }, { "code": null, "e": 6800, "s": 6654, "text": "With the previous walkthrough, you should have a basic experience using NDArray in Java. To summarize, here is the three key advantages using it:" }, { "code": null, "e": 6879, "s": 6800, "text": "Easy: Access to 60+ operators in Java with a simple input and the same output." }, { "code": null, "e": 7074, "s": 6879, "text": "Fast: Full support for the most used deep learning frameworks including TensorFlow, PyTorch, and MXNet. Now, you can get your computation accelerated by MKLDNN on CPU, CUDA on GPU and lots more." }, { "code": null, "e": 7339, "s": 7074, "text": "Deep Learning ready: It supports high dimensional arrays and sparse NDArray inputs*. You can apply this toolkit on all platforms including Apache Spark and Apache Beam for large-scale data processing. It’s a perfect tool for data preprocessing and post-processing." }, { "code": null, "e": 7413, "s": 7339, "text": "*Sparse currently only covers COO in PyTorch and CSR/Row_Sparse in MXNet." }, { "code": null, "e": 7603, "s": 7413, "text": "After trying NDArray creation and operation, you might wonder how DJL implement NDArray to achieve these behaviors. In this section, we will briefly walkthrough the architecture of NDArray." }, { "code": null, "e": 8409, "s": 7603, "text": "As shown above, there are three key layers to the NDArray. The Interface layer contains NDArray, it is a Java Interface that defines what the NDArray should look like. We carefully evaluated it and made all functions’ signature general enough and easy to use. In the EngineProvider layer, there are different engine’s implementation to the NDArray. This layer served as an interpretation layer that maps Engine specific behavior to NumPy behavior. As a result, all engines implementation are behaved the same way as NumPy have. In the C++ Layer, we built JNI and JNA that expose C++ methods for Java to call. It would ensure we have enough methods to build the entire NDArray stack. Also it ensures the best performance by calling directly from Java to C++ since all Engines are implemented in C/C++." } ]
How to save as PDF on Chrome using Selenium
We can save a pdf file on Chrome using the Selenium webdriver. To download the pdf file in a specific location we have to take the help of the Options class. We shall create an object of this class and apply add_experimental_option on it. Then pass the values - prefs and the path where the pdf is to be downloaded as parameters to this method. o = Options() o.add_experimental_option("prefs" , {"download.default_directory": "../downloads"} ) Code Implementation from selenium import webdriver from selenium.webdriver.chrome.options import Options #object of Options o = Options() #path of downloaded pdf o.add_experimental_option("prefs",{"download.default_directory": "../downloads"}) #pass Option to driver driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=o) #implicit wait driver.implicitly_wait(0.5) #url launch driver.get("http://demo.automationtesting.in/FileDownload.html") #maximize browser driver.maximize_window() #identify elements l = driver.find_element_by_id('pdfbox') l.send_keys("test") m = driver.find_element_by_id('createPdf') m.click() n = driver.find_element_by_id('pdf-link-to-download') n.click() #driver quit driver.quit()
[ { "code": null, "e": 1220, "s": 1062, "text": "We can save a pdf file on Chrome using the Selenium webdriver. To download the pdf file in a specific location we have to take the help of the Options class." }, { "code": null, "e": 1407, "s": 1220, "text": "We shall create an object of this class and apply add_experimental_option on it. Then pass the values - prefs and the path where the pdf is to be downloaded as parameters to this method." }, { "code": null, "e": 1506, "s": 1407, "text": "o = Options()\no.add_experimental_option(\"prefs\" ,\n{\"download.default_directory\": \"../downloads\"} )" }, { "code": null, "e": 1526, "s": 1506, "text": "Code Implementation" }, { "code": null, "e": 2239, "s": 1526, "text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#object of Options\no = Options()\n#path of downloaded pdf\no.add_experimental_option(\"prefs\",{\"download.default_directory\": \"../downloads\"})\n#pass Option to driver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=o)\n#implicit wait\ndriver.implicitly_wait(0.5)\n#url launch\ndriver.get(\"http://demo.automationtesting.in/FileDownload.html\")\n#maximize browser\ndriver.maximize_window()\n#identify elements\nl = driver.find_element_by_id('pdfbox')\nl.send_keys(\"test\")\nm = driver.find_element_by_id('createPdf')\nm.click()\nn = driver.find_element_by_id('pdf-link-to-download')\nn.click()\n#driver quit\ndriver.quit()" } ]
Python program to convert ASCII to Binary - GeeksforGeeks
31 Aug, 2021 In this article, we are going to discuss the conversion of ASCII to Binary in the Python programming language. Binascii helps convert between binary and various ASCII-encoded binary representations. a2b_uu() function: Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program. The a2b_uu() function is used to convert the specified ASCII format to its corresponding binary equivalent. Syntax: a2b_uu(Text) Parameter: This function accepts a single parameter which is illustrated below: Text: This is the specified ASCII string that is going to be converted into its binary equivalent. Return Values: This function returns the binary equivalent. Python3 # Python program to illustrate the# conversion of ASCII to Binary # Importing binascii moduleimport binascii # Initializing a ASCII stringText = "21T9'(&ES(&$@0U,@4&]R=&%L" # Calling the a2b_uu() function to# Convert the ascii string to binaryBinary = binascii.a2b_uu(Text) # Getting the Binary valueprint(Binary) Output: b'GFG is a CS Portal' Firstly, call string.encode() function to turn the specified string into an array of bytes and then call int.from_bytes(byte_array, byte_order) with byte_order as “big” to convert the byte_array into a binary integer. Finally, call bin(binary_int) to convert binary_int to a string of binary characters. Python3 # Python program to illustrate the# conversion of ASCII to Binary # Calling string.encode() function to# turn the specified string into an array# of bytesbyte_array = "GFG".encode() # Converting the byte_array into a binary # integerbinary_int = int.from_bytes(byte_array, "big") # Converting binary_int to a string of # binary charactersbinary_string = bin(binary_int) # Getting the converted binary charactersprint(binary_string) Output: 0b10001110100011001000111 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24317, "s": 24289, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24428, "s": 24317, "text": "In this article, we are going to discuss the conversion of ASCII to Binary in the Python programming language." }, { "code": null, "e": 24516, "s": 24428, "text": "Binascii helps convert between binary and various ASCII-encoded binary representations." }, { "code": null, "e": 24809, "s": 24516, "text": "a2b_uu() function: Here the “uu” stands for “UNIX-to-UNIX encoding” which takes care of the data conversion from strings to binary and ASCII values according to the specified program. The a2b_uu() function is used to convert the specified ASCII format to its corresponding binary equivalent." }, { "code": null, "e": 24830, "s": 24809, "text": "Syntax: a2b_uu(Text)" }, { "code": null, "e": 24910, "s": 24830, "text": "Parameter: This function accepts a single parameter which is illustrated below:" }, { "code": null, "e": 25009, "s": 24910, "text": "Text: This is the specified ASCII string that is going to be converted into its binary equivalent." }, { "code": null, "e": 25069, "s": 25009, "text": "Return Values: This function returns the binary equivalent." }, { "code": null, "e": 25077, "s": 25069, "text": "Python3" }, { "code": "# Python program to illustrate the# conversion of ASCII to Binary # Importing binascii moduleimport binascii # Initializing a ASCII stringText = \"21T9'(&ES(&$@0U,@4&]R=&%L\" # Calling the a2b_uu() function to# Convert the ascii string to binaryBinary = binascii.a2b_uu(Text) # Getting the Binary valueprint(Binary)", "e": 25395, "s": 25077, "text": null }, { "code": null, "e": 25403, "s": 25395, "text": "Output:" }, { "code": null, "e": 25425, "s": 25403, "text": "b'GFG is a CS Portal'" }, { "code": null, "e": 25729, "s": 25425, "text": "Firstly, call string.encode() function to turn the specified string into an array of bytes and then call int.from_bytes(byte_array, byte_order) with byte_order as “big” to convert the byte_array into a binary integer. Finally, call bin(binary_int) to convert binary_int to a string of binary characters." }, { "code": null, "e": 25737, "s": 25729, "text": "Python3" }, { "code": "# Python program to illustrate the# conversion of ASCII to Binary # Calling string.encode() function to# turn the specified string into an array# of bytesbyte_array = \"GFG\".encode() # Converting the byte_array into a binary # integerbinary_int = int.from_bytes(byte_array, \"big\") # Converting binary_int to a string of # binary charactersbinary_string = bin(binary_int) # Getting the converted binary charactersprint(binary_string)", "e": 26173, "s": 25737, "text": null }, { "code": null, "e": 26181, "s": 26173, "text": "Output:" }, { "code": null, "e": 26207, "s": 26181, "text": "0b10001110100011001000111" }, { "code": null, "e": 26230, "s": 26207, "text": "Python string-programs" }, { "code": null, "e": 26237, "s": 26230, "text": "Python" }, { "code": null, "e": 26253, "s": 26237, "text": "Python Programs" }, { "code": null, "e": 26351, "s": 26253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26383, "s": 26351, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26439, "s": 26383, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26481, "s": 26439, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26523, "s": 26481, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26578, "s": 26523, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26600, "s": 26578, "text": "Defaultdict in Python" }, { "code": null, "e": 26646, "s": 26600, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26685, "s": 26646, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26723, "s": 26685, "text": "Python | Convert a list to dictionary" } ]
Password Matching using JavaScript
21 Sep, 2018 Given two boxes i.e. password and confirm password. The task is to check the entered password is matched or not. It is used in online application form or social sites to signup account to verify the entered password by user is correct or not. It is the simple method to verify the password matches. First password is stored into a password1 variable and confirm password is stored in password2 variable. Then check if both variable value is equal then password match otherwise password does not match. Below is the implementation of above approach: <!DOCTYPE html><html> <head> <script> // Function to check Whether both passwords // is same or not. function checkPassword(form) { password1 = form.password1.value; password2 = form.password2.value; // If password not entered if (password1 == '') alert ("Please enter Password"); // If confirm password not entered else if (password2 == '') alert ("Please enter confirm password"); // If Not same return False. else if (password1 != password2) { alert ("\nPassword did not match: Please try again...") return false; } // If same return True. else{ alert("Password Match: Welcome to GeeksforGeeks!") return true; } } </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <form onSubmit = "return checkPassword(this)"> <table border = 1 align = "center"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <input type = submit value = "Submit"></td> </tr> </table> </form> </body></html> Output: Web technologies JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Sep, 2018" }, { "code": null, "e": 165, "s": 52, "text": "Given two boxes i.e. password and confirm password. The task is to check the entered password is matched or not." }, { "code": null, "e": 554, "s": 165, "text": "It is used in online application form or social sites to signup account to verify the entered password by user is correct or not. It is the simple method to verify the password matches. First password is stored into a password1 variable and confirm password is stored in password2 variable. Then check if both variable value is equal then password match otherwise password does not match." }, { "code": null, "e": 601, "s": 554, "text": "Below is the implementation of above approach:" }, { "code": "<!DOCTYPE html><html> <head> <script> // Function to check Whether both passwords // is same or not. function checkPassword(form) { password1 = form.password1.value; password2 = form.password2.value; // If password not entered if (password1 == '') alert (\"Please enter Password\"); // If confirm password not entered else if (password2 == '') alert (\"Please enter confirm password\"); // If Not same return False. else if (password1 != password2) { alert (\"\\nPassword did not match: Please try again...\") return false; } // If same return True. else{ alert(\"Password Match: Welcome to GeeksforGeeks!\") return true; } } </script> <style> .gfg { font-size:40px; color:green; font-weight:bold; text-align:center; } .geeks { font-size:17px; text-align:center; margin-bottom:20px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <form onSubmit = \"return checkPassword(this)\"> <table border = 1 align = \"center\"> <tr> <!-- Enter Username --> <td>Username:</td> <td><input type = text name = name size = 25</td> </tr> <tr> <!-- Enter Password. --> <td>Password:</td> <td><input type = password name = password1 size = 25</td> </tr> <tr> <!-- To Confirm Password. --> <td>Confirm Password:</td> <td><input type = password name = password2 size = 25></td> </tr> <tr> <td colspan = 2 align = right> <input type = submit value = \"Submit\"></td> </tr> </table> </form> </body></html> ", "e": 2954, "s": 601, "text": null }, { "code": null, "e": 2962, "s": 2954, "text": "Output:" }, { "code": null, "e": 2979, "s": 2962, "text": "Web technologies" }, { "code": null, "e": 2990, "s": 2979, "text": "JavaScript" }, { "code": null, "e": 3007, "s": 2990, "text": "Web Technologies" }, { "code": null, "e": 3105, "s": 3007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3166, "s": 3105, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3238, "s": 3166, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3278, "s": 3238, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3319, "s": 3278, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3371, "s": 3319, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3404, "s": 3371, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3466, "s": 3404, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3527, "s": 3466, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3577, "s": 3527, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Year getValue() method in Java with Examples
01 Nov, 2019 The getValue() method of Year class in Java is used to get the integral value of the current Year object. Syntax: public int getValue() Parameter: This method does not accepts any parameter. Return Value: It returns an integer denoting the value of the current year object. Below programs illustrate the getValue() method of Year in Java: Program 1: // Program to illustrate the getvalue() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Creates a Year object Year firstYear = Year.of(1997); // Print the value of the current year // using getValue() method System.out.println(firstYear.getValue()); }} 1997 Program 2: // Program to illustrate the getvalue() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Creates a Year object Year firstYear = Year.of(2018); // Print the value of the current year // using getValue() method System.out.println(firstYear.getValue()); }} 2018 Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#getValue– Akanksha_Rai Java-Functions Java-time package Java-Year Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2019" }, { "code": null, "e": 134, "s": 28, "text": "The getValue() method of Year class in Java is used to get the integral value of the current Year object." }, { "code": null, "e": 142, "s": 134, "text": "Syntax:" }, { "code": null, "e": 165, "s": 142, "text": "public int getValue()\n" }, { "code": null, "e": 220, "s": 165, "text": "Parameter: This method does not accepts any parameter." }, { "code": null, "e": 303, "s": 220, "text": "Return Value: It returns an integer denoting the value of the current year object." }, { "code": null, "e": 368, "s": 303, "text": "Below programs illustrate the getValue() method of Year in Java:" }, { "code": null, "e": 379, "s": 368, "text": "Program 1:" }, { "code": "// Program to illustrate the getvalue() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Creates a Year object Year firstYear = Year.of(1997); // Print the value of the current year // using getValue() method System.out.println(firstYear.getValue()); }}", "e": 783, "s": 379, "text": null }, { "code": null, "e": 789, "s": 783, "text": "1997\n" }, { "code": null, "e": 800, "s": 789, "text": "Program 2:" }, { "code": "// Program to illustrate the getvalue() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Creates a Year object Year firstYear = Year.of(2018); // Print the value of the current year // using getValue() method System.out.println(firstYear.getValue()); }}", "e": 1204, "s": 800, "text": null }, { "code": null, "e": 1210, "s": 1204, "text": "2018\n" }, { "code": null, "e": 1293, "s": 1210, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#getValue–" }, { "code": null, "e": 1306, "s": 1293, "text": "Akanksha_Rai" }, { "code": null, "e": 1321, "s": 1306, "text": "Java-Functions" }, { "code": null, "e": 1339, "s": 1321, "text": "Java-time package" }, { "code": null, "e": 1349, "s": 1339, "text": "Java-Year" }, { "code": null, "e": 1354, "s": 1349, "text": "Java" }, { "code": null, "e": 1359, "s": 1354, "text": "Java" } ]
Memcached - Clear Data
Memcached flush_all command is used to delete all data (key-value pairs) from the Memcached server. It accepts an optional parameter called time that sets a time after which the Memcached data is to be cleared. The basic syntax of Memcached flush_all command is as shown below − flush_all [time] [noreply] The above command always returns OK. In the following example, we store some data into the Memcached server and then clear all the data. set tutorialspoint 0 900 9 memcached STORED get tutorialspoint VALUE tutorialspoint 0 9 memcached END flush_all OK get tutorialspoint END To clear data from a Memcached server, you need to use the Memcached flush method. import net.spy.memcached.MemcachedClient; public class MemcachedJava { public static void main(String[] args) { // Connecting to Memcached server on localhost MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211)); System.out.println("Connection to server sucessfully"); System.out.println("set status:"+mcc.set("count", 900, "5").isDone()); // Get value from cache System.out.println("Get from Cache:"+mcc.get("count")); // now increase the stored value System.out.println("Increment value:"+mcc.incr("count", 2)); // now decrease the stored value System.out.println("Decrement value:"+mcc.decr("count", 1)); // now get the final stored value System.out.println("Get from Cache:"+mcc.get("count")); // now clear all this data System.out.println("Clear data:"+mcc.flush().isDone()); } } On compiling and executing the program, you get to see the following output − Connection to server successfully set status:true Get from Cache:5 Increment value:7 Decrement value:6 Get from Cache:6
[ { "code": null, "e": 2450, "s": 2239, "text": "Memcached flush_all command is used to delete all data (key-value pairs) from the Memcached server. It accepts an optional parameter called time that sets a time after which the Memcached data is to be cleared." }, { "code": null, "e": 2518, "s": 2450, "text": "The basic syntax of Memcached flush_all command is as shown below −" }, { "code": null, "e": 2546, "s": 2518, "text": "flush_all [time] [noreply]\n" }, { "code": null, "e": 2583, "s": 2546, "text": "The above command always returns OK." }, { "code": null, "e": 2683, "s": 2583, "text": "In the following example, we store some data into the Memcached server and then clear all the data." }, { "code": null, "e": 2822, "s": 2683, "text": "set tutorialspoint 0 900 9\nmemcached\nSTORED\nget tutorialspoint\nVALUE tutorialspoint 0 9\nmemcached\nEND\nflush_all\nOK\nget tutorialspoint\nEND\n" }, { "code": null, "e": 2905, "s": 2822, "text": "To clear data from a Memcached server, you need to use the Memcached flush method." }, { "code": null, "e": 3856, "s": 2905, "text": "import net.spy.memcached.MemcachedClient;\npublic class MemcachedJava {\n public static void main(String[] args) {\n \n // Connecting to Memcached server on localhost\n MemcachedClient mcc = new MemcachedClient(new\n InetSocketAddress(\"127.0.0.1\", 11211));\n System.out.println(\"Connection to server sucessfully\");\n System.out.println(\"set status:\"+mcc.set(\"count\", 900, \"5\").isDone());\n \n // Get value from cache\n System.out.println(\"Get from Cache:\"+mcc.get(\"count\"));\n \n // now increase the stored value\n System.out.println(\"Increment value:\"+mcc.incr(\"count\", 2));\n \n // now decrease the stored value\n System.out.println(\"Decrement value:\"+mcc.decr(\"count\", 1));\n \n // now get the final stored value\n System.out.println(\"Get from Cache:\"+mcc.get(\"count\"));\n \n // now clear all this data\n System.out.println(\"Clear data:\"+mcc.flush().isDone());\n }\n}" }, { "code": null, "e": 3934, "s": 3856, "text": "On compiling and executing the program, you get to see the following output −" } ]
How to make table searchable and sortable with pagination using jQuery?
26 May, 2022 The jQuery fancyTable plugin helps the developers to design HTML tables that are searchable and sortable with pagination feature. This plugin is totally based on JavaScript and HTML. Official website for plugin: Please take care of file paths while implementing the codes. https://github.com/myspace-nu/jquery.fancyTable Example 1: The following code demonstrates the simple search and sort with pagination using the jQuery fancyTable plugin. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"> </head> <body><br/> <div class="container"> <h3 style=""> Table with search and sortable headings </h3> <table id="mytableID" style="width:100%" class="table table-striped sampleTable"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Samy</td> <td>Watson</td> <td>41</td> </tr> <tr> <td>Samsamder</td> <td>Watra</td> <td>42</td> </tr> <tr> <td>Samantha</td> <td>Challa</td> <td>31</td> </tr> <tr> <td>Samuel</td> <td>Miranda</td> <td>45</td> </tr> <tr> <td>Samy</td> <td>Joseph</td> <td>37</td> </tr> </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"> </script> <script src="fancyTable.js"> </script> <script type="text/javascript"> $(document).ready(function() { $(".sampleTable").fancyTable({ /* Column number for initial sorting*/ sortColumn:0, /* Setting pagination or enabling */ pagination: true, /* Rows per page kept for display */ perPage:3, globalSearch:true }); }); </script> </body></html> Output: Before Execute: Search execution: Pagination output: Example 2: The following example demonstrates other options like globalSearchExcludeColumns and use of data-attributes like data-sortas=”case-insensitive”. It also handles callback functions like onInit() and onUpdate(). The developer can make use of other option settings as per the need. html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h3>Table with sortable headings and global search</h3> <table id="tableID" class="table table-striped"> <thead> <tr> <th data-sortas="case-insensitive">Firstname</th> <th>Lastname</th> <th>Profession</th> <th data-sortas="numeric">Age</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Caprio</td> <td>Engineer</td> <td>37</td> <td>Hyderabad</td> </tr> <tr> <td>Bikram</td> <td>Sharma</td> <td>Businessman</td> <td>42</td> <td>Delhi</td> </tr> <tr> <td>Amit</td> <td>Chowdhary</td> <td>Engineer</td> <td>58</td> <td>Chennai</td> </tr> <tr> <td>Thomas</td> <td>Einstein</td> <td>Scientist</td> <td>35</td> <td>Mumbai</td> </tr> </tbody> </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"> </script> <script src="fancyTable.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#tableID").fancyTable({ sortColumn:0, /* Setting pagination or enabling */ pagination: false, globalSearch:true, /* Exclude 2nd column from global search.*/ globalSearchExcludeColumns: [2], onInit:function(){ /* On initialization of table */ console.log({ element:this }); }, onUpdate:function(){ /* On update like search and sort of table */ console.log({ element:this }); } }); }); </script> </body></html> Output: Data attribute usage: The following shows the output after the use of data attributes. Exclude column from search: The following output shows the exclusion of the second column from the search feature. Callback functions output: the following output displays the console after function initialization and update. sumitgumber28 jQuery-Plugin HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 211, "s": 28, "text": "The jQuery fancyTable plugin helps the developers to design HTML tables that are searchable and sortable with pagination feature. This plugin is totally based on JavaScript and HTML." }, { "code": null, "e": 301, "s": 211, "text": "Official website for plugin: Please take care of file paths while implementing the codes." }, { "code": null, "e": 349, "s": 301, "text": "https://github.com/myspace-nu/jquery.fancyTable" }, { "code": null, "e": 471, "s": 349, "text": "Example 1: The following code demonstrates the simple search and sort with pagination using the jQuery fancyTable plugin." }, { "code": null, "e": 476, "s": 471, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css\" rel=\"stylesheet\"> </head> <body><br/> <div class=\"container\"> <h3 style=\"\"> Table with search and sortable headings </h3> <table id=\"mytableID\" style=\"width:100%\" class=\"table table-striped sampleTable\"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Samy</td> <td>Watson</td> <td>41</td> </tr> <tr> <td>Samsamder</td> <td>Watra</td> <td>42</td> </tr> <tr> <td>Samantha</td> <td>Challa</td> <td>31</td> </tr> <tr> <td>Samuel</td> <td>Miranda</td> <td>45</td> </tr> <tr> <td>Samy</td> <td>Joseph</td> <td>37</td> </tr> </table> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js\"> </script> <script src=\"fancyTable.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function() { $(\".sampleTable\").fancyTable({ /* Column number for initial sorting*/ sortColumn:0, /* Setting pagination or enabling */ pagination: true, /* Rows per page kept for display */ perPage:3, globalSearch:true }); }); </script> </body></html>", "e": 2932, "s": 476, "text": null }, { "code": null, "e": 2941, "s": 2932, "text": "Output: " }, { "code": null, "e": 2957, "s": 2941, "text": "Before Execute:" }, { "code": null, "e": 2975, "s": 2957, "text": "Search execution:" }, { "code": null, "e": 2994, "s": 2975, "text": "Pagination output:" }, { "code": null, "e": 3284, "s": 2994, "text": "Example 2: The following example demonstrates other options like globalSearchExcludeColumns and use of data-attributes like data-sortas=”case-insensitive”. It also handles callback functions like onInit() and onUpdate(). The developer can make use of other option settings as per the need." }, { "code": null, "e": 3289, "s": 3284, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css\" rel=\"stylesheet\"> </head> <body> <div class=\"container\"> <h3>Table with sortable headings and global search</h3> <table id=\"tableID\" class=\"table table-striped\"> <thead> <tr> <th data-sortas=\"case-insensitive\">Firstname</th> <th>Lastname</th> <th>Profession</th> <th data-sortas=\"numeric\">Age</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Caprio</td> <td>Engineer</td> <td>37</td> <td>Hyderabad</td> </tr> <tr> <td>Bikram</td> <td>Sharma</td> <td>Businessman</td> <td>42</td> <td>Delhi</td> </tr> <tr> <td>Amit</td> <td>Chowdhary</td> <td>Engineer</td> <td>58</td> <td>Chennai</td> </tr> <tr> <td>Thomas</td> <td>Einstein</td> <td>Scientist</td> <td>35</td> <td>Mumbai</td> </tr> </tbody> </table> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js\"> </script> <script src=\"fancyTable.js\"></script> <script type=\"text/javascript\"> $(document).ready(function(){ $(\"#tableID\").fancyTable({ sortColumn:0, /* Setting pagination or enabling */ pagination: false, globalSearch:true, /* Exclude 2nd column from global search.*/ globalSearchExcludeColumns: [2], onInit:function(){ /* On initialization of table */ console.log({ element:this }); }, onUpdate:function(){ /* On update like search and sort of table */ console.log({ element:this }); } }); }); </script> </body></html>", "e": 6342, "s": 3289, "text": null }, { "code": null, "e": 6350, "s": 6342, "text": "Output:" }, { "code": null, "e": 6437, "s": 6350, "text": "Data attribute usage: The following shows the output after the use of data attributes." }, { "code": null, "e": 6552, "s": 6437, "text": "Exclude column from search: The following output shows the exclusion of the second column from the search feature." }, { "code": null, "e": 6663, "s": 6552, "text": "Callback functions output: the following output displays the console after function initialization and update." }, { "code": null, "e": 6677, "s": 6663, "text": "sumitgumber28" }, { "code": null, "e": 6691, "s": 6677, "text": "jQuery-Plugin" }, { "code": null, "e": 6696, "s": 6691, "text": "HTML" }, { "code": null, "e": 6703, "s": 6696, "text": "JQuery" }, { "code": null, "e": 6720, "s": 6703, "text": "Web Technologies" }, { "code": null, "e": 6725, "s": 6720, "text": "HTML" } ]
How to change the background color of the options menu in Android?
This example demonstrates how to change the background color of the options menu in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Changing Option Menu Background and text Color" android:textColor="#1a7902" android:textSize="20sp" /> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="16dp" android:autoLink="web" android:gravity="center" android:text="Hello World" android:textSize="30sp" /> </LinearLayout> Step 3 − Add the following code to res/menu/menu_items.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/option_menu_item_1" android:orderInCategory="1" android:title="Menu 1" app:showAsAction="never" /> <item android:id="@+id/option_menu_item_2" android:orderInCategory="2" android:title="Menu 2" app:showAsAction="never" /> <item android:id="@+id/option_menu_item_3" android:orderInCategory="3" android:title="Menu 3" app:showAsAction="never" /> </menu> Step 4 − Add the following code to res/values/styles.xml <resources> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:textColor">@color/colorPrimary</item> <item name="android:itemBackground">@color/skyBlue</item> </style> </resources> Step 5 − Add the following code to res/values/colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#008577</color> <color name="colorPrimaryDark">#00574B</color> <color name="colorAccent">#D81B60</color> <color name="skyBlue">#87CEEB</color> </resources> Step 6 − Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_items, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.option_menu_item_1: return true; case R.id.option_menu_item_2: return true; case R.id.option_menu_item_3: return true; default: return super.onOptionsItemSelected(item); } } } Step 7 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1280, "s": 1187, "text": "This example demonstrates how to change the background color of the options menu in Android." }, { "code": null, "e": 1409, "s": 1280, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1474, "s": 1409, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2379, "s": 1474, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Changing Option Menu Background and text Color\"\n android:textColor=\"#1a7902\"\n android:textSize=\"20sp\" />\n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_marginTop=\"16dp\"\n android:autoLink=\"web\"\n android:gravity=\"center\"\n android:text=\"Hello World\"\n android:textSize=\"30sp\" />\n</LinearLayout>" }, { "code": null, "e": 2438, "s": 2379, "text": "Step 3 − Add the following code to res/menu/menu_items.xml" }, { "code": null, "e": 3059, "s": 2438, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n <item\n android:id=\"@+id/option_menu_item_1\"\n android:orderInCategory=\"1\"\n android:title=\"Menu 1\"\n app:showAsAction=\"never\" />\n <item\n android:id=\"@+id/option_menu_item_2\"\n android:orderInCategory=\"2\"\n android:title=\"Menu 2\"\n app:showAsAction=\"never\" />\n <item\n android:id=\"@+id/option_menu_item_3\"\n android:orderInCategory=\"3\"\n android:title=\"Menu 3\"\n app:showAsAction=\"never\" />\n</menu>" }, { "code": null, "e": 3116, "s": 3059, "text": "Step 4 − Add the following code to res/values/styles.xml" }, { "code": null, "e": 3536, "s": 3116, "text": "<resources>\n <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n <item name=\"colorPrimary\">@color/colorPrimary</item>\n <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n <item name=\"colorAccent\">@color/colorAccent</item>\n <item name=\"android:textColor\">@color/colorPrimary</item>\n <item name=\"android:itemBackground\">@color/skyBlue</item>\n </style>\n</resources>" }, { "code": null, "e": 3593, "s": 3536, "text": "Step 5 − Add the following code to res/values/colors.xml" }, { "code": null, "e": 3839, "s": 3593, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <color name=\"colorPrimary\">#008577</color>\n <color name=\"colorPrimaryDark\">#00574B</color>\n <color name=\"colorAccent\">#D81B60</color>\n <color name=\"skyBlue\">#87CEEB</color>\n</resources>" }, { "code": null, "e": 3896, "s": 3839, "text": "Step 6 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4748, "s": 3896, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_items, menu);\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.option_menu_item_1: return true;\n case R.id.option_menu_item_2: return true;\n case R.id.option_menu_item_3: return true;\n default: return super.onOptionsItemSelected(item);\n }\n }\n}" }, { "code": null, "e": 4813, "s": 4748, "text": "Step 7 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 5486, "s": 4813, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5837, "s": 5486, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5878, "s": 5837, "text": "Click here to download the project code." } ]
Useful Date and Time Functions in PL/SQL
11 Feb, 2019 Date and Time Function formats are different various database. we are going to discuss most common functions used in Oracle database. The function SYSDATE returns 7 bytes of data, which includes: Century Year Month Day Hour Minute Second 1. Extract():Oracle helps you to extract Year, Month and Day from a date using Extract() Function. Example-1: Extracting Year:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Year FROM SYSDATE) AS ONLY_CURRENT_YEARFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_YEAR05.Feb.2019 07:29:242019Explanation:Useful to retrieve only year from the System date/Current date or particular specified date. SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Year FROM SYSDATE) AS ONLY_CURRENT_YEARFROM Dual Output: Explanation:Useful to retrieve only year from the System date/Current date or particular specified date. Example-2: Extracting Month:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Month FROM SYSDATE) AS ONLY_CURRENT_MONTHFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_MONTH05.Feb.2019 07:29:24FebExplanation:Useful to retrieve only month from the System date/Current date or particular specified date. SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Month FROM SYSDATE) AS ONLY_CURRENT_MONTHFROM Dual Output: Explanation:Useful to retrieve only month from the System date/Current date or particular specified date. Example-3: Extracting Day:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Day FROM SYSDATE) AS ONLY_CURRENT_DAYFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_DAY05.Feb.2019 07:29:245Explanation:Useful to retrieve only day from the System date/Current date or particular specified date. SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Day FROM SYSDATE) AS ONLY_CURRENT_DAYFROM Dual Output: Explanation:Useful to retrieve only day from the System date/Current date or particular specified date. 2. ADD_MONTHS (date, n):Using this method in PL/SQL you can add as well as subtract number of months(n) to a date. Here ‘n’ can be both negative or positive. Example-4:SELECT ADD_MONTHS(SYSDATE, -1) AS PREV_MONTH, SYSDATE AS CURRENT_DATE, ADD_MONTHS(SYSDATE, 1) as NEXT_MONTHFROM DualOutput:PREV_MONTHCURRENT_DATENEXT_MONTH02.Jan.2019 09:15:4602.Feb.2019 09:15:4602.Mar.2019 09:15:46Explanation:ADD_MONTHS function have two parameters one is date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date. SELECT ADD_MONTHS(SYSDATE, -1) AS PREV_MONTH, SYSDATE AS CURRENT_DATE, ADD_MONTHS(SYSDATE, 1) as NEXT_MONTHFROM Dual Output: Explanation:ADD_MONTHS function have two parameters one is date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date. 3. LAST_DAY(date):Using this method in PL/SQL you can get the last day in the month of specified date. Example-5:SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) AS LAST_DAY_OF_MONTH, LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTHFROM DualOutput:CURRENT_DATELAST_DAY_OF_MONTHFIRST_DAY_OF_NEXT_MONTH02.Feb.2019 09:32:0028.Feb.2019 09:32:0001.Mar.2019 09:32:00Explanation:In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month. SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) AS LAST_DAY_OF_MONTH, LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTHFROM Dual Output: Explanation:In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month. Example-6: Number of Days left in the monthSELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) - SYSDATE AS DAYS_LEFT_IN_MONTHFROM DualOutput:CURRENT_DATEDAYS_LEFT_IN_MONTH02.Feb.2019 09:32:0026 SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) - SYSDATE AS DAYS_LEFT_IN_MONTHFROM Dual Output: 4. MONTHS_BETWEEN (date1, date2):Using this method in PL/SQL you can calculate the number of months between two entered dates date1 and date2. if date1 is later than date2 then the result would be positive and if date1 is earlier than date2 then result is negative. Note:If a fractional month is calculated, the MONTHS_BETWEEN function calculates the fraction based on a 31-day month. Example-7:SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'), TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHSFROM DualOutput:NUMBER_OF_MONTHS3.58Explanation:Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers.Eneterd date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function.Let’s select the number of months an employee has worked for the company. SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'), TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHSFROM Dual Output: Explanation:Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers.Eneterd date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function. Let’s select the number of months an employee has worked for the company. Example-8:SELECT MONTHS_BETWEEN (SYSDATE, DATE_OF_HIRE) AS NUMBER_OF_MONTHSFROM EmployeesInput:SYSTEM_DATEDATE_OF_HIRE02-02-201931-10-201702-02-201903-12-201702-02-201924-09-201802-02-201922-12-201602-02-201918-06-2018Output:NUMBER_OF_MONTHS15.06413.9674.29025.3547.483 SELECT MONTHS_BETWEEN (SYSDATE, DATE_OF_HIRE) AS NUMBER_OF_MONTHSFROM Employees Input: Output: 5. NEXT_DAY(date, day_of_week):It will return the upcoming date of the first weekday that is later than the entered date.It has two parameters first date where, system date or specified date can be entered; second day of week which should be in character form. Example-9:SELECT NEXT_DAY(SYSDATE, 'SUNDAY') AS NEXT_SUNDAYFROM DualOutput:NEXT_SUNDAY17-FEB-2019Explanation:It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated. SELECT NEXT_DAY(SYSDATE, 'SUNDAY') AS NEXT_SUNDAYFROM Dual Output: Explanation:It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Feb, 2019" }, { "code": null, "e": 187, "s": 53, "text": "Date and Time Function formats are different various database. we are going to discuss most common functions used in Oracle database." }, { "code": null, "e": 249, "s": 187, "text": "The function SYSDATE returns 7 bytes of data, which includes:" }, { "code": null, "e": 257, "s": 249, "text": "Century" }, { "code": null, "e": 262, "s": 257, "text": "Year" }, { "code": null, "e": 268, "s": 262, "text": "Month" }, { "code": null, "e": 272, "s": 268, "text": "Day" }, { "code": null, "e": 277, "s": 272, "text": "Hour" }, { "code": null, "e": 284, "s": 277, "text": "Minute" }, { "code": null, "e": 291, "s": 284, "text": "Second" }, { "code": null, "e": 390, "s": 291, "text": "1. Extract():Oracle helps you to extract Year, Month and Day from a date using Extract() Function." }, { "code": null, "e": 680, "s": 390, "text": "Example-1: Extracting Year:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Year FROM SYSDATE) AS ONLY_CURRENT_YEARFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_YEAR05.Feb.2019 07:29:242019Explanation:Useful to retrieve only year from the System date/Current date or particular specified date." }, { "code": "SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Year FROM SYSDATE) AS ONLY_CURRENT_YEARFROM Dual", "e": 774, "s": 680, "text": null }, { "code": null, "e": 782, "s": 774, "text": "Output:" }, { "code": null, "e": 887, "s": 782, "text": "Explanation:Useful to retrieve only year from the System date/Current date or particular specified date." }, { "code": null, "e": 1181, "s": 887, "text": "Example-2: Extracting Month:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Month FROM SYSDATE) AS ONLY_CURRENT_MONTHFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_MONTH05.Feb.2019 07:29:24FebExplanation:Useful to retrieve only month from the System date/Current date or particular specified date." }, { "code": "SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Month FROM SYSDATE) AS ONLY_CURRENT_MONTHFROM Dual", "e": 1277, "s": 1181, "text": null }, { "code": null, "e": 1285, "s": 1277, "text": "Output:" }, { "code": null, "e": 1391, "s": 1285, "text": "Explanation:Useful to retrieve only month from the System date/Current date or particular specified date." }, { "code": null, "e": 1673, "s": 1391, "text": "Example-3: Extracting Day:SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Day FROM SYSDATE) AS ONLY_CURRENT_DAYFROM DualOutput:CURRENT_DATE_TIMEONLY_CURRENT_DAY05.Feb.2019 07:29:245Explanation:Useful to retrieve only day from the System date/Current date or particular specified date." }, { "code": "SELECT SYSDATE AS CURRENT_DATE_TIME, EXTRACT(Day FROM SYSDATE) AS ONLY_CURRENT_DAYFROM Dual", "e": 1765, "s": 1673, "text": null }, { "code": null, "e": 1773, "s": 1765, "text": "Output:" }, { "code": null, "e": 1877, "s": 1773, "text": "Explanation:Useful to retrieve only day from the System date/Current date or particular specified date." }, { "code": null, "e": 2035, "s": 1877, "text": "2. ADD_MONTHS (date, n):Using this method in PL/SQL you can add as well as subtract number of months(n) to a date. Here ‘n’ can be both negative or positive." }, { "code": null, "e": 2549, "s": 2035, "text": "Example-4:SELECT ADD_MONTHS(SYSDATE, -1) AS PREV_MONTH, SYSDATE AS CURRENT_DATE, ADD_MONTHS(SYSDATE, 1) as NEXT_MONTHFROM DualOutput:PREV_MONTHCURRENT_DATENEXT_MONTH02.Jan.2019 09:15:4602.Feb.2019 09:15:4602.Mar.2019 09:15:46Explanation:ADD_MONTHS function have two parameters one is date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date." }, { "code": "SELECT ADD_MONTHS(SYSDATE, -1) AS PREV_MONTH, SYSDATE AS CURRENT_DATE, ADD_MONTHS(SYSDATE, 1) as NEXT_MONTHFROM Dual", "e": 2700, "s": 2549, "text": null }, { "code": null, "e": 2708, "s": 2700, "text": "Output:" }, { "code": null, "e": 2963, "s": 2708, "text": "Explanation:ADD_MONTHS function have two parameters one is date, where it could be any specified/particular date or System date as current date and second is ‘n’, it is an integer value could be positive or negative to get upcoming date or previous date." }, { "code": null, "e": 3066, "s": 2963, "text": "3. LAST_DAY(date):Using this method in PL/SQL you can get the last day in the month of specified date." }, { "code": null, "e": 3587, "s": 3066, "text": "Example-5:SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) AS LAST_DAY_OF_MONTH, LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTHFROM DualOutput:CURRENT_DATELAST_DAY_OF_MONTHFIRST_DAY_OF_NEXT_MONTH02.Feb.2019 09:32:0028.Feb.2019 09:32:0001.Mar.2019 09:32:00Explanation:In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month." }, { "code": "SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) AS LAST_DAY_OF_MONTH, LAST_DAY(SYSDATE)+1 AS FIRST_DAY_OF_NEXT_MONTHFROM Dual", "e": 3747, "s": 3587, "text": null }, { "code": null, "e": 3755, "s": 3747, "text": "Output:" }, { "code": null, "e": 3988, "s": 3755, "text": "Explanation:In above example, we are getting current date using SYSDATE function and last date of the month would be retrieved using LAST_DAY function and this function be also helpful for retrieving the first day of the next month." }, { "code": null, "e": 4181, "s": 3988, "text": "Example-6: Number of Days left in the monthSELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) - SYSDATE AS DAYS_LEFT_IN_MONTHFROM DualOutput:CURRENT_DATEDAYS_LEFT_IN_MONTH02.Feb.2019 09:32:0026" }, { "code": "SELECT SYSDATE AS CURRENT_DATE, LAST_DAY(SYSDATE) - SYSDATE AS DAYS_LEFT_IN_MONTHFROM Dual", "e": 4272, "s": 4181, "text": null }, { "code": null, "e": 4280, "s": 4272, "text": "Output:" }, { "code": null, "e": 4546, "s": 4280, "text": "4. MONTHS_BETWEEN (date1, date2):Using this method in PL/SQL you can calculate the number of months between two entered dates date1 and date2. if date1 is later than date2 then the result would be positive and if date1 is earlier than date2 then result is negative." }, { "code": null, "e": 4665, "s": 4546, "text": "Note:If a fractional month is calculated, the MONTHS_BETWEEN function calculates the fraction based on a 31-day month." }, { "code": null, "e": 5264, "s": 4665, "text": "Example-7:SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'), TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHSFROM DualOutput:NUMBER_OF_MONTHS3.58Explanation:Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers.Eneterd date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function.Let’s select the number of months an employee has worked for the company." }, { "code": "SELECT MONTHS_BETWEEN (TO_DATE ('01-07-2003', 'dd-mm-yyyy'), TO_DATE ('14-03-2003', 'dd-mm-yyyy')) AS NUMBER_OF_MONTHSFROM Dual", "e": 5415, "s": 5264, "text": null }, { "code": null, "e": 5423, "s": 5415, "text": "Output:" }, { "code": null, "e": 5762, "s": 5423, "text": "Explanation:Here date1 and date2 are not on the same day of the month that’s why we are getting the value in fractions, as well as date1 is later than date2 so the resulting value is in integers.Eneterd date should be in particular date format, that is the reason of using TO_DATE function while comparison within MONTHS_BETWEEN function." }, { "code": null, "e": 5836, "s": 5762, "text": "Let’s select the number of months an employee has worked for the company." }, { "code": null, "e": 6106, "s": 5836, "text": "Example-8:SELECT MONTHS_BETWEEN (SYSDATE, DATE_OF_HIRE) AS NUMBER_OF_MONTHSFROM EmployeesInput:SYSTEM_DATEDATE_OF_HIRE02-02-201931-10-201702-02-201903-12-201702-02-201924-09-201802-02-201922-12-201602-02-201918-06-2018Output:NUMBER_OF_MONTHS15.06413.9674.29025.3547.483" }, { "code": "SELECT MONTHS_BETWEEN (SYSDATE, DATE_OF_HIRE) AS NUMBER_OF_MONTHSFROM Employees", "e": 6186, "s": 6106, "text": null }, { "code": null, "e": 6193, "s": 6186, "text": "Input:" }, { "code": null, "e": 6201, "s": 6193, "text": "Output:" }, { "code": null, "e": 6462, "s": 6201, "text": "5. NEXT_DAY(date, day_of_week):It will return the upcoming date of the first weekday that is later than the entered date.It has two parameters first date where, system date or specified date can be entered; second day of week which should be in character form." }, { "code": null, "e": 6780, "s": 6462, "text": "Example-9:SELECT NEXT_DAY(SYSDATE, 'SUNDAY') AS NEXT_SUNDAYFROM DualOutput:NEXT_SUNDAY17-FEB-2019Explanation:It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated." }, { "code": "SELECT NEXT_DAY(SYSDATE, 'SUNDAY') AS NEXT_SUNDAYFROM Dual", "e": 6839, "s": 6780, "text": null }, { "code": null, "e": 6847, "s": 6839, "text": "Output:" }, { "code": null, "e": 7068, "s": 6847, "text": "Explanation:It will help to provide the next upcoming date corresponding to the day, return type is always DATE regardless of datatype date. The second parameter must be a day of the week either full name or abbreviated." }, { "code": null, "e": 7079, "s": 7068, "text": "SQL-PL/SQL" }, { "code": null, "e": 7083, "s": 7079, "text": "SQL" }, { "code": null, "e": 7087, "s": 7083, "text": "SQL" } ]
Python program to find IP Address
09 Nov, 2017 An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g., router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).This article focus on How to get IP address of your computer in python.You have to first import socket library and then use IP = socket.gethostbyname(hostname) and then print the value of the ip into the print() function your IP address as output as shown in the program given below. # Python Program to Get IP Addressimport socket hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print("Your Computer Name is:" + hostname) print("Your Computer IP Address is:" + IPAddr) Output: Your Computer Name is:pppContainer Your Computer IP Address is:10.98.162.168 Related Post : Java program to find IP address of your computer This article is contributed by ajay0007. 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. Computer Networks-IP Addressing Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Nov, 2017" }, { "code": null, "e": 519, "s": 28, "text": "An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g., router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).This article focus on How to get IP address of your computer in python.You have to first import socket library and then use" }, { "code": null, "e": 556, "s": 519, "text": "IP = socket.gethostbyname(hostname) " }, { "code": null, "e": 680, "s": 556, "text": "and then print the value of the ip into the print() function your IP address as output as shown in the program given below." }, { "code": "# Python Program to Get IP Addressimport socket hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print(\"Your Computer Name is:\" + hostname) print(\"Your Computer IP Address is:\" + IPAddr) ", "e": 901, "s": 680, "text": null }, { "code": null, "e": 909, "s": 901, "text": "Output:" }, { "code": null, "e": 987, "s": 909, "text": "Your Computer Name is:pppContainer\nYour Computer IP Address is:10.98.162.168\n" }, { "code": null, "e": 1051, "s": 987, "text": "Related Post : Java program to find IP address of your computer" }, { "code": null, "e": 1347, "s": 1051, "text": "This article is contributed by ajay0007. 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": 1472, "s": 1347, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1504, "s": 1472, "text": "Computer Networks-IP Addressing" }, { "code": null, "e": 1511, "s": 1504, "text": "Python" }, { "code": null, "e": 1530, "s": 1511, "text": "Technical Scripter" } ]
Role of keys in Cassandra
27 Nov, 2019 In this article we are going to discuss why keys are important and how they are work and different from relational database. Basically, Keys are used for grouping and organizing data into columns and rows in the database, so let’s have a look. There are many portioning keys are available in Cassandra.1. Simple Primary key 2. Composite key 3. Using a compound primary key Let’s discuss the concept of partitioning key one by one.1. Simple Primary key:In a basic primary key one column uses for column name as the partition key. In this case primary key consists of only the partition key. Only primary key can be specified when retrieving data from the table.CREATE KEYSPACE Employee WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };USE Employee;CREATE TABLE Employee_info ( Employee_id UUID PRIMARY KEY, Emp_name text, Emp_domain text ); 2. Composite key:In Cassandra composite partition key, we can use for more sorted row with the help of key. Let’s take an example to understand. Below given Employee_name is a part of primary key which is called the composite partition key for Employee_info table.CREATE TABLE Employee_info ( Employee_id int, Employee_name text, Employee_domain text, Employee_add text PRIMARY KEY ((Emplyee_id, Employee_name), Employee_domain) ); In the above given table Employee_id and Employee_name used for composite partition key. Here Employee_domain extra column in primary key to return sorted result. let’s take a scenario where clustering column more helpful.INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add) VALUES (1, ‘Ashish’, ‘A’, ‘Delhi’); INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add) VALUES (1, ‘Ashish’, ‘B’, ‘Mumbai’); INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add ) VALUES (2, ‘Ashish’, ‘C’, ‘Hyd’); Select * from Employee_info; Output:Employee_idEmployee_nameEmployee_domainEmployee_add1AshishADelhi1AshishBMumbai2AshishCHydIt shows with the help of clustering key column we can stored data in sorted way what we are actually expecting it is exact result what we return with the help of Employee_domain column in sorted order.3. Using a Compound primary key:Use a compound primary key to create multiple columns that you can use to query and return sorted results.Let’s take an example of Employee_info table where we will de-normalize the data. To create a table having a compound primary key, use two or more columns as the primary key.Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order.CREATE TABLE Employee.Employee_info ( Employee_name text, Employee_points int, Employee_id UUID, PRIMARY KEY (Employee_name, Employee_points) ); Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order.CREATE TABLE Employee.Employee_info ( Employee_name text, Employee_points int, Employee_id int, PRIMARY KEY (Employee_name, Employee_points) ) WITH CLUSTERING ORDER BY (Employee_points DESC); Now, let’s insert data into table Employee_info and used the following CQL query for the same.INSERT INTO Employee_info (Employee_name, Employee_points, Employee_id) VALUES (‘Ashish’, 90, 1); INSERT INTO Employee_info (Employee_name, Employee_points, Employee_id ) VALUES (‘Rana’, 95, 2); INSERT INTO Employee_info(Employee_name, Employee_points, Employee_id) VALUES (‘Ashish’, 85, 3); Select * from Employee_info; Output:Employee_nameEmployee_pointsEmployee_idRana952Ashish901Ashish853My Personal Notes arrow_drop_upSave 1. Simple Primary key 2. Composite key 3. Using a compound primary key Let’s discuss the concept of partitioning key one by one. 1. Simple Primary key:In a basic primary key one column uses for column name as the partition key. In this case primary key consists of only the partition key. Only primary key can be specified when retrieving data from the table. CREATE KEYSPACE Employee WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }; USE Employee; CREATE TABLE Employee_info ( Employee_id UUID PRIMARY KEY, Emp_name text, Emp_domain text ); 2. Composite key:In Cassandra composite partition key, we can use for more sorted row with the help of key. Let’s take an example to understand. Below given Employee_name is a part of primary key which is called the composite partition key for Employee_info table. CREATE TABLE Employee_info ( Employee_id int, Employee_name text, Employee_domain text, Employee_add text PRIMARY KEY ((Emplyee_id, Employee_name), Employee_domain) ); In the above given table Employee_id and Employee_name used for composite partition key. Here Employee_domain extra column in primary key to return sorted result. let’s take a scenario where clustering column more helpful. INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add) VALUES (1, ‘Ashish’, ‘A’, ‘Delhi’); INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add) VALUES (1, ‘Ashish’, ‘B’, ‘Mumbai’); INSERT INTO Employee_info(Employee_id, Employee_name, Employee_domain, Employee_add ) VALUES (2, ‘Ashish’, ‘C’, ‘Hyd’); Select * from Employee_info; Output: 3. Using a Compound primary key:Use a compound primary key to create multiple columns that you can use to query and return sorted results.Let’s take an example of Employee_info table where we will de-normalize the data. To create a table having a compound primary key, use two or more columns as the primary key.Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order. CREATE TABLE Employee.Employee_info ( Employee_name text, Employee_points int, Employee_id UUID, PRIMARY KEY (Employee_name, Employee_points) ); Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order. CREATE TABLE Employee.Employee_info ( Employee_name text, Employee_points int, Employee_id int, PRIMARY KEY (Employee_name, Employee_points) ) WITH CLUSTERING ORDER BY (Employee_points DESC); Now, let’s insert data into table Employee_info and used the following CQL query for the same. INSERT INTO Employee_info (Employee_name, Employee_points, Employee_id) VALUES (‘Ashish’, 90, 1); INSERT INTO Employee_info (Employee_name, Employee_points, Employee_id ) VALUES (‘Rana’, 95, 2); INSERT INTO Employee_info(Employee_name, Employee_points, Employee_id) VALUES (‘Ashish’, 85, 3); Select * from Employee_info; Output: Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 SQL Trigger | Student Database Introduction of B-Tree SQL Interview Questions SQL | Views Introduction of ER Model Data Preprocessing in Data Mining Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Nov, 2019" }, { "code": null, "e": 272, "s": 28, "text": "In this article we are going to discuss why keys are important and how they are work and different from relational database. Basically, Keys are used for grouping and organizing data into columns and rows in the database, so let’s have a look." }, { "code": null, "e": 3970, "s": 272, "text": "There are many portioning keys are available in Cassandra.1. Simple Primary key\n2. Composite key\n3. Using a compound primary key Let’s discuss the concept of partitioning key one by one.1. Simple Primary key:In a basic primary key one column uses for column name as the partition key. In this case primary key consists of only the partition key. Only primary key can be specified when retrieving data from the table.CREATE KEYSPACE Employee\nWITH REPLICATION = { 'class' : 'SimpleStrategy', \n 'replication_factor' : 1 };USE Employee;CREATE TABLE Employee_info ( \nEmployee_id UUID PRIMARY KEY, \nEmp_name text, \nEmp_domain text \n);\n2. Composite key:In Cassandra composite partition key, we can use for more sorted row with the help of key. Let’s take an example to understand. Below given Employee_name is a part of primary key which is called the composite partition key for Employee_info table.CREATE TABLE Employee_info\n(\nEmployee_id int,\nEmployee_name text,\nEmployee_domain text,\nEmployee_add text\nPRIMARY KEY ((Emplyee_id, Employee_name), Employee_domain) \n); In the above given table Employee_id and Employee_name used for composite partition key. Here Employee_domain extra column in primary key to return sorted result. let’s take a scenario where clustering column more helpful.INSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add) \n VALUES (1, ‘Ashish’, ‘A’, ‘Delhi’);\nINSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add) \n VALUES (1, ‘Ashish’, ‘B’, ‘Mumbai’);\nINSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add ) \n VALUES (2, ‘Ashish’, ‘C’, ‘Hyd’); Select * \nfrom Employee_info; Output:Employee_idEmployee_nameEmployee_domainEmployee_add1AshishADelhi1AshishBMumbai2AshishCHydIt shows with the help of clustering key column we can stored data in sorted way what we are actually expecting it is exact result what we return with the help of Employee_domain column in sorted order.3. Using a Compound primary key:Use a compound primary key to create multiple columns that you can use to query and return sorted results.Let’s take an example of Employee_info table where we will de-normalize the data. To create a table having a compound primary key, use two or more columns as the primary key.Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order.CREATE TABLE Employee.Employee_info ( \nEmployee_name text, \nEmployee_points int, \nEmployee_id UUID, \nPRIMARY KEY (Employee_name, Employee_points)\n); Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order.CREATE TABLE Employee.Employee_info ( \nEmployee_name text, \nEmployee_points int, \nEmployee_id int, \nPRIMARY KEY (Employee_name, Employee_points)\n) WITH CLUSTERING ORDER BY (Employee_points DESC); Now, let’s insert data into table Employee_info and used the following CQL query for the same.INSERT INTO Employee_info (Employee_name, Employee_points, \n Employee_id) \n VALUES (‘Ashish’, 90, 1);\nINSERT INTO Employee_info (Employee_name, Employee_points, \n Employee_id ) \n VALUES (‘Rana’, 95, 2);\nINSERT INTO Employee_info(Employee_name, Employee_points, \n Employee_id) \n VALUES (‘Ashish’, 85, 3); Select * \nfrom Employee_info; Output:Employee_nameEmployee_pointsEmployee_idRana952Ashish901Ashish853My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 4042, "s": 3970, "text": "1. Simple Primary key\n2. Composite key\n3. Using a compound primary key " }, { "code": null, "e": 4100, "s": 4042, "text": "Let’s discuss the concept of partitioning key one by one." }, { "code": null, "e": 4331, "s": 4100, "text": "1. Simple Primary key:In a basic primary key one column uses for column name as the partition key. In this case primary key consists of only the partition key. Only primary key can be specified when retrieving data from the table." }, { "code": null, "e": 4455, "s": 4331, "text": "CREATE KEYSPACE Employee\nWITH REPLICATION = { 'class' : 'SimpleStrategy', \n 'replication_factor' : 1 };" }, { "code": null, "e": 4469, "s": 4455, "text": "USE Employee;" }, { "code": null, "e": 4567, "s": 4469, "text": "CREATE TABLE Employee_info ( \nEmployee_id UUID PRIMARY KEY, \nEmp_name text, \nEmp_domain text \n);\n" }, { "code": null, "e": 4832, "s": 4567, "text": "2. Composite key:In Cassandra composite partition key, we can use for more sorted row with the help of key. Let’s take an example to understand. Below given Employee_name is a part of primary key which is called the composite partition key for Employee_info table." }, { "code": null, "e": 5002, "s": 4832, "text": "CREATE TABLE Employee_info\n(\nEmployee_id int,\nEmployee_name text,\nEmployee_domain text,\nEmployee_add text\nPRIMARY KEY ((Emplyee_id, Employee_name), Employee_domain) \n); " }, { "code": null, "e": 5225, "s": 5002, "text": "In the above given table Employee_id and Employee_name used for composite partition key. Here Employee_domain extra column in primary key to return sorted result. let’s take a scenario where clustering column more helpful." }, { "code": null, "e": 5696, "s": 5225, "text": "INSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add) \n VALUES (1, ‘Ashish’, ‘A’, ‘Delhi’);\nINSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add) \n VALUES (1, ‘Ashish’, ‘B’, ‘Mumbai’);\nINSERT INTO Employee_info(Employee_id, Employee_name, \n Employee_domain, Employee_add ) \n VALUES (2, ‘Ashish’, ‘C’, ‘Hyd’); " }, { "code": null, "e": 5727, "s": 5696, "text": "Select * \nfrom Employee_info; " }, { "code": null, "e": 5735, "s": 5727, "text": "Output:" }, { "code": null, "e": 6176, "s": 5735, "text": "3. Using a Compound primary key:Use a compound primary key to create multiple columns that you can use to query and return sorted results.Let’s take an example of Employee_info table where we will de-normalize the data. To create a table having a compound primary key, use two or more columns as the primary key.Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order." }, { "code": null, "e": 6327, "s": 6176, "text": "CREATE TABLE Employee.Employee_info ( \nEmployee_name text, \nEmployee_points int, \nEmployee_id UUID, \nPRIMARY KEY (Employee_name, Employee_points)\n); " }, { "code": null, "e": 6456, "s": 6327, "text": "Let’s take an example which uses an additional clause WITH CLUSTERING ORDER BY to order the Employee_points in descending order." }, { "code": null, "e": 6654, "s": 6456, "text": "CREATE TABLE Employee.Employee_info ( \nEmployee_name text, \nEmployee_points int, \nEmployee_id int, \nPRIMARY KEY (Employee_name, Employee_points)\n) WITH CLUSTERING ORDER BY (Employee_points DESC); " }, { "code": null, "e": 6749, "s": 6654, "text": "Now, let’s insert data into table Employee_info and used the following CQL query for the same." }, { "code": null, "e": 7200, "s": 6749, "text": "INSERT INTO Employee_info (Employee_name, Employee_points, \n Employee_id) \n VALUES (‘Ashish’, 90, 1);\nINSERT INTO Employee_info (Employee_name, Employee_points, \n Employee_id ) \n VALUES (‘Rana’, 95, 2);\nINSERT INTO Employee_info(Employee_name, Employee_points, \n Employee_id) \n VALUES (‘Ashish’, 85, 3); " }, { "code": null, "e": 7231, "s": 7200, "text": "Select * \nfrom Employee_info; " }, { "code": null, "e": 7239, "s": 7231, "text": "Output:" }, { "code": null, "e": 7246, "s": 7239, "text": "Apache" }, { "code": null, "e": 7251, "s": 7246, "text": "DBMS" }, { "code": null, "e": 7256, "s": 7251, "text": "DBMS" }, { "code": null, "e": 7354, "s": 7256, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7365, "s": 7354, "text": "CTE in SQL" }, { "code": null, "e": 7418, "s": 7365, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 7476, "s": 7418, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 7507, "s": 7476, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 7530, "s": 7507, "text": "Introduction of B-Tree" }, { "code": null, "e": 7554, "s": 7530, "text": "SQL Interview Questions" }, { "code": null, "e": 7566, "s": 7554, "text": "SQL | Views" }, { "code": null, "e": 7591, "s": 7566, "text": "Introduction of ER Model" }, { "code": null, "e": 7625, "s": 7591, "text": "Data Preprocessing in Data Mining" } ]