title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Create and Call a Stored Procedure in SQL?
25 Oct, 2021 With this article, we will learn how to Create and Call a Stored Procedure in SQL. For this article, we are going to use MSSQL as our database server. A stored procedure is a pre-written SQL query that can be called multiple times and will run as the same. Like we can create a Stored procedure for Insert, select, update in SQL database. We can also pass parameters to the Stored procedures. So, we will create a database first: Step 1: Creating Database Query: CREATE DATABASE GFG Step 2: Using Database Query: USE GFG Step 3: Create a table Query: CREATE TABLE gfgTutorial( id integer, Name varchar(20) ) Step 4: Describe the table Query: sp_help 'dbo.gfgTutorial' Output: Created Table schema Step 5: Insert some data into the table Query: INSERT INTO [dbo].[gfgTutorial] ([id] ,[Name]) VALUES (1, 'Devesh') GO INSERT INTO [dbo].[gfgTutorial] ([id] ,[Name]) VALUES (2, 'Geeks') GO INSERT INTO [dbo].[gfgTutorial] ([id] ,[Name]) VALUES (3, 'For') GO INSERT INTO [dbo].[gfgTutorial] ([id] ,[Name]) VALUES (4, 'Geeks') GO INSERT INTO [dbo].[gfgTutorial]E ([id] ,[Name]) VALUES (5, 'GFG') GO Step 6: Create a Stored procedure for Select all the rows from a table Query: CREATE PROCEDURE select_all_data AS SELECT * FROM gfgTutorial GO; Output: Successfully created the stored procedure Execute Stored procedure select_all_data Query: EXEC select_all_data Output: Executing stored procedure to select all data Now we have seen how to create a basic stored procedure now let’s see how to create the parameterized stored procedure Step 1: Create a parameterized stored procedure to insert data in the table Query: CREATE PROCEDURE insertData @Name varchar(30), @id varchar(30) AS INSERT INTO gfgTutorial VALUES(@id, @Name) GO Step 2: Execute stored procedure Query: EXEC insertData @Name = 'Inserted Name', @id = 6 Data insertion successful Check the data is inserted or not. Data is inserted by the stored procedure. Picked 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? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2021" }, { "code": null, "e": 179, "s": 28, "text": "With this article, we will learn how to Create and Call a Stored Procedure in SQL. For this article, we are going to use MSSQL as our database server." }, { "code": null, "e": 458, "s": 179, "text": "A stored procedure is a pre-written SQL query that can be called multiple times and will run as the same. Like we can create a Stored procedure for Insert, select, update in SQL database. We can also pass parameters to the Stored procedures. So, we will create a database first:" }, { "code": null, "e": 484, "s": 458, "text": "Step 1: Creating Database" }, { "code": null, "e": 491, "s": 484, "text": "Query:" }, { "code": null, "e": 511, "s": 491, "text": "CREATE DATABASE GFG" }, { "code": null, "e": 534, "s": 511, "text": "Step 2: Using Database" }, { "code": null, "e": 541, "s": 534, "text": "Query:" }, { "code": null, "e": 549, "s": 541, "text": "USE GFG" }, { "code": null, "e": 572, "s": 549, "text": "Step 3: Create a table" }, { "code": null, "e": 579, "s": 572, "text": "Query:" }, { "code": null, "e": 636, "s": 579, "text": "CREATE TABLE gfgTutorial(\nid integer,\nName varchar(20)\n)" }, { "code": null, "e": 663, "s": 636, "text": "Step 4: Describe the table" }, { "code": null, "e": 670, "s": 663, "text": "Query:" }, { "code": null, "e": 696, "s": 670, "text": "sp_help 'dbo.gfgTutorial'" }, { "code": null, "e": 704, "s": 696, "text": "Output:" }, { "code": null, "e": 725, "s": 704, "text": "Created Table schema" }, { "code": null, "e": 765, "s": 725, "text": "Step 5: Insert some data into the table" }, { "code": null, "e": 772, "s": 765, "text": "Query:" }, { "code": null, "e": 1314, "s": 772, "text": "INSERT INTO [dbo].[gfgTutorial]\n ([id]\n ,[Name])\n VALUES\n (1, 'Devesh')\nGO\n\nINSERT INTO [dbo].[gfgTutorial]\n ([id]\n ,[Name])\n VALUES\n (2, 'Geeks')\nGO\n\nINSERT INTO [dbo].[gfgTutorial]\n ([id]\n ,[Name])\n VALUES\n (3, 'For')\nGO\n\nINSERT INTO [dbo].[gfgTutorial]\n ([id]\n ,[Name])\n VALUES\n (4, 'Geeks')\nGO\n\nINSERT INTO [dbo].[gfgTutorial]E\n ([id]\n ,[Name])\n VALUES\n (5, 'GFG')\nGO" }, { "code": null, "e": 1385, "s": 1314, "text": "Step 6: Create a Stored procedure for Select all the rows from a table" }, { "code": null, "e": 1392, "s": 1385, "text": "Query:" }, { "code": null, "e": 1458, "s": 1392, "text": "CREATE PROCEDURE select_all_data\nAS\nSELECT * FROM gfgTutorial\nGO;" }, { "code": null, "e": 1466, "s": 1458, "text": "Output:" }, { "code": null, "e": 1508, "s": 1466, "text": "Successfully created the stored procedure" }, { "code": null, "e": 1550, "s": 1508, "text": "Execute Stored procedure select_all_data " }, { "code": null, "e": 1557, "s": 1550, "text": "Query:" }, { "code": null, "e": 1578, "s": 1557, "text": "EXEC select_all_data" }, { "code": null, "e": 1586, "s": 1578, "text": "Output:" }, { "code": null, "e": 1632, "s": 1586, "text": "Executing stored procedure to select all data" }, { "code": null, "e": 1751, "s": 1632, "text": "Now we have seen how to create a basic stored procedure now let’s see how to create the parameterized stored procedure" }, { "code": null, "e": 1827, "s": 1751, "text": "Step 1: Create a parameterized stored procedure to insert data in the table" }, { "code": null, "e": 1834, "s": 1827, "text": "Query:" }, { "code": null, "e": 1946, "s": 1834, "text": "CREATE PROCEDURE insertData\n@Name varchar(30), @id varchar(30)\nAS\nINSERT INTO gfgTutorial VALUES(@id, @Name)\nGO" }, { "code": null, "e": 1979, "s": 1946, "text": "Step 2: Execute stored procedure" }, { "code": null, "e": 1986, "s": 1979, "text": "Query:" }, { "code": null, "e": 2035, "s": 1986, "text": "EXEC insertData @Name = 'Inserted Name', @id = 6" }, { "code": null, "e": 2061, "s": 2035, "text": "Data insertion successful" }, { "code": null, "e": 2096, "s": 2061, "text": "Check the data is inserted or not." }, { "code": null, "e": 2138, "s": 2096, "text": "Data is inserted by the stored procedure." }, { "code": null, "e": 2145, "s": 2138, "text": "Picked" }, { "code": null, "e": 2156, "s": 2145, "text": "SQL-Server" }, { "code": null, "e": 2160, "s": 2156, "text": "SQL" }, { "code": null, "e": 2164, "s": 2160, "text": "SQL" }, { "code": null, "e": 2262, "s": 2164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2328, "s": 2262, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2352, "s": 2328, "text": "Window functions in SQL" }, { "code": null, "e": 2384, "s": 2352, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2417, "s": 2384, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2434, "s": 2417, "text": "SQL using Python" }, { "code": null, "e": 2464, "s": 2434, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2542, "s": 2464, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2578, "s": 2542, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2609, "s": 2578, "text": "SQL Query to Compare Two Dates" } ]
Find last remaining Array element by multiplying boundary elements based on given rules
28 Jun, 2022 Given an array arr[], the task is to find the only remaining element in the array after applying the below operation till there is only one element left in the array. In an operation, multiply the boundary elements of this array and if the size of the array is: Even: Insert the product in the middle of the array and remove the boundary elements Odd: Subtract the middle element from the product and replace the middle element with the absolute difference and remove the boundary elements. Examples: Input: arr[] = [ 1, 2, 3, 4, 5, 6 ]Output: 8Explanation: See the image below for explanation. Input: arr[] = [ 3, 5, 1, 8, 9]Output: 14 Approach: The solution is based on greedy approach. Delete the elements from the ends of the array and insert the data in the middle of the array. Now follow the below steps to solve this problem: Run a while loop, till the size of the array arr[] is greater than 1. In each iteration of this loop:Take the product of the first and the last elements and then pop them.If the size of the array is even, then insert the product in the middle of the array arr[].If it is odd then subtract the middle element from the product and replace it with the middle element.After the loop ends, print the only remaining element in the array. Run a while loop, till the size of the array arr[] is greater than 1. In each iteration of this loop:Take the product of the first and the last elements and then pop them.If the size of the array is even, then insert the product in the middle of the array arr[].If it is odd then subtract the middle element from the product and replace it with the middle element. Take the product of the first and the last elements and then pop them. If the size of the array is even, then insert the product in the middle of the array arr[]. If it is odd then subtract the middle element from the product and replace it with the middle element. After the loop ends, print the only remaining element in the array. C++ Java Python3 C# Javascript // C++ program for the baove approach#include <bits/stdc++.h>using namespace std; // Function to reduce arrayvoid PSarray(vector<int> A){ while (A.size() != 1) { // If size of array is Even if (A.size() % 2 == 0) { // Product of boundary element int x = A[0] * A[A.size() - 1]; A.erase(A.begin()); A.pop_back(); int n = A.size(); // Insert product in middle of element A.insert(A.begin() + n / 2, x); } // Else if size of array is Odd else { int x = A[0] * A[A.size() - 1]; A.erase(A.begin()); A.pop_back(); int n = A.size(); // Subtract middle element from product and // replace middle element A[n / 2] = x - A[n / 2]; } } // Print the last remaining array element cout << A[0] << endl;}// Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4, 5, 6 }; PSarray(arr); return 0;} // This code is contributed by Tapesh (tapeshdua420) // Java program for the baove approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ // Function to reduce array static void PSarray(ArrayList<Integer> A) { while (A.size() != 1) { // If size of array is Even if (A.size() % 2 == 0){ // Product of boundary element int x = A.get(0)*A.get(A.size()-1); A.remove(0); A.remove(A.size() - 1); int n = A.size(); // Insert product in middle of element A.add(n/2, x); } // Else if size of array is Odd else { int x = A.get(0)*A.get(A.size() - 1); A.remove(0); A.remove(A.size() - 1); int n = A.size(); // Subtract middle element from product and // replace middle element A.set(n / 2, x - A.get(n / 2)); } } // Print the last remaining array element System.out.println(A); } // Driver Code public static void main(String[] args) { Integer []arr = {1, 2, 3, 4, 5, 6}; ArrayList<Integer> A = new ArrayList<>(Arrays.asList(arr)); PSarray(A); }} // This code is contributed by shikhasingrajput # Python program for the baove approach # Function to reduce arraydef PSarray(A): while len(A) != 1: # If size of array is Even if len(A) % 2 == 0: # Product of boundary element x = A.pop(0)*A.pop() n = len(A) # Insert product in middle of element A.insert(n//2, x) # Else if size of array is Odd else: x = A.pop(0)*A.pop() n = len(A) # Subtract middle element from product and # replace middle element A[n//2] = x-A[n//2] # Print the last remaining array element print(A[0]) # Driver Codeif __name__ == "__main__": A = [1, 2, 3, 4, 5, 6] PSarray(A) // C# program for the baove approachusing System;using System.Collections.Generic; public class GFG{ // Function to reduce array static void PSarray(List<int> A) { while (A.Count != 1) { // If size of array is Even if (A.Count % 2 == 0){ // Product of boundary element int x = A[0]*A[A.Count-1]; A.RemoveAt(0); A.RemoveAt(A.Count - 1); int n = A.Count; // Insert product in middle of element A.Insert(n/2,x); } // Else if size of array is Odd else { int x = A[0]*A[A.Count - 1]; A.RemoveAt(0); A.RemoveAt(A.Count - 1); int n = A.Count; // Subtract middle element from product and // replace middle element A[n / 2] = x - A[n / 2]; } } // Print the last remaining array element A.ForEach(x=>Console.Write(x)); } // Driver Code public static void Main(String[] args) { int []arr = {1, 2, 3, 4, 5, 6}; List<int> A = new List<int>(arr); PSarray(A); }} // This code is contributed by 29AjayKumar <script> // JavaScript program for the baove approach // Function to reduce arrayfunction PSarray(A){ while (A.length != 1) { // If size of array is Even if (A.length % 2 == 0) { // Product of boundary element let x = A.shift() * A.pop() let n = A.length // Insert product in middle of element let p1 = A.slice(0, Math.floor(A.length / 2)) p1.push(x) let p2 = A.slice(Math.floor(A.length / 2)) A = p1.concat(p2) } // Else if size of array is Odd else { let x = A.shift() * A.pop() let n = A.length // Subtract middle element from product and // replace middle element A[Math.floor(n / 2)] = x - A[Math.floor(n / 2)] } // Print the last remaining array element } document.write(A[0])} // Driver Codelet A = [ 1, 2, 3, 4, 5, 6 ] PSarray(A) // This code is contributed by Potta Lokesh </script> 8 Time Complexity: O(N2)Auxiliary Space: O(1) lokeshpotta20 shikhasingrajput 29AjayKumar tapeshdua420 Algo-Geek 2021 Algo Geek Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximise minimum element possible in Array after performing given operations Smallest set of vertices to visit all nodes of the given Graph Check if every row in given Matrix contains all the integers from 1 to N Maximum count of adjacent pairs with even sum in given Circular Array Find sum of the series 1! - 2! + 3! - 4! + 5! . . . till Nth term Arrays in Java Multidimensional Arrays in Java Arrays in C/C++ Find the smallest positive integer value that cannot be represented as sum of any subset of a given array Maximum and minimum of an array using minimum number of comparisons
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 290, "s": 28, "text": "Given an array arr[], the task is to find the only remaining element in the array after applying the below operation till there is only one element left in the array. In an operation, multiply the boundary elements of this array and if the size of the array is:" }, { "code": null, "e": 375, "s": 290, "text": "Even: Insert the product in the middle of the array and remove the boundary elements" }, { "code": null, "e": 519, "s": 375, "text": "Odd: Subtract the middle element from the product and replace the middle element with the absolute difference and remove the boundary elements." }, { "code": null, "e": 529, "s": 519, "text": "Examples:" }, { "code": null, "e": 623, "s": 529, "text": "Input: arr[] = [ 1, 2, 3, 4, 5, 6 ]Output: 8Explanation: See the image below for explanation." }, { "code": null, "e": 665, "s": 623, "text": "Input: arr[] = [ 3, 5, 1, 8, 9]Output: 14" }, { "code": null, "e": 862, "s": 665, "text": "Approach: The solution is based on greedy approach. Delete the elements from the ends of the array and insert the data in the middle of the array. Now follow the below steps to solve this problem:" }, { "code": null, "e": 1294, "s": 862, "text": "Run a while loop, till the size of the array arr[] is greater than 1. In each iteration of this loop:Take the product of the first and the last elements and then pop them.If the size of the array is even, then insert the product in the middle of the array arr[].If it is odd then subtract the middle element from the product and replace it with the middle element.After the loop ends, print the only remaining element in the array." }, { "code": null, "e": 1659, "s": 1294, "text": "Run a while loop, till the size of the array arr[] is greater than 1. In each iteration of this loop:Take the product of the first and the last elements and then pop them.If the size of the array is even, then insert the product in the middle of the array arr[].If it is odd then subtract the middle element from the product and replace it with the middle element." }, { "code": null, "e": 1730, "s": 1659, "text": "Take the product of the first and the last elements and then pop them." }, { "code": null, "e": 1822, "s": 1730, "text": "If the size of the array is even, then insert the product in the middle of the array arr[]." }, { "code": null, "e": 1925, "s": 1822, "text": "If it is odd then subtract the middle element from the product and replace it with the middle element." }, { "code": null, "e": 1993, "s": 1925, "text": "After the loop ends, print the only remaining element in the array." }, { "code": null, "e": 1997, "s": 1993, "text": "C++" }, { "code": null, "e": 2002, "s": 1997, "text": "Java" }, { "code": null, "e": 2010, "s": 2002, "text": "Python3" }, { "code": null, "e": 2013, "s": 2010, "text": "C#" }, { "code": null, "e": 2024, "s": 2013, "text": "Javascript" }, { "code": "// C++ program for the baove approach#include <bits/stdc++.h>using namespace std; // Function to reduce arrayvoid PSarray(vector<int> A){ while (A.size() != 1) { // If size of array is Even if (A.size() % 2 == 0) { // Product of boundary element int x = A[0] * A[A.size() - 1]; A.erase(A.begin()); A.pop_back(); int n = A.size(); // Insert product in middle of element A.insert(A.begin() + n / 2, x); } // Else if size of array is Odd else { int x = A[0] * A[A.size() - 1]; A.erase(A.begin()); A.pop_back(); int n = A.size(); // Subtract middle element from product and // replace middle element A[n / 2] = x - A[n / 2]; } } // Print the last remaining array element cout << A[0] << endl;}// Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4, 5, 6 }; PSarray(arr); return 0;} // This code is contributed by Tapesh (tapeshdua420)", "e": 3078, "s": 2024, "text": null }, { "code": "// Java program for the baove approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ // Function to reduce array static void PSarray(ArrayList<Integer> A) { while (A.size() != 1) { // If size of array is Even if (A.size() % 2 == 0){ // Product of boundary element int x = A.get(0)*A.get(A.size()-1); A.remove(0); A.remove(A.size() - 1); int n = A.size(); // Insert product in middle of element A.add(n/2, x); } // Else if size of array is Odd else { int x = A.get(0)*A.get(A.size() - 1); A.remove(0); A.remove(A.size() - 1); int n = A.size(); // Subtract middle element from product and // replace middle element A.set(n / 2, x - A.get(n / 2)); } } // Print the last remaining array element System.out.println(A); } // Driver Code public static void main(String[] args) { Integer []arr = {1, 2, 3, 4, 5, 6}; ArrayList<Integer> A = new ArrayList<>(Arrays.asList(arr)); PSarray(A); }} // This code is contributed by shikhasingrajput", "e": 4195, "s": 3078, "text": null }, { "code": "# Python program for the baove approach # Function to reduce arraydef PSarray(A): while len(A) != 1: # If size of array is Even if len(A) % 2 == 0: # Product of boundary element x = A.pop(0)*A.pop() n = len(A) # Insert product in middle of element A.insert(n//2, x) # Else if size of array is Odd else: x = A.pop(0)*A.pop() n = len(A) # Subtract middle element from product and # replace middle element A[n//2] = x-A[n//2] # Print the last remaining array element print(A[0]) # Driver Codeif __name__ == \"__main__\": A = [1, 2, 3, 4, 5, 6] PSarray(A)", "e": 4901, "s": 4195, "text": null }, { "code": "// C# program for the baove approachusing System;using System.Collections.Generic; public class GFG{ // Function to reduce array static void PSarray(List<int> A) { while (A.Count != 1) { // If size of array is Even if (A.Count % 2 == 0){ // Product of boundary element int x = A[0]*A[A.Count-1]; A.RemoveAt(0); A.RemoveAt(A.Count - 1); int n = A.Count; // Insert product in middle of element A.Insert(n/2,x); } // Else if size of array is Odd else { int x = A[0]*A[A.Count - 1]; A.RemoveAt(0); A.RemoveAt(A.Count - 1); int n = A.Count; // Subtract middle element from product and // replace middle element A[n / 2] = x - A[n / 2]; } } // Print the last remaining array element A.ForEach(x=>Console.Write(x)); } // Driver Code public static void Main(String[] args) { int []arr = {1, 2, 3, 4, 5, 6}; List<int> A = new List<int>(arr); PSarray(A); }} // This code is contributed by 29AjayKumar", "e": 5962, "s": 4901, "text": null }, { "code": "<script> // JavaScript program for the baove approach // Function to reduce arrayfunction PSarray(A){ while (A.length != 1) { // If size of array is Even if (A.length % 2 == 0) { // Product of boundary element let x = A.shift() * A.pop() let n = A.length // Insert product in middle of element let p1 = A.slice(0, Math.floor(A.length / 2)) p1.push(x) let p2 = A.slice(Math.floor(A.length / 2)) A = p1.concat(p2) } // Else if size of array is Odd else { let x = A.shift() * A.pop() let n = A.length // Subtract middle element from product and // replace middle element A[Math.floor(n / 2)] = x - A[Math.floor(n / 2)] } // Print the last remaining array element } document.write(A[0])} // Driver Codelet A = [ 1, 2, 3, 4, 5, 6 ] PSarray(A) // This code is contributed by Potta Lokesh </script>", "e": 7015, "s": 5962, "text": null }, { "code": null, "e": 7017, "s": 7015, "text": "8" }, { "code": null, "e": 7061, "s": 7017, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 7077, "s": 7063, "text": "lokeshpotta20" }, { "code": null, "e": 7094, "s": 7077, "text": "shikhasingrajput" }, { "code": null, "e": 7106, "s": 7094, "text": "29AjayKumar" }, { "code": null, "e": 7119, "s": 7106, "text": "tapeshdua420" }, { "code": null, "e": 7134, "s": 7119, "text": "Algo-Geek 2021" }, { "code": null, "e": 7144, "s": 7134, "text": "Algo Geek" }, { "code": null, "e": 7151, "s": 7144, "text": "Arrays" }, { "code": null, "e": 7158, "s": 7151, "text": "Arrays" }, { "code": null, "e": 7256, "s": 7158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7333, "s": 7256, "text": "Maximise minimum element possible in Array after performing given operations" }, { "code": null, "e": 7396, "s": 7333, "text": "Smallest set of vertices to visit all nodes of the given Graph" }, { "code": null, "e": 7469, "s": 7396, "text": "Check if every row in given Matrix contains all the integers from 1 to N" }, { "code": null, "e": 7539, "s": 7469, "text": "Maximum count of adjacent pairs with even sum in given Circular Array" }, { "code": null, "e": 7605, "s": 7539, "text": "Find sum of the series 1! - 2! + 3! - 4! + 5! . . . till Nth term" }, { "code": null, "e": 7620, "s": 7605, "text": "Arrays in Java" }, { "code": null, "e": 7652, "s": 7620, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7668, "s": 7652, "text": "Arrays in C/C++" }, { "code": null, "e": 7774, "s": 7668, "text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array" } ]
Print all paths from a given source to a destination using BFS
03 Feb, 2022 Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’. Consider the following directed graph. Let the src be 2 and dst be 3. There are 3 different paths from 2 to 3. We have already discussed Print all paths from a given source to a destination using DFS.Below is BFS based solution. Algorithm : create a queue which will store path(s) of type vector initialise the queue with first path starting from src Now run a loop till queue is not empty get the frontmost path from queue check if the lastnode of this path is destination if true then print the path run a loop for all the vertices connected to the current vertex i.e. lastnode extracted from path if the vertex is not visited in current path a) create a new path from earlier path and append this vertex b) insert this new path to queue C++ Java Python3 C# // C++ program to print all paths of source to// destination in given graph#include <bits/stdc++.h>using namespace std; // utility function for printing// the found path in graphvoid printpath(vector<int>& path){ int size = path.size(); for (int i = 0; i < size; i++) cout << path[i] << " "; cout << endl;} // utility function to check if current// vertex is already present in pathint isNotVisited(int x, vector<int>& path){ int size = path.size(); for (int i = 0; i < size; i++) if (path[i] == x) return 0; return 1;} // utility function for finding paths in graph// from source to destinationvoid findpaths(vector<vector<int> >&g, int src, int dst, int v){ // create a queue which stores // the paths queue<vector<int> > q; // path vector to store the current path vector<int> path; path.push_back(src); q.push(path); while (!q.empty()) { path = q.front(); q.pop(); int last = path[path.size() - 1]; // if last vertex is the desired destination // then print the path if (last == dst) printpath(path); // traverse to all the nodes connected to // current vertex and push new path to queue for (int i = 0; i < g[last].size(); i++) { if (isNotVisited(g[last][i], path)) { vector<int> newpath(path); newpath.push_back(g[last][i]); q.push(newpath); } } }} // driver programint main(){ vector<vector<int> > g; // number of vertices int v = 4; g.resize(4); // construct a graph g[0].push_back(3); g[0].push_back(1); g[0].push_back(2); g[1].push_back(3); g[2].push_back(0); g[2].push_back(1); int src = 2, dst = 3; cout << "path from src " << src << " to dst " << dst << " are \n"; // function for finding the paths findpaths(g, src, dst, v); return 0;} // Java program to print all paths of source to// destination in given graphimport java.io.*;import java.util.*; class Graph{ // utility function for printing// the found path in graphprivate static void printPath(List<Integer> path){ int size = path.size(); for(Integer v : path) { System.out.print(v + " "); } System.out.println();} // Utility function to check if current// vertex is already present in pathprivate static boolean isNotVisited(int x, List<Integer> path){ int size = path.size(); for(int i = 0; i < size; i++) if (path.get(i) == x) return false; return true;} // Utility function for finding paths in graph// from source to destinationprivate static void findpaths(List<List<Integer> > g, int src, int dst, int v){ // Create a queue which stores // the paths Queue<List<Integer> > queue = new LinkedList<>(); // Path vector to store the current path List<Integer> path = new ArrayList<>(); path.add(src); queue.offer(path); while (!queue.isEmpty()) { path = queue.poll(); int last = path.get(path.size() - 1); // If last vertex is the desired destination // then print the path if (last == dst) { printPath(path); } // Traverse to all the nodes connected to // current vertex and push new path to queue List<Integer> lastNode = g.get(last); for(int i = 0; i < lastNode.size(); i++) { if (isNotVisited(lastNode.get(i), path)) { List<Integer> newpath = new ArrayList<>(path); newpath.add(lastNode.get(i)); queue.offer(newpath); } } }} // Driver codepublic static void main(String[] args){ List<List<Integer> > g = new ArrayList<>(); int v = 4; for(int i = 0; i < 4; i++) { g.add(new ArrayList<>()); } // Construct a graph g.get(0).add(3); g.get(0).add(1); g.get(0).add(2); g.get(1).add(3); g.get(2).add(0); g.get(2).add(1); int src = 2, dst = 3; System.out.println("path from src " + src + " to dst " + dst + " are "); // Function for finding the paths findpaths(g, src, dst, v);}} // This code is contributed by rajatsri94 # Python3 program to print all paths of# source to destination in given graphfrom typing import Listfrom collections import deque # Utility function for printing# the found path in graphdef printpath(path: List[int]) -> None: size = len(path) for i in range(size): print(path[i], end = " ") print() # Utility function to check if current# vertex is already present in pathdef isNotVisited(x: int, path: List[int]) -> int: size = len(path) for i in range(size): if (path[i] == x): return 0 return 1 # Utility function for finding paths in graph# from source to destinationdef findpaths(g: List[List[int]], src: int, dst: int, v: int) -> None: # Create a queue which stores # the paths q = deque() # Path vector to store the current path path = [] path.append(src) q.append(path.copy()) while q: path = q.popleft() last = path[len(path) - 1] # If last vertex is the desired destination # then print the path if (last == dst): printpath(path) # Traverse to all the nodes connected to # current vertex and push new path to queue for i in range(len(g[last])): if (isNotVisited(g[last][i], path)): newpath = path.copy() newpath.append(g[last][i]) q.append(newpath) # Driver codeif __name__ == "__main__": # Number of vertices v = 4 g = [[] for _ in range(4)] # Construct a graph g[0].append(3) g[0].append(1) g[0].append(2) g[1].append(3) g[2].append(0) g[2].append(1) src = 2 dst = 3 print("path from src {} to dst {} are".format( src, dst)) # Function for finding the paths findpaths(g, src, dst, v) # This code is contributed by sanjeev2552 // C# program to print all paths of source to// destination in given graph using System;using System.Collections.Generic; public class Graph{ // utility function for printing// the found path in graphstatic void printPath(List<int> path){ int size = path.Count; foreach(int v in path) { Console.Write(v + " "); } Console.WriteLine();} // Utility function to check if current// vertex is already present in pathstatic bool isNotVisited(int x, List<int> path){ int size = path.Count; for(int i = 0; i < size; i++) if (path[i] == x) return false; return true;} // Utility function for finding paths in graph// from source to destinationprivate static void findpaths(List<List<int> > g, int src, int dst, int v){ // Create a queue which stores // the paths Queue<List<int> > queue = new Queue<List<int>>(); // Path vector to store the current path List<int> path = new List<int>(); path.Add(src); queue.Enqueue(path); while (queue.Count!=0) { path = queue.Dequeue(); int last = path[path.Count - 1]; // If last vertex is the desired destination // then print the path if (last == dst) { printPath(path); } // Traverse to all the nodes connected to // current vertex and push new path to queue List<int> lastNode = g[last]; for(int i = 0; i < lastNode.Count; i++) { if (isNotVisited(lastNode[i], path)) { List<int> newpath = new List<int>(path); newpath.Add(lastNode[i]); queue.Enqueue(newpath); } } }} // Driver codepublic static void Main(String[] args){ List<List<int> > g = new List<List<int>>(); int v = 4; for(int i = 0; i < 4; i++) { g.Add(new List<int>()); } // Construct a graph g[0].Add(3); g[0].Add(1); g[0].Add(2); g[1].Add(3); g[2].Add(0); g[2].Add(1); int src = 2, dst = 3; Console.WriteLine("path from src " + src + " to dst " + dst + " are "); // Function for finding the paths findpaths(g, src, dst, v);}} // This code is contributed by shikhasingrajput Output: path from src 2 to dst 3 are 2 0 3 2 1 3 2 0 1 3 This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 rajatsri94 shikhasingrajput BFS Graph Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Detect Cycle in a Directed Graph Introduction to Data Structures Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Floyd Warshall Algorithm | DP-16 What is Data Structure: Types, Classifications and Applications Find if there is a path between two vertices in an undirected graph Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Feb, 2022" }, { "code": null, "e": 175, "s": 54, "text": "Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’." }, { "code": null, "e": 287, "s": 175, "text": "Consider the following directed graph. Let the src be 2 and dst be 3. There are 3 different paths from 2 to 3. " }, { "code": null, "e": 405, "s": 287, "text": "We have already discussed Print all paths from a given source to a destination using DFS.Below is BFS based solution." }, { "code": null, "e": 419, "s": 405, "text": "Algorithm : " }, { "code": null, "e": 976, "s": 419, "text": "create a queue which will store path(s) of type vector\ninitialise the queue with first path starting from src\n\nNow run a loop till queue is not empty\n get the frontmost path from queue\n check if the lastnode of this path is destination\n if true then print the path\n run a loop for all the vertices connected to the\n current vertex i.e. lastnode extracted from path\n if the vertex is not visited in current path\n a) create a new path from earlier path and \n append this vertex\n b) insert this new path to queue" }, { "code": null, "e": 980, "s": 976, "text": "C++" }, { "code": null, "e": 985, "s": 980, "text": "Java" }, { "code": null, "e": 993, "s": 985, "text": "Python3" }, { "code": null, "e": 996, "s": 993, "text": "C#" }, { "code": "// C++ program to print all paths of source to// destination in given graph#include <bits/stdc++.h>using namespace std; // utility function for printing// the found path in graphvoid printpath(vector<int>& path){ int size = path.size(); for (int i = 0; i < size; i++) cout << path[i] << \" \"; cout << endl;} // utility function to check if current// vertex is already present in pathint isNotVisited(int x, vector<int>& path){ int size = path.size(); for (int i = 0; i < size; i++) if (path[i] == x) return 0; return 1;} // utility function for finding paths in graph// from source to destinationvoid findpaths(vector<vector<int> >&g, int src, int dst, int v){ // create a queue which stores // the paths queue<vector<int> > q; // path vector to store the current path vector<int> path; path.push_back(src); q.push(path); while (!q.empty()) { path = q.front(); q.pop(); int last = path[path.size() - 1]; // if last vertex is the desired destination // then print the path if (last == dst) printpath(path); // traverse to all the nodes connected to // current vertex and push new path to queue for (int i = 0; i < g[last].size(); i++) { if (isNotVisited(g[last][i], path)) { vector<int> newpath(path); newpath.push_back(g[last][i]); q.push(newpath); } } }} // driver programint main(){ vector<vector<int> > g; // number of vertices int v = 4; g.resize(4); // construct a graph g[0].push_back(3); g[0].push_back(1); g[0].push_back(2); g[1].push_back(3); g[2].push_back(0); g[2].push_back(1); int src = 2, dst = 3; cout << \"path from src \" << src << \" to dst \" << dst << \" are \\n\"; // function for finding the paths findpaths(g, src, dst, v); return 0;}", "e": 2969, "s": 996, "text": null }, { "code": "// Java program to print all paths of source to// destination in given graphimport java.io.*;import java.util.*; class Graph{ // utility function for printing// the found path in graphprivate static void printPath(List<Integer> path){ int size = path.size(); for(Integer v : path) { System.out.print(v + \" \"); } System.out.println();} // Utility function to check if current// vertex is already present in pathprivate static boolean isNotVisited(int x, List<Integer> path){ int size = path.size(); for(int i = 0; i < size; i++) if (path.get(i) == x) return false; return true;} // Utility function for finding paths in graph// from source to destinationprivate static void findpaths(List<List<Integer> > g, int src, int dst, int v){ // Create a queue which stores // the paths Queue<List<Integer> > queue = new LinkedList<>(); // Path vector to store the current path List<Integer> path = new ArrayList<>(); path.add(src); queue.offer(path); while (!queue.isEmpty()) { path = queue.poll(); int last = path.get(path.size() - 1); // If last vertex is the desired destination // then print the path if (last == dst) { printPath(path); } // Traverse to all the nodes connected to // current vertex and push new path to queue List<Integer> lastNode = g.get(last); for(int i = 0; i < lastNode.size(); i++) { if (isNotVisited(lastNode.get(i), path)) { List<Integer> newpath = new ArrayList<>(path); newpath.add(lastNode.get(i)); queue.offer(newpath); } } }} // Driver codepublic static void main(String[] args){ List<List<Integer> > g = new ArrayList<>(); int v = 4; for(int i = 0; i < 4; i++) { g.add(new ArrayList<>()); } // Construct a graph g.get(0).add(3); g.get(0).add(1); g.get(0).add(2); g.get(1).add(3); g.get(2).add(0); g.get(2).add(1); int src = 2, dst = 3; System.out.println(\"path from src \" + src + \" to dst \" + dst + \" are \"); // Function for finding the paths findpaths(g, src, dst, v);}} // This code is contributed by rajatsri94", "e": 5378, "s": 2969, "text": null }, { "code": "# Python3 program to print all paths of# source to destination in given graphfrom typing import Listfrom collections import deque # Utility function for printing# the found path in graphdef printpath(path: List[int]) -> None: size = len(path) for i in range(size): print(path[i], end = \" \") print() # Utility function to check if current# vertex is already present in pathdef isNotVisited(x: int, path: List[int]) -> int: size = len(path) for i in range(size): if (path[i] == x): return 0 return 1 # Utility function for finding paths in graph# from source to destinationdef findpaths(g: List[List[int]], src: int, dst: int, v: int) -> None: # Create a queue which stores # the paths q = deque() # Path vector to store the current path path = [] path.append(src) q.append(path.copy()) while q: path = q.popleft() last = path[len(path) - 1] # If last vertex is the desired destination # then print the path if (last == dst): printpath(path) # Traverse to all the nodes connected to # current vertex and push new path to queue for i in range(len(g[last])): if (isNotVisited(g[last][i], path)): newpath = path.copy() newpath.append(g[last][i]) q.append(newpath) # Driver codeif __name__ == \"__main__\": # Number of vertices v = 4 g = [[] for _ in range(4)] # Construct a graph g[0].append(3) g[0].append(1) g[0].append(2) g[1].append(3) g[2].append(0) g[2].append(1) src = 2 dst = 3 print(\"path from src {} to dst {} are\".format( src, dst)) # Function for finding the paths findpaths(g, src, dst, v) # This code is contributed by sanjeev2552", "e": 7234, "s": 5378, "text": null }, { "code": "// C# program to print all paths of source to// destination in given graph using System;using System.Collections.Generic; public class Graph{ // utility function for printing// the found path in graphstatic void printPath(List<int> path){ int size = path.Count; foreach(int v in path) { Console.Write(v + \" \"); } Console.WriteLine();} // Utility function to check if current// vertex is already present in pathstatic bool isNotVisited(int x, List<int> path){ int size = path.Count; for(int i = 0; i < size; i++) if (path[i] == x) return false; return true;} // Utility function for finding paths in graph// from source to destinationprivate static void findpaths(List<List<int> > g, int src, int dst, int v){ // Create a queue which stores // the paths Queue<List<int> > queue = new Queue<List<int>>(); // Path vector to store the current path List<int> path = new List<int>(); path.Add(src); queue.Enqueue(path); while (queue.Count!=0) { path = queue.Dequeue(); int last = path[path.Count - 1]; // If last vertex is the desired destination // then print the path if (last == dst) { printPath(path); } // Traverse to all the nodes connected to // current vertex and push new path to queue List<int> lastNode = g[last]; for(int i = 0; i < lastNode.Count; i++) { if (isNotVisited(lastNode[i], path)) { List<int> newpath = new List<int>(path); newpath.Add(lastNode[i]); queue.Enqueue(newpath); } } }} // Driver codepublic static void Main(String[] args){ List<List<int> > g = new List<List<int>>(); int v = 4; for(int i = 0; i < 4; i++) { g.Add(new List<int>()); } // Construct a graph g[0].Add(3); g[0].Add(1); g[0].Add(2); g[1].Add(3); g[2].Add(0); g[2].Add(1); int src = 2, dst = 3; Console.WriteLine(\"path from src \" + src + \" to dst \" + dst + \" are \"); // Function for finding the paths findpaths(g, src, dst, v);}} // This code is contributed by shikhasingrajput", "e": 9534, "s": 7234, "text": null }, { "code": null, "e": 9543, "s": 9534, "text": "Output: " }, { "code": null, "e": 9595, "s": 9543, "text": "path from src 2 to dst 3 are \n2 0 3 \n2 1 3 \n2 0 1 3" }, { "code": null, "e": 10017, "s": 9595, "text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10029, "s": 10017, "text": "sanjeev2552" }, { "code": null, "e": 10040, "s": 10029, "text": "rajatsri94" }, { "code": null, "e": 10057, "s": 10040, "text": "shikhasingrajput" }, { "code": null, "e": 10061, "s": 10057, "text": "BFS" }, { "code": null, "e": 10067, "s": 10061, "text": "Graph" }, { "code": null, "e": 10073, "s": 10067, "text": "Graph" }, { "code": null, "e": 10077, "s": 10073, "text": "BFS" }, { "code": null, "e": 10175, "s": 10077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10195, "s": 10175, "text": "Topological Sorting" }, { "code": null, "e": 10260, "s": 10195, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 10318, "s": 10260, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 10351, "s": 10318, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 10383, "s": 10351, "text": "Introduction to Data Structures" }, { "code": null, "e": 10458, "s": 10383, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 10491, "s": 10458, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 10555, "s": 10491, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 10623, "s": 10555, "text": "Find if there is a path between two vertices in an undirected graph" } ]
Find the first non-repeating character from a stream of characters
24 Jun, 2022 Given a stream of characters, find the first non-repeating character from the stream. You need to tell the first non-repeating character in O(1) time at any moment. If we follow the first approach discussed here, then we need to store the stream so that we can traverse it one more time to find the first non-repeating character at any moment. If we use the extended approach discussed in the same post, we need to go through the count array every time the first non-repeating element is queried. We can find the first non-repeating character from the stream at any moment without traversing any array. The idea is to use a DLL (Doubly Linked List) to efficiently get the first non-repeating character from a stream. The DLL contains all non-repeating characters in order, i.e., the head of DLL contains first non-repeating character, the second node contains the second non-repeating, and so on. We also maintain two arrays: one array is to maintain characters that are already visited two or more times, we call it repeated[], the other array is an array of pointers to linked list nodes, we call it inDLL[]. The size of both arrays is equal to alphabet size which is typically 256. Create an empty DLL. Also, create two arrays inDLL[] and repeated[] of size 256. In DLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x] is true if x is repeated two or more times, otherwise false. inDLL[x] contains a pointer to a DLL node if character x is present in DLL, otherwise NULL.Initialize all entries of inDLL[] as NULL and repeated[] as false.To get the first non-repeating character, return character at the head of DLL.Following are steps to process a new character ‘x’ in a stream. If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream)If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x].If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true. Create an empty DLL. Also, create two arrays inDLL[] and repeated[] of size 256. In DLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x] is true if x is repeated two or more times, otherwise false. inDLL[x] contains a pointer to a DLL node if character x is present in DLL, otherwise NULL. Initialize all entries of inDLL[] as NULL and repeated[] as false. To get the first non-repeating character, return character at the head of DLL. Following are steps to process a new character ‘x’ in a stream. If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream)If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x].If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true. If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream) If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x]. If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true. Note that appending a new node to DLL is O(1) operation if we maintain a tail pointer. Removing a node from DLL is also O(1). So both operations, addition of new character and finding first non-repeating character take O(1) time. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // A C++ program to find first// non-repeating character// from a stream of characters#include <iostream>#define MAX_CHAR 256using namespace std; // A linked list nodestruct node { char a; struct node *next, *prev;}; // A utility function to append a character x at the end// of DLL. Note that the function may change head and tail// pointers, that is why pointers to these pointers are// passed.void appendNode(struct node** head_ref, struct node** tail_ref, char x){ struct node* temp = new node; temp->a = x; temp->prev = temp->next = NULL; if (*head_ref == NULL) { *head_ref = *tail_ref = temp; return; } (*tail_ref)->next = temp; temp->prev = *tail_ref; *tail_ref = temp;} // A utility function to remove a node 'temp' from DLL.// Note that the function may change the head and tail pointers,// that is why pointers to these pointers are passed.void removeNode(struct node** head_ref, struct node** tail_ref, struct node* temp){ if (*head_ref == NULL) return; if (*head_ref == temp) *head_ref = (*head_ref)->next; if (*tail_ref == temp) *tail_ref = (*tail_ref)->prev; if (temp->next != NULL) temp->next->prev = temp->prev; if (temp->prev != NULL) temp->prev->next = temp->next; delete (temp);} void findFirstNonRepeating(){ // inDLL[x] contains pointer to // a DLL node if x is present // in DLL. If x is not present, then inDLL[x] is NULL struct node* inDLL[MAX_CHAR]; // repeated[x] is true if x is repeated two or more // times. If x is not seen so far or x is seen only // once. then repeated[x] is false bool repeated[MAX_CHAR]; // Initialize the above two arrays struct node *head = NULL, *tail = NULL; for (int i = 0; i < MAX_CHAR; i++) { inDLL[i] = NULL; repeated[i] = false; } // Let us consider following stream and see the process char stream[] = "geeksforgeeksandgeeksquizfor"; for (int i = 0; stream[i]; i++) { char x = stream[i]; cout << "Reading " << x << " from stream \n"; // We process this character only if it has not // occurred or occurred only once. repeated[x] is // true if x is repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add this // at the end of DLL. if (inDLL[x] == NULL) { appendNode(&head, &tail, stream[i]); inDLL[x] = tail; } else // Otherwise remove this character from DLL { removeNode(&head, &tail, inDLL[x]); inDLL[x] = NULL; repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating character // from stream if (head != NULL) cout << "First non-repeating character so far " "is " << head->a << endl; }} /* Driver code */int main(){ findFirstNonRepeating(); return 0;} // A Java program to find first non-repeating character// from a stream of characters import java.util.ArrayList;import java.util.List; public class NonReapeatingC { final static int MAX_CHAR = 256; static void findFirstNonRepeating() { // inDLL[x] contains pointer to a DLL node if x is // present in DLL. If x is not present, then // inDLL[x] is NULL List<Character> inDLL = new ArrayList<Character>(); // repeated[x] is true if x is repeated two or more // times. If x is not seen so far or x is seen only // once. then repeated[x] is false boolean[] repeated = new boolean[MAX_CHAR]; // Let us consider following stream and see the // process String stream = "geeksforgeeksandgeeksquizfor"; for (int i = 0; i < stream.length(); i++) { char x = stream.charAt(i); System.out.println("Reading " + x + " from stream \n"); // We process this character only if it has not // occurred or occurred only once. repeated[x] // is true if x is repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add // this at the end of DLL. if (!(inDLL.contains(x))) { inDLL.add(x); } else // Otherwise remove this character from // DLL { inDLL.remove((Character)x); repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating // character from stream if (inDLL.size() != 0) { System.out.print( "First non-repeating character so far is "); System.out.println(inDLL.get(0)); } } } /* Driver code */ public static void main(String[] args) { findFirstNonRepeating(); }}// This code is contributed by Sumit Ghosh # A Python program to find first non-repeating character from# a stream of charactersMAX_CHAR = 256 def findFirstNonRepeating(): # inDLL[x] contains pointer to a DLL node if x is present # in DLL. If x is not present, then inDLL[x] is NULL inDLL = [] * MAX_CHAR # repeated[x] is true if x is repeated two or more times. # If x is not seen so far or x is seen only once. then # repeated[x] is false repeated = [False] * MAX_CHAR # Let us consider following stream and see the process stream = "geekforgeekandgeeksandquizfor" for i in range(len(stream)): x = stream[i] print ("Reading " + x + " from stream") # We process this character only if it has not occurred # or occurred only once. repeated[x] is true if x is # repeated twice or more.s if not repeated[ord(x)]: # If the character is not in DLL, then add this # at the end of DLL if not x in inDLL: inDLL.append(x) else: inDLL.remove(x) repeated[ord(x)] = True if len(inDLL) != 0: print ("First non-repeating character so far is ") print (str(inDLL[0])) # Driver programfindFirstNonRepeating() # This code is contributed by BHAVYA JAIN // A C# program to find first non-repeating character// from a stream of charactersusing System;using System.Collections.Generic; public class NonReapeatingC { readonly static int MAX_CHAR = 256; static void findFirstNonRepeating() { // inDLL[x] contains pointer to a DLL node if x is present // in DLL. If x is not present, then inDLL[x] is NULL List<char> inDLL = new List<char>(); // repeated[x] is true if x is repeated two or more times. // If x is not seen so far or x is seen only once. then // repeated[x] is false bool[] repeated = new bool[MAX_CHAR]; // Let us consider following stream and see the process String stream = "geeksforgeeksandgeeksquizfor"; for (int i = 0; i < stream.Length; i++) { char x = stream[i]; Console.WriteLine("Reading " + x + " from stream \n"); // We process this character only if it has not occurred // or occurred only once. repeated[x] is true if x is // repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add this at // the end of DLL. if (!(inDLL.Contains(x))) { inDLL.Add(x); } else // Otherwise remove this character from DLL { inDLL.Remove((char)x); repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating character from // stream if (inDLL.Count != 0) { Console.Write("First non-repeating character so far is "); Console.WriteLine(inDLL[0]); } } } /* Driver code*/ public static void Main(String[] args) { findFirstNonRepeating(); }} // This code has been contributed by 29AjayKumar <script> // A Javascript program to find first // non-repeating character from a// stream of characterslet MAX_CHAR = 256; function findFirstNonRepeating(){ // inDLL[x] contains pointer to a DLL // node if x is present in DLL. If x // is not present, then inDLL[x] is NULL let inDLL = []; // repeated[x] is true if x is repeated // two or more times. If x is not seen // so far or x is seen only once. // then repeated[x] is false let repeated = new Array(MAX_CHAR); for(let i = 0; i < MAX_CHAR; i++) { repeated[i] = false; } // Let us consider following stream and see the // process let stream = "geeksforgeeksandgeeksquizfor"; for(let i = 0; i < stream.length; i++) { let x = stream[i]; document.write("Reading " + x + " from stream <br>"); // We process this character only if it has not // occurred or occurred only once. repeated[x] // is true if x is repeated twice or more.s if (!repeated[x.charCodeAt(0)]) { // If the character is not in DLL, then add // this at the end of DLL. if (!(inDLL.includes(x))) { inDLL.push(x); } // Otherwise remove this character from // DLL else { inDLL.splice(inDLL.indexOf(x), 1); // Also mark it as repeated repeated[x.charCodeAt(0)] = true; } } // Print the current first non-repeating // character from stream if (inDLL.length != 0) { document.write("First non-repeating " + "character so far is "); document.write(inDLL[0] + "<br>"); } }} // Driver code findFirstNonRepeating(); // This code is contributed by rag2127 </script> Output: Reading g from stream First non-repeating character so far is g Reading e from stream First non-repeating character so far is g Reading e from stream First non-repeating character so far is g Reading k from stream First non-repeating character so far is g Reading s from stream First non-repeating character so far is g Reading f from stream First non-repeating character so far is g Reading o from stream First non-repeating character so far is g Reading r from stream First non-repeating character so far is g Reading g from stream First non-repeating character so far is k Reading e from stream First non-repeating character so far is k Reading e from stream First non-repeating character so far is k Reading k from stream First non-repeating character so far is s Reading s from stream First non-repeating character so far is f Reading a from stream First non-repeating character so far is f Reading n from stream First non-repeating character so far is f Reading d from stream First non-repeating character so far is f Reading g from stream First non-repeating character so far is f Reading e from stream First non-repeating character so far is f Reading e from stream First non-repeating character so far is f Reading k from stream First non-repeating character so far is f Reading s from stream First non-repeating character so far is f Reading q from stream First non-repeating character so far is f Reading u from stream First non-repeating character so far is f Reading i from stream First non-repeating character so far is f Reading z from stream First non-repeating character so far is f Reading f from stream First non-repeating character so far is o Reading o from stream First non-repeating character so far is r Reading r from stream First non-repeating character so far is a Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Amit Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar RaviParkash officialshivsagar rag2127 kumaripunam984122 akashish__ Amazon array-stream FactSet Flipkart Microsoft Payu Yahoo Hash Linked List Python Queue Strings Flipkart Amazon Microsoft FactSet Payu Yahoo Linked List Hash Strings Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Hashing | Set 1 (Introduction) Internal Working of HashMap in Java Longest Consecutive Subsequence Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 217, "s": 52, "text": "Given a stream of characters, find the first non-repeating character from the stream. You need to tell the first non-repeating character in O(1) time at any moment." }, { "code": null, "e": 656, "s": 217, "text": "If we follow the first approach discussed here, then we need to store the stream so that we can traverse it one more time to find the first non-repeating character at any moment. If we use the extended approach discussed in the same post, we need to go through the count array every time the first non-repeating element is queried. We can find the first non-repeating character from the stream at any moment without traversing any array. " }, { "code": null, "e": 951, "s": 656, "text": "The idea is to use a DLL (Doubly Linked List) to efficiently get the first non-repeating character from a stream. The DLL contains all non-repeating characters in order, i.e., the head of DLL contains first non-repeating character, the second node contains the second non-repeating, and so on. " }, { "code": null, "e": 1239, "s": 951, "text": "We also maintain two arrays: one array is to maintain characters that are already visited two or more times, we call it repeated[], the other array is an array of pointers to linked list nodes, we call it inDLL[]. The size of both arrays is equal to alphabet size which is typically 256." }, { "code": null, "e": 2187, "s": 1239, "text": "Create an empty DLL. Also, create two arrays inDLL[] and repeated[] of size 256. In DLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x] is true if x is repeated two or more times, otherwise false. inDLL[x] contains a pointer to a DLL node if character x is present in DLL, otherwise NULL.Initialize all entries of inDLL[] as NULL and repeated[] as false.To get the first non-repeating character, return character at the head of DLL.Following are steps to process a new character ‘x’ in a stream. If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream)If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x].If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true." }, { "code": null, "e": 2509, "s": 2187, "text": "Create an empty DLL. Also, create two arrays inDLL[] and repeated[] of size 256. In DLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x] is true if x is repeated two or more times, otherwise false. inDLL[x] contains a pointer to a DLL node if character x is present in DLL, otherwise NULL." }, { "code": null, "e": 2576, "s": 2509, "text": "Initialize all entries of inDLL[] as NULL and repeated[] as false." }, { "code": null, "e": 2655, "s": 2576, "text": "To get the first non-repeating character, return character at the head of DLL." }, { "code": null, "e": 3138, "s": 2655, "text": "Following are steps to process a new character ‘x’ in a stream. If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream)If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x].If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true." }, { "code": null, "e": 3240, "s": 3138, "text": "If repeated[x] is true, ignore this character (x is already repeated two or more times in the stream)" }, { "code": null, "e": 3376, "s": 3240, "text": "If repeated[x] is false and inDLL[x] is NULL (x is seen the first time). Append x to DLL and store address of new DLL node in inDLL[x]." }, { "code": null, "e": 3559, "s": 3376, "text": "If repeated[x] is false and inDLL[x] is not NULL (x is seen a second time). Get DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as NULL and repeated[x] as true." }, { "code": null, "e": 3789, "s": 3559, "text": "Note that appending a new node to DLL is O(1) operation if we maintain a tail pointer. Removing a node from DLL is also O(1). So both operations, addition of new character and finding first non-repeating character take O(1) time." }, { "code": null, "e": 3838, "s": 3789, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 3889, "s": 3838, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3893, "s": 3889, "text": "C++" }, { "code": null, "e": 3898, "s": 3893, "text": "Java" }, { "code": null, "e": 3906, "s": 3898, "text": "Python3" }, { "code": null, "e": 3909, "s": 3906, "text": "C#" }, { "code": null, "e": 3920, "s": 3909, "text": "Javascript" }, { "code": "// A C++ program to find first// non-repeating character// from a stream of characters#include <iostream>#define MAX_CHAR 256using namespace std; // A linked list nodestruct node { char a; struct node *next, *prev;}; // A utility function to append a character x at the end// of DLL. Note that the function may change head and tail// pointers, that is why pointers to these pointers are// passed.void appendNode(struct node** head_ref, struct node** tail_ref, char x){ struct node* temp = new node; temp->a = x; temp->prev = temp->next = NULL; if (*head_ref == NULL) { *head_ref = *tail_ref = temp; return; } (*tail_ref)->next = temp; temp->prev = *tail_ref; *tail_ref = temp;} // A utility function to remove a node 'temp' from DLL.// Note that the function may change the head and tail pointers,// that is why pointers to these pointers are passed.void removeNode(struct node** head_ref, struct node** tail_ref, struct node* temp){ if (*head_ref == NULL) return; if (*head_ref == temp) *head_ref = (*head_ref)->next; if (*tail_ref == temp) *tail_ref = (*tail_ref)->prev; if (temp->next != NULL) temp->next->prev = temp->prev; if (temp->prev != NULL) temp->prev->next = temp->next; delete (temp);} void findFirstNonRepeating(){ // inDLL[x] contains pointer to // a DLL node if x is present // in DLL. If x is not present, then inDLL[x] is NULL struct node* inDLL[MAX_CHAR]; // repeated[x] is true if x is repeated two or more // times. If x is not seen so far or x is seen only // once. then repeated[x] is false bool repeated[MAX_CHAR]; // Initialize the above two arrays struct node *head = NULL, *tail = NULL; for (int i = 0; i < MAX_CHAR; i++) { inDLL[i] = NULL; repeated[i] = false; } // Let us consider following stream and see the process char stream[] = \"geeksforgeeksandgeeksquizfor\"; for (int i = 0; stream[i]; i++) { char x = stream[i]; cout << \"Reading \" << x << \" from stream \\n\"; // We process this character only if it has not // occurred or occurred only once. repeated[x] is // true if x is repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add this // at the end of DLL. if (inDLL[x] == NULL) { appendNode(&head, &tail, stream[i]); inDLL[x] = tail; } else // Otherwise remove this character from DLL { removeNode(&head, &tail, inDLL[x]); inDLL[x] = NULL; repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating character // from stream if (head != NULL) cout << \"First non-repeating character so far \" \"is \" << head->a << endl; }} /* Driver code */int main(){ findFirstNonRepeating(); return 0;}", "e": 7010, "s": 3920, "text": null }, { "code": "// A Java program to find first non-repeating character// from a stream of characters import java.util.ArrayList;import java.util.List; public class NonReapeatingC { final static int MAX_CHAR = 256; static void findFirstNonRepeating() { // inDLL[x] contains pointer to a DLL node if x is // present in DLL. If x is not present, then // inDLL[x] is NULL List<Character> inDLL = new ArrayList<Character>(); // repeated[x] is true if x is repeated two or more // times. If x is not seen so far or x is seen only // once. then repeated[x] is false boolean[] repeated = new boolean[MAX_CHAR]; // Let us consider following stream and see the // process String stream = \"geeksforgeeksandgeeksquizfor\"; for (int i = 0; i < stream.length(); i++) { char x = stream.charAt(i); System.out.println(\"Reading \" + x + \" from stream \\n\"); // We process this character only if it has not // occurred or occurred only once. repeated[x] // is true if x is repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add // this at the end of DLL. if (!(inDLL.contains(x))) { inDLL.add(x); } else // Otherwise remove this character from // DLL { inDLL.remove((Character)x); repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating // character from stream if (inDLL.size() != 0) { System.out.print( \"First non-repeating character so far is \"); System.out.println(inDLL.get(0)); } } } /* Driver code */ public static void main(String[] args) { findFirstNonRepeating(); }}// This code is contributed by Sumit Ghosh", "e": 9104, "s": 7010, "text": null }, { "code": "# A Python program to find first non-repeating character from# a stream of charactersMAX_CHAR = 256 def findFirstNonRepeating(): # inDLL[x] contains pointer to a DLL node if x is present # in DLL. If x is not present, then inDLL[x] is NULL inDLL = [] * MAX_CHAR # repeated[x] is true if x is repeated two or more times. # If x is not seen so far or x is seen only once. then # repeated[x] is false repeated = [False] * MAX_CHAR # Let us consider following stream and see the process stream = \"geekforgeekandgeeksandquizfor\" for i in range(len(stream)): x = stream[i] print (\"Reading \" + x + \" from stream\") # We process this character only if it has not occurred # or occurred only once. repeated[x] is true if x is # repeated twice or more.s if not repeated[ord(x)]: # If the character is not in DLL, then add this # at the end of DLL if not x in inDLL: inDLL.append(x) else: inDLL.remove(x) repeated[ord(x)] = True if len(inDLL) != 0: print (\"First non-repeating character so far is \") print (str(inDLL[0])) # Driver programfindFirstNonRepeating() # This code is contributed by BHAVYA JAIN", "e": 10401, "s": 9104, "text": null }, { "code": "// A C# program to find first non-repeating character// from a stream of charactersusing System;using System.Collections.Generic; public class NonReapeatingC { readonly static int MAX_CHAR = 256; static void findFirstNonRepeating() { // inDLL[x] contains pointer to a DLL node if x is present // in DLL. If x is not present, then inDLL[x] is NULL List<char> inDLL = new List<char>(); // repeated[x] is true if x is repeated two or more times. // If x is not seen so far or x is seen only once. then // repeated[x] is false bool[] repeated = new bool[MAX_CHAR]; // Let us consider following stream and see the process String stream = \"geeksforgeeksandgeeksquizfor\"; for (int i = 0; i < stream.Length; i++) { char x = stream[i]; Console.WriteLine(\"Reading \" + x + \" from stream \\n\"); // We process this character only if it has not occurred // or occurred only once. repeated[x] is true if x is // repeated twice or more.s if (!repeated[x]) { // If the character is not in DLL, then add this at // the end of DLL. if (!(inDLL.Contains(x))) { inDLL.Add(x); } else // Otherwise remove this character from DLL { inDLL.Remove((char)x); repeated[x] = true; // Also mark it as repeated } } // Print the current first non-repeating character from // stream if (inDLL.Count != 0) { Console.Write(\"First non-repeating character so far is \"); Console.WriteLine(inDLL[0]); } } } /* Driver code*/ public static void Main(String[] args) { findFirstNonRepeating(); }} // This code has been contributed by 29AjayKumar", "e": 12337, "s": 10401, "text": null }, { "code": "<script> // A Javascript program to find first // non-repeating character from a// stream of characterslet MAX_CHAR = 256; function findFirstNonRepeating(){ // inDLL[x] contains pointer to a DLL // node if x is present in DLL. If x // is not present, then inDLL[x] is NULL let inDLL = []; // repeated[x] is true if x is repeated // two or more times. If x is not seen // so far or x is seen only once. // then repeated[x] is false let repeated = new Array(MAX_CHAR); for(let i = 0; i < MAX_CHAR; i++) { repeated[i] = false; } // Let us consider following stream and see the // process let stream = \"geeksforgeeksandgeeksquizfor\"; for(let i = 0; i < stream.length; i++) { let x = stream[i]; document.write(\"Reading \" + x + \" from stream <br>\"); // We process this character only if it has not // occurred or occurred only once. repeated[x] // is true if x is repeated twice or more.s if (!repeated[x.charCodeAt(0)]) { // If the character is not in DLL, then add // this at the end of DLL. if (!(inDLL.includes(x))) { inDLL.push(x); } // Otherwise remove this character from // DLL else { inDLL.splice(inDLL.indexOf(x), 1); // Also mark it as repeated repeated[x.charCodeAt(0)] = true; } } // Print the current first non-repeating // character from stream if (inDLL.length != 0) { document.write(\"First non-repeating \" + \"character so far is \"); document.write(inDLL[0] + \"<br>\"); } }} // Driver code findFirstNonRepeating(); // This code is contributed by rag2127 </script>", "e": 14280, "s": 12337, "text": null }, { "code": null, "e": 14289, "s": 14280, "text": "Output: " }, { "code": null, "e": 16081, "s": 14289, "text": "Reading g from stream\nFirst non-repeating character so far is g\nReading e from stream\nFirst non-repeating character so far is g\nReading e from stream\nFirst non-repeating character so far is g\nReading k from stream\nFirst non-repeating character so far is g\nReading s from stream\nFirst non-repeating character so far is g\nReading f from stream\nFirst non-repeating character so far is g\nReading o from stream\nFirst non-repeating character so far is g\nReading r from stream\nFirst non-repeating character so far is g\nReading g from stream\nFirst non-repeating character so far is k\nReading e from stream\nFirst non-repeating character so far is k\nReading e from stream\nFirst non-repeating character so far is k\nReading k from stream\nFirst non-repeating character so far is s\nReading s from stream\nFirst non-repeating character so far is f\nReading a from stream\nFirst non-repeating character so far is f\nReading n from stream\nFirst non-repeating character so far is f\nReading d from stream\nFirst non-repeating character so far is f\nReading g from stream\nFirst non-repeating character so far is f\nReading e from stream\nFirst non-repeating character so far is f\nReading e from stream\nFirst non-repeating character so far is f\nReading k from stream\nFirst non-repeating character so far is f\nReading s from stream\nFirst non-repeating character so far is f\nReading q from stream\nFirst non-repeating character so far is f\nReading u from stream\nFirst non-repeating character so far is f\nReading i from stream\nFirst non-repeating character so far is f\nReading z from stream\nFirst non-repeating character so far is f\nReading f from stream\nFirst non-repeating character so far is o\nReading o from stream\nFirst non-repeating character so far is r\nReading r from stream\nFirst non-repeating character so far is a" }, { "code": null, "e": 16103, "s": 16081, "text": "Time Complexity: O(n)" }, { "code": null, "e": 16125, "s": 16103, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 16293, "s": 16125, "text": "This article is contributed by Amit Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 16305, "s": 16293, "text": "29AjayKumar" }, { "code": null, "e": 16317, "s": 16305, "text": "RaviParkash" }, { "code": null, "e": 16335, "s": 16317, "text": "officialshivsagar" }, { "code": null, "e": 16343, "s": 16335, "text": "rag2127" }, { "code": null, "e": 16361, "s": 16343, "text": "kumaripunam984122" }, { "code": null, "e": 16372, "s": 16361, "text": "akashish__" }, { "code": null, "e": 16379, "s": 16372, "text": "Amazon" }, { "code": null, "e": 16392, "s": 16379, "text": "array-stream" }, { "code": null, "e": 16400, "s": 16392, "text": "FactSet" }, { "code": null, "e": 16409, "s": 16400, "text": "Flipkart" }, { "code": null, "e": 16419, "s": 16409, "text": "Microsoft" }, { "code": null, "e": 16424, "s": 16419, "text": "Payu" }, { "code": null, "e": 16430, "s": 16424, "text": "Yahoo" }, { "code": null, "e": 16435, "s": 16430, "text": "Hash" }, { "code": null, "e": 16447, "s": 16435, "text": "Linked List" }, { "code": null, "e": 16454, "s": 16447, "text": "Python" }, { "code": null, "e": 16460, "s": 16454, "text": "Queue" }, { "code": null, "e": 16468, "s": 16460, "text": "Strings" }, { "code": null, "e": 16477, "s": 16468, "text": "Flipkart" }, { "code": null, "e": 16484, "s": 16477, "text": "Amazon" }, { "code": null, "e": 16494, "s": 16484, "text": "Microsoft" }, { "code": null, "e": 16502, "s": 16494, "text": "FactSet" }, { "code": null, "e": 16507, "s": 16502, "text": "Payu" }, { "code": null, "e": 16513, "s": 16507, "text": "Yahoo" }, { "code": null, "e": 16525, "s": 16513, "text": "Linked List" }, { "code": null, "e": 16530, "s": 16525, "text": "Hash" }, { "code": null, "e": 16538, "s": 16530, "text": "Strings" }, { "code": null, "e": 16544, "s": 16538, "text": "Queue" }, { "code": null, "e": 16642, "s": 16544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16727, "s": 16642, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 16765, "s": 16727, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16796, "s": 16765, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 16832, "s": 16796, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 16864, "s": 16832, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 16899, "s": 16864, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 16938, "s": 16899, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 16960, "s": 16938, "text": "Reverse a linked list" }, { "code": null, "e": 17008, "s": 16960, "text": "Stack Data Structure (Introduction and Program)" } ]
Tensorflow.js tf.browser.fromPixels() Function
21 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.browser.fromPixels() function is used to creates a Tensor of pixels values of an specified image. Syntax: tf.browser.fromPixels (pixels, numChannels) Parameters: This function accepts two parameters which are illustrated below: pixels: It is the pixels of the input image from which the Tensor is going to be constructed. The supported image types are all 4-channel. numchannels: It is the number of channels of the output Tensor. It’s default value is 3 and the upper limit is up to 4. Return Value: This function returns the created Tensor of pixels values of the specified image. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating a image from some specified// pixel valuesconst image = new ImageData(2, 2);image.data[0] = 5;image.data[1] = 10;image.data[2] = 15;image.data[3] = 20; // Calling the .fromPixels() function // over the above image as its parameter// without using numChannels value,so// it prints only 3 pixels value as// the default value of numchannels // parameter is 3tf.browser.fromPixels(image).print(); Output: Tensor [[[5, 10, 15], [0, 0 , 0 ]], [[0, 0 , 0 ], [0, 0 , 0 ]]] Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating a image from some specified// pixels valuesconst image = new ImageData(1, 1);image.data[0] = 5;image.data[1] = 10;image.data[2] = 15;image.data[3] = 20; // Calling the .fromPixels() function // over the above image as its parameter// along with 4 value for numChannels parametertf.browser.fromPixels(image, 4).print(); Output: Tensor [ [[5, 10, 15, 20],]] Reference:https://js.tensorflow.org/api/1.0.0/#browser.fromPixels Picked Tensorflow Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2021" }, { "code": null, "e": 194, "s": 28, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 300, "s": 194, "text": "The tf.browser.fromPixels() function is used to creates a Tensor of pixels values of an specified image. " }, { "code": null, "e": 308, "s": 300, "text": "Syntax:" }, { "code": null, "e": 352, "s": 308, "text": "tf.browser.fromPixels (pixels, numChannels)" }, { "code": null, "e": 430, "s": 352, "text": "Parameters: This function accepts two parameters which are illustrated below:" }, { "code": null, "e": 569, "s": 430, "text": "pixels: It is the pixels of the input image from which the Tensor is going to be constructed. The supported image types are all 4-channel." }, { "code": null, "e": 689, "s": 569, "text": "numchannels: It is the number of channels of the output Tensor. It’s default value is 3 and the upper limit is up to 4." }, { "code": null, "e": 786, "s": 689, "text": "Return Value: This function returns the created Tensor of pixels values of the specified image. " }, { "code": null, "e": 797, "s": 786, "text": "Example 1:" }, { "code": null, "e": 808, "s": 797, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Creating a image from some specified// pixel valuesconst image = new ImageData(2, 2);image.data[0] = 5;image.data[1] = 10;image.data[2] = 15;image.data[3] = 20; // Calling the .fromPixels() function // over the above image as its parameter// without using numChannels value,so// it prints only 3 pixels value as// the default value of numchannels // parameter is 3tf.browser.fromPixels(image).print();", "e": 1292, "s": 808, "text": null }, { "code": null, "e": 1300, "s": 1292, "text": "Output:" }, { "code": null, "e": 1382, "s": 1300, "text": "Tensor\n [[[5, 10, 15],\n [0, 0 , 0 ]],\n\n [[0, 0 , 0 ],\n [0, 0 , 0 ]]]" }, { "code": null, "e": 1393, "s": 1382, "text": "Example 2:" }, { "code": null, "e": 1404, "s": 1393, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Creating a image from some specified// pixels valuesconst image = new ImageData(1, 1);image.data[0] = 5;image.data[1] = 10;image.data[2] = 15;image.data[3] = 20; // Calling the .fromPixels() function // over the above image as its parameter// along with 4 value for numChannels parametertf.browser.fromPixels(image, 4).print();", "e": 1814, "s": 1404, "text": null }, { "code": null, "e": 1822, "s": 1814, "text": "Output:" }, { "code": null, "e": 1855, "s": 1822, "text": "Tensor\n [ [[5, 10, 15, 20],]]" }, { "code": null, "e": 1921, "s": 1855, "text": "Reference:https://js.tensorflow.org/api/1.0.0/#browser.fromPixels" }, { "code": null, "e": 1928, "s": 1921, "text": "Picked" }, { "code": null, "e": 1939, "s": 1928, "text": "Tensorflow" }, { "code": null, "e": 1953, "s": 1939, "text": "Tensorflow.js" }, { "code": null, "e": 1964, "s": 1953, "text": "JavaScript" }, { "code": null, "e": 1981, "s": 1964, "text": "Web Technologies" }, { "code": null, "e": 2079, "s": 1981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2140, "s": 2079, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2212, "s": 2140, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2252, "s": 2212, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2305, "s": 2252, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2357, "s": 2305, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2419, "s": 2357, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2452, "s": 2419, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2513, "s": 2452, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2563, "s": 2513, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
numpy.minimum() in Python
28 Nov, 2018 numpy.minimum() function is used to find the element-wise minimum of array elements. It compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. Syntax : numpy.minimum(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘minimum’) Parameters :arr1 : [array_like] Input array.arr2 : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. Return : [ndarray or scalar] Result.The minimum of arr1 and arr2, element-wise. This is a scalar if both arr1 and arr2 are scalars. Code #1 : Working # Python program explaining# minimum() function import numpy as geekin_num1 = 10in_num2 = 21 print ("Input number1 : ", in_num1)print ("Input number2 : ", in_num2) out_num = geek.minimum(in_num1, in_num2) print ("minimum of 10 and 21 : ", out_num) Output : Input number1 : 10 Input number2 : 21 minimum of 10 and 21 : 10 Code #2 : # Python program explaining# minimum() function import numpy as geek in_arr1 = [2, 8, 125]in_arr2 = [3, 3, 15] print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2) out_arr = geek.minimum(in_arr1, in_arr2) print ("Output array after selecting minimum: ", out_arr) Output : Input array1 : [2, 8, 125] Input array2 : [3, 3, 15] Output array after selecting minimum: [ 2 3 15] Code #3 : # Python program explaining# minimum() function import numpy as geek in_arr1 = [geek.nan, 0, geek.nan]in_arr2 = [geek.nan, geek.nan, 0] print ("Input array1 : ", in_arr1) print ("Input array2 : ", in_arr2) out_arr = geek.minimum(in_arr1, in_arr2) print ("Output array after selecting minimum: ", out_arr) Output : Input array1 : [nan, 0, nan] Input array2 : [nan, nan, 0] Output array after selecting minimum: [ nan nan nan] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 113, "s": 28, "text": "numpy.minimum() function is used to find the element-wise minimum of array elements." }, { "code": null, "e": 328, "s": 113, "text": "It compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned." }, { "code": null, "e": 452, "s": 328, "text": "Syntax : numpy.minimum(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘minimum’)" }, { "code": null, "e": 1044, "s": 452, "text": "Parameters :arr1 : [array_like] Input array.arr2 : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone." }, { "code": null, "e": 1176, "s": 1044, "text": "Return : [ndarray or scalar] Result.The minimum of arr1 and arr2, element-wise. This is a scalar if both arr1 and arr2 are scalars." }, { "code": null, "e": 1194, "s": 1176, "text": "Code #1 : Working" }, { "code": "# Python program explaining# minimum() function import numpy as geekin_num1 = 10in_num2 = 21 print (\"Input number1 : \", in_num1)print (\"Input number2 : \", in_num2) out_num = geek.minimum(in_num1, in_num2) print (\"minimum of 10 and 21 : \", out_num) ", "e": 1451, "s": 1194, "text": null }, { "code": null, "e": 1460, "s": 1451, "text": "Output :" }, { "code": null, "e": 1530, "s": 1460, "text": "Input number1 : 10\nInput number2 : 21\nminimum of 10 and 21 : 10\n" }, { "code": null, "e": 1541, "s": 1530, "text": " Code #2 :" }, { "code": "# Python program explaining# minimum() function import numpy as geek in_arr1 = [2, 8, 125]in_arr2 = [3, 3, 15] print (\"Input array1 : \", in_arr1) print (\"Input array2 : \", in_arr2) out_arr = geek.minimum(in_arr1, in_arr2) print (\"Output array after selecting minimum: \", out_arr) ", "e": 1829, "s": 1541, "text": null }, { "code": null, "e": 1838, "s": 1829, "text": "Output :" }, { "code": null, "e": 1944, "s": 1838, "text": "Input array1 : [2, 8, 125]\nInput array2 : [3, 3, 15]\nOutput array after selecting minimum: [ 2 3 15]\n" }, { "code": null, "e": 1955, "s": 1944, "text": " Code #3 :" }, { "code": "# Python program explaining# minimum() function import numpy as geek in_arr1 = [geek.nan, 0, geek.nan]in_arr2 = [geek.nan, geek.nan, 0] print (\"Input array1 : \", in_arr1) print (\"Input array2 : \", in_arr2) out_arr = geek.minimum(in_arr1, in_arr2) print (\"Output array after selecting minimum: \", out_arr) ", "e": 2268, "s": 1955, "text": null }, { "code": null, "e": 2277, "s": 2268, "text": "Output :" }, { "code": null, "e": 2394, "s": 2277, "text": "Input array1 : [nan, 0, nan]\nInput array2 : [nan, nan, 0]\nOutput array after selecting minimum: [ nan nan nan]\n" }, { "code": null, "e": 2429, "s": 2394, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2442, "s": 2429, "text": "Python-numpy" }, { "code": null, "e": 2449, "s": 2442, "text": "Python" }, { "code": null, "e": 2547, "s": 2449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2565, "s": 2547, "text": "Python Dictionary" }, { "code": null, "e": 2607, "s": 2565, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2633, "s": 2607, "text": "Python String | replace()" }, { "code": null, "e": 2665, "s": 2633, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2694, "s": 2665, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2721, "s": 2694, "text": "Python Classes and Objects" }, { "code": null, "e": 2757, "s": 2721, "text": "Convert integer to string in Python" }, { "code": null, "e": 2778, "s": 2757, "text": "Python OOPs Concepts" }, { "code": null, "e": 2801, "s": 2778, "text": "Introduction To PYTHON" } ]
Python | Insert a number in string
25 Jun, 2019 Sometimes, while dealing with strings, we may encounter a problem in which we might have a numeric variable whose value keeps changing and we need to print the string including that number. Strings and numbers being different data types have to be solved in different ways. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using Type conversionThe simplest way in which this task can be performed is by converting the integer explicitly into string datatype using the basic type conversion and adding it to appropriate position. # Python3 code to demonstrate working of# Inserting a number in string # Using type conversion # initializing string test_str = "Geeks" # initializing numbertest_int = 4 # printing original string print("The original string is : " + test_str) # printing numberprint("The original number : " + str(test_int)) # using type conversion# Inserting number in string res = test_str + str(test_int) + test_str # printing result print("The string after adding number is : " + str(res)) The original string is : Geeks The original number : 4 The string after adding number is : Geeks4Geeks Method #2 : Using %d operatorThis operator can be used to format the string to add the integer. The “d” represents that the datatype to be inserted to string is an integer. This can be changed according to the requirements. # Python3 code to demonstrate working of# Inserting a number in string # Using % d operator # initializing string test_str = "Geeks" # initializing numbertest_int = 4 # printing original string print("The original string is : " + test_str) # printing numberprint("The original number : " + str(test_int)) # using % d operator# Inserting number in string res = (test_str + "% d" + test_str) % test_int # printing result print("The string after adding number is : " + str(res)) The original string is : Geeks The original number : 4 The string after adding number is : Geeks4Geeks Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Jun, 2019" }, { "code": null, "e": 391, "s": 53, "text": "Sometimes, while dealing with strings, we may encounter a problem in which we might have a numeric variable whose value keeps changing and we need to print the string including that number. Strings and numbers being different data types have to be solved in different ways. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 609, "s": 391, "text": "Method #1 : Using Type conversionThe simplest way in which this task can be performed is by converting the integer explicitly into string datatype using the basic type conversion and adding it to appropriate position." }, { "code": "# Python3 code to demonstrate working of# Inserting a number in string # Using type conversion # initializing string test_str = \"Geeks\" # initializing numbertest_int = 4 # printing original string print(\"The original string is : \" + test_str) # printing numberprint(\"The original number : \" + str(test_int)) # using type conversion# Inserting number in string res = test_str + str(test_int) + test_str # printing result print(\"The string after adding number is : \" + str(res))", "e": 1094, "s": 609, "text": null }, { "code": null, "e": 1199, "s": 1094, "text": "The original string is : Geeks\nThe original number : 4\nThe string after adding number is : Geeks4Geeks\n" }, { "code": null, "e": 1425, "s": 1201, "text": "Method #2 : Using %d operatorThis operator can be used to format the string to add the integer. The “d” represents that the datatype to be inserted to string is an integer. This can be changed according to the requirements." }, { "code": "# Python3 code to demonstrate working of# Inserting a number in string # Using % d operator # initializing string test_str = \"Geeks\" # initializing numbertest_int = 4 # printing original string print(\"The original string is : \" + test_str) # printing numberprint(\"The original number : \" + str(test_int)) # using % d operator# Inserting number in string res = (test_str + \"% d\" + test_str) % test_int # printing result print(\"The string after adding number is : \" + str(res))", "e": 1909, "s": 1425, "text": null }, { "code": null, "e": 2014, "s": 1909, "text": "The original string is : Geeks\nThe original number : 4\nThe string after adding number is : Geeks4Geeks\n" }, { "code": null, "e": 2037, "s": 2014, "text": "Python string-programs" }, { "code": null, "e": 2044, "s": 2037, "text": "Python" }, { "code": null, "e": 2060, "s": 2044, "text": "Python Programs" } ]
Java program to check if string is pangram
A pangram is a string that contains all the letters of the English alphabet. An example of a pangram is "The quick brown fox jumps over the lazy dog". A program that checks if a string is pangram or not is given as follows. Live Demo public class Example { public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog"; boolean[] alphaList = new boolean[26]; int index = 0; int flag = 1; for (int i = 0; i < str.length(); i++) { if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') { index = str.charAt(i) - 'A'; }else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { index = str.charAt(i) - 'a'; } alphaList[index] = true; } for (int i = 0; i <= 25; i++) { if (alphaList[i] == false) flag = 0; } System.out.print("String: " + str); if (flag == 1) System.out.print("\nThe above string is a pangram."); else System.out.print("\nThe above string is not a pangram."); } } String: The quick brown fox jumps over the lazy dog The above string is a pangram. Now let us understand the above program. The string str is traversed using a for loop and for every alphabet, the corresponding index in aplhaList is set to true. The code snippet that demonstrates this is given as follows − for (int i = 0; i < str.length(); i++) { if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') { index = str.charAt(i) - 'A'; }else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { index = str.charAt(i) - 'a'; } alphaList[index] = true; } After this, the array alphaList is traversed. If all the values are true, then string is a pangram and value of flag remains 1. However, if even 1 value is false, then string is not a pangram and the value of flag is set to 0. Then it is displayed if string is pangram or not. The code snippet that demonstrates this is given as follows. for (int i = 0; i <= 25; i++) { if (alphaList[i] == false) flag = 0; } System.out.print("String: " + str); if (flag == 1) System.out.print("\nThe above string is a pangram."); else System.out.print("\nThe above string is not a pangram."); }
[ { "code": null, "e": 1338, "s": 1187, "text": "A pangram is a string that contains all the letters of the English alphabet. An example of a pangram is \"The quick brown fox jumps over the lazy dog\"." }, { "code": null, "e": 1411, "s": 1338, "text": "A program that checks if a string is pangram or not is given as follows." }, { "code": null, "e": 1422, "s": 1411, "text": " Live Demo" }, { "code": null, "e": 2228, "s": 1422, "text": "public class Example {\n public static void main(String[] args) {\n String str = \"The quick brown fox jumps over the lazy dog\";\n boolean[] alphaList = new boolean[26];\n int index = 0;\n int flag = 1;\n for (int i = 0; i < str.length(); i++) {\n if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {\n index = str.charAt(i) - 'A';\n }else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {\n index = str.charAt(i) - 'a';\n }\n alphaList[index] = true;\n }\n for (int i = 0; i <= 25; i++) {\n if (alphaList[i] == false)\n flag = 0;\n }\n System.out.print(\"String: \" + str);\n if (flag == 1)\n System.out.print(\"\\nThe above string is a pangram.\");\n else\n System.out.print(\"\\nThe above string is not a pangram.\");\n }\n}" }, { "code": null, "e": 2311, "s": 2228, "text": "String: The quick brown fox jumps over the lazy dog\nThe above string is a pangram." }, { "code": null, "e": 2352, "s": 2311, "text": "Now let us understand the above program." }, { "code": null, "e": 2536, "s": 2352, "text": "The string str is traversed using a for loop and for every alphabet, the corresponding index in aplhaList is set to true. The code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2799, "s": 2536, "text": "for (int i = 0; i < str.length(); i++) {\n if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {\n index = str.charAt(i) - 'A';\n }else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {\n index = str.charAt(i) - 'a';\n }\n alphaList[index] = true;\n}" }, { "code": null, "e": 3137, "s": 2799, "text": "After this, the array alphaList is traversed. If all the values are true, then string is a pangram and value of flag remains 1. However, if even 1 value is false, then string is not a pangram and the value of flag is set to 0. Then it is displayed if string is pangram or not. The code snippet that demonstrates this is given as follows." }, { "code": null, "e": 3411, "s": 3137, "text": "for (int i = 0; i <= 25; i++) {\n if (alphaList[i] == false)\n flag = 0;\n }\n System.out.print(\"String: \" + str);\n if (flag == 1)\n System.out.print(\"\\nThe above string is a pangram.\");\n else\n System.out.print(\"\\nThe above string is not a pangram.\");\n}" } ]
How to compare two ArrayList for equality in Java?
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false. Live Demo import java.util.ArrayList; public class ComparingList { public static void main(String[] args) { ArrayList<String> list1 = new ArrayList<String>(); list1.add("JavaFx"); list1.add("Java"); list1.add("WebGL"); list1.add("OpenCV"); ArrayList<String> list2 = new ArrayList<String>(); list2.add("JavaFx"); list2.add("Java"); list2.add("WebGL"); list2.add("OpenCV"); System.out.println(list2); System.out.println(list1.equals(list2)); } }
[ { "code": null, "e": 1297, "s": 1062, "text": "You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false." }, { "code": null, "e": 1308, "s": 1297, "text": " Live Demo" }, { "code": null, "e": 1821, "s": 1308, "text": "import java.util.ArrayList;\n\npublic class ComparingList {\n public static void main(String[] args) {\n ArrayList<String> list1 = new ArrayList<String>();\n list1.add(\"JavaFx\");\n list1.add(\"Java\");\n list1.add(\"WebGL\");\n list1.add(\"OpenCV\");\n ArrayList<String> list2 = new ArrayList<String>();\n list2.add(\"JavaFx\");\n list2.add(\"Java\");\n list2.add(\"WebGL\");\n list2.add(\"OpenCV\");\n System.out.println(list2);\n System.out.println(list1.equals(list2));\n }\n}" } ]
How can we use MySQL ALTER TABLE command for adding comments on columns?
We can use ‘COMMENT’ keyword with ALTER TABLE command while modifying the column to add comments on columns. For example if we want to add comment in column ‘id’ of table ‘testing’ then following query will do it − mysql> ALTER TABLE testing MODIFY id INT COMMENT 'id of employees'; Query OK, 0 rows affected (0.07 sec) Records: 0 Duplicates: 0 Warnings: 0 With following query it can be checked in the comment field of a column. mysql> Show full columns from testing\G *************************** 1. row *************************** Field: id Type: int(11) Collation: NULL Null: NO Key: PRI Default: 0 Extra: Privileges: select,insert,update,references Comment: id of employees *************************** 2. row *************************** Field: Name Type: varchar(20) Collation: latin1_swedish_ci Null: YES Key: Default: NULL Extra: Privileges: select,insert,update,references Comment: 2 rows in set (0.05 sec)
[ { "code": null, "e": 1277, "s": 1062, "text": "We can use ‘COMMENT’ keyword with ALTER TABLE command while modifying the column to add comments on columns. For example if we want to add comment in column ‘id’ of table ‘testing’ then following query will do it −" }, { "code": null, "e": 1419, "s": 1277, "text": "mysql> ALTER TABLE testing MODIFY id INT COMMENT 'id of employees';\nQuery OK, 0 rows affected (0.07 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1492, "s": 1419, "text": "With following query it can be checked in the comment field of a column." }, { "code": null, "e": 2048, "s": 1492, "text": "mysql> Show full columns from testing\\G\n*************************** 1. row ***************************\n Field: id\n Type: int(11)\n Collation: NULL\n Null: NO\n Key: PRI\n Default: 0\n Extra:\nPrivileges: select,insert,update,references\n Comment: id of employees\n*************************** 2. row ***************************\n Field: Name\n Type: varchar(20)\n Collation: latin1_swedish_ci\n Null: YES\n Key:\n Default: NULL\n Extra:\nPrivileges: select,insert,update,references\n Comment:\n2 rows in set (0.05 sec)" } ]
Java Program to remove all white spaces from a String.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "". Live Demo public class DuplicateCharacters { public static void main(String[] args){ String str = "Hello how are you"; str = str.replaceAll(" ", ""); System.out.println(str); } } Hellohowareyou
[ { "code": null, "e": 1283, "s": 1062, "text": "The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing \" \" with \"\"." }, { "code": null, "e": 1294, "s": 1283, "text": " Live Demo" }, { "code": null, "e": 1487, "s": 1294, "text": "public class DuplicateCharacters {\n public static void main(String[] args){\n String str = \"Hello how are you\";\n str = str.replaceAll(\" \", \"\");\n System.out.println(str);\n }\n}" }, { "code": null, "e": 1502, "s": 1487, "text": "Hellohowareyou" } ]
How to put text outside Python plots?
To put text outside a plot, we can change the text position by changing the value of text_pos_x and text_pos_y Create data points for x and y. Initialize the text position of x and y. To plot x and y, use plot() method with color='red'. Use text() method to add text to figure. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(1, 5, 100) y = np.exp(x) text_pos_x = 0.60 text_pos_y = 0.50 plt.plot(x, y, c='red') plt.text(text_pos_x, text_pos_y, "$\mathit{y}=e^{x}$", fontsize=14, transform=plt.gcf().transFigure, color='green') plt.show()
[ { "code": null, "e": 1173, "s": 1062, "text": "To put text outside a plot, we can change the text position by changing the value of text_pos_x and text_pos_y" }, { "code": null, "e": 1205, "s": 1173, "text": "Create data points for x and y." }, { "code": null, "e": 1246, "s": 1205, "text": "Initialize the text position of x and y." }, { "code": null, "e": 1299, "s": 1246, "text": "To plot x and y, use plot() method with color='red'." }, { "code": null, "e": 1340, "s": 1299, "text": "Use text() method to add text to figure." }, { "code": null, "e": 1382, "s": 1340, "text": "To display the figure, use show() method." }, { "code": null, "e": 1753, "s": 1382, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(1, 5, 100)\ny = np.exp(x)\ntext_pos_x = 0.60\ntext_pos_y = 0.50\nplt.plot(x, y, c='red')\nplt.text(text_pos_x, text_pos_y, \"$\\mathit{y}=e^{x}$\", fontsize=14,\ntransform=plt.gcf().transFigure, color='green')\nplt.show()" } ]
Tau - A Mathematical Constant - GeeksforGeeks
22 Jul, 2021 What is Tau?The constant is numerically equal to 2*pi (2 times pi), and with value approximately 6.28. The ratio equates to 2*C/D. Where C is circumference and D is diameter of circle.Applications of Tau There are many expressions that actually require “2*pi” calculation, having tau being equal to that simplifies them to great extent, for e.g Circumference of circle = 2*pi*r = tau*r. Concept of tau can be useful in angular measurements like angles in radians, representing as a complete “one-turn” and cos,sine functions in trigonometry have period of tau. These concepts can be useful for teaching geometry as would reduce the confusion of using “pi” and “2*pi” at many applications and would help get rid of factor of 2. Tau simplifies euler’s identity by eradicating the factor of 2. It is useful at many places where “2*pi” are used such as fourier transforms, cauchy integral formula’s etc. Criticism against Tau Since it contradicts with the symbols of torque, shear stress and time, this symbol has been a lot of criticism. We already had a ratio of “C/D” equal to pi, having another circle ratio with factor of two will create confusion in choice. There exist formulas which look more elegant as expression of “pi” rather than tau, for example, area of circle = pi*r*r = (tau*r*r)/2, introducing an extra factor of “1/2”. Coding Prospects Since Programming has always been trying to match up with mathematical advancements, symbol of tau has been introduced as a constant in recent python 3.6 under the math module. Below is the illustration of it. Python3 # Python code to demonstrate the working# of tau import math # Printing the value of tau using 2*piprint ("The value of tau (using 2*pi) is : ",end="")print (math.pi*2) # Printing the value of tau using in-built tau functionprint ("The value of tau (using in-built tau) is : ",end="")print (math.tau); Output: The value of tau (using 2*pi) is : 6.283185307179586 The value of tau (using in-built tau) is : 6.283185307179586 Note: This code won’t work on Geeksforgeeks IDE as Python 3.6 is not supported. Reference : http://math.wikia.com/wiki/Tau_(constant)This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. adnanirshad158 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Program for Decimal to Binary Conversion Program to find sum of elements in a given array Sieve of Eratosthenes The Knight's tour problem | Backtracking-1 Program for factorial of a number Find all factors of a natural number | Set 1
[ { "code": null, "e": 24707, "s": 24679, "text": "\n22 Jul, 2021" }, { "code": null, "e": 24913, "s": 24707, "text": "What is Tau?The constant is numerically equal to 2*pi (2 times pi), and with value approximately 6.28. The ratio equates to 2*C/D. Where C is circumference and D is diameter of circle.Applications of Tau " }, { "code": null, "e": 25096, "s": 24913, "text": "There are many expressions that actually require “2*pi” calculation, having tau being equal to that simplifies them to great extent, for e.g Circumference of circle = 2*pi*r = tau*r." }, { "code": null, "e": 25270, "s": 25096, "text": "Concept of tau can be useful in angular measurements like angles in radians, representing as a complete “one-turn” and cos,sine functions in trigonometry have period of tau." }, { "code": null, "e": 25436, "s": 25270, "text": "These concepts can be useful for teaching geometry as would reduce the confusion of using “pi” and “2*pi” at many applications and would help get rid of factor of 2." }, { "code": null, "e": 25500, "s": 25436, "text": "Tau simplifies euler’s identity by eradicating the factor of 2." }, { "code": null, "e": 25609, "s": 25500, "text": "It is useful at many places where “2*pi” are used such as fourier transforms, cauchy integral formula’s etc." }, { "code": null, "e": 25633, "s": 25609, "text": "Criticism against Tau " }, { "code": null, "e": 25746, "s": 25633, "text": "Since it contradicts with the symbols of torque, shear stress and time, this symbol has been a lot of criticism." }, { "code": null, "e": 25871, "s": 25746, "text": "We already had a ratio of “C/D” equal to pi, having another circle ratio with factor of two will create confusion in choice." }, { "code": null, "e": 26045, "s": 25871, "text": "There exist formulas which look more elegant as expression of “pi” rather than tau, for example, area of circle = pi*r*r = (tau*r*r)/2, introducing an extra factor of “1/2”." }, { "code": null, "e": 26274, "s": 26045, "text": "Coding Prospects Since Programming has always been trying to match up with mathematical advancements, symbol of tau has been introduced as a constant in recent python 3.6 under the math module. Below is the illustration of it. " }, { "code": null, "e": 26282, "s": 26274, "text": "Python3" }, { "code": "# Python code to demonstrate the working# of tau import math # Printing the value of tau using 2*piprint (\"The value of tau (using 2*pi) is : \",end=\"\")print (math.pi*2) # Printing the value of tau using in-built tau functionprint (\"The value of tau (using in-built tau) is : \",end=\"\")print (math.tau);", "e": 26584, "s": 26282, "text": null }, { "code": null, "e": 26594, "s": 26584, "text": "Output: " }, { "code": null, "e": 26708, "s": 26594, "text": "The value of tau (using 2*pi) is : 6.283185307179586\nThe value of tau (using in-built tau) is : 6.283185307179586" }, { "code": null, "e": 27263, "s": 26708, "text": "Note: This code won’t work on Geeksforgeeks IDE as Python 3.6 is not supported. Reference : http://math.wikia.com/wiki/Tau_(constant)This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27278, "s": 27263, "text": "adnanirshad158" }, { "code": null, "e": 27291, "s": 27278, "text": "Mathematical" }, { "code": null, "e": 27304, "s": 27291, "text": "Mathematical" }, { "code": null, "e": 27402, "s": 27304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27411, "s": 27402, "text": "Comments" }, { "code": null, "e": 27424, "s": 27411, "text": "Old Comments" }, { "code": null, "e": 27448, "s": 27424, "text": "Merge two sorted arrays" }, { "code": null, "e": 27491, "s": 27448, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 27505, "s": 27491, "text": "Prime Numbers" }, { "code": null, "e": 27547, "s": 27505, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 27588, "s": 27547, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 27637, "s": 27588, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 27659, "s": 27637, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 27702, "s": 27659, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 27736, "s": 27702, "text": "Program for factorial of a number" } ]
sciPy stats.tstd() function | Python - GeeksforGeeks
10 Feb, 2019 scipy.stats.tstd(array, limits=None, inclusive=(True, True)) calculates the trimmed standard deviation of the array elements along the specified axis of the array. It’s formula – Parameters :array: Input array or object having the elements to calculate the trimmed standard deviation.axis: Axis along which the trimmed standard deviation is to be computed. By default axis = 0.limits: Lower and upper bound of the array to consider, values less than the lower limit or greater than the upper limit will be ignored. If limits is None [default], then all values are used. Returns : Trimmed standard deviation of the array elements based on the set parameters. Code #1: # Trimmed Standard Deviation from scipy import statsimport numpy as np # array elements ranging from 0 to 19x = np.arange(20) print("Trimmed Standard Deviation :", stats.tstd(x)) print("\nTrimmed Standard Deviation by setting limit : ", stats.tstd(x, (2, 10))) Trimmed Standard Deviation : 5.9160797831 Trimmed Standard Deviation by setting limit : 2.73861278753 Code #2: With multi-dimensional data, axis() working # Trimmed Standard Deviation from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [5, 3, 18], [17, 16, 333], [3, 6, 82]] # using axis = 0print("Trimmed Standard Deviation is with default axis = 0 : \n", stats.tstd(arr1, axis = 1)) Trimmed Standard Deviation is with default axis = 0 : 94.0423824505 Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n10 Feb, 2019" }, { "code": null, "e": 25701, "s": 25537, "text": "scipy.stats.tstd(array, limits=None, inclusive=(True, True)) calculates the trimmed standard deviation of the array elements along the specified axis of the array." }, { "code": null, "e": 25716, "s": 25701, "text": "It’s formula –" }, { "code": null, "e": 26107, "s": 25716, "text": "Parameters :array: Input array or object having the elements to calculate the trimmed standard deviation.axis: Axis along which the trimmed standard deviation is to be computed. By default axis = 0.limits: Lower and upper bound of the array to consider, values less than the lower limit or greater than the upper limit will be ignored. If limits is None [default], then all values are used." }, { "code": null, "e": 26195, "s": 26107, "text": "Returns : Trimmed standard deviation of the array elements based on the set parameters." }, { "code": null, "e": 26204, "s": 26195, "text": "Code #1:" }, { "code": "# Trimmed Standard Deviation from scipy import statsimport numpy as np # array elements ranging from 0 to 19x = np.arange(20) print(\"Trimmed Standard Deviation :\", stats.tstd(x)) print(\"\\nTrimmed Standard Deviation by setting limit : \", stats.tstd(x, (2, 10)))", "e": 26486, "s": 26204, "text": null }, { "code": null, "e": 26591, "s": 26486, "text": "Trimmed Standard Deviation : 5.9160797831\n\nTrimmed Standard Deviation by setting limit : 2.73861278753\n" }, { "code": null, "e": 26645, "s": 26591, "text": " Code #2: With multi-dimensional data, axis() working" }, { "code": "# Trimmed Standard Deviation from scipy import statsimport numpy as np arr1 = [[1, 3, 27], [5, 3, 18], [17, 16, 333], [3, 6, 82]] # using axis = 0print(\"Trimmed Standard Deviation is with default axis = 0 : \\n\", stats.tstd(arr1, axis = 1))", "e": 26925, "s": 26645, "text": null }, { "code": null, "e": 26996, "s": 26925, "text": "Trimmed Standard Deviation is with default axis = 0 : \n 94.0423824505\n" }, { "code": null, "e": 27025, "s": 26996, "text": "Python scipy-stats-functions" }, { "code": null, "e": 27038, "s": 27025, "text": "Python-scipy" }, { "code": null, "e": 27045, "s": 27038, "text": "Python" }, { "code": null, "e": 27143, "s": 27045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27175, "s": 27143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27217, "s": 27175, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27259, "s": 27217, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27315, "s": 27259, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27342, "s": 27315, "text": "Python Classes and Objects" }, { "code": null, "e": 27381, "s": 27342, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27412, "s": 27381, "text": "Python | os.path.join() method" }, { "code": null, "e": 27434, "s": 27412, "text": "Defaultdict in Python" }, { "code": null, "e": 27463, "s": 27434, "text": "Create a directory in Python" } ]
AngularJS Forms ngSubmit() Method - GeeksforGeeks
14 Jun, 2021 In this article, we are going to see what is ngSubmit method in Angular 10 and how to use it. The ngSubmit() method is called when the ‘submit’ event is triggered on the ngForm. Syntax: <form (ngSubmit)='method($event)'></form> Parameters: $event: the “submit” event object Approach: Create an Angular app that to be used. In app.component.ts, make an array that takes the value from the form. In app.component.html, make a form and send the value using (ngSubmit) method. Serve the angular app using ng serve to see the output. Example: app.component.ts import { Component, Inject } from '@angular/core';import { FormGroup, FormControl, FormArray, NgForm } from '@angular/forms'@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { submit(form: NgForm) { console.log(form.value); }} app.component.html <form #form="ngForm" (ngSubmit)="submit(form)" novalidate> <input name="first" ngModel required #first="ngModel"> <input name="last" ngModel> <button>Submit</button></form> Output: Reference: https://angular.io/api/forms/NgForm#onsubmit Angular10 AngularJS-API AngularJS-Function 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": "\n14 Jun, 2021" }, { "code": null, "e": 26448, "s": 26354, "text": "In this article, we are going to see what is ngSubmit method in Angular 10 and how to use it." }, { "code": null, "e": 26532, "s": 26448, "text": "The ngSubmit() method is called when the ‘submit’ event is triggered on the ngForm." }, { "code": null, "e": 26540, "s": 26532, "text": "Syntax:" }, { "code": null, "e": 26582, "s": 26540, "text": "<form (ngSubmit)='method($event)'></form>" }, { "code": null, "e": 26594, "s": 26582, "text": "Parameters:" }, { "code": null, "e": 26628, "s": 26594, "text": "$event: the “submit” event object" }, { "code": null, "e": 26641, "s": 26630, "text": "Approach: " }, { "code": null, "e": 26680, "s": 26641, "text": "Create an Angular app that to be used." }, { "code": null, "e": 26751, "s": 26680, "text": "In app.component.ts, make an array that takes the value from the form." }, { "code": null, "e": 26830, "s": 26751, "text": "In app.component.html, make a form and send the value using (ngSubmit) method." }, { "code": null, "e": 26886, "s": 26830, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 26895, "s": 26886, "text": "Example:" }, { "code": null, "e": 26912, "s": 26895, "text": "app.component.ts" }, { "code": "import { Component, Inject } from '@angular/core';import { FormGroup, FormControl, FormArray, NgForm } from '@angular/forms'@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { submit(form: NgForm) { console.log(form.value); }}", "e": 27251, "s": 26912, "text": null }, { "code": null, "e": 27270, "s": 27251, "text": "app.component.html" }, { "code": "<form #form=\"ngForm\" (ngSubmit)=\"submit(form)\" novalidate> <input name=\"first\" ngModel required #first=\"ngModel\"> <input name=\"last\" ngModel> <button>Submit</button></form>", "e": 27452, "s": 27270, "text": null }, { "code": null, "e": 27460, "s": 27452, "text": "Output:" }, { "code": null, "e": 27516, "s": 27460, "text": "Reference: https://angular.io/api/forms/NgForm#onsubmit" }, { "code": null, "e": 27526, "s": 27516, "text": "Angular10" }, { "code": null, "e": 27540, "s": 27526, "text": "AngularJS-API" }, { "code": null, "e": 27559, "s": 27540, "text": "AngularJS-Function" }, { "code": null, "e": 27569, "s": 27559, "text": "AngularJS" }, { "code": null, "e": 27586, "s": 27569, "text": "Web Technologies" }, { "code": null, "e": 27684, "s": 27586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27719, "s": 27684, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27754, "s": 27719, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 27778, "s": 27754, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27813, "s": 27778, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 27866, "s": 27813, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27906, "s": 27866, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27939, "s": 27906, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27984, "s": 27939, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28027, "s": 27984, "text": "How to fetch data from an API in ReactJS ?" } ]
Split-apply-combine strategy on DataFrames in Julia - GeeksforGeeks
18 Aug, 2021 Julia is a high performance, dynamic programming language that has a high-level syntax. It might also be considered as a new and easier variant of python language. Data frames can be created, manipulated, and visualized in various ways for data science and machine learning purposes with Julia. For some tasks in data analysis, splitting data frames is required to apply multiple functions, and the final results are combined. We have to access the necessary packages and can use the by or the aggregate function to implement this strategy. First, we have to add the necessary packages to use DataFrames, CSV files, and required functions. Julia # Adding Packages for using DataFrames,# CSV files, and statistical functionsusing PkgPkg.add("DataFrames")Pkg.add("CSV")Pkg.add("Statistics") Now we read a CSV file into a DataFrame. A dataset of video game sales information, located in the local memory is being used here. Julia # Enabling use of necessary packagesusing DataFrames, CSV, Statistics # Reading a CSV file into a DataFrameds = CSV.read("C:\\Users\\metal\\vgsales.csv"); This dataframe is now split into two parts with the use of pre-defined functions head() and tail(). Julia # Displaying the first few rows of the DataFramehead(ds) Julia # Displaying the last few rows of the DataFrametail(ds) Now, we use the by function and the three arguments that can be passed in the function are: DataFrameColumns to split the DataFrame onFunctions to be applied after splitting of the DataFrame DataFrame Columns to split the DataFrame on Functions to be applied after splitting of the DataFrame Now the DataFrame is split on a column and we will perform various functions on it. Julia # Calculating the number of rows and columns# for each of the publishers in the DataFrameby(ds, :Publisher, size) Julia # Calculating the mean of the global sales of each Publisherby(ds, :Publisher, df -> mean(df.Global_Sales)) Julia # Calculating number of entries for each publisherby(ds, :Publisher, df -> DataFrame(N = size(df, 1))) We can also place the functions and expressions in a do block as shown below: Julia # Calculating the mean and variance# of global sales of each publisherby(ds, :Publisher) do df DataFrame(Mean = mean(df.Global_Sales), Variance = var(df.Global_Sales))end As mentioned, the aggregate() function can also be used to implement the strategy, which takes in the same three arguments as the by() function. After passing the arguments with a specific function, it creates new columns as a result, named with the syntax ‘column.name_function’. Julia # Calculating the number of entries# in each column for each publisheraggregate(ds, :Publisher, length) We can also create subsets by splitting the dataset using the groupby() function Julia # Creating a subset of entries for each publisherfor subdf in groupby(ds, :Publisher) println(size(subdf, 1))end Various other functions can be passed as arguments for the by() and the aggregate() functions to implement the Split-Apply-Combine strategy to achieve the desired results and insights. gulshankumarar231 julia-DataFrames Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia String concatenation in Julia Getting rounded value of a number in Julia - round() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Storing Output on a File in Julia Formatting of Strings in Julia Manipulating matrices in Julia while loop in Julia Creating array with repeated elements in Julia - repeat() Method Reshaping array dimensions in Julia | Array reshape() Method
[ { "code": null, "e": 25601, "s": 25573, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25897, "s": 25601, "text": "Julia is a high performance, dynamic programming language that has a high-level syntax. It might also be considered as a new and easier variant of python language. Data frames can be created, manipulated, and visualized in various ways for data science and machine learning purposes with Julia. " }, { "code": null, "e": 26143, "s": 25897, "text": "For some tasks in data analysis, splitting data frames is required to apply multiple functions, and the final results are combined. We have to access the necessary packages and can use the by or the aggregate function to implement this strategy." }, { "code": null, "e": 26242, "s": 26143, "text": "First, we have to add the necessary packages to use DataFrames, CSV files, and required functions." }, { "code": null, "e": 26248, "s": 26242, "text": "Julia" }, { "code": "# Adding Packages for using DataFrames,# CSV files, and statistical functionsusing PkgPkg.add(\"DataFrames\")Pkg.add(\"CSV\")Pkg.add(\"Statistics\")", "e": 26391, "s": 26248, "text": null }, { "code": null, "e": 26525, "s": 26391, "text": " Now we read a CSV file into a DataFrame. A dataset of video game sales information, located in the local memory is being used here." }, { "code": null, "e": 26531, "s": 26525, "text": "Julia" }, { "code": "# Enabling use of necessary packagesusing DataFrames, CSV, Statistics # Reading a CSV file into a DataFrameds = CSV.read(\"C:\\\\Users\\\\metal\\\\vgsales.csv\");", "e": 26686, "s": 26531, "text": null }, { "code": null, "e": 26787, "s": 26686, "text": " This dataframe is now split into two parts with the use of pre-defined functions head() and tail()." }, { "code": null, "e": 26793, "s": 26787, "text": "Julia" }, { "code": "# Displaying the first few rows of the DataFramehead(ds)", "e": 26850, "s": 26793, "text": null }, { "code": null, "e": 26856, "s": 26850, "text": "Julia" }, { "code": "# Displaying the last few rows of the DataFrametail(ds)", "e": 26912, "s": 26856, "text": null }, { "code": null, "e": 27004, "s": 26912, "text": "Now, we use the by function and the three arguments that can be passed in the function are:" }, { "code": null, "e": 27103, "s": 27004, "text": "DataFrameColumns to split the DataFrame onFunctions to be applied after splitting of the DataFrame" }, { "code": null, "e": 27113, "s": 27103, "text": "DataFrame" }, { "code": null, "e": 27147, "s": 27113, "text": "Columns to split the DataFrame on" }, { "code": null, "e": 27204, "s": 27147, "text": "Functions to be applied after splitting of the DataFrame" }, { "code": null, "e": 27288, "s": 27204, "text": "Now the DataFrame is split on a column and we will perform various functions on it." }, { "code": null, "e": 27294, "s": 27288, "text": "Julia" }, { "code": "# Calculating the number of rows and columns# for each of the publishers in the DataFrameby(ds, :Publisher, size)", "e": 27408, "s": 27294, "text": null }, { "code": null, "e": 27414, "s": 27408, "text": "Julia" }, { "code": "# Calculating the mean of the global sales of each Publisherby(ds, :Publisher, df -> mean(df.Global_Sales))", "e": 27522, "s": 27414, "text": null }, { "code": null, "e": 27528, "s": 27522, "text": "Julia" }, { "code": "# Calculating number of entries for each publisherby(ds, :Publisher, df -> DataFrame(N = size(df, 1)))", "e": 27631, "s": 27528, "text": null }, { "code": null, "e": 27709, "s": 27631, "text": "We can also place the functions and expressions in a do block as shown below:" }, { "code": null, "e": 27715, "s": 27709, "text": "Julia" }, { "code": "# Calculating the mean and variance# of global sales of each publisherby(ds, :Publisher) do df DataFrame(Mean = mean(df.Global_Sales), Variance = var(df.Global_Sales))end", "e": 27887, "s": 27715, "text": null }, { "code": null, "e": 28168, "s": 27887, "text": "As mentioned, the aggregate() function can also be used to implement the strategy, which takes in the same three arguments as the by() function. After passing the arguments with a specific function, it creates new columns as a result, named with the syntax ‘column.name_function’." }, { "code": null, "e": 28174, "s": 28168, "text": "Julia" }, { "code": "# Calculating the number of entries# in each column for each publisheraggregate(ds, :Publisher, length)", "e": 28278, "s": 28174, "text": null }, { "code": null, "e": 28360, "s": 28278, "text": "We can also create subsets by splitting the dataset using the groupby() function " }, { "code": null, "e": 28366, "s": 28360, "text": "Julia" }, { "code": "# Creating a subset of entries for each publisherfor subdf in groupby(ds, :Publisher) println(size(subdf, 1))end", "e": 28481, "s": 28366, "text": null }, { "code": null, "e": 28670, "s": 28484, "text": "Various other functions can be passed as arguments for the by() and the aggregate() functions to implement the Split-Apply-Combine strategy to achieve the desired results and insights. " }, { "code": null, "e": 28688, "s": 28670, "text": "gulshankumarar231" }, { "code": null, "e": 28705, "s": 28688, "text": "julia-DataFrames" }, { "code": null, "e": 28712, "s": 28705, "text": "Picked" }, { "code": null, "e": 28718, "s": 28712, "text": "Julia" }, { "code": null, "e": 28816, "s": 28718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28833, "s": 28816, "text": "Vectors in Julia" }, { "code": null, "e": 28863, "s": 28833, "text": "String concatenation in Julia" }, { "code": null, "e": 28923, "s": 28863, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 28996, "s": 28923, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 29030, "s": 28996, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 29061, "s": 29030, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 29092, "s": 29061, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 29112, "s": 29092, "text": "while loop in Julia" }, { "code": null, "e": 29177, "s": 29112, "text": "Creating array with repeated elements in Julia - repeat() Method" } ]
Output of C++ Program | Set 5 - GeeksforGeeks
05 Jan, 2022 Difficulty Level: RookiePredict the output of below C++ programs.Question 1 C++ #include<iostream>using namespace std; class Test { int value;public: Test(int v);}; Test::Test(int v) { value = v;} int main() { Test t[100]; return 0;} Output: Compiler error The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this). Following modified program works without any error. C++ #include<iostream>using namespace std; class Test { int value;public: Test(int v = 0);}; Test::Test(int v) { value = v;} int main() { Test t[100]; return 0;} Question 2 C++ #include<iostream>using namespace std;int &fun() { static int a = 10; return a;} int main() { int &y = fun(); y = y +30; cout<<fun(); return 0;} Output: 40 The program works fine because ‘a’ is static. Since ‘a’ is static, memory location of it remains valid even after fun() returns. So a reference to static variable can be returned.Question 3 C++ #include<iostream>using namespace std; class Test{public: Test();}; Test::Test() { cout<<"Constructor Called \n";} int main(){ cout<<"Start \n"; Test t1(); cout<<"End \n"; return 0;} Output: Start End Note that the line “Test t1();” is not a constructor call. Compiler considers this line as declaration of function t1 that doesn’t receive any parameter and returns object of type Test.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above kalrap615 healer CPP-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of Java program | Set 18 (Overriding) Output of Java Program | Set 11 Output of Java programs | Set 13 (Collections) Output of C++ programs | Set 34 (File Handling) Different ways to copy a string in C/C++ Output of Java Program | Set 3 Runtime Errors Output of Java program | Set 28 Output of Java program | Set 5 Output of Java Programs | Set 12
[ { "code": null, "e": 25339, "s": 25311, "text": "\n05 Jan, 2022" }, { "code": null, "e": 25417, "s": 25339, "text": "Difficulty Level: RookiePredict the output of below C++ programs.Question 1 " }, { "code": null, "e": 25421, "s": 25417, "text": "C++" }, { "code": "#include<iostream>using namespace std; class Test { int value;public: Test(int v);}; Test::Test(int v) { value = v;} int main() { Test t[100]; return 0;}", "e": 25590, "s": 25421, "text": null }, { "code": null, "e": 25600, "s": 25590, "text": "Output: " }, { "code": null, "e": 25615, "s": 25600, "text": "Compiler error" }, { "code": null, "e": 25905, "s": 25615, "text": "The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this). Following modified program works without any error. " }, { "code": null, "e": 25909, "s": 25905, "text": "C++" }, { "code": "#include<iostream>using namespace std; class Test { int value;public: Test(int v = 0);}; Test::Test(int v) { value = v;} int main() { Test t[100]; return 0;}", "e": 26082, "s": 25909, "text": null }, { "code": null, "e": 26095, "s": 26082, "text": "Question 2 " }, { "code": null, "e": 26099, "s": 26095, "text": "C++" }, { "code": "#include<iostream>using namespace std;int &fun() { static int a = 10; return a;} int main() { int &y = fun(); y = y +30; cout<<fun(); return 0;}", "e": 26250, "s": 26099, "text": null }, { "code": null, "e": 26260, "s": 26250, "text": "Output: " }, { "code": null, "e": 26263, "s": 26260, "text": "40" }, { "code": null, "e": 26455, "s": 26263, "text": "The program works fine because ‘a’ is static. Since ‘a’ is static, memory location of it remains valid even after fun() returns. So a reference to static variable can be returned.Question 3 " }, { "code": null, "e": 26459, "s": 26455, "text": "C++" }, { "code": "#include<iostream>using namespace std; class Test{public: Test();}; Test::Test() { cout<<\"Constructor Called \\n\";} int main(){ cout<<\"Start \\n\"; Test t1(); cout<<\"End \\n\"; return 0;}", "e": 26659, "s": 26459, "text": null }, { "code": null, "e": 26669, "s": 26659, "text": "Output: " }, { "code": null, "e": 26679, "s": 26669, "text": "Start\nEnd" }, { "code": null, "e": 27013, "s": 26679, "text": "Note that the line “Test t1();” is not a constructor call. Compiler considers this line as declaration of function t1 that doesn’t receive any parameter and returns object of type Test.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above " }, { "code": null, "e": 27023, "s": 27013, "text": "kalrap615" }, { "code": null, "e": 27030, "s": 27023, "text": "healer" }, { "code": null, "e": 27041, "s": 27030, "text": "CPP-Output" }, { "code": null, "e": 27056, "s": 27041, "text": "Program Output" }, { "code": null, "e": 27154, "s": 27056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27199, "s": 27154, "text": "Output of Java program | Set 18 (Overriding)" }, { "code": null, "e": 27231, "s": 27199, "text": "Output of Java Program | Set 11" }, { "code": null, "e": 27278, "s": 27231, "text": "Output of Java programs | Set 13 (Collections)" }, { "code": null, "e": 27326, "s": 27278, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 27367, "s": 27326, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 27398, "s": 27367, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 27413, "s": 27398, "text": "Runtime Errors" }, { "code": null, "e": 27445, "s": 27413, "text": "Output of Java program | Set 28" }, { "code": null, "e": 27476, "s": 27445, "text": "Output of Java program | Set 5" } ]
Structure Equality in Golang - GeeksforGeeks
17 Jan, 2022 A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class which does not support inheritance but supports composition. In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method. Both the operator and method return true if the structures are identically equal(in terms of their fields values) to each other, otherwise, return false. And, if the compared variables belong to different structures, then the compiler will give an error. Let us discuss this concept with the help of the examples:Note: The DeeplyEqual() method is defined under “reflect” package.Example 1: C // Go program to illustrate the// concept of struct equality// using == operator package main import "fmt" // Creating a structuretype Author struct { name string branch string language string Particles int} // Main functionfunc main() { // Creating variables // of Author structure a1 := Author{ name: "Moana", branch: "CSE", language: "Python", Particles: 38, } a2 := Author{ name: "Moana", branch: "CSE", language: "Python", Particles: 38, } a3 := Author{ name: "Dona", branch: "CSE", language: "Python", Particles: 38, } // Checking if a1 is equal // to a2 or not // Using == operator if a1 == a2 { fmt.Println("Variable a1 is equal to variable a2") } else { fmt.Println("Variable a1 is not equal to variable a2") } // Checking if a1 is equal // to a2 or not // Using == operator if a2 == a3 { fmt.Println("Variable a2 is equal to variable a3") } else { fmt.Println("Variable a2 is not equal to variable a3") }} Output: Variable a1 is equal to variable a2 Variable a2 is not equal to variable a3 Example 2: C // Go program to illustrate the// concept of struct equality// using DeepEqual() methodpackage main import ( "fmt" "reflect") // Creating a structuretype Author struct { name string branch string language string Particles int} // Main functionfunc main() { // Creating variables // of Author structure a1 := Author{ name: "Soana", branch: "CSE", language: "Perl", Particles: 48, } a2 := Author{ name: "Soana", branch: "CSE", language: "Perl", Particles: 48, } a3 := Author{ name: "Dia", branch: "CSE", language: "Perl", Particles: 48, } // Comparing a1 with a2 // Using DeepEqual() method fmt.Println("Is a1 equal to a2: ", reflect.DeepEqual(a1, a2)) // Comparing a2 with a3 // Using DeepEqual() method fmt.Println("Is a2 equal to a3: ", reflect.DeepEqual(a2, a3))} Output: Is a1 equal to a2: true Is a2 equal to a3: false surinderdawra388 Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go How to Split a String in Golang? Slices in Golang Golang Maps Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang How to Trim a String in Golang? How to compare times in Golang?
[ { "code": null, "e": 25667, "s": 25639, "text": "\n17 Jan, 2022" }, { "code": null, "e": 26657, "s": 25667, "text": "A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming. It can be termed as a lightweight class which does not support inheritance but supports composition. In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method. Both the operator and method return true if the structures are identically equal(in terms of their fields values) to each other, otherwise, return false. And, if the compared variables belong to different structures, then the compiler will give an error. Let us discuss this concept with the help of the examples:Note: The DeeplyEqual() method is defined under “reflect” package.Example 1: " }, { "code": null, "e": 26659, "s": 26657, "text": "C" }, { "code": "// Go program to illustrate the// concept of struct equality// using == operator package main import \"fmt\" // Creating a structuretype Author struct { name string branch string language string Particles int} // Main functionfunc main() { // Creating variables // of Author structure a1 := Author{ name: \"Moana\", branch: \"CSE\", language: \"Python\", Particles: 38, } a2 := Author{ name: \"Moana\", branch: \"CSE\", language: \"Python\", Particles: 38, } a3 := Author{ name: \"Dona\", branch: \"CSE\", language: \"Python\", Particles: 38, } // Checking if a1 is equal // to a2 or not // Using == operator if a1 == a2 { fmt.Println(\"Variable a1 is equal to variable a2\") } else { fmt.Println(\"Variable a1 is not equal to variable a2\") } // Checking if a1 is equal // to a2 or not // Using == operator if a2 == a3 { fmt.Println(\"Variable a2 is equal to variable a3\") } else { fmt.Println(\"Variable a2 is not equal to variable a3\") }}", "e": 27838, "s": 26659, "text": null }, { "code": null, "e": 27848, "s": 27838, "text": "Output: " }, { "code": null, "e": 27924, "s": 27848, "text": "Variable a1 is equal to variable a2\nVariable a2 is not equal to variable a3" }, { "code": null, "e": 27936, "s": 27924, "text": "Example 2: " }, { "code": null, "e": 27938, "s": 27936, "text": "C" }, { "code": "// Go program to illustrate the// concept of struct equality// using DeepEqual() methodpackage main import ( \"fmt\" \"reflect\") // Creating a structuretype Author struct { name string branch string language string Particles int} // Main functionfunc main() { // Creating variables // of Author structure a1 := Author{ name: \"Soana\", branch: \"CSE\", language: \"Perl\", Particles: 48, } a2 := Author{ name: \"Soana\", branch: \"CSE\", language: \"Perl\", Particles: 48, } a3 := Author{ name: \"Dia\", branch: \"CSE\", language: \"Perl\", Particles: 48, } // Comparing a1 with a2 // Using DeepEqual() method fmt.Println(\"Is a1 equal to a2: \", reflect.DeepEqual(a1, a2)) // Comparing a2 with a3 // Using DeepEqual() method fmt.Println(\"Is a2 equal to a3: \", reflect.DeepEqual(a2, a3))}", "e": 28893, "s": 27938, "text": null }, { "code": null, "e": 28902, "s": 28893, "text": "Output: " }, { "code": null, "e": 28953, "s": 28902, "text": "Is a1 equal to a2: true\nIs a2 equal to a3: false" }, { "code": null, "e": 28972, "s": 28955, "text": "surinderdawra388" }, { "code": null, "e": 28979, "s": 28972, "text": "Golang" }, { "code": null, "e": 28991, "s": 28979, "text": "Go Language" }, { "code": null, "e": 29089, "s": 28991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29135, "s": 29089, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 29148, "s": 29135, "text": "Arrays in Go" }, { "code": null, "e": 29181, "s": 29148, "text": "How to Split a String in Golang?" }, { "code": null, "e": 29198, "s": 29181, "text": "Slices in Golang" }, { "code": null, "e": 29210, "s": 29198, "text": "Golang Maps" }, { "code": null, "e": 29232, "s": 29210, "text": "Inheritance in GoLang" }, { "code": null, "e": 29286, "s": 29232, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 29307, "s": 29286, "text": "Interfaces in Golang" }, { "code": null, "e": 29339, "s": 29307, "text": "How to Trim a String in Golang?" } ]
Creating nested dataclass objects in Python - GeeksforGeeks
29 Aug, 2020 Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator examines class to find fields(a class variable that contains a type annotation). Then the dataclass decorator adds special methods. Syntax: @dataclass class user_defined_class: Here, we’ll tackle the idea of having nested dataclass objects in our program. Even though dataclasses are easy to use, they still increase the complexity of the program by one bar, and nesting such objects can be seen a little challenging but here we’ll take on each scenario and how to handle it. Carefully examine the following code: @dataclassclass A: a: int b: str @dataclassclass B: c: str d: A Starting with class A, it is being decorated by a dataclass. This class is then being nested within class B as a field of B which also is being decorated by a dataclass object. So far this code just shows the nesting of dataclass objects, next we discuss how do we employ such implementation. # importing modulefrom dataclasses import dataclass @dataclassclass A: a: int b: str @dataclassclass B: c: str d: A # FIRST APPROACH# creating object for class b with following values # c ='hello'# a = 4# b ='bye'data ={'c':'hello', 'd':{'a':4, 'b':'bye'}}b = B(**data)print (b) # SECOND APPROACHdata ={'c':'hello', 'd': A(**{'a':4, 'b':'bye'})}c = B(**data)print(c) Output: B(c='hello', d={'a': 4, 'b': 'bye'}) B(c='hello', d=A(a=4, b='bye')) The problem with the first approach is that the output gives no idea about the nested object or the class A and its attributes, and if that is ones requirement then we are good to go. The second approach does the trick but it seems tedious if you have multiple nested objects in your dataclass objects, not just this, with increase in number of nested objects the complexity of the program will also increase and so will the method for calling them. Thus, we require a way to achieve the output of the second approach but without making the calling and initializing process complex. The above problem can be resolved by wrapping generated __init__() method that will check for parameters passed to kwargs, check if any field belongs to a dataclass field type and if it does generate the nested object prior to the original __init__(). What this means is shown below : from dataclasses import dataclass, is_dataclass # decorator to wrap original __init__def nested_deco(*args, **kwargs): def wrapper(check_class): # passing class to investigate check_class = dataclass(check_class, **kwargs) o_init = check_class.__init__ def __init__(self, *args, **kwargs): for name, value in kwargs.items(): # getting field type ft = check_class.__annotations__.get(name, None) if is_dataclass(ft) and isinstance(value, dict): obj = ft(**value) kwargs[name]= obj o_init(self, *args, **kwargs) check_class.__init__=__init__ return check_class return wrapper(args[0]) if args else wrapper @dataclassclass A: a: int b: str @nested_decoclass B: c: str d: A data ={'c':'hello', 'd':{'a':4, 'b':'bye'}}b = B(**data)print (b) Output: B(c='hello', d=A(a=4, b='bye')) Note that apart from problems generated by __init__() this also doesn’t allow __init__=false to be returned to the code. python-modules python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25563, "s": 25535, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25740, "s": 25563, "text": "Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes." }, { "code": null, "e": 26046, "s": 25740, "text": "Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator examines class to find fields(a class variable that contains a type annotation). Then the dataclass decorator adds special methods." }, { "code": null, "e": 26054, "s": 26046, "text": "Syntax:" }, { "code": null, "e": 26092, "s": 26054, "text": "@dataclass\nclass user_defined_class:\n" }, { "code": null, "e": 26391, "s": 26092, "text": "Here, we’ll tackle the idea of having nested dataclass objects in our program. Even though dataclasses are easy to use, they still increase the complexity of the program by one bar, and nesting such objects can be seen a little challenging but here we’ll take on each scenario and how to handle it." }, { "code": null, "e": 26429, "s": 26391, "text": "Carefully examine the following code:" }, { "code": "@dataclassclass A: a: int b: str @dataclassclass B: c: str d: A", "e": 26506, "s": 26429, "text": null }, { "code": null, "e": 26799, "s": 26506, "text": "Starting with class A, it is being decorated by a dataclass. This class is then being nested within class B as a field of B which also is being decorated by a dataclass object. So far this code just shows the nesting of dataclass objects, next we discuss how do we employ such implementation." }, { "code": "# importing modulefrom dataclasses import dataclass @dataclassclass A: a: int b: str @dataclassclass B: c: str d: A # FIRST APPROACH# creating object for class b with following values # c ='hello'# a = 4# b ='bye'data ={'c':'hello', 'd':{'a':4, 'b':'bye'}}b = B(**data)print (b) # SECOND APPROACHdata ={'c':'hello', 'd': A(**{'a':4, 'b':'bye'})}c = B(**data)print(c)", "e": 27182, "s": 26799, "text": null }, { "code": null, "e": 27190, "s": 27182, "text": "Output:" }, { "code": null, "e": 27259, "s": 27190, "text": "B(c='hello', d={'a': 4, 'b': 'bye'})\nB(c='hello', d=A(a=4, b='bye'))" }, { "code": null, "e": 27842, "s": 27259, "text": "The problem with the first approach is that the output gives no idea about the nested object or the class A and its attributes, and if that is ones requirement then we are good to go. The second approach does the trick but it seems tedious if you have multiple nested objects in your dataclass objects, not just this, with increase in number of nested objects the complexity of the program will also increase and so will the method for calling them. Thus, we require a way to achieve the output of the second approach but without making the calling and initializing process complex." }, { "code": null, "e": 28094, "s": 27842, "text": "The above problem can be resolved by wrapping generated __init__() method that will check for parameters passed to kwargs, check if any field belongs to a dataclass field type and if it does generate the nested object prior to the original __init__()." }, { "code": null, "e": 28127, "s": 28094, "text": "What this means is shown below :" }, { "code": "from dataclasses import dataclass, is_dataclass # decorator to wrap original __init__def nested_deco(*args, **kwargs): def wrapper(check_class): # passing class to investigate check_class = dataclass(check_class, **kwargs) o_init = check_class.__init__ def __init__(self, *args, **kwargs): for name, value in kwargs.items(): # getting field type ft = check_class.__annotations__.get(name, None) if is_dataclass(ft) and isinstance(value, dict): obj = ft(**value) kwargs[name]= obj o_init(self, *args, **kwargs) check_class.__init__=__init__ return check_class return wrapper(args[0]) if args else wrapper @dataclassclass A: a: int b: str @nested_decoclass B: c: str d: A data ={'c':'hello', 'd':{'a':4, 'b':'bye'}}b = B(**data)print (b)", "e": 29132, "s": 28127, "text": null }, { "code": null, "e": 29140, "s": 29132, "text": "Output:" }, { "code": null, "e": 29172, "s": 29140, "text": "B(c='hello', d=A(a=4, b='bye'))" }, { "code": null, "e": 29293, "s": 29172, "text": "Note that apart from problems generated by __init__() this also doesn’t allow __init__=false to be returned to the code." }, { "code": null, "e": 29308, "s": 29293, "text": "python-modules" }, { "code": null, "e": 29328, "s": 29308, "text": "python-oop-concepts" }, { "code": null, "e": 29335, "s": 29328, "text": "Python" }, { "code": null, "e": 29433, "s": 29335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29451, "s": 29433, "text": "Python Dictionary" }, { "code": null, "e": 29486, "s": 29451, "text": "Read a file line by line in Python" }, { "code": null, "e": 29518, "s": 29486, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29540, "s": 29518, "text": "Enumerate() in Python" }, { "code": null, "e": 29582, "s": 29540, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29612, "s": 29582, "text": "Iterate over a list in Python" }, { "code": null, "e": 29638, "s": 29612, "text": "Python String | replace()" }, { "code": null, "e": 29667, "s": 29638, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29711, "s": 29667, "text": "Reading and Writing to text files in Python" } ]
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph - GeeksforGeeks
31 Aug, 2021 Prerequisite – Graph Theory Basics – Set 1 1. Walk – A walk is a sequence of vertices and edges of a graph i.e. if we traverse a graph then we get a walk. Note: Vertices and Edges can be repeated. Here, 1->2->3->4->2->1->3 is a walk. Walk can be open or closed. Open walk- A walk is said to be an open walk if the starting and ending vertices are different i.e. the origin vertex and terminal vertex are different. Closed walk- A walk is said to be a closed walk if the starting and ending vertices are identical i.e. if a walk starts and ends at the same vertex, then it is said to be a closed walk. In the above diagram: 1->2->3->4->5->3 is an open walk. 1->2->3->4->5->3->1 is a closed walk. 2. Trail – Trail is an open walk in which no edge is repeated. Vertex can be repeated. Here 1->3->8->6->3->2 is trail Also 1->3->8->6->3->2->1 will be a closed trail 3. Circuit – Traversing a graph such that not an edge is repeated but vertex can be repeated and it is closed also i.e. it is a closed trail. Vertex can be repeated.Edge can not be repeated. Here 1->2->4->3->6->8->3->1 is a circuit. Circuit is a closed trail. These can have repeated vertices only. 4. Path – It is a trail in which neither vertices nor edges are repeated i.e. if we traverse a graph such that we do not repeat a vertex and nor we repeat an edge. As path is also a trail, thus it is also an open walk. Vertex not repeated Edge not repeated Here 6->8->3->1->2->4 is a Path 5. Cycle – Traversing a graph such that we do not repeat a vertex nor we repeat a edge but the starting and ending vertex must be same i.e. we can repeat starting and ending vertex only then we get a cycle. Vertex not repeated Edge not repeated Here 1->2->4->3->1 is a cycle. Cycle is a closed path. These can not have repeat anything (neither edges nor vertices). Note that for closed sequences start and end vertices are the only ones that can repeat. mohitg593 rwells1703 kevind28198014 amitkrraj Discrete Mathematics Picked Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Activation Functions Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 31278, "s": 31250, "text": "\n31 Aug, 2021" }, { "code": null, "e": 31322, "s": 31278, "text": "Prerequisite – Graph Theory Basics – Set 1 " }, { "code": null, "e": 31477, "s": 31322, "text": "1. Walk – A walk is a sequence of vertices and edges of a graph i.e. if we traverse a graph then we get a walk. Note: Vertices and Edges can be repeated." }, { "code": null, "e": 31516, "s": 31479, "text": "Here, 1->2->3->4->2->1->3 is a walk." }, { "code": null, "e": 31544, "s": 31516, "text": "Walk can be open or closed." }, { "code": null, "e": 31884, "s": 31544, "text": "Open walk- A walk is said to be an open walk if the starting and ending vertices are different i.e. the origin vertex and terminal vertex are different. Closed walk- A walk is said to be a closed walk if the starting and ending vertices are identical i.e. if a walk starts and ends at the same vertex, then it is said to be a closed walk. " }, { "code": null, "e": 31979, "s": 31884, "text": "In the above diagram: 1->2->3->4->5->3 is an open walk. 1->2->3->4->5->3->1 is a closed walk. " }, { "code": null, "e": 32043, "s": 31979, "text": "2. Trail – Trail is an open walk in which no edge is repeated. " }, { "code": null, "e": 32067, "s": 32043, "text": "Vertex can be repeated." }, { "code": null, "e": 32149, "s": 32069, "text": "Here 1->3->8->6->3->2 is trail Also 1->3->8->6->3->2->1 will be a closed trail " }, { "code": null, "e": 32342, "s": 32149, "text": "3. Circuit – Traversing a graph such that not an edge is repeated but vertex can be repeated and it is closed also i.e. it is a closed trail. Vertex can be repeated.Edge can not be repeated. " }, { "code": null, "e": 32386, "s": 32344, "text": "Here 1->2->4->3->6->8->3->1 is a circuit." }, { "code": null, "e": 32453, "s": 32386, "text": "Circuit is a closed trail. \nThese can have repeated vertices only." }, { "code": null, "e": 32673, "s": 32453, "text": "4. Path – It is a trail in which neither vertices nor edges are repeated i.e. if we traverse a graph such that we do not repeat a vertex and nor we repeat an edge. As path is also a trail, thus it is also an open walk. " }, { "code": null, "e": 32712, "s": 32673, "text": "Vertex not repeated Edge not repeated " }, { "code": null, "e": 32747, "s": 32714, "text": "Here 6->8->3->1->2->4 is a Path " }, { "code": null, "e": 32955, "s": 32747, "text": "5. Cycle – Traversing a graph such that we do not repeat a vertex nor we repeat a edge but the starting and ending vertex must be same i.e. we can repeat starting and ending vertex only then we get a cycle. " }, { "code": null, "e": 32994, "s": 32955, "text": "Vertex not repeated Edge not repeated " }, { "code": null, "e": 33028, "s": 32996, "text": "Here 1->2->4->3->1 is a cycle. " }, { "code": null, "e": 33118, "s": 33028, "text": "Cycle is a closed path. \nThese can not have repeat anything (neither edges nor vertices)." }, { "code": null, "e": 33208, "s": 33118, "text": "Note that for closed sequences start and end vertices are the only ones that can repeat. " }, { "code": null, "e": 33218, "s": 33208, "text": "mohitg593" }, { "code": null, "e": 33229, "s": 33218, "text": "rwells1703" }, { "code": null, "e": 33244, "s": 33229, "text": "kevind28198014" }, { "code": null, "e": 33254, "s": 33244, "text": "amitkrraj" }, { "code": null, "e": 33275, "s": 33254, "text": "Discrete Mathematics" }, { "code": null, "e": 33282, "s": 33275, "text": "Picked" }, { "code": null, "e": 33306, "s": 33282, "text": "Engineering Mathematics" }, { "code": null, "e": 33314, "s": 33306, "text": "GATE CS" }, { "code": null, "e": 33412, "s": 33314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33434, "s": 33412, "text": "Inequalities in LaTeX" }, { "code": null, "e": 33455, "s": 33434, "text": "Activation Functions" }, { "code": null, "e": 33478, "s": 33455, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 33528, "s": 33478, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 33551, "s": 33528, "text": "Set Notations in LaTeX" }, { "code": null, "e": 33571, "s": 33551, "text": "Layers of OSI Model" }, { "code": null, "e": 33595, "s": 33571, "text": "ACID Properties in DBMS" }, { "code": null, "e": 33608, "s": 33595, "text": "TCP/IP Model" }, { "code": null, "e": 33635, "s": 33608, "text": "Types of Operating Systems" } ]
How to Create Bootable USB for Arch Linux? - GeeksforGeeks
11 May, 2021 A bootable USB or live USB is a USB flash drive that contains a bootable operating system. We create these USB flash drives when we wanted to refresh or change our operating system. Let’s discuss how we can create a Bootable USB flash drive for Arch Linux. Download the Arch ISO image from the Arch download page. Here, https://archlinux.org/download/. Arch Linux ISO Method 1: Using dd command Step 1: Check the available disks on the system using the following command. fdisk is a command-line utility used to get info about removable and non-removable disks. Here, -l flag means listing available disks. sudo fdisk -l Listing available disks The highlighted one is my removable disk of 32gb. Run the above command and note down the path where the disk is mounted. Here, my disk is mounted at /dev/sdc. Step 2: Write the ISO image to the removable USB. dd is an acronym for convert and copy, it is called dd because cc is already in use by the C compiler. dd is a command-line utility tool used for creating bootable USB. It converts and copies the ISO image to the USB flash drive. bs is used to set the input and output block size. sudo dd bs=4M if=path/to/the/archlinux.iso of=/dev/sdc Successfully created a bootable USB Method 2: Using imagewriter Step 1: Open up the image writer tool using the following command : imagewriter Step 2: Insert a USB stick into the computer. Step 3: Select the downloaded Arch ISO. Step 4: Click on the write button, a popup will be promoted click the button, and you’re all done. imagewriter Step 5: Wait until it completes the writing ISO, then unplug the USB. Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n11 May, 2021" }, { "code": null, "e": 26004, "s": 25651, "text": "A bootable USB or live USB is a USB flash drive that contains a bootable operating system. We create these USB flash drives when we wanted to refresh or change our operating system. Let’s discuss how we can create a Bootable USB flash drive for Arch Linux. Download the Arch ISO image from the Arch download page. Here, https://archlinux.org/download/." }, { "code": null, "e": 26019, "s": 26004, "text": "Arch Linux ISO" }, { "code": null, "e": 26046, "s": 26019, "text": "Method 1: Using dd command" }, { "code": null, "e": 26258, "s": 26046, "text": "Step 1: Check the available disks on the system using the following command. fdisk is a command-line utility used to get info about removable and non-removable disks. Here, -l flag means listing available disks." }, { "code": null, "e": 26272, "s": 26258, "text": "sudo fdisk -l" }, { "code": null, "e": 26296, "s": 26272, "text": "Listing available disks" }, { "code": null, "e": 26456, "s": 26296, "text": "The highlighted one is my removable disk of 32gb. Run the above command and note down the path where the disk is mounted. Here, my disk is mounted at /dev/sdc." }, { "code": null, "e": 26788, "s": 26456, "text": "Step 2: Write the ISO image to the removable USB. dd is an acronym for convert and copy, it is called dd because cc is already in use by the C compiler. dd is a command-line utility tool used for creating bootable USB. It converts and copies the ISO image to the USB flash drive. bs is used to set the input and output block size. " }, { "code": null, "e": 26843, "s": 26788, "text": "sudo dd bs=4M if=path/to/the/archlinux.iso of=/dev/sdc" }, { "code": null, "e": 26879, "s": 26843, "text": "Successfully created a bootable USB" }, { "code": null, "e": 26907, "s": 26879, "text": "Method 2: Using imagewriter" }, { "code": null, "e": 26975, "s": 26907, "text": "Step 1: Open up the image writer tool using the following command :" }, { "code": null, "e": 26987, "s": 26975, "text": "imagewriter" }, { "code": null, "e": 27033, "s": 26987, "text": "Step 2: Insert a USB stick into the computer." }, { "code": null, "e": 27073, "s": 27033, "text": "Step 3: Select the downloaded Arch ISO." }, { "code": null, "e": 27172, "s": 27073, "text": "Step 4: Click on the write button, a popup will be promoted click the button, and you’re all done." }, { "code": null, "e": 27184, "s": 27172, "text": "imagewriter" }, { "code": null, "e": 27254, "s": 27184, "text": "Step 5: Wait until it completes the writing ISO, then unplug the USB." }, { "code": null, "e": 27261, "s": 27254, "text": "Picked" }, { "code": null, "e": 27272, "s": 27261, "text": "Linux-Unix" }, { "code": null, "e": 27370, "s": 27272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27405, "s": 27370, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27439, "s": 27405, "text": "mv command in Linux with examples" }, { "code": null, "e": 27465, "s": 27439, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27494, "s": 27465, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27531, "s": 27494, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27568, "s": 27531, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27610, "s": 27568, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27636, "s": 27610, "text": "Thread functions in C/C++" }, { "code": null, "e": 27672, "s": 27636, "text": "uniq Command in LINUX with examples" } ]
Trapezoidal Rule for Approximate Value of Definite Integral - GeeksforGeeks
17 Jun, 2021 In the field of numerical analysis, Trapezoidal rule is used to find the approximation of a definite integral. The basic idea in Trapezoidal rule is to assume the region under the graph of the given function to be a trapezoid and calculate its area. It follows that:For more accurate results the domain of the graph is divided into n segments of equal size as shown below: Grid spacing or segment size h = (b-a) / n. Therefore, approximate value of the integral can be given by: C++ Java Python3 C# PHP Javascript // C++ program to implement Trapezoidal rule#include<stdio.h> // A sample function whose definite integral's// approximate value is computed using Trapezoidal// rulefloat y(float x){ // Declaring the function f(x) = 1/(1+x*x) return 1/(1+x*x);} // Function to evaluate the value of integralfloat trapezoidal(float a, float b, float n){ // Grid spacing float h = (b-a)/n; // Computing sum of first and last terms // in above formula float s = y(a)+y(b); // Adding middle terms in above formula for (int i = 1; i < n; i++) s += 2*y(a+i*h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h/2)*s;} // Driver program to test above functionint main(){ // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher value means // more accuracy int n = 6; printf("Value of integral is %6.4f\n", trapezoidal(x0, xn, n)); return 0;} // Java program to implement Trapezoidal rule class GFG{ // A sample function whose definite // integral's approximate value // is computed using Trapezoidal // rule static float y(float x) { // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x); } // Function to evaluate the value of integral static float trapezoidal(float a, float b, float n) { // Grid spacing float h = (b - a) / n; // Computing sum of first and last terms // in above formula float s = y(a) + y(b); // Adding middle terms in above formula for (int i = 1; i < n; i++) s += 2 * y( a + i * h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h / 2) * s; } // Driver code public static void main (String[] args) { // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher // value means more accuracy int n = 6; System.out.println("Value of integral is "+ Math.round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); }} // This code is contributed by Anant Agarwal. # Python3 code to implement Trapezoidal rule # A sample function whose definite# integral's approximate value is# computed using Trapezoidal ruledef y( x ): # Declaring the function # f(x) = 1/(1+x*x) return (1 / (1 + x * x)) # Function to evaluate the value of integraldef trapezoidal (a, b, n): # Grid spacing h = (b - a) / n # Computing sum of first and last terms # in above formula s = (y(a) + y(b)) # Adding middle terms in above formula i = 1 while i < n: s += 2 * y(a + i * h) i += 1 # h/2 indicates (b-a)/2n. # Multiplying h/2 with s. return ((h / 2) * s) # Driver code to test above function# Range of definite integralx0 = 0xn = 1 # Number of grids. Higher value means# more accuracyn = 6print ("Value of integral is ", "%.4f"%trapezoidal(x0, xn, n)) # This code is contributed by "Sharad_Bhardwaj". // C# program to implement Trapezoidal// rule.using System; class GFG { // A sample function whose definite // integral's approximate value // is computed using Trapezoidal // rule static float y(float x) { // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x); } // Function to evaluate the value // of integral static float trapezoidal(float a, float b, float n) { // Grid spacing float h = (b - a) / n; // Computing sum of first and // last terms in above formula float s = y(a) + y(b); // Adding middle terms in above // formula for (int i = 1; i < n; i++) s += 2 * y( a + i * h); // h/2 indicates (b-a)/2n. // Multiplying h/2 with s. return (h / 2) * s; } // Driver code public static void Main () { // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher // value means more accuracy int n = 6; Console.Write("Value of integral is " + Math.Round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); }} // This code is contributed by nitin mittal. <?php// PHP program to implement Trapezoidal rule // A sample function whose definite// integral's approximate value is// computed using Trapezoidal rulefunction y($x){ // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + $x * $x);} // Function to evaluate the// value of integralfunction trapezoidal($a, $b, $n){ // Grid spacing $h = ($b - $a) / $n; // Computing sum of first // and last terms // in above formula $s = y($a) + y($b); // Adding middle terms // in above formula for ($i = 1; $i < $n; $i++) $s += 2 * Y($a + $i * $h); // h/2 indicates (b-a)/2n. // Multiplying h/2 with s. return ($h / 2) * $s;} // Driver Code // Range of definite integral $x0 = 0; $xn = 1; // Number of grids. // Higher value means // more accuracy $n = 6; echo("Value of integral is "); echo(trapezoidal($x0, $xn, $n)); // This code is contributed by nitin mittal?> <script> // Javascript program to implement Trapezoidal rule // A sample function whose definite// integral's approximate value // is computed using Trapezoidal// rulefunction y(x){ // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x);} // Function to evaluate the value of integralfunction trapezoidal(a, b, n){ // Grid spacing let h = (b - a) / n; // Computing sum of first and last terms // in above formula let s = y(a) + y(b); // Adding middle terms in above formula for(let i = 1; i < n; i++) s += 2 * y(a + i * h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h / 2) * s;} // Driver code // Range of definite integrallet x0 = 0;let xn = 1; // Number of grids. Higher// value means more accuracylet n = 6; document.write("Value of integral is "+ Math.round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); // This code is contributed by code_hunt </script> Output: Value of integral is 0.7842 References: https://en.wikipedia.org/wiki/Trapezoidal_rule This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal code_hunt varshagumber28 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ Program for factorial of a number The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Program for Decimal to Binary Conversion Program to find sum of elements in a given array
[ { "code": null, "e": 26217, "s": 26189, "text": "\n17 Jun, 2021" }, { "code": null, "e": 26592, "s": 26217, "text": "In the field of numerical analysis, Trapezoidal rule is used to find the approximation of a definite integral. The basic idea in Trapezoidal rule is to assume the region under the graph of the given function to be a trapezoid and calculate its area. It follows that:For more accurate results the domain of the graph is divided into n segments of equal size as shown below: " }, { "code": null, "e": 26699, "s": 26592, "text": "Grid spacing or segment size h = (b-a) / n. Therefore, approximate value of the integral can be given by: " }, { "code": null, "e": 26703, "s": 26699, "text": "C++" }, { "code": null, "e": 26708, "s": 26703, "text": "Java" }, { "code": null, "e": 26716, "s": 26708, "text": "Python3" }, { "code": null, "e": 26719, "s": 26716, "text": "C#" }, { "code": null, "e": 26723, "s": 26719, "text": "PHP" }, { "code": null, "e": 26734, "s": 26723, "text": "Javascript" }, { "code": "// C++ program to implement Trapezoidal rule#include<stdio.h> // A sample function whose definite integral's// approximate value is computed using Trapezoidal// rulefloat y(float x){ // Declaring the function f(x) = 1/(1+x*x) return 1/(1+x*x);} // Function to evaluate the value of integralfloat trapezoidal(float a, float b, float n){ // Grid spacing float h = (b-a)/n; // Computing sum of first and last terms // in above formula float s = y(a)+y(b); // Adding middle terms in above formula for (int i = 1; i < n; i++) s += 2*y(a+i*h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h/2)*s;} // Driver program to test above functionint main(){ // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher value means // more accuracy int n = 6; printf(\"Value of integral is %6.4f\\n\", trapezoidal(x0, xn, n)); return 0;}", "e": 27684, "s": 26734, "text": null }, { "code": "// Java program to implement Trapezoidal rule class GFG{ // A sample function whose definite // integral's approximate value // is computed using Trapezoidal // rule static float y(float x) { // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x); } // Function to evaluate the value of integral static float trapezoidal(float a, float b, float n) { // Grid spacing float h = (b - a) / n; // Computing sum of first and last terms // in above formula float s = y(a) + y(b); // Adding middle terms in above formula for (int i = 1; i < n; i++) s += 2 * y( a + i * h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h / 2) * s; } // Driver code public static void main (String[] args) { // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher // value means more accuracy int n = 6; System.out.println(\"Value of integral is \"+ Math.round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); }} // This code is contributed by Anant Agarwal.", "e": 28955, "s": 27684, "text": null }, { "code": "# Python3 code to implement Trapezoidal rule # A sample function whose definite# integral's approximate value is# computed using Trapezoidal ruledef y( x ): # Declaring the function # f(x) = 1/(1+x*x) return (1 / (1 + x * x)) # Function to evaluate the value of integraldef trapezoidal (a, b, n): # Grid spacing h = (b - a) / n # Computing sum of first and last terms # in above formula s = (y(a) + y(b)) # Adding middle terms in above formula i = 1 while i < n: s += 2 * y(a + i * h) i += 1 # h/2 indicates (b-a)/2n. # Multiplying h/2 with s. return ((h / 2) * s) # Driver code to test above function# Range of definite integralx0 = 0xn = 1 # Number of grids. Higher value means# more accuracyn = 6print (\"Value of integral is \", \"%.4f\"%trapezoidal(x0, xn, n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 29856, "s": 28955, "text": null }, { "code": "// C# program to implement Trapezoidal// rule.using System; class GFG { // A sample function whose definite // integral's approximate value // is computed using Trapezoidal // rule static float y(float x) { // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x); } // Function to evaluate the value // of integral static float trapezoidal(float a, float b, float n) { // Grid spacing float h = (b - a) / n; // Computing sum of first and // last terms in above formula float s = y(a) + y(b); // Adding middle terms in above // formula for (int i = 1; i < n; i++) s += 2 * y( a + i * h); // h/2 indicates (b-a)/2n. // Multiplying h/2 with s. return (h / 2) * s; } // Driver code public static void Main () { // Range of definite integral float x0 = 0; float xn = 1; // Number of grids. Higher // value means more accuracy int n = 6; Console.Write(\"Value of integral is \" + Math.Round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); }} // This code is contributed by nitin mittal.", "e": 31173, "s": 29856, "text": null }, { "code": "<?php// PHP program to implement Trapezoidal rule // A sample function whose definite// integral's approximate value is// computed using Trapezoidal rulefunction y($x){ // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + $x * $x);} // Function to evaluate the// value of integralfunction trapezoidal($a, $b, $n){ // Grid spacing $h = ($b - $a) / $n; // Computing sum of first // and last terms // in above formula $s = y($a) + y($b); // Adding middle terms // in above formula for ($i = 1; $i < $n; $i++) $s += 2 * Y($a + $i * $h); // h/2 indicates (b-a)/2n. // Multiplying h/2 with s. return ($h / 2) * $s;} // Driver Code // Range of definite integral $x0 = 0; $xn = 1; // Number of grids. // Higher value means // more accuracy $n = 6; echo(\"Value of integral is \"); echo(trapezoidal($x0, $xn, $n)); // This code is contributed by nitin mittal?>", "e": 32134, "s": 31173, "text": null }, { "code": "<script> // Javascript program to implement Trapezoidal rule // A sample function whose definite// integral's approximate value // is computed using Trapezoidal// rulefunction y(x){ // Declaring the function // f(x) = 1/(1+x*x) return 1 / (1 + x * x);} // Function to evaluate the value of integralfunction trapezoidal(a, b, n){ // Grid spacing let h = (b - a) / n; // Computing sum of first and last terms // in above formula let s = y(a) + y(b); // Adding middle terms in above formula for(let i = 1; i < n; i++) s += 2 * y(a + i * h); // h/2 indicates (b-a)/2n. Multiplying h/2 // with s. return (h / 2) * s;} // Driver code // Range of definite integrallet x0 = 0;let xn = 1; // Number of grids. Higher// value means more accuracylet n = 6; document.write(\"Value of integral is \"+ Math.round(trapezoidal(x0, xn, n) * 10000.0) / 10000.0); // This code is contributed by code_hunt </script>", "e": 33149, "s": 32134, "text": null }, { "code": null, "e": 33158, "s": 33149, "text": "Output: " }, { "code": null, "e": 33186, "s": 33158, "text": "Value of integral is 0.7842" }, { "code": null, "e": 33245, "s": 33186, "text": "References: https://en.wikipedia.org/wiki/Trapezoidal_rule" }, { "code": null, "e": 33667, "s": 33245, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33680, "s": 33667, "text": "nitin mittal" }, { "code": null, "e": 33690, "s": 33680, "text": "code_hunt" }, { "code": null, "e": 33705, "s": 33690, "text": "varshagumber28" }, { "code": null, "e": 33718, "s": 33705, "text": "Mathematical" }, { "code": null, "e": 33731, "s": 33718, "text": "Mathematical" }, { "code": null, "e": 33829, "s": 33731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33853, "s": 33829, "text": "Merge two sorted arrays" }, { "code": null, "e": 33896, "s": 33853, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33910, "s": 33896, "text": "Prime Numbers" }, { "code": null, "e": 33983, "s": 33910, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34004, "s": 33983, "text": "Operators in C / C++" }, { "code": null, "e": 34038, "s": 34004, "text": "Program for factorial of a number" }, { "code": null, "e": 34081, "s": 34038, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34134, "s": 34081, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 34175, "s": 34134, "text": "Program for Decimal to Binary Conversion" } ]
Minimum Points To Reach Destination | Practice | GeeksforGeeks
Given a grid of size M*N with each cell consisting of an integer which represents points. We can move across a cell only if we have positive points. Whenever we pass through a cell, points in that cell are added to our overall points, the task is to find minimum initial points to reach cell (m-1, n-1) from (0, 0) by following these certain set of rules : 1. From a cell (i, j) we can move to (i + 1, j) or (i, j + 1). 2. We cannot move from (i, j) if your overall points at (i, j) are <= 0. 3. We have to reach at (n-1, m-1) with minimum positive points i.e., > 0. Example 1: Input: M = 3, N = 3 arr[][] = {{-2,-3,3}, {-5,-10,1}, {10,30,-5}}; Output: 7 Explanation: 7 is the minimum value to reach the destination with positive throughout the path. Below is the path. (0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2) We start from (0, 0) with 7, we reach (0, 1) with 5, (0, 2) with 2, (1, 2) with 5, (2, 2) with and finally we have 1 point (we needed greater than 0 points at the end). Input: M = 3, N = 2 arr[][] = {{2,3}, {5,10}, {10,30}}; Output: 1 Explanation: Take any path, all of them are positive. So, required one point at the start Your Task: You don't need to read input or print anything. Complete the function minPoints() which takes N, M and 2-d vector as input parameters and returns the integer value Expected Time Complexity: O(N*M) Expected Auxiliary Space: O(N*M) Constraints: 1 ≤ N ≤ 103 0 artistdarkangel2 months ago JAVA Code TC: O(N*M) space : O(1) execution time : 0.5 sec public int minPoints(int a[][],int m,int n) { if(a[m-1][n-1]>0) a[m-1][n-1]=0; for(int i=n-2; i>=0; i--) { a[m-1][i]+=a[m-1][i+1]; if(a[m-1][i]>0) { a[m-1][i]=0; } } for(int i=m-2; i>=0; i--) { a[i][n-1]+=a[i+1][n-1]; if(a[i][n-1]>0) { a[i][n-1]=0; } } for(int i=m-2; i>=0; i--) { for(int j=n-2; j>=0; j--) { a[i][j]+=Math.max(a[i+1][j],a[i][j+1]); if(a[i][j]>0) a[i][j]=0; } } return Math.abs(a[0][0])+1;} 0 shivambhadani1236 months ago int minPoints(vector<vector<int>> points, int M, int N) { int dp[M][N]; dp[M-1][N-1] = 0; if(points[M-1][N-1]<0) dp[M-1][N-1] = points[M-1][N-1]; for(int i=M-1; i>=0; i--) { for(int j=N-1; j>=0; j--) { if(i==M-1 && j==N-1) continue; if(i+1<M && j+1<N) { dp[i][j] = points[i][j] + max(dp[i+1][j], dp[i][j+1]); if(dp[i][j]>0) dp[i][j] = 0; } else if(i+1<M) { dp[i][j] = points[i][j] + dp[i+1][j]; if(dp[i][j]>0) dp[i][j] = 0; } else if(j+1<N) { dp[i][j] = points[i][j] + dp[i][j+1]; if(dp[i][j]>0) dp[i][j] = 0; } } } return abs(dp[0][0])+1; } 0 CSE_010_Tanveer Ahmed10 months ago CSE_010_Tanveer Ahmed TC: O(N*M) space : O(n*m) execution time : 0.5 sec int dp[1001][1001]; bool issafe(int r,int c, int rows,int cols){ if(r<rows &&="" c<cols)return="" true;="" return="" false;="" }="" int="" paths[2][2]="{{1,0},{0,1}};" int="" solve(vector<vector<int=""> > & points , int rows,int cols,int r,int c){ if(dp[r][c]!=INT_MAX) return dp[r][c]; if(r==rows-1 && c == cols- 1) { //if the final destination is negative then return negative else return 0; if(points[r][c]>=0) return dp[r][c]=0; else return dp[r][c] = points[r][c]; } int down= INT_MIN,right= INT_MIN; if(issafe(r+1,c,rows, cols)) { down = solve(points,rows,cols,r+1,c) + points[r][c]; if(down >0) down = 0; } if(issafe(r,c+1 ,rows, cols)) { right = solve(points,rows,cols,r,c+1)+ points[r][c]; if(right >0) right = 0; } dp[r][c] = max(down,right); return max(down,right);}int minPoints(vector<vector<int>> points, int M, int N) { for(int i=0;i<m;i++)for(int j="0;j&lt;N;j++)dp[i][j]" =="" int_max;="" int="" result="solve(points,M,N,0,0);" return="" abs(result)+1;="" }=""> 0 wallflower10 months ago wallflower Easy bottom up DP java https://ide.geeksforgeeks.o... 0 AMAN SHAKYA1 year ago AMAN SHAKYA HINT :- SIMILAR QUESTION RAT IN A MAZE PATH 1. DECLARE THE MEANING OF EACH CELL YOU CAN ABLE TO DO THIS QUESTION EASILY 0 yash makadia1 year ago yash makadia I read the editoral couple of times , still can't figure out why we can't go top left to bottom right. Can anyone explain 0 raghav2 years ago raghav BEST SOLUTION[ EDITORIAL ] #define ll long long #define vi vector<int>class Solution{public:int minPoints(vector<vector<int>> p , int M, int N) { vector< vi > t ; t = p ; t[M-1][N-1] = t[M-1][N-1] > 0 ? 1 : abs( t[M-1][N-1] ) + 1 ; for( int i = M-2 ; i >= 0 ; i-- )t[i][N-1] = max( t[i+1][N-1] - p[i][N-1] , 1 ); for( int j = N-2 ; j >= 0 ; j-- )t[M-1][j] = max( t[M-1][j+1] - p[M-1][j] , 1 ); for( int i = M-2 ; i >= 0 ; i-- ) for( int j = N-2 ; j >= 0 ; j-- ) { int c = min( t[i+1][j] , t[i][j+1] ) - p[i][j] ; t[i][j] = max( c , 1 ) ; } return t[0][0] ; } }; 0 Projjal Sengupta2 years ago Projjal Sengupta For example 1, the output should be 8, right?. If not then can someone explain? 0 Wajahat Yusuf2 years ago Wajahat Yusuf Should be in the medium categorysimple recursive solutionhttps://ide.geeksforgeeks.o... 0 Vishal Kaushik2 years ago Vishal Kaushik In my code am getting error like first ans got print and then some garbage value is printed...help me in finding the errror.....code is given below #include <iostream>using namespace std; int helper(int **grid,int r,int c){ int **dp=new int*[r]; for(int i=0;i<r;i++) {="" dp[i]="new" int[c];="" for(int="" j="0;j&lt;c;j++)" {="" dp[i][j]="-1;" }="" }="" dp[r-1][c-1]="grid[r-1][c-1]">0?1:abs(grid[r-1][c-1])+1; //fill last row for(int i=r-2;i>=0;i--) { dp[i][c-1]=max(1,dp[i+1][c-1]-grid[i][c-1]); } for(int i=c-2;i>=0;i--)//fill the last column { dp[r-1][i]=max(1,dp[r-1][i+1]-grid[r-1][i]); } for(int i=r-2;i>=0;i--) { for(int j=c-2;j>=0;j--) { int a=min(dp[i+1][j],dp[i][j+1]); dp[i][j]=max(1,a-grid[i][j]); } } int ans=dp[0][0]; for(int i=0;i<r;i++) delete[]="" dp[i];="" return="" ans;="" }="" int="" main()="" {="" int="" t;="" cin="">>t;while(t!=0){ int r,c; cin>>r>>c; int **grid=new int*[r]; for(int i=0;i<r;i++) {="" grid[i]="new" int[c];="" for(int="" j="0;j&lt;c;j++)" {="" cin="">>grid[i][j]; } } int a=helper(grid,r,c); cout<<a; t--;="" }="" return="" 0;="" }=""> 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": 807, "s": 238, "text": "Given a grid of size M*N with each cell consisting of an integer which represents points. We can move across a cell only if we have positive points. Whenever we pass through a cell, points in that cell are added to our overall points, the task is to find minimum initial points to reach cell (m-1, n-1) from (0, 0) by following these certain set of rules :\n \n1. From a cell (i, j) we can move to (i + 1, j) or (i, j + 1).\n2. We cannot move from (i, j) if your overall points at (i, j) are <= 0.\n3. We have to reach at (n-1, m-1) with minimum positive points i.e., > 0." }, { "code": null, "e": 818, "s": 807, "text": "Example 1:" }, { "code": null, "e": 1271, "s": 818, "text": "Input: M = 3, N = 3 \n arr[][] = {{-2,-3,3}, \n {-5,-10,1}, \n {10,30,-5}}; \n\nOutput: 7\nExplanation: 7 is the minimum value to\nreach the destination with positive\nthroughout the path. Below is the path.\n(0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2)\nWe start from (0, 0) with 7, we reach\n(0, 1) with 5, (0, 2) with 2, (1, 2)\nwith 5, (2, 2) with and finally we have\n1 point (we needed greater than 0 points\nat the end)." }, { "code": null, "e": 1476, "s": 1271, "text": "Input: M = 3, N = 2\n arr[][] = {{2,3}, \n {5,10}, \n {10,30}}; \nOutput: 1\nExplanation: Take any path, all of them \nare positive. So, required one point \nat the start\n" }, { "code": null, "e": 1747, "s": 1476, "text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function minPoints() which takes N, M and 2-d vector as input parameters and returns the integer value\n\nExpected Time Complexity: O(N*M)\nExpected Auxiliary Space: O(N*M)\n\nConstraints:\n1 ≤ N ≤ 103" }, { "code": null, "e": 1749, "s": 1747, "text": "0" }, { "code": null, "e": 1777, "s": 1749, "text": "artistdarkangel2 months ago" }, { "code": null, "e": 1787, "s": 1777, "text": "JAVA Code" }, { "code": null, "e": 1836, "s": 1787, "text": "TC: O(N*M) space : O(1) execution time : 0.5 sec" }, { "code": null, "e": 2439, "s": 1838, "text": "public int minPoints(int a[][],int m,int n) { if(a[m-1][n-1]>0) a[m-1][n-1]=0; for(int i=n-2; i>=0; i--) { a[m-1][i]+=a[m-1][i+1]; if(a[m-1][i]>0) { a[m-1][i]=0; } } for(int i=m-2; i>=0; i--) { a[i][n-1]+=a[i+1][n-1]; if(a[i][n-1]>0) { a[i][n-1]=0; } } for(int i=m-2; i>=0; i--) { for(int j=n-2; j>=0; j--) { a[i][j]+=Math.max(a[i+1][j],a[i][j+1]); if(a[i][j]>0) a[i][j]=0; } } return Math.abs(a[0][0])+1;} " }, { "code": null, "e": 2441, "s": 2439, "text": "0" }, { "code": null, "e": 2470, "s": 2441, "text": "shivambhadani1236 months ago" }, { "code": null, "e": 3257, "s": 2470, "text": "\tint minPoints(vector<vector<int>> points, int M, int N) \n\t{\n\t int dp[M][N];\n\t dp[M-1][N-1] = 0;\n\t if(points[M-1][N-1]<0) dp[M-1][N-1] = points[M-1][N-1];\n\t for(int i=M-1; i>=0; i--) {\n\t for(int j=N-1; j>=0; j--) {\n\t if(i==M-1 && j==N-1) continue;\n\t if(i+1<M && j+1<N) {\n\t dp[i][j] = points[i][j] + max(dp[i+1][j], dp[i][j+1]);\n\t if(dp[i][j]>0) dp[i][j] = 0;\n\t }\n\t else if(i+1<M) {\n\t dp[i][j] = points[i][j] + dp[i+1][j];\n\t if(dp[i][j]>0) dp[i][j] = 0;\n\t }\n\t else if(j+1<N) {\n\t dp[i][j] = points[i][j] + dp[i][j+1];\n\t if(dp[i][j]>0) dp[i][j] = 0;\n\t }\n\t }\n\t }\n\t return abs(dp[0][0])+1;\n\t}" }, { "code": null, "e": 3259, "s": 3257, "text": "0" }, { "code": null, "e": 3294, "s": 3259, "text": "CSE_010_Tanveer Ahmed10 months ago" }, { "code": null, "e": 3316, "s": 3294, "text": "CSE_010_Tanveer Ahmed" }, { "code": null, "e": 3880, "s": 3316, "text": "TC: O(N*M) space : O(n*m) execution time : 0.5 sec int dp[1001][1001]; bool issafe(int r,int c, int rows,int cols){ if(r<rows &&=\"\" c<cols)return=\"\" true;=\"\" return=\"\" false;=\"\" }=\"\" int=\"\" paths[2][2]=\"{{1,0},{0,1}};\" int=\"\" solve(vector<vector<int=\"\"> > & points , int rows,int cols,int r,int c){ if(dp[r][c]!=INT_MAX) return dp[r][c]; if(r==rows-1 && c == cols- 1) { //if the final destination is negative then return negative else return 0; if(points[r][c]>=0) return dp[r][c]=0; else return dp[r][c] = points[r][c]; }" }, { "code": null, "e": 4487, "s": 3880, "text": " int down= INT_MIN,right= INT_MIN; if(issafe(r+1,c,rows, cols)) { down = solve(points,rows,cols,r+1,c) + points[r][c]; if(down >0) down = 0; } if(issafe(r,c+1 ,rows, cols)) { right = solve(points,rows,cols,r,c+1)+ points[r][c]; if(right >0) right = 0; } dp[r][c] = max(down,right); return max(down,right);}int minPoints(vector<vector<int>> points, int M, int N) { for(int i=0;i<m;i++)for(int j=\"0;j&lt;N;j++)dp[i][j]\" ==\"\" int_max;=\"\" int=\"\" result=\"solve(points,M,N,0,0);\" return=\"\" abs(result)+1;=\"\" }=\"\">" }, { "code": null, "e": 4489, "s": 4487, "text": "0" }, { "code": null, "e": 4513, "s": 4489, "text": "wallflower10 months ago" }, { "code": null, "e": 4524, "s": 4513, "text": "wallflower" }, { "code": null, "e": 4547, "s": 4524, "text": "Easy bottom up DP java" }, { "code": null, "e": 4578, "s": 4547, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 4580, "s": 4578, "text": "0" }, { "code": null, "e": 4602, "s": 4580, "text": "AMAN SHAKYA1 year ago" }, { "code": null, "e": 4614, "s": 4602, "text": "AMAN SHAKYA" }, { "code": null, "e": 4735, "s": 4614, "text": "HINT :- SIMILAR QUESTION RAT IN A MAZE PATH 1. DECLARE THE MEANING OF EACH CELL YOU CAN ABLE TO DO THIS QUESTION EASILY" }, { "code": null, "e": 4737, "s": 4735, "text": "0" }, { "code": null, "e": 4760, "s": 4737, "text": "yash makadia1 year ago" }, { "code": null, "e": 4773, "s": 4760, "text": "yash makadia" }, { "code": null, "e": 4895, "s": 4773, "text": "I read the editoral couple of times , still can't figure out why we can't go top left to bottom right. Can anyone explain" }, { "code": null, "e": 4897, "s": 4895, "text": "0" }, { "code": null, "e": 4915, "s": 4897, "text": "raghav2 years ago" }, { "code": null, "e": 4922, "s": 4915, "text": "raghav" }, { "code": null, "e": 5533, "s": 4922, "text": " BEST SOLUTION[ EDITORIAL ] #define ll long long #define vi vector<int>class Solution{public:int minPoints(vector<vector<int>> p , int M, int N) { vector< vi > t ; t = p ; t[M-1][N-1] = t[M-1][N-1] > 0 ? 1 : abs( t[M-1][N-1] ) + 1 ; for( int i = M-2 ; i >= 0 ; i-- )t[i][N-1] = max( t[i+1][N-1] - p[i][N-1] , 1 ); for( int j = N-2 ; j >= 0 ; j-- )t[M-1][j] = max( t[M-1][j+1] - p[M-1][j] , 1 ); for( int i = M-2 ; i >= 0 ; i-- ) for( int j = N-2 ; j >= 0 ; j-- ) { int c = min( t[i+1][j] , t[i][j+1] ) - p[i][j] ; t[i][j] = max( c , 1 ) ; } return t[0][0] ; } };" }, { "code": null, "e": 5535, "s": 5533, "text": "0" }, { "code": null, "e": 5563, "s": 5535, "text": "Projjal Sengupta2 years ago" }, { "code": null, "e": 5580, "s": 5563, "text": "Projjal Sengupta" }, { "code": null, "e": 5660, "s": 5580, "text": "For example 1, the output should be 8, right?. If not then can someone explain?" }, { "code": null, "e": 5662, "s": 5660, "text": "0" }, { "code": null, "e": 5687, "s": 5662, "text": "Wajahat Yusuf2 years ago" }, { "code": null, "e": 5701, "s": 5687, "text": "Wajahat Yusuf" }, { "code": null, "e": 5789, "s": 5701, "text": "Should be in the medium categorysimple recursive solutionhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 5791, "s": 5789, "text": "0" }, { "code": null, "e": 5817, "s": 5791, "text": "Vishal Kaushik2 years ago" }, { "code": null, "e": 5832, "s": 5817, "text": "Vishal Kaushik" }, { "code": null, "e": 5980, "s": 5832, "text": "In my code am getting error like first ans got print and then some garbage value is printed...help me in finding the errror.....code is given below" }, { "code": null, "e": 6020, "s": 5980, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 7037, "s": 6020, "text": "int helper(int **grid,int r,int c){ int **dp=new int*[r]; for(int i=0;i<r;i++) {=\"\" dp[i]=\"new\" int[c];=\"\" for(int=\"\" j=\"0;j&lt;c;j++)\" {=\"\" dp[i][j]=\"-1;\" }=\"\" }=\"\" dp[r-1][c-1]=\"grid[r-1][c-1]\">0?1:abs(grid[r-1][c-1])+1; //fill last row for(int i=r-2;i>=0;i--) { dp[i][c-1]=max(1,dp[i+1][c-1]-grid[i][c-1]); } for(int i=c-2;i>=0;i--)//fill the last column { dp[r-1][i]=max(1,dp[r-1][i+1]-grid[r-1][i]); } for(int i=r-2;i>=0;i--) { for(int j=c-2;j>=0;j--) { int a=min(dp[i+1][j],dp[i][j+1]); dp[i][j]=max(1,a-grid[i][j]); } } int ans=dp[0][0]; for(int i=0;i<r;i++) delete[]=\"\" dp[i];=\"\" return=\"\" ans;=\"\" }=\"\" int=\"\" main()=\"\" {=\"\" int=\"\" t;=\"\" cin=\"\">>t;while(t!=0){ int r,c; cin>>r>>c; int **grid=new int*[r]; for(int i=0;i<r;i++) {=\"\" grid[i]=\"new\" int[c];=\"\" for(int=\"\" j=\"0;j&lt;c;j++)\" {=\"\" cin=\"\">>grid[i][j]; } } int a=helper(grid,r,c); cout<<a; t--;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 7183, "s": 7037, "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": 7219, "s": 7183, "text": " Login to access your submissions. " }, { "code": null, "e": 7229, "s": 7219, "text": "\nProblem\n" }, { "code": null, "e": 7239, "s": 7229, "text": "\nContest\n" }, { "code": null, "e": 7302, "s": 7239, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7450, "s": 7302, "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": 7658, "s": 7450, "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": 7764, "s": 7658, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Analog Clock in Flutter - GeeksforGeeks
15 Feb, 2021 In Flutter, everything is a widget. Plugins, commonly called dependencies are tools that are quite commonly used in Flutter, which helps in making the code work easier and faster. There are plenty of plugins used in Flutter, out of which for creating an analog clock, the “analog_clock” plugin can be used. Steps for adding the plugin to the Flutter app is as follows: Step 1: Open “pubspec.yaml” file from the project folder. pubspec.yaml file Step 2: In the pubspec.yaml file, type “analog_clock:” under dependencies. After adding, the code looks like this: Dart dependencies: flutter: sdk: flutter analog_clock: Step 3: Now click “Pub Get” button at the top of the application (i,e., in Android Studio). Step 4: The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully. Step 5: Now import the plugin or package by adding the “import ‘package:analog_clock/analog_clock.dart’;” code to the top of the “main.dart” file. The analog_clock plugin has many parameters in it, which plays a major role in designing the clock. These parameters are completely customizable making it more user-friendly. The major parameters of the analog_clock plugin are as follows: datetime: It helps to set the time from which the clock needs to run.showTicks: The measurements available in the borders of the clock are called “ticks”. These ticks can be hidden using the “false” condition and vice versa.showNumbers: It helps to hide the numbers near the ticks by using the “false” condition.showSecondHand: It helps to hide the second hand by using the “false” condition.showDigitalClock: It helps us to make the digital clock that has hours, minutes, and seconds readings in it, visible inside the analog clock.tickColor, minuteHandColor, hourHandColor, secondHandColor, digitalClockColor, numberColor: These parameters help in assigning a color to the ticks, minute hand, hour hand, second hand, digital clock, and number respectively.isLive: It is used to let the clock running live after the time is set.decoration: This parameter helps to design the clock using the available decoration widgets in a flutter.height, width: These parameters help to set the height and width of the clock.textScaleFactor: It helps to set the size of the digital clock and the numbers near the ticks. datetime: It helps to set the time from which the clock needs to run. showTicks: The measurements available in the borders of the clock are called “ticks”. These ticks can be hidden using the “false” condition and vice versa. showNumbers: It helps to hide the numbers near the ticks by using the “false” condition. showSecondHand: It helps to hide the second hand by using the “false” condition. showDigitalClock: It helps us to make the digital clock that has hours, minutes, and seconds readings in it, visible inside the analog clock. tickColor, minuteHandColor, hourHandColor, secondHandColor, digitalClockColor, numberColor: These parameters help in assigning a color to the ticks, minute hand, hour hand, second hand, digital clock, and number respectively. isLive: It is used to let the clock running live after the time is set. decoration: This parameter helps to design the clock using the available decoration widgets in a flutter. height, width: These parameters help to set the height and width of the clock. textScaleFactor: It helps to set the size of the digital clock and the numbers near the ticks. In flutter, there are two types of widgets – Stateless and Stateful widget. The stateless widget is used to create static widgets and the stateful widget is used to create dynamic widgets. Since time is a dynamic factor, we need to use the stateful widget to create the analog clock. So, it is required to create a “state” in which the clock runs and the AnalogClock function is called to make use of the parameters to design the clock that’s needed. Dart import 'package:analog_clock/analog_clock.dart';import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) => MaterialApp( home: Scaffold( appBar: AppBar( backgroundColor: Colors.green[900], title: Text('Geeks for Geeks'), ), backgroundColor: Colors.green, body: Center( child: AnalogClock( decoration: BoxDecoration( border: Border.all(width: 3.0, color: Colors.black), color: Colors.black, shape: BoxShape.circle), width: 200.0, isLive: true, hourHandColor: Colors.white, minuteHandColor: Colors.white, showSecondHand: true, numberColor: Colors.white, showNumbers: true, textScaleFactor: 1.5, showTicks: true, showDigitalClock: true, digitalClockColor: Colors.white, datetime: DateTime(2020, 8, 4, 9, 11, 0), ), ), ), );} android Flutter Flutter UI-components Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 26407, "s": 26379, "text": "\n15 Feb, 2021" }, { "code": null, "e": 26714, "s": 26407, "text": "In Flutter, everything is a widget. Plugins, commonly called dependencies are tools that are quite commonly used in Flutter, which helps in making the code work easier and faster. There are plenty of plugins used in Flutter, out of which for creating an analog clock, the “analog_clock” plugin can be used." }, { "code": null, "e": 26776, "s": 26714, "text": "Steps for adding the plugin to the Flutter app is as follows:" }, { "code": null, "e": 26834, "s": 26776, "text": "Step 1: Open “pubspec.yaml” file from the project folder." }, { "code": null, "e": 26852, "s": 26834, "text": "pubspec.yaml file" }, { "code": null, "e": 26967, "s": 26852, "text": "Step 2: In the pubspec.yaml file, type “analog_clock:” under dependencies. After adding, the code looks like this:" }, { "code": null, "e": 26972, "s": 26967, "text": "Dart" }, { "code": "dependencies: flutter: sdk: flutter analog_clock:", "e": 27027, "s": 26972, "text": null }, { "code": null, "e": 27119, "s": 27027, "text": "Step 3: Now click “Pub Get” button at the top of the application (i,e., in Android Studio)." }, { "code": null, "e": 27236, "s": 27119, "text": "Step 4: The “Process finished with exit code 0“ in the console shows that the dependency is been added successfully." }, { "code": null, "e": 27384, "s": 27236, "text": "Step 5: Now import the plugin or package by adding the “import ‘package:analog_clock/analog_clock.dart’;” code to the top of the “main.dart” file." }, { "code": null, "e": 27559, "s": 27384, "text": "The analog_clock plugin has many parameters in it, which plays a major role in designing the clock. These parameters are completely customizable making it more user-friendly." }, { "code": null, "e": 27623, "s": 27559, "text": "The major parameters of the analog_clock plugin are as follows:" }, { "code": null, "e": 28730, "s": 27623, "text": "datetime: It helps to set the time from which the clock needs to run.showTicks: The measurements available in the borders of the clock are called “ticks”. These ticks can be hidden using the “false” condition and vice versa.showNumbers: It helps to hide the numbers near the ticks by using the “false” condition.showSecondHand: It helps to hide the second hand by using the “false” condition.showDigitalClock: It helps us to make the digital clock that has hours, minutes, and seconds readings in it, visible inside the analog clock.tickColor, minuteHandColor, hourHandColor, secondHandColor, digitalClockColor, numberColor: These parameters help in assigning a color to the ticks, minute hand, hour hand, second hand, digital clock, and number respectively.isLive: It is used to let the clock running live after the time is set.decoration: This parameter helps to design the clock using the available decoration widgets in a flutter.height, width: These parameters help to set the height and width of the clock.textScaleFactor: It helps to set the size of the digital clock and the numbers near the ticks." }, { "code": null, "e": 28800, "s": 28730, "text": "datetime: It helps to set the time from which the clock needs to run." }, { "code": null, "e": 28956, "s": 28800, "text": "showTicks: The measurements available in the borders of the clock are called “ticks”. These ticks can be hidden using the “false” condition and vice versa." }, { "code": null, "e": 29045, "s": 28956, "text": "showNumbers: It helps to hide the numbers near the ticks by using the “false” condition." }, { "code": null, "e": 29126, "s": 29045, "text": "showSecondHand: It helps to hide the second hand by using the “false” condition." }, { "code": null, "e": 29268, "s": 29126, "text": "showDigitalClock: It helps us to make the digital clock that has hours, minutes, and seconds readings in it, visible inside the analog clock." }, { "code": null, "e": 29494, "s": 29268, "text": "tickColor, minuteHandColor, hourHandColor, secondHandColor, digitalClockColor, numberColor: These parameters help in assigning a color to the ticks, minute hand, hour hand, second hand, digital clock, and number respectively." }, { "code": null, "e": 29566, "s": 29494, "text": "isLive: It is used to let the clock running live after the time is set." }, { "code": null, "e": 29672, "s": 29566, "text": "decoration: This parameter helps to design the clock using the available decoration widgets in a flutter." }, { "code": null, "e": 29751, "s": 29672, "text": "height, width: These parameters help to set the height and width of the clock." }, { "code": null, "e": 29846, "s": 29751, "text": "textScaleFactor: It helps to set the size of the digital clock and the numbers near the ticks." }, { "code": null, "e": 29922, "s": 29846, "text": "In flutter, there are two types of widgets – Stateless and Stateful widget." }, { "code": null, "e": 30297, "s": 29922, "text": "The stateless widget is used to create static widgets and the stateful widget is used to create dynamic widgets. Since time is a dynamic factor, we need to use the stateful widget to create the analog clock. So, it is required to create a “state” in which the clock runs and the AnalogClock function is called to make use of the parameters to design the clock that’s needed." }, { "code": null, "e": 30302, "s": 30297, "text": "Dart" }, { "code": "import 'package:analog_clock/analog_clock.dart';import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) => MaterialApp( home: Scaffold( appBar: AppBar( backgroundColor: Colors.green[900], title: Text('Geeks for Geeks'), ), backgroundColor: Colors.green, body: Center( child: AnalogClock( decoration: BoxDecoration( border: Border.all(width: 3.0, color: Colors.black), color: Colors.black, shape: BoxShape.circle), width: 200.0, isLive: true, hourHandColor: Colors.white, minuteHandColor: Colors.white, showSecondHand: true, numberColor: Colors.white, showNumbers: true, textScaleFactor: 1.5, showTicks: true, showDigitalClock: true, digitalClockColor: Colors.white, datetime: DateTime(2020, 8, 4, 9, 11, 0), ), ), ), );}", "e": 31552, "s": 30302, "text": null }, { "code": null, "e": 31560, "s": 31552, "text": "android" }, { "code": null, "e": 31568, "s": 31560, "text": "Flutter" }, { "code": null, "e": 31590, "s": 31568, "text": "Flutter UI-components" }, { "code": null, "e": 31606, "s": 31590, "text": "Flutter-widgets" }, { "code": null, "e": 31614, "s": 31606, "text": "Android" }, { "code": null, "e": 31619, "s": 31614, "text": "Dart" }, { "code": null, "e": 31627, "s": 31619, "text": "Flutter" }, { "code": null, "e": 31635, "s": 31627, "text": "Android" }, { "code": null, "e": 31733, "s": 31635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31771, "s": 31733, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 31810, "s": 31771, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31860, "s": 31810, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31911, "s": 31860, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 31953, "s": 31911, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31985, "s": 31953, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 32013, "s": 31985, "text": "Listview.builder in Flutter" }, { "code": null, "e": 32035, "s": 32013, "text": "Flutter - Asset Image" }, { "code": null, "e": 32060, "s": 32035, "text": "Splash Screen in Flutter" } ]
Different Ways to Add Image to Toast in Android - GeeksforGeeks
07 Mar, 2021 A Toast is a feedback message. It takes very little space for displaying while the overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If the user wants a permanently visible message, a Notification can be used. Another type of Toast is custom Toast, in which images can be used instead of a simple message. So in this article, we are going to discuss three different ways to Add Images to Toast on Android. Note that we are going to implement this project using the Java language. Step 1: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We will create a simple TextView inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Show image in Toast" android:textSize="22sp" android:textStyle="bold" /> </LinearLayout> Step 2: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); // on click on show text images toast will be shown show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Initialising Toast Toast toast = new Toast(getApplicationContext()); ImageView view = new ImageView(getApplicationContext()); // set image resource to be shown view.setImageResource(R.drawable.screenshot); // setting view to toast toast.setView(view); // showing toast toast.show(); } }); }} Output: Step 1: Working with the activity_main.xml file The activity_main.xml file will be the same. Step 2: Create a new toast_image_layout.xml file Go to the app > res > layout > right-click > New > Layout Resource File and name the file as toast_image_layout. Below is the code for the toast_image_layout.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white"> <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Toast Notification Type" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@android:color/black"></TextView> <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_margin="5dip" android:src="@drawable/gfgimage"></ImageView> </RelativeLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LayoutInflater inflater = getLayoutInflater(); // inflate layout file in Layout Inflater View view = inflater.inflate(R.layout.toast_image_layout, (ViewGroup) findViewById(R.id.relativeLayout1)); Toast toast = new Toast(getApplicationContext()); // add view of toast to // toast_image_layout file toast.setView(view); // show toast toast.show(); } }); }} Output: Step 1: Working with the activity_main.xml file The activity_main.xml file will be the same. Step 2: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText msg; TextView show; ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LinearLayout linearLayout = new LinearLayout(getApplicationContext()); // populate layout with your image and text // or whatever you want to put in here ImageView imageView = new ImageView(getApplicationContext()); // adding image to be shown imageView.setImageResource(R.drawable.geeks); // adding image to linearlayout linearLayout.addView(imageView); Toast toast = new Toast(getApplicationContext()); // showing toast on bottom toast.setGravity(Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_LONG); // setting view of toast to linear layout toast.setView(linearLayout); toast.show(); } }); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24749, "s": 24721, "text": "\n07 Mar, 2021" }, { "code": null, "e": 25301, "s": 24749, "text": "A Toast is a feedback message. It takes very little space for displaying while the overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If the user wants a permanently visible message, a Notification can be used. Another type of Toast is custom Toast, in which images can be used instead of a simple message. So in this article, we are going to discuss three different ways to Add Images to Toast on Android. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25349, "s": 25301, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 25561, "s": 25349, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We will create a simple TextView inside the activity_main.xml file. " }, { "code": null, "e": 25565, "s": 25561, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/show\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"Show image in Toast\" android:textSize=\"22sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 26204, "s": 25565, "text": null }, { "code": null, "e": 26252, "s": 26204, "text": "Step 2: Working with the MainActivity.java file" }, { "code": null, "e": 26442, "s": 26252, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 26447, "s": 26442, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); // on click on show text images toast will be shown show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Initialising Toast Toast toast = new Toast(getApplicationContext()); ImageView view = new ImageView(getApplicationContext()); // set image resource to be shown view.setImageResource(R.drawable.screenshot); // setting view to toast toast.setView(view); // showing toast toast.show(); } }); }}", "e": 27628, "s": 26447, "text": null }, { "code": null, "e": 27636, "s": 27628, "text": "Output:" }, { "code": null, "e": 27684, "s": 27636, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 27729, "s": 27684, "text": "The activity_main.xml file will be the same." }, { "code": null, "e": 27779, "s": 27729, "text": "Step 2: Create a new toast_image_layout.xml file " }, { "code": null, "e": 27948, "s": 27779, "text": "Go to the app > res > layout > right-click > New > Layout Resource File and name the file as toast_image_layout. Below is the code for the toast_image_layout.xml file. " }, { "code": null, "e": 27952, "s": 27948, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/relativeLayout1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@android:color/white\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"Toast Notification Type\" android:textAppearance=\"?android:attr/textAppearanceLarge\" android:textColor=\"@android:color/black\"></TextView> <ImageView android:id=\"@+id/imageView1\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/textView1\" android:layout_margin=\"5dip\" android:src=\"@drawable/gfgimage\"></ImageView> </RelativeLayout>", "e": 28862, "s": 27952, "text": null }, { "code": null, "e": 28910, "s": 28862, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 29100, "s": 28910, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29105, "s": 29100, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LayoutInflater inflater = getLayoutInflater(); // inflate layout file in Layout Inflater View view = inflater.inflate(R.layout.toast_image_layout, (ViewGroup) findViewById(R.id.relativeLayout1)); Toast toast = new Toast(getApplicationContext()); // add view of toast to // toast_image_layout file toast.setView(view); // show toast toast.show(); } }); }}", "e": 30316, "s": 29105, "text": null }, { "code": null, "e": 30324, "s": 30316, "text": "Output:" }, { "code": null, "e": 30372, "s": 30324, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 30417, "s": 30372, "text": "The activity_main.xml file will be the same." }, { "code": null, "e": 30465, "s": 30417, "text": "Step 2: Working with the MainActivity.java file" }, { "code": null, "e": 30655, "s": 30465, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 30660, "s": 30655, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText msg; TextView show; ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = findViewById(R.id.show); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LinearLayout linearLayout = new LinearLayout(getApplicationContext()); // populate layout with your image and text // or whatever you want to put in here ImageView imageView = new ImageView(getApplicationContext()); // adding image to be shown imageView.setImageResource(R.drawable.geeks); // adding image to linearlayout linearLayout.addView(imageView); Toast toast = new Toast(getApplicationContext()); // showing toast on bottom toast.setGravity(Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_LONG); // setting view of toast to linear layout toast.setView(linearLayout); toast.show(); } }); }}", "e": 32341, "s": 30660, "text": null }, { "code": null, "e": 32349, "s": 32341, "text": "Output:" }, { "code": null, "e": 32357, "s": 32349, "text": "Android" }, { "code": null, "e": 32362, "s": 32357, "text": "Java" }, { "code": null, "e": 32367, "s": 32362, "text": "Java" }, { "code": null, "e": 32375, "s": 32367, "text": "Android" }, { "code": null, "e": 32473, "s": 32375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32482, "s": 32473, "text": "Comments" }, { "code": null, "e": 32495, "s": 32482, "text": "Old Comments" }, { "code": null, "e": 32534, "s": 32495, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32584, "s": 32534, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32635, "s": 32584, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32673, "s": 32635, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32715, "s": 32673, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32730, "s": 32715, "text": "Arrays in Java" }, { "code": null, "e": 32774, "s": 32730, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32796, "s": 32774, "text": "For-each loop in Java" }, { "code": null, "e": 32821, "s": 32796, "text": "Reverse a string in Java" } ]
Changing color randomly in JavaScript
We are required to write a JavaScript function, let’s say randomColor that returns a randomly generated hex color every time it is called. Following is the code − const randomColor = () => { let color = '#'; for (let i = 0; i < 6; i++){ const random = Math.random(); const bit = (random * 16) | 0; color += (bit).toString(16); }; return color; }; console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); console.log(randomColor()); This will produce the following output in console − #762b46 #cfa0bf #a20ee1 #c2f7e0 #5d5822 #380f30 #805408
[ { "code": null, "e": 1201, "s": 1062, "text": "We are required to write a JavaScript function, let’s say randomColor that returns a randomly generated hex color every time it is called." }, { "code": null, "e": 1225, "s": 1201, "text": "Following is the code −" }, { "code": null, "e": 1635, "s": 1225, "text": "const randomColor = () => {\n let color = '#';\n for (let i = 0; i < 6; i++){\n const random = Math.random();\n const bit = (random * 16) | 0;\n color += (bit).toString(16);\n };\n return color;\n};\nconsole.log(randomColor());\nconsole.log(randomColor());\nconsole.log(randomColor());\nconsole.log(randomColor());\nconsole.log(randomColor());\nconsole.log(randomColor());\nconsole.log(randomColor());" }, { "code": null, "e": 1687, "s": 1635, "text": "This will produce the following output in console −" }, { "code": null, "e": 1743, "s": 1687, "text": "#762b46\n#cfa0bf\n#a20ee1\n#c2f7e0\n#5d5822\n#380f30\n#805408" } ]
Merge two strings | Practice | GeeksforGeeks
Given two strings S1 and S2 as input, the task is to merge them alternatively i.e. the first character of S1 then the first character of S2 and so on till the strings end. NOTE: Add the whole string if other string is empty. Example 1: Input: S1 = "Hello" S2 = "Bye" Output: HBeylelo Explanation: The characters of both the given strings are arranged alternatlively. ​Example 2: Input: S1 = "abc", S2 = "def" Output: adbecf Explanation: The characters of both the given strings are arranged alternatlively. Your Task: You don't need to read input or print anything. Your task is to complete the function merge() which takes the strings S1 and S2 as input and returns the resultant string by merging both S1 and S2 alternatively starting from S1. Expected Time Complexity: O(|S1| + |S2|). Expected Auxiliary Space: O(1). Constraints: 1<=|S1|, |S2| <=103 0 singhvatsal593 weeks ago string merge (string S1, string S2){ // your code here int i=0; string result="" ; for(int i=0;i<S1.length() || i<S2.length();i++){ if(i<S1.length()){ result+=S1[i]; } if(i<S2.length()){ result+=S2[i]; } } return result;} 0 kshitijmagare194 weeks ago class Solution { StringBuilder merge(String S1, String S2) { // code here StringBuilder str = new StringBuilder(); int s1 =S1.length(); int s2 = S2.length(); int j = 0; int i; if(s1<s2){ for(i = 0; i< s1;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); j = i + 1; } for(i = j ; i< s2;i++){ str.append(S2.charAt(i)); } } else if(s1>s2){ for(i = 0; i< s2;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); j = i + 1; } for(i = j; i< s1;i++){ str.append(S1.charAt(i)); } } else{ for(i = 0; i< s1;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); } } return str; }} +1 codewithshoaib191 month ago String merge(String S1, String S2) { // code here String result = ""; int n1 = S1.length(); int n2 = S2.length(); if (n1 > n2) { for (int i = 0; i < n2; i++) { result += S1.charAt(i); result += S2.charAt(i); } return result + S1.substring(n2); } for (int i = 0; i < n1; i++) { result += S1.charAt(i); result += S2.charAt(i); } return result + S2.substring(n1); } 0 bsricharan2461 month ago Python Easy & Fast Approach | Time Taken = 0.0/2.2 class Solution: def merge(self, S1, S2): # code here res = "" j=0 k=0 for i in range(0, min(len(S1), len(S2))*2,1): if i%2 ==0: res+=S1[j] j+=1 else: res+=S2[k] k+=1 if len(S1) != len(S2): if min(len(S1), len(S2)) == len(S1): res+=S2[k:] else: res+=S1[j:] return res 0 akanshasaraswat13 months ago 100% accurate String merge(String S1, String S2) { // code here String merge = ""; int i=0; int j=0; int k=0; while(i<S1.length() && j<S2.length()){ if(k%2==0){ merge = merge + S1.charAt(i); i++; } else{ merge = merge + S2.charAt(j); j++; } k++; } while(i<S1.length()){ merge = merge + S1.charAt(i); i++; } while(j<S2.length()){ merge = merge + S2.charAt(j);j++;} return merge; } +3 rahulpankaj97543 months ago string merge (string S1, string S2) { string S=""; int n1=S1.size(); int n2=S2.size(); int i=0,j=0; for(int k=0; k<n1+n2; k++) { if(i<n1) { S+=S1[i]; } if(j<n2) { S+=S2[i]; } i++; j++; } return S; } 0 anmol1neema4 months ago time taken -0.2 String merge(String S1, String S2) { // code here int j=0,k=0, p=0; int greatA=0, greatB =0; int valA= S1.length(); int valB = S2.length(); int n = valA + valB; char[] c = new char[n]; if(valA>valB){ greatA = valA-valB; }else{ greatB = valB-valA; } for(int i=0;i<n;i++){ if(i%2==0 && j<valA){ c[i]= S1.charAt(j); j++; }else if(k<valB){ c[i] = S2.charAt(k); k++; }else if(greatA>0){ c[i] = S1.charAt(j); j++; }else if(greatB>0){ c[i] = S2.charAt(k); k++; } } String s = new String(c); return s; } 0 rajithrock4444445 months ago Time Taken-→0.3/2.2 String s4=""; int len=0; if(s1.length()>s2.length()){ len=s1.length(); } else{ len=s2.length(); } for(int i=0;i<len;i++){ if(i<s1.length()){ s4+=s1.charAt(i); } if(i<s2.length()){ s4+=s2.charAt(i); } } return s4; +1 saptarshithe426 months ago class Solution: def merge(self, s1, s2): # code here if ((len(s1) == 0) or (len(s2) == 0)): return (s1 + s2) s = "" for i in range(min(len(s1), len(s2))): s = s + s1[i] + s2[i] if (len(s1) > len(s2)): rem = s1[i + 1:] else: rem = s2[i+1:] return (s + rem) 0 badgujarsachin836 months ago string merge (string S1, string S2) { // your code here string ss=""; bool ans=true; int i=0; int j=0; while( i<S1.size() && j<S2.size()){ if(ans==true){ ss+=S1[i]; ans=false; i++; } if(ans==false){ ss+=S2[j]; ans=true; j++; } } while(i<S1.size()){ ss+=S1[i]; i++; } while(j<S2.size()){ ss+=S2[j]; j++; } return ss; } 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": 451, "s": 226, "text": "Given two strings S1 and S2 as input, the task is to merge them alternatively i.e. the first character of S1 then the first character of S2 and so on till the strings end.\nNOTE: Add the whole string if other string is empty." }, { "code": null, "e": 462, "s": 451, "text": "Example 1:" }, { "code": null, "e": 595, "s": 462, "text": "Input:\nS1 = \"Hello\" S2 = \"Bye\"\nOutput: HBeylelo\nExplanation: The characters of both the \ngiven strings are arranged alternatlively.\n" }, { "code": null, "e": 610, "s": 595, "text": "​Example 2:" }, { "code": null, "e": 740, "s": 610, "text": "Input: \nS1 = \"abc\", S2 = \"def\"\nOutput: adbecf\nExplanation: The characters of both the\ngiven strings are arranged alternatlively.\n" }, { "code": null, "e": 980, "s": 740, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function merge() which takes the strings S1 and S2 as input and returns the resultant string by merging both S1 and S2 alternatively starting from S1." }, { "code": null, "e": 1055, "s": 980, "text": "\nExpected Time Complexity: O(|S1| + |S2|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1089, "s": 1055, "text": "\nConstraints:\n1<=|S1|, |S2| <=103" }, { "code": null, "e": 1091, "s": 1089, "text": "0" }, { "code": null, "e": 1116, "s": 1091, "text": "singhvatsal593 weeks ago" }, { "code": null, "e": 1406, "s": 1118, "text": "string merge (string S1, string S2){ // your code here int i=0; string result=\"\" ; for(int i=0;i<S1.length() || i<S2.length();i++){ if(i<S1.length()){ result+=S1[i]; } if(i<S2.length()){ result+=S2[i]; } } return result;}" }, { "code": null, "e": 1408, "s": 1406, "text": "0" }, { "code": null, "e": 1435, "s": 1408, "text": "kshitijmagare194 weeks ago" }, { "code": null, "e": 2384, "s": 1435, "text": "class Solution { StringBuilder merge(String S1, String S2) { // code here StringBuilder str = new StringBuilder(); int s1 =S1.length(); int s2 = S2.length(); int j = 0; int i; if(s1<s2){ for(i = 0; i< s1;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); j = i + 1; } for(i = j ; i< s2;i++){ str.append(S2.charAt(i)); } } else if(s1>s2){ for(i = 0; i< s2;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); j = i + 1; } for(i = j; i< s1;i++){ str.append(S1.charAt(i)); } } else{ for(i = 0; i< s1;i++){ str.append(S1.charAt(i)); str.append(S2.charAt(i)); } } return str; }} " }, { "code": null, "e": 2387, "s": 2384, "text": "+1" }, { "code": null, "e": 2415, "s": 2387, "text": "codewithshoaib191 month ago" }, { "code": null, "e": 2915, "s": 2415, "text": "String merge(String S1, String S2) { // code here String result = \"\"; int n1 = S1.length(); int n2 = S2.length(); if (n1 > n2) { for (int i = 0; i < n2; i++) { result += S1.charAt(i); result += S2.charAt(i); } return result + S1.substring(n2); } for (int i = 0; i < n1; i++) { result += S1.charAt(i); result += S2.charAt(i); } return result + S2.substring(n1); }" }, { "code": null, "e": 2917, "s": 2915, "text": "0" }, { "code": null, "e": 2942, "s": 2917, "text": "bsricharan2461 month ago" }, { "code": null, "e": 2993, "s": 2942, "text": "Python Easy & Fast Approach | Time Taken = 0.0/2.2" }, { "code": null, "e": 3428, "s": 2993, "text": "class Solution: def merge(self, S1, S2): # code here res = \"\" j=0 k=0 for i in range(0, min(len(S1), len(S2))*2,1): if i%2 ==0: res+=S1[j] j+=1 else: res+=S2[k] k+=1 if len(S1) != len(S2): if min(len(S1), len(S2)) == len(S1): res+=S2[k:] else: res+=S1[j:] return res" }, { "code": null, "e": 3430, "s": 3428, "text": "0" }, { "code": null, "e": 3459, "s": 3430, "text": "akanshasaraswat13 months ago" }, { "code": null, "e": 3474, "s": 3459, "text": "100% accurate " }, { "code": null, "e": 4093, "s": 3474, "text": "String merge(String S1, String S2) { // code here String merge = \"\"; int i=0; int j=0; int k=0; while(i<S1.length() && j<S2.length()){ if(k%2==0){ merge = merge + S1.charAt(i); i++; } else{ merge = merge + S2.charAt(j); j++; } k++; } while(i<S1.length()){ merge = merge + S1.charAt(i); i++; } while(j<S2.length()){ merge = merge + S2.charAt(j);j++;} return merge; }" }, { "code": null, "e": 4096, "s": 4093, "text": "+3" }, { "code": null, "e": 4124, "s": 4096, "text": "rahulpankaj97543 months ago" }, { "code": null, "e": 4458, "s": 4124, "text": "string merge (string S1, string S2)\n{ \n string S=\"\";\n int n1=S1.size();\n int n2=S2.size();\n int i=0,j=0;\n for(int k=0; k<n1+n2; k++)\n { \n if(i<n1)\n {\n S+=S1[i];\n }\n if(j<n2)\n {\n S+=S2[i];\n }\n i++;\n j++;\n }\n return S;\n}" }, { "code": null, "e": 4460, "s": 4458, "text": "0" }, { "code": null, "e": 4484, "s": 4460, "text": "anmol1neema4 months ago" }, { "code": null, "e": 4501, "s": 4484, "text": " time taken -0.2" }, { "code": null, "e": 5228, "s": 4501, "text": "String merge(String S1, String S2) { // code here int j=0,k=0, p=0; int greatA=0, greatB =0; int valA= S1.length(); int valB = S2.length(); int n = valA + valB; char[] c = new char[n]; if(valA>valB){ greatA = valA-valB; }else{ greatB = valB-valA; } for(int i=0;i<n;i++){ if(i%2==0 && j<valA){ c[i]= S1.charAt(j); j++; }else if(k<valB){ c[i] = S2.charAt(k); k++; }else if(greatA>0){ c[i] = S1.charAt(j); j++; }else if(greatB>0){ c[i] = S2.charAt(k); k++; } } String s = new String(c); return s; }" }, { "code": null, "e": 5230, "s": 5228, "text": "0" }, { "code": null, "e": 5259, "s": 5230, "text": "rajithrock4444445 months ago" }, { "code": null, "e": 5279, "s": 5259, "text": "Time Taken-→0.3/2.2" }, { "code": null, "e": 5648, "s": 5281, "text": "String s4=\"\"; int len=0; if(s1.length()>s2.length()){ len=s1.length(); } else{ len=s2.length(); } for(int i=0;i<len;i++){ if(i<s1.length()){ s4+=s1.charAt(i); } if(i<s2.length()){ s4+=s2.charAt(i); } } return s4;" }, { "code": null, "e": 5651, "s": 5648, "text": "+1" }, { "code": null, "e": 5678, "s": 5651, "text": "saptarshithe426 months ago" }, { "code": null, "e": 6055, "s": 5678, "text": "class Solution:\n def merge(self, s1, s2):\n # code here\n if ((len(s1) == 0) or (len(s2) == 0)):\n return (s1 + s2)\n \n s = \"\"\n for i in range(min(len(s1), len(s2))):\n s = s + s1[i] + s2[i]\n if (len(s1) > len(s2)):\n rem = s1[i + 1:]\n else:\n rem = s2[i+1:]\n return (s + rem)" }, { "code": null, "e": 6057, "s": 6055, "text": "0" }, { "code": null, "e": 6086, "s": 6057, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 6595, "s": 6086, "text": "string merge (string S1, string S2)\n{\n // your code here\n string ss=\"\";\n bool ans=true;\n int i=0;\n int j=0;\n while( i<S1.size() && j<S2.size()){\n if(ans==true){\n ss+=S1[i];\n ans=false;\n i++;\n }\n if(ans==false){\n ss+=S2[j];\n ans=true;\n j++;\n }\n }\n while(i<S1.size()){\n ss+=S1[i];\n i++;\n }\n while(j<S2.size()){\n ss+=S2[j];\n j++;\n }\n return ss;\n \n}" }, { "code": null, "e": 6741, "s": 6595, "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": 6777, "s": 6741, "text": " Login to access your submissions. " }, { "code": null, "e": 6787, "s": 6777, "text": "\nProblem\n" }, { "code": null, "e": 6797, "s": 6787, "text": "\nContest\n" }, { "code": null, "e": 6860, "s": 6797, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7008, "s": 6860, "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": 7216, "s": 7008, "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": 7322, "s": 7216, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How do we reset all the input fields in HTML forms?
Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. The <input> tag helps you to take user input using the type attribute. To clear all the input in an HTML form, use the <input> tag with the type attribute as reset. You can try to run the following code to reset input fields in HTML − Live Demo <!DOCTYPE html> <html> <body> <form> Student Name:<br> <input type="text" name="sname"> <br> Student Subject:<br> <input type="text" name="ssubject"> <br> <input type="reset" value="reset"> </form> </body> </html>
[ { "code": null, "e": 1276, "s": 1062, "text": "Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc." }, { "code": null, "e": 1441, "s": 1276, "text": "The <input> tag helps you to take user input using the type attribute. To clear all the input in an HTML form, use the <input> tag with the type attribute as reset." }, { "code": null, "e": 1511, "s": 1441, "text": "You can try to run the following code to reset input fields in HTML −" }, { "code": null, "e": 1521, "s": 1511, "text": "Live Demo" }, { "code": null, "e": 1816, "s": 1521, "text": "<!DOCTYPE html>\n<html>\n <body>\n <form>\n Student Name:<br>\n <input type=\"text\" name=\"sname\">\n <br>\n Student Subject:<br>\n <input type=\"text\" name=\"ssubject\">\n <br>\n <input type=\"reset\" value=\"reset\">\n </form>\n </body>\n</html>" } ]
Apache Airflow 2.0 on Steroids — EKS Kubernetes & MWAA | by Gagandeep Singh | Towards Data Science
Last month, May 2021, AWS released its update on AWS Managed Workflows for Apache Airflow (MWAA) which included Airflow 2.0 and that got me thinking why would someone manage Airflow on its own now (typical cloud dilemmas) when AWS is giving a managed service with the latest stable release with not that expensive pricing and not to mention the support that we can get from AWS (previously MWAA had an old Airflow release with no Cloudformation support). But I was wary of being on the bleeding edge of the technology that has not been battle-tested. On the other hand, AWS had a release couple of months ago regarding Airflow on EKS and we all know the scalability of K8s so I thought to give it a try. I will be on the bleeding edge of technology, but at least it will not be a black box. Assuming we all know parts that constitute Kubernetes and what are helm charts, I will divide the post into two sub-topics i.e.: Deploying Airflow 2.0 on EKS vs MWAA &Adding DAGs, Variables, Plugins, Connections, etc Deploying Airflow 2.0 on EKS vs MWAA & Adding DAGs, Variables, Plugins, Connections, etc Briefly, the node groups in K8s can be created using AWS Fargate or Node-managed EC2. Both will scale out but the major difference is, with Fargate AWS will manage the worker node scaling and its AMI configuration whereas in Node-Managed we have to do both things but the benefit of it is considerable. Since Fargate does not support daemonsets, with the managed Node group, we don't have to put the agents of monitoring services like Dynatrace, Splunk, or Datadog in a sidecar container and hence more reliability. Additionally, Fargate does not cache container images and hence startup time will be more. Based on my experience, Fargate is more suited for Airflow based workflows where most of it are batches whereas node-managed is more suited for Streaming-related patterns. A Linux-based environment is set up where your role has desired access. I am using the Ubuntu windows app. Before creating the cluster we need to install kubectl and eksctl. eksctl will create and manage the cluster whereas kubectl will communicate with the cluster API server in retrieving nodes, pods, namespaces whatever is needed. Thankfully, the binaries are available for both of them. curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.20.4/2021-04-12/bin/linux/amd64/kubectlchmod +x ./kubectlmkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$PATH:$HOME/bin And for eksctl, curl — silent — location “https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz” | tar xz -C /tmpsudo mv /tmp/eksctl /usr/local/bin Now let's create a k8 cluster using Fargate with the following command. It will take about 15–20minutes and one can check in the cloudformation about the resources (Vpc, subnets, etc) it will be creating. eksctl create cluster \ — name test-cluster \ — region ap-southeast-2 \ — fargate And it will show something like: ... [✓] EKS cluster “test-cluster” in “ap-southeast-2" region is ready Next, let's create a node-managed cluster, and here comes the difference. We need to first create the pub private key pair in the local to be used in EC2 connection. aws ec2 create-key-pair — region us-west-2 — key-name myKeyPaireksctl create cluster \ — name eksctl-airflow-cluster \ — region ap-southeast-2 \ — with-oidc \ — ssh-access \ — ssh-public-key <your-key> \ — managed One can check in the CFN about node groups created. By running the below we can confirm the installation and it should show the nodes present in the cluster: kubectl get nodes -o wide Next, we need to update the kubeconfig so that whenever we run kubectl, it should point out to the right cluster. aws eks — region ap-southeast-2 update-kubeconfig — name eksctl-airflow-cluster Next, is to create the namespace so that we can deploy the airflow in it. It is just an abstraction to maintain the related resources in one place much like a stack. One cluster can have many namespaces that can communicate with each other. kubectl create namespace airflow Before creating airflow in the namespace, we need to install helm $ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3$ chmod 700 get_helm.sh$ ./get_helm.sh and the following will create airflow resources and you can view it at localhost:8080 once it gets completed. We can give any release_name as you want. helm repo add airflow-stable https://airflow-helm.github.io/chartshelm repo updatehelm install RELEASE_NAME airflow-stable/airflow — namespace airflow \ — version 8.3.0 You can find other chart versions at https://github.com/airflow-helm/charts/releases corresponding to the latest Airflow releases. Before checking the GUI, we need to forward the 8080 port from the pod to the localhost using: export POD_NAME=$(kubectl get pods — namespace NAMESPACE -l “component=web,app=airflow” -o jsonpath=”{.items[0].metadata.name}”)kubectl port-forward — namespace NAMESPACE $POD_NAME 8080:8080 Now here comes the interesting part, helm charts give values.yml where all the airflow configurations, variables, dagbag folders, etc are mentioned which help in updating the actual airflow.cfg. And hence the only thing left now is to give it the desired values and update using the below command: helm upgrade airflow airflow-stable/airflow — namespace airflow — version 8.3.0 — values values.yml — debug The following is a part of values.yml where we can specify the python modules that need to be installed airflow: extraPipPackages: — “pandas” — “awscli” Similarly, the following is a part of values.yml where persistent volume and claim are specified that we got after deploying efs. airflow: extraVolumeMounts: — name: airflow-efs-dag mountPath: /opt/efs/ extraVolumes: — name: airflow-efs-dag persistentVolumeClaim: claimName: efs-storage-claim And the following will be its dagbag: dags: path: /opt/efs/dags Interesting to know is that MWAA has a similar setup where it asks us to mention all these details in the Cloudformation template itself. To add an airflow variable, MWAA uses the environment variables, and to update env we need to mention it in the CFN. Since AWS SSM is the backend of MWAA, we can specify the key name of the connection containing the conn_string, and MWAA will pick it using the key name and deploy it in Airflow. And as far as the DAG, Plugins folders, and requirements.txt are concerned, we need to give it an s3 folder but the problem is all should be in the same bucket. Not a bottleneck for anyone who is starting. MWAA uses RDS or Aurora at the backend but it does not let the user fiddle around it. It only uses Celery Executor and provides three types of cluster based on different machine types. In all, it can only support 1000 dags running. Hence, MWAA is good for SMEs but not for large-scale companies. At the time of writing, one of the drawbacks of using MWAA is, even if you update an airflow variable through CFN, the scheduler will be stopped at the time of deployment and takes about 10–20min to get it running. And hence a proper release strategy needs to be thought of where no or fewer dags are running whenever there is a new build to be deployed. EKS also takes a couple of minutes in completing helm upgrade but that is more transparent than MWAA as it gives logs with it. Also, in the case of EKS, we need to integrate EFS and RDS by ourselves which should not be much of a problem, and then any CICD can push the updated DAGs from the code repository to EFS. values.yml of airflow helm: https://github.com/airflow-helm/charts/blob/main/charts/airflow/values.yaml While using k8 executor in Airflow, each of the tasks gets to run on the pod whereas the airflow can be running on a separate machine. However in EKS, all the parts of airflow i.e. airflow db, scheduler, etc are running in separate pods and hence more HA and reliability are there. If you have made it through till now then congratulations you have learned how to deploy Airflow 2.0 on EKS using fargate and node-managed ec2. We have also learned how to customize values.yml that will have airflow config and other provisions like specifying variables, connections, etc. In my opinion, everything will be kubernetes in a matter of time where we have the advantage of separating storage from computing with potentially non-finite amount of computing available on tap. It all depends on what part of the journey you are at in understanding & implementing Data Engineering Landscape.
[ { "code": null, "e": 963, "s": 172, "text": "Last month, May 2021, AWS released its update on AWS Managed Workflows for Apache Airflow (MWAA) which included Airflow 2.0 and that got me thinking why would someone manage Airflow on its own now (typical cloud dilemmas) when AWS is giving a managed service with the latest stable release with not that expensive pricing and not to mention the support that we can get from AWS (previously MWAA had an old Airflow release with no Cloudformation support). But I was wary of being on the bleeding edge of the technology that has not been battle-tested. On the other hand, AWS had a release couple of months ago regarding Airflow on EKS and we all know the scalability of K8s so I thought to give it a try. I will be on the bleeding edge of technology, but at least it will not be a black box." }, { "code": null, "e": 1092, "s": 963, "text": "Assuming we all know parts that constitute Kubernetes and what are helm charts, I will divide the post into two sub-topics i.e.:" }, { "code": null, "e": 1180, "s": 1092, "text": "Deploying Airflow 2.0 on EKS vs MWAA &Adding DAGs, Variables, Plugins, Connections, etc" }, { "code": null, "e": 1219, "s": 1180, "text": "Deploying Airflow 2.0 on EKS vs MWAA &" }, { "code": null, "e": 1269, "s": 1219, "text": "Adding DAGs, Variables, Plugins, Connections, etc" }, { "code": null, "e": 2048, "s": 1269, "text": "Briefly, the node groups in K8s can be created using AWS Fargate or Node-managed EC2. Both will scale out but the major difference is, with Fargate AWS will manage the worker node scaling and its AMI configuration whereas in Node-Managed we have to do both things but the benefit of it is considerable. Since Fargate does not support daemonsets, with the managed Node group, we don't have to put the agents of monitoring services like Dynatrace, Splunk, or Datadog in a sidecar container and hence more reliability. Additionally, Fargate does not cache container images and hence startup time will be more. Based on my experience, Fargate is more suited for Airflow based workflows where most of it are batches whereas node-managed is more suited for Streaming-related patterns." }, { "code": null, "e": 2155, "s": 2048, "text": "A Linux-based environment is set up where your role has desired access. I am using the Ubuntu windows app." }, { "code": null, "e": 2440, "s": 2155, "text": "Before creating the cluster we need to install kubectl and eksctl. eksctl will create and manage the cluster whereas kubectl will communicate with the cluster API server in retrieving nodes, pods, namespaces whatever is needed. Thankfully, the binaries are available for both of them." }, { "code": null, "e": 2645, "s": 2440, "text": "curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.20.4/2021-04-12/bin/linux/amd64/kubectlchmod +x ./kubectlmkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$PATH:$HOME/bin" }, { "code": null, "e": 2661, "s": 2645, "text": "And for eksctl," }, { "code": null, "e": 2833, "s": 2661, "text": "curl — silent — location “https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz” | tar xz -C /tmpsudo mv /tmp/eksctl /usr/local/bin" }, { "code": null, "e": 3038, "s": 2833, "text": "Now let's create a k8 cluster using Fargate with the following command. It will take about 15–20minutes and one can check in the cloudformation about the resources (Vpc, subnets, etc) it will be creating." }, { "code": null, "e": 3120, "s": 3038, "text": "eksctl create cluster \\ — name test-cluster \\ — region ap-southeast-2 \\ — fargate" }, { "code": null, "e": 3153, "s": 3120, "text": "And it will show something like:" }, { "code": null, "e": 3224, "s": 3153, "text": "... [✓] EKS cluster “test-cluster” in “ap-southeast-2\" region is ready" }, { "code": null, "e": 3390, "s": 3224, "text": "Next, let's create a node-managed cluster, and here comes the difference. We need to first create the pub private key pair in the local to be used in EC2 connection." }, { "code": null, "e": 3604, "s": 3390, "text": "aws ec2 create-key-pair — region us-west-2 — key-name myKeyPaireksctl create cluster \\ — name eksctl-airflow-cluster \\ — region ap-southeast-2 \\ — with-oidc \\ — ssh-access \\ — ssh-public-key <your-key> \\ — managed" }, { "code": null, "e": 3656, "s": 3604, "text": "One can check in the CFN about node groups created." }, { "code": null, "e": 3762, "s": 3656, "text": "By running the below we can confirm the installation and it should show the nodes present in the cluster:" }, { "code": null, "e": 3788, "s": 3762, "text": "kubectl get nodes -o wide" }, { "code": null, "e": 3902, "s": 3788, "text": "Next, we need to update the kubeconfig so that whenever we run kubectl, it should point out to the right cluster." }, { "code": null, "e": 3982, "s": 3902, "text": "aws eks — region ap-southeast-2 update-kubeconfig — name eksctl-airflow-cluster" }, { "code": null, "e": 4223, "s": 3982, "text": "Next, is to create the namespace so that we can deploy the airflow in it. It is just an abstraction to maintain the related resources in one place much like a stack. One cluster can have many namespaces that can communicate with each other." }, { "code": null, "e": 4256, "s": 4223, "text": "kubectl create namespace airflow" }, { "code": null, "e": 4322, "s": 4256, "text": "Before creating airflow in the namespace, we need to install helm" }, { "code": null, "e": 4458, "s": 4322, "text": "$ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3$ chmod 700 get_helm.sh$ ./get_helm.sh" }, { "code": null, "e": 4610, "s": 4458, "text": "and the following will create airflow resources and you can view it at localhost:8080 once it gets completed. We can give any release_name as you want." }, { "code": null, "e": 4780, "s": 4610, "text": "helm repo add airflow-stable https://airflow-helm.github.io/chartshelm repo updatehelm install RELEASE_NAME airflow-stable/airflow — namespace airflow \\ — version 8.3.0" }, { "code": null, "e": 4911, "s": 4780, "text": "You can find other chart versions at https://github.com/airflow-helm/charts/releases corresponding to the latest Airflow releases." }, { "code": null, "e": 5006, "s": 4911, "text": "Before checking the GUI, we need to forward the 8080 port from the pod to the localhost using:" }, { "code": null, "e": 5197, "s": 5006, "text": "export POD_NAME=$(kubectl get pods — namespace NAMESPACE -l “component=web,app=airflow” -o jsonpath=”{.items[0].metadata.name}”)kubectl port-forward — namespace NAMESPACE $POD_NAME 8080:8080" }, { "code": null, "e": 5495, "s": 5197, "text": "Now here comes the interesting part, helm charts give values.yml where all the airflow configurations, variables, dagbag folders, etc are mentioned which help in updating the actual airflow.cfg. And hence the only thing left now is to give it the desired values and update using the below command:" }, { "code": null, "e": 5603, "s": 5495, "text": "helm upgrade airflow airflow-stable/airflow — namespace airflow — version 8.3.0 — values values.yml — debug" }, { "code": null, "e": 5707, "s": 5603, "text": "The following is a part of values.yml where we can specify the python modules that need to be installed" }, { "code": null, "e": 5774, "s": 5707, "text": "airflow: extraPipPackages: — “pandas” — “awscli”" }, { "code": null, "e": 5904, "s": 5774, "text": "Similarly, the following is a part of values.yml where persistent volume and claim are specified that we got after deploying efs." }, { "code": null, "e": 6119, "s": 5904, "text": "airflow: extraVolumeMounts: — name: airflow-efs-dag mountPath: /opt/efs/ extraVolumes: — name: airflow-efs-dag persistentVolumeClaim: claimName: efs-storage-claim" }, { "code": null, "e": 6157, "s": 6119, "text": "And the following will be its dagbag:" }, { "code": null, "e": 6186, "s": 6157, "text": "dags: path: /opt/efs/dags" }, { "code": null, "e": 7604, "s": 6186, "text": "Interesting to know is that MWAA has a similar setup where it asks us to mention all these details in the Cloudformation template itself. To add an airflow variable, MWAA uses the environment variables, and to update env we need to mention it in the CFN. Since AWS SSM is the backend of MWAA, we can specify the key name of the connection containing the conn_string, and MWAA will pick it using the key name and deploy it in Airflow. And as far as the DAG, Plugins folders, and requirements.txt are concerned, we need to give it an s3 folder but the problem is all should be in the same bucket. Not a bottleneck for anyone who is starting. MWAA uses RDS or Aurora at the backend but it does not let the user fiddle around it. It only uses Celery Executor and provides three types of cluster based on different machine types. In all, it can only support 1000 dags running. Hence, MWAA is good for SMEs but not for large-scale companies. At the time of writing, one of the drawbacks of using MWAA is, even if you update an airflow variable through CFN, the scheduler will be stopped at the time of deployment and takes about 10–20min to get it running. And hence a proper release strategy needs to be thought of where no or fewer dags are running whenever there is a new build to be deployed. EKS also takes a couple of minutes in completing helm upgrade but that is more transparent than MWAA as it gives logs with it." }, { "code": null, "e": 7792, "s": 7604, "text": "Also, in the case of EKS, we need to integrate EFS and RDS by ourselves which should not be much of a problem, and then any CICD can push the updated DAGs from the code repository to EFS." }, { "code": null, "e": 7896, "s": 7792, "text": "values.yml of airflow helm: https://github.com/airflow-helm/charts/blob/main/charts/airflow/values.yaml" }, { "code": null, "e": 8178, "s": 7896, "text": "While using k8 executor in Airflow, each of the tasks gets to run on the pod whereas the airflow can be running on a separate machine. However in EKS, all the parts of airflow i.e. airflow db, scheduler, etc are running in separate pods and hence more HA and reliability are there." } ]
AJAX - Quick Guide
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. A user can continue to use the application while the client program requests information from the server in the background. Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger. Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger. Data-driven as opposed to page-driven. Data-driven as opposed to page-driven. AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug. AJAX is based on the following open standards − Browser-based presentation using HTML and Cascading Style Sheets (CSS). Data is stored in XML format and fetched from the server. Behind-the-scenes data fetches using XMLHttpRequest objects in the browser. JavaScript to make everything happen. AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages. Loosely typed scripting language. JavaScript function is called when an event occurs in a page. Glue for the whole AJAX operation. API for accessing and manipulating structured documents. Represents the structure of XML and HTML documents. Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript JavaScript object that performs asynchronous interaction with the server. Here is a list of some famous web applications that make use of AJAX. A user can drag an entire map by using the mouse, rather than clicking on a button. https://maps.google.com/ https://maps.google.com/ As you type, Google offers suggestions. Use the arrow keys to navigate the results. https://www.google.com/webhp?complete=1&hl=en https://www.google.com/webhp?complete=1&hl=en Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and useful. https://gmail.com/ https://gmail.com/ Now it's even easier and more fun to get where you're going! https://maps.yahoo.com/ https://maps.yahoo.com/ Try these two examples one by one and you will feel the difference. While trying AJAX example, there is no discontinuity and you get the response very quickly, but when you try the standard GCI example, you would have to wait for the response and your page also gets refreshed. NOTE − We have given a more complex example in AJAX Database. All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX. Mozilla Firefox 1.0 and above. Netscape version 7.1 and above. Apple Safari 1.2 and above. Microsoft Internet Explorer 5 and above. Konqueror. Opera 7.6 and above. When you write your next application, do consider the browsers that do not support AJAX. NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object – XMLHttpRequest object. The simplest way to make your source code compatible with a browser is to use try...catch blocks in your JavaScript. <html> <body> <script language = "javascript" type = "text/javascript"> <!-- //Browser Support Code function ajaxFunction() { var ajaxRequest; // The variable that makes Ajax possible! try { // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } } //--> </script> <form name = 'myForm'> Name: <input type = 'text' name = 'username' /> <br /> Time: <input type = 'text' name = 'time' /> </form> </body> </html> In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt − ajaxRequest = new XMLHttpRequest(); It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with − ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); If it doesn't work, then we can use a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support AJAX. Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter. This chapter gives you a clear picture of the exact steps of AJAX operation. A client event occurs. An XMLHttpRequest object is created. The XMLHttpRequest object is configured. The XMLHttpRequest object makes an asynchronous request to the Webserver. The Webserver returns the result containing XML document. The XMLHttpRequest object calls the callback() function and processes the result. The HTML DOM is updated. Let us take these steps one by one. A JavaScript function is called as the result of an event. A JavaScript function is called as the result of an event. Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to "userid" Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to "userid" <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">. <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">. var ajaxRequest; // The variable that makes Ajax possible! function ajaxFunction() { try { // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } } In this step, we will write a function that will be triggered by the client event and a callback function processRequest() will be registered. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value); ajaxRequest.open("GET", url, true); ajaxRequest.send(null); } Source code is available in the above piece of code. Code written in bold typeface is responsible to make a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest. function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; if (!target) target = document.getElementById("userid"); var url = "validate?id = " + escape(target.value); ajaxRequest.open("GET", url, true); ajaxRequest.send(null); } Assume you enter Zara in the userid box, then in the above request, the URL is set to "validate?id = Zara". You can implement your server-side script in any language, however its logic should be as follows. Get a request from the client. Parse the input from the client. Do required processing. Send the output to the client. If we assume that you are going to write a servlet, then here is the piece of code. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !accounts.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>true</valid>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>false</valid>"); } } The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will receive the result from the server and will do the required processing. As in the following example, it sets a variable message on true or false based on the returned value from the Webserver. function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; ... } This is the final step and in this step, your HTML page will be updated. It happens in the following way − JavaScript gets a reference to any element in a page using DOM API. The recommended way to gain a reference to an element is to call. document.getElementById("userIdMessage"), // where "userIdMessage" is the ID attribute // of an element appearing in the HTML document JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example − JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example − <script type = "text/javascript"> <!-- function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple // replace it otherwise append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } --> </script> <body> <div id = "userIdMessage"><div> </body> If you have understood the above-mentioned seven steps, then you are almost done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail. The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0 in 2005 became popular. XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side. The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text. You already have seen a couple of examples on how to create an XMLHttpRequest object. Listed below are some of the methods and properties that you have to get familiar with. abort() Cancels the current request. abort() Cancels the current request. getAllResponseHeaders() Returns the complete set of HTTP headers as a string. getAllResponseHeaders() Returns the complete set of HTTP headers as a string. getResponseHeader( headerName ) Returns the value of the specified HTTP header. getResponseHeader( headerName ) Returns the value of the specified HTTP header. open( method, URL ) open( method, URL ) open( method, URL, async ) open( method, URL, async ) open( method, URL, async, userName ) open( method, URL, async, userName ) open( method, URL, async, userName, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods such as "PUT" and "DELETE" (primarily used in REST applications) may be possible. The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing. open( method, URL, async, userName, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods such as "PUT" and "DELETE" (primarily used in REST applications) may be possible. The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing. send( content ) Sends the request. send( content ) Sends the request. setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent. setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent. onreadystatechange An event handler for an event that fires at every state change. onreadystatechange An event handler for an event that fires at every state change. readyState The readyState property defines the current state of the XMLHttpRequest object. The following table provides a list of the possible values for the readyState property − readyState The readyState property defines the current state of the XMLHttpRequest object. The following table provides a list of the possible values for the readyState property − readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method. readyState = 1 After you have called the open() method, but before you have called send(). readyState = 2 After you have called send(). readyState = 3 After the browser has established a communication with the server, but before the server has completed the response. readyState = 4 After the request has been completed, and the response data has been completely received from the server. responseText Returns the response as a string. responseText Returns the response as a string. responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties. responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties. status Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK"). status Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK"). statusText Returns the status as a string (e.g., "Not Found" or "OK"). statusText Returns the status as a string (e.g., "Not Found" or "OK"). To clearly illustrate how easy it is to access information from a database using AJAX, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, let us do the ground work. Create a table using the following command. NOTE − We are assuming you have sufficient privilege to perform the following MySQL operations. CREATE TABLE 'ajax_example' ( 'name' varchar(50) NOT NULL, 'age' int(11) NOT NULL, 'sex' varchar(1) NOT NULL, 'wpm' int(11) NOT NULL, PRIMARY KEY ('name') ) Now dump the following data into this table using the following SQL statements − INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20); INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44); INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87); INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72); INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0); INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90); Now let us have our client side HTML file, which is ajax.html, and it will have the following code − <html> <body> <script language = "javascript" type = "text/javascript"> <!-- //Browser Support Code function ajaxFunction() { var ajaxRequest; // The variable that makes Ajax possible! try { // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data // sent from the server and will update // div section in the same page. ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4) { var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } // Now get the value from user and pass it to // server script. var age = document.getElementById('age').value; var wpm = document.getElementById('wpm').value; var sex = document.getElementById('sex').value; var queryString = "?age = " + age ; queryString += "&wpm = " + wpm + "&sex = " + sex; ajaxRequest.open("GET", "ajax-example.php" + queryString, true); ajaxRequest.send(null); } //--> </script> <form name = 'myForm'> Max Age: <input type = 'text' id = 'age' /> <br /> Max WPM: <input type = 'text' id = 'wpm' /> <br /> Sex: <select id = 'sex'> <option value = "m">m</option> <option value = "f">f</option> </select> <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/> </form> <div id = 'ajaxDiv'>Your result will display here</div> </body> </html> NOTE − The way of passing variables in the Query is according to HTTP standard and have formA. URL?variable1 = value1;&variable2 = value2; The above code will give you a screen as given below − Max Age: Max WPM: Sex: m f Your result will display here in this section after you have made your entry. NOTE − This is a dummy screen. Your client-side script is ready. Now, we have to write our server-side script, which will fetch age, wpm, and sex from the database and will send it back to the client. Put the following code into the file "ajax-example.php". <?php $dbhost = "localhost"; $dbuser = "dbusername"; $dbpass = "dbpassword"; $dbname = "dbname"; //Connect to MySQL Server mysql_connect($dbhost, $dbuser, $dbpass); //Select Database mysql_select_db($dbname) or die(mysql_error()); // Retrieve data from Query String $age = $_GET['age']; $sex = $_GET['sex']; $wpm = $_GET['wpm']; // Escape User Input to help prevent SQL Injection $age = mysql_real_escape_string($age); $sex = mysql_real_escape_string($sex); $wpm = mysql_real_escape_string($wpm); //build query $query = "SELECT * FROM ajax_example WHERE sex = '$sex'"; if(is_numeric($age)) $query .= " AND age <= $age"; if(is_numeric($wpm)) $query .= " AND wpm <= $wpm"; //Execute query $qry_result = mysql_query($query) or die(mysql_error()); //Build Result String $display_string = "<table>"; $display_string .= "<tr>"; $display_string .= "<th>Name</th>"; $display_string .= "<th>Age</th>"; $display_string .= "<th>Sex</th>"; $display_string .= "<th>WPM</th>"; $display_string .= "</tr>"; // Insert a new row in the table for each person returned while($row = mysql_fetch_array($qry_result)) { $display_string .= "<tr>"; $display_string .= "<td>$row[name]</td>"; $display_string .= "<td>$row[age]</td>"; $display_string .= "<td>$row[sex]</td>"; $display_string .= "<td>$row[wpm]</td>"; $display_string .= "</tr>"; } echo "Query: " . $query . "<br />"; $display_string .= "</table>"; echo $display_string; ?> Now try by entering a valid value (e.g., 120) in Max Age or any other box and then click Query MySQL button. Max Age: Max WPM: Sex: m f Your result will display here in this section after you have made your entry. If you have successfully completed this lesson, then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write AJAX applications. AJAX-based Web applications use the same server-side security schemes of regular Web applications. AJAX-based Web applications use the same server-side security schemes of regular Web applications. You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programmatic). You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programmatic). AJAX-based Web applications are subject to the same security threats as regular Web applications. AJAX-based Web applications are subject to the same security threats as regular Web applications. JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-side weaknesses. JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-side weaknesses. JavaScript code is downloaded from the server and executed ("eval") at the client and can compromise the client by mal-intended code. JavaScript code is downloaded from the server and executed ("eval") at the client and can compromise the client by mal-intended code. Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for signed JavaScript. Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for signed JavaScript. AJAX is growing very fast and that is the reason that it contains many issues with it. We hope with the passes of time, they will be resolved and AJAX will become ideal for web applications. We are listing down a few issues that AJAX currently suffers from. Complexity is increased Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic. Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic. Page developers must have JavaScript technology skills. Page developers must have JavaScript technology skills. AJAX-based applications can be difficult to debug, test, and maintain JavaScript is hard to test - automatic testing is hard. Weak modularity in JavaScript. Lack of design patterns or best practice guidelines yet. Toolkits/Frameworks are not mature yet Most of them are in beta phase. No standardization of the XMLHttpRequest yet Future version of IE will address this. No support of XMLHttpRequest in old browsers Iframe will help. JavaScript technology dependency and incompatibility Must be enabled for applications to function. Still some browser incompatibilities exist. JavaScript code is visible to a hacker Poorly designed JavaScript code can invite security problems. 72 Lectures 4.5 hours Frahaan Hussain 20 Lectures 1 hours Laurence Svekis 29 Lectures 2 hours YouAccel 20 Lectures 1.5 hours YouAccel 18 Lectures 2.5 hours Stone River ELearning 47 Lectures 5.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 1926, "s": 1736, "text": "AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script." }, { "code": null, "e": 2054, "s": 1926, "text": "Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display." }, { "code": null, "e": 2182, "s": 2054, "text": "Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display." }, { "code": null, "e": 2394, "s": 2182, "text": "Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server." }, { "code": null, "e": 2606, "s": 2394, "text": "Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server." }, { "code": null, "e": 2835, "s": 2606, "text": "With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server." }, { "code": null, "e": 3064, "s": 2835, "text": "With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server." }, { "code": null, "e": 3182, "s": 3064, "text": "XML is commonly used as the format for receiving server data, although any format, including plain text, can be used." }, { "code": null, "e": 3300, "s": 3182, "text": "XML is commonly used as the format for receiving server data, although any format, including plain text, can be used." }, { "code": null, "e": 3369, "s": 3300, "text": "AJAX is a web browser technology independent of web server software." }, { "code": null, "e": 3438, "s": 3369, "text": "AJAX is a web browser technology independent of web server software." }, { "code": null, "e": 3562, "s": 3438, "text": "A user can continue to use the application while the client program requests information from the server in the background." }, { "code": null, "e": 3686, "s": 3562, "text": "A user can continue to use the application while the client program requests information from the server in the background." }, { "code": null, "e": 3798, "s": 3686, "text": "Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger." }, { "code": null, "e": 3910, "s": 3798, "text": "Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient event trigger." }, { "code": null, "e": 3949, "s": 3910, "text": "Data-driven as opposed to page-driven." }, { "code": null, "e": 3988, "s": 3949, "text": "Data-driven as opposed to page-driven." }, { "code": null, "e": 4283, "s": 3988, "text": "AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript, which is hard to maintain and debug." }, { "code": null, "e": 4331, "s": 4283, "text": "AJAX is based on the following open standards −" }, { "code": null, "e": 4403, "s": 4331, "text": "Browser-based presentation using HTML and Cascading Style Sheets (CSS)." }, { "code": null, "e": 4461, "s": 4403, "text": "Data is stored in XML format and fetched from the server." }, { "code": null, "e": 4537, "s": 4461, "text": "Behind-the-scenes data fetches using XMLHttpRequest objects in the browser." }, { "code": null, "e": 4575, "s": 4537, "text": "JavaScript to make everything happen." }, { "code": null, "e": 4689, "s": 4575, "text": "AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages." }, { "code": null, "e": 4723, "s": 4689, "text": "Loosely typed scripting language." }, { "code": null, "e": 4785, "s": 4723, "text": "JavaScript function is called when an event occurs in a page." }, { "code": null, "e": 4820, "s": 4785, "text": "Glue for the whole AJAX operation." }, { "code": null, "e": 4877, "s": 4820, "text": "API for accessing and manipulating structured documents." }, { "code": null, "e": 4929, "s": 4877, "text": "Represents the structure of XML and HTML documents." }, { "code": null, "e": 5052, "s": 4929, "text": "Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript" }, { "code": null, "e": 5126, "s": 5052, "text": "JavaScript object that performs asynchronous interaction with the server." }, { "code": null, "e": 5196, "s": 5126, "text": "Here is a list of some famous web applications that make use of AJAX." }, { "code": null, "e": 5280, "s": 5196, "text": "A user can drag an entire map by using the mouse, rather than clicking on a button." }, { "code": null, "e": 5305, "s": 5280, "text": "https://maps.google.com/" }, { "code": null, "e": 5330, "s": 5305, "text": "https://maps.google.com/" }, { "code": null, "e": 5414, "s": 5330, "text": "As you type, Google offers suggestions. Use the arrow keys to navigate the results." }, { "code": null, "e": 5460, "s": 5414, "text": "https://www.google.com/webhp?complete=1&hl=en" }, { "code": null, "e": 5506, "s": 5460, "text": "https://www.google.com/webhp?complete=1&hl=en" }, { "code": null, "e": 5601, "s": 5506, "text": "Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and useful." }, { "code": null, "e": 5620, "s": 5601, "text": "https://gmail.com/" }, { "code": null, "e": 5639, "s": 5620, "text": "https://gmail.com/" }, { "code": null, "e": 5700, "s": 5639, "text": "Now it's even easier and more fun to get where you're going!" }, { "code": null, "e": 5724, "s": 5700, "text": "https://maps.yahoo.com/" }, { "code": null, "e": 5748, "s": 5724, "text": "https://maps.yahoo.com/" }, { "code": null, "e": 6026, "s": 5748, "text": "Try these two examples one by one and you will feel the difference. While trying AJAX example, there is no discontinuity and you get the response very quickly, but when you try the standard GCI example, you would have to wait for the response and your page also gets refreshed." }, { "code": null, "e": 6088, "s": 6026, "text": "NOTE − We have given a more complex example in AJAX Database." }, { "code": null, "e": 6188, "s": 6088, "text": "All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX." }, { "code": null, "e": 6219, "s": 6188, "text": "Mozilla Firefox 1.0 and above." }, { "code": null, "e": 6251, "s": 6219, "text": "Netscape version 7.1 and above." }, { "code": null, "e": 6279, "s": 6251, "text": "Apple Safari 1.2 and above." }, { "code": null, "e": 6320, "s": 6279, "text": "Microsoft Internet Explorer 5 and above." }, { "code": null, "e": 6331, "s": 6320, "text": "Konqueror." }, { "code": null, "e": 6352, "s": 6331, "text": "Opera 7.6 and above." }, { "code": null, "e": 6441, "s": 6352, "text": "When you write your next application, do consider the browsers that do not support AJAX." }, { "code": null, "e": 6607, "s": 6441, "text": "NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object – XMLHttpRequest object." }, { "code": null, "e": 6724, "s": 6607, "text": "The simplest way to make your source code compatible with a browser is to use try...catch blocks in your JavaScript." }, { "code": null, "e": 7835, "s": 6724, "text": "<html>\n <body>\n <script language = \"javascript\" type = \"text/javascript\">\n <!-- \n //Browser Support Code\n function ajaxFunction() {\n var ajaxRequest; // The variable that makes Ajax possible!\n\n try {\n // Opera 8.0+, Firefox, Safari \n ajaxRequest = new XMLHttpRequest();\n } catch (e) {\n\n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n \n try {\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n\n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n }\n //-->\n </script>\n \n <form name = 'myForm'>\n Name: <input type = 'text' name = 'username' /> <br />\n Time: <input type = 'text' name = 'time' />\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 7939, "s": 7835, "text": "In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt −" }, { "code": null, "e": 7975, "s": 7939, "text": "ajaxRequest = new XMLHttpRequest();" }, { "code": null, "e": 8129, "s": 7975, "text": "It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with −" }, { "code": null, "e": 8180, "s": 8129, "text": "ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");" }, { "code": null, "e": 8234, "s": 8180, "text": "ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");" }, { "code": null, "e": 8373, "s": 8234, "text": "If it doesn't work, then we can use a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support AJAX." }, { "code": null, "e": 8594, "s": 8373, "text": "Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter." }, { "code": null, "e": 8671, "s": 8594, "text": "This chapter gives you a clear picture of the exact steps of AJAX operation." }, { "code": null, "e": 8694, "s": 8671, "text": "A client event occurs." }, { "code": null, "e": 8731, "s": 8694, "text": "An XMLHttpRequest object is created." }, { "code": null, "e": 8772, "s": 8731, "text": "The XMLHttpRequest object is configured." }, { "code": null, "e": 8846, "s": 8772, "text": "The XMLHttpRequest object makes an asynchronous request to the Webserver." }, { "code": null, "e": 8904, "s": 8846, "text": "The Webserver returns the result containing XML document." }, { "code": null, "e": 8986, "s": 8904, "text": "The XMLHttpRequest object calls the callback() function and processes the result." }, { "code": null, "e": 9011, "s": 8986, "text": "The HTML DOM is updated." }, { "code": null, "e": 9047, "s": 9011, "text": "Let us take these steps one by one." }, { "code": null, "e": 9106, "s": 9047, "text": "A JavaScript function is called as the result of an event." }, { "code": null, "e": 9165, "s": 9106, "text": "A JavaScript function is called as the result of an event." }, { "code": null, "e": 9310, "s": 9165, "text": "Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to \"userid\"" }, { "code": null, "e": 9455, "s": 9310, "text": "Example − validateUserId() JavaScript function is mapped as an event handler to an onkeyup event on input form field whose id is set to \"userid\"" }, { "code": null, "e": 9546, "s": 9455, "text": "<input type = \"text\" size = \"20\" id = \"userid\" name = \"id\" onkeyup = \"validateUserId();\">." }, { "code": null, "e": 9637, "s": 9546, "text": "<input type = \"text\" size = \"20\" id = \"userid\" name = \"id\" onkeyup = \"validateUserId();\">." }, { "code": null, "e": 10208, "s": 9637, "text": "var ajaxRequest; // The variable that makes Ajax possible!\nfunction ajaxFunction() {\n try {\n // Opera 8.0+, Firefox, Safari\n ajaxRequest = new XMLHttpRequest();\n } catch (e) {\n \n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n \n try {\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n \n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n}" }, { "code": null, "e": 10351, "s": 10208, "text": "In this step, we will write a function that will be triggered by the client event and a callback function processRequest() will be registered." }, { "code": null, "e": 10696, "s": 10351, "text": "function validateUserId() {\n ajaxFunction();\n \n // Here processRequest() is the callback function.\n ajaxRequest.onreadystatechange = processRequest;\n \n if (!target) target = document.getElementById(\"userid\");\n var url = \"validate?id=\" + escape(target.value);\n \n ajaxRequest.open(\"GET\", url, true);\n ajaxRequest.send(null);\n}" }, { "code": null, "e": 10898, "s": 10696, "text": "Source code is available in the above piece of code. Code written in bold typeface is responsible to make a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest." }, { "code": null, "e": 11245, "s": 10898, "text": "function validateUserId() {\n ajaxFunction();\n \n // Here processRequest() is the callback function.\n ajaxRequest.onreadystatechange = processRequest;\n \n if (!target) target = document.getElementById(\"userid\");\n var url = \"validate?id = \" + escape(target.value);\n \n ajaxRequest.open(\"GET\", url, true);\n ajaxRequest.send(null);\n}" }, { "code": null, "e": 11353, "s": 11245, "text": "Assume you enter Zara in the userid box, then in the above request, the URL is set to \"validate?id = Zara\"." }, { "code": null, "e": 11452, "s": 11353, "text": "You can implement your server-side script in any language, however its logic should be as follows." }, { "code": null, "e": 11483, "s": 11452, "text": "Get a request from the client." }, { "code": null, "e": 11516, "s": 11483, "text": "Parse the input from the client." }, { "code": null, "e": 11540, "s": 11516, "text": "Do required processing." }, { "code": null, "e": 11571, "s": 11540, "text": "Send the output to the client." }, { "code": null, "e": 11655, "s": 11571, "text": "If we assume that you are going to write a servlet, then here is the piece of code." }, { "code": null, "e": 12227, "s": 11655, "text": "public void doGet(HttpServletRequest request,\n HttpServletResponse response) throws IOException, ServletException {\n String targetId = request.getParameter(\"id\");\n \n if ((targetId != null) && !accounts.containsKey(targetId.trim())) {\n response.setContentType(\"text/xml\");\n response.setHeader(\"Cache-Control\", \"no-cache\");\n response.getWriter().write(\"<valid>true</valid>\");\n } else {\n response.setContentType(\"text/xml\");\n response.setHeader(\"Cache-Control\", \"no-cache\");\n response.getWriter().write(\"<valid>false</valid>\");\n }\n}" }, { "code": null, "e": 12599, "s": 12227, "text": "The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will receive the result from the server and will do the required processing. As in the following example, it sets a variable message on true or false based on the returned value from the Webserver." }, { "code": null, "e": 12724, "s": 12599, "text": " \nfunction processRequest() {\n if (req.readyState == 4) {\n if (req.status == 200) {\n var message = ...;\n...\n}" }, { "code": null, "e": 12831, "s": 12724, "text": "This is the final step and in this step, your HTML page will be updated. It happens in the following way −" }, { "code": null, "e": 12899, "s": 12831, "text": "JavaScript gets a reference to any element in a page using DOM API." }, { "code": null, "e": 12965, "s": 12899, "text": "The recommended way to gain a reference to an element is to call." }, { "code": null, "e": 13102, "s": 12965, "text": "document.getElementById(\"userIdMessage\"), \n// where \"userIdMessage\" is the ID attribute \n// of an element appearing in the HTML document" }, { "code": null, "e": 13271, "s": 13102, "text": "JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example −" }, { "code": null, "e": 13440, "s": 13271, "text": "JavaScript may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify the child elements. Here is an example −" }, { "code": null, "e": 14339, "s": 13440, "text": "<script type = \"text/javascript\">\n <!--\n function setMessageUsingDOM(message) {\n var userMessageElement = document.getElementById(\"userIdMessage\");\n var messageText;\n \n if (message == \"false\") {\n userMessageElement.style.color = \"red\";\n messageText = \"Invalid User Id\";\n } else {\n userMessageElement.style.color = \"green\";\n messageText = \"Valid User Id\";\n }\n \n var messageBody = document.createTextNode(messageText);\n \n // if the messageBody element has been created simple \n // replace it otherwise append the new element\n if (userMessageElement.childNodes[0]) {\n userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);\n } else {\n userMessageElement.appendChild(messageBody);\n }\n }\n -->\n</script>\n\n<body>\n <div id = \"userIdMessage\"><div>\n</body>" }, { "code": null, "e": 14502, "s": 14339, "text": "If you have understood the above-mentioned seven steps, then you are almost done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail." }, { "code": null, "e": 14706, "s": 14502, "text": "The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0 in 2005 became popular." }, { "code": null, "e": 14998, "s": 14706, "text": "XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side." }, { "code": null, "e": 15190, "s": 14998, "text": "The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text." }, { "code": null, "e": 15276, "s": 15190, "text": "You already have seen a couple of examples on how to create an XMLHttpRequest object." }, { "code": null, "e": 15364, "s": 15276, "text": "Listed below are some of the methods and properties that you have to get familiar with." }, { "code": null, "e": 15401, "s": 15364, "text": "abort()\nCancels the current request." }, { "code": null, "e": 15409, "s": 15401, "text": "abort()" }, { "code": null, "e": 15438, "s": 15409, "text": "Cancels the current request." }, { "code": null, "e": 15516, "s": 15438, "text": "getAllResponseHeaders()\nReturns the complete set of HTTP headers as a string." }, { "code": null, "e": 15540, "s": 15516, "text": "getAllResponseHeaders()" }, { "code": null, "e": 15594, "s": 15540, "text": "Returns the complete set of HTTP headers as a string." }, { "code": null, "e": 15674, "s": 15594, "text": "getResponseHeader( headerName )\nReturns the value of the specified HTTP header." }, { "code": null, "e": 15706, "s": 15674, "text": "getResponseHeader( headerName )" }, { "code": null, "e": 15754, "s": 15706, "text": "Returns the value of the specified HTTP header." }, { "code": null, "e": 15774, "s": 15754, "text": "open( method, URL )" }, { "code": null, "e": 15794, "s": 15774, "text": "open( method, URL )" }, { "code": null, "e": 15821, "s": 15794, "text": "open( method, URL, async )" }, { "code": null, "e": 15848, "s": 15821, "text": "open( method, URL, async )" }, { "code": null, "e": 15885, "s": 15848, "text": "open( method, URL, async, userName )" }, { "code": null, "e": 15922, "s": 15885, "text": "open( method, URL, async, userName )" }, { "code": null, "e": 16501, "s": 15922, "text": "open( method, URL, async, userName, password )\nSpecifies the method, URL, and other optional attributes of a request.\nThe method parameter can have a value of \"GET\", \"POST\", or \"HEAD\". Other HTTP methods such as \"PUT\" and \"DELETE\" (primarily used in REST applications) may be possible.\nThe \"async\" parameter specifies whether the request should be handled asynchronously or not. \"true\" means that the script processing carries on after the send() method without waiting for a response, and \"false\" means that the script waits for a response before continuing script processing.\n" }, { "code": null, "e": 16548, "s": 16501, "text": "open( method, URL, async, userName, password )" }, { "code": null, "e": 16619, "s": 16548, "text": "Specifies the method, URL, and other optional attributes of a request." }, { "code": null, "e": 16787, "s": 16619, "text": "The method parameter can have a value of \"GET\", \"POST\", or \"HEAD\". Other HTTP methods such as \"PUT\" and \"DELETE\" (primarily used in REST applications) may be possible." }, { "code": null, "e": 17079, "s": 16787, "text": "The \"async\" parameter specifies whether the request should be handled asynchronously or not. \"true\" means that the script processing carries on after the send() method without waiting for a response, and \"false\" means that the script waits for a response before continuing script processing." }, { "code": null, "e": 17114, "s": 17079, "text": "send( content )\nSends the request." }, { "code": null, "e": 17130, "s": 17114, "text": "send( content )" }, { "code": null, "e": 17149, "s": 17130, "text": "Sends the request." }, { "code": null, "e": 17237, "s": 17149, "text": "setRequestHeader( label, value )\nAdds a label/value pair to the HTTP header to be sent." }, { "code": null, "e": 17270, "s": 17237, "text": "setRequestHeader( label, value )" }, { "code": null, "e": 17325, "s": 17270, "text": "Adds a label/value pair to the HTTP header to be sent." }, { "code": null, "e": 17408, "s": 17325, "text": "onreadystatechange\nAn event handler for an event that fires at every state change." }, { "code": null, "e": 17427, "s": 17408, "text": "onreadystatechange" }, { "code": null, "e": 17491, "s": 17427, "text": "An event handler for an event that fires at every state change." }, { "code": null, "e": 17672, "s": 17491, "text": "readyState\nThe readyState property defines the current state of the XMLHttpRequest object.\nThe following table provides a list of the possible values for the readyState property −\n" }, { "code": null, "e": 17683, "s": 17672, "text": "readyState" }, { "code": null, "e": 17763, "s": 17683, "text": "The readyState property defines the current state of the XMLHttpRequest object." }, { "code": null, "e": 17852, "s": 17763, "text": "The following table provides a list of the possible values for the readyState property −" }, { "code": null, "e": 17963, "s": 17852, "text": "readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method." }, { "code": null, "e": 18054, "s": 17963, "text": "readyState = 1 After you have called the open() method, but before you have called send()." }, { "code": null, "e": 18099, "s": 18054, "text": "readyState = 2 After you have called send()." }, { "code": null, "e": 18231, "s": 18099, "text": "readyState = 3 After the browser has established a communication with the server, but before the server has completed the response." }, { "code": null, "e": 18352, "s": 18231, "text": "readyState = 4 After the request has been completed, and the response data has been completely received from the server." }, { "code": null, "e": 18399, "s": 18352, "text": "responseText\nReturns the response as a string." }, { "code": null, "e": 18412, "s": 18399, "text": "responseText" }, { "code": null, "e": 18446, "s": 18412, "text": "Returns the response as a string." }, { "code": null, "e": 18618, "s": 18446, "text": "responseXML\nReturns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties." }, { "code": null, "e": 18630, "s": 18618, "text": "responseXML" }, { "code": null, "e": 18790, "s": 18630, "text": "Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties." }, { "code": null, "e": 18874, "s": 18790, "text": "status\nReturns the status as a number (e.g., 404 for \"Not Found\" and 200 for \"OK\")." }, { "code": null, "e": 18881, "s": 18874, "text": "status" }, { "code": null, "e": 18958, "s": 18881, "text": "Returns the status as a number (e.g., 404 for \"Not Found\" and 200 for \"OK\")." }, { "code": null, "e": 19029, "s": 18958, "text": "statusText\nReturns the status as a string (e.g., \"Not Found\" or \"OK\")." }, { "code": null, "e": 19040, "s": 19029, "text": "statusText" }, { "code": null, "e": 19100, "s": 19040, "text": "Returns the status as a string (e.g., \"Not Found\" or \"OK\")." }, { "code": null, "e": 19368, "s": 19100, "text": "To clearly illustrate how easy it is to access information from a database using AJAX, we are going to build MySQL queries on the fly and display the results on \"ajax.html\". But before we proceed, let us do the ground work. Create a table using the following command." }, { "code": null, "e": 19464, "s": 19368, "text": "NOTE − We are assuming you have sufficient privilege to perform the following MySQL operations." }, { "code": null, "e": 19639, "s": 19464, "text": "CREATE TABLE 'ajax_example' (\n 'name' varchar(50) NOT NULL,\n 'age' int(11) NOT NULL,\n 'sex' varchar(1) NOT NULL,\n 'wpm' int(11) NOT NULL,\n PRIMARY KEY ('name')\n) \n" }, { "code": null, "e": 19720, "s": 19639, "text": "Now dump the following data into this table using the following SQL statements −" }, { "code": null, "e": 20068, "s": 19720, "text": "INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);\nINSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);\nINSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);\nINSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);\nINSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);\nINSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);\n" }, { "code": null, "e": 20169, "s": 20068, "text": "Now let us have our client side HTML file, which is ajax.html, and it will have the following code −" }, { "code": null, "e": 22600, "s": 20169, "text": "<html>\n <body>\n <script language = \"javascript\" type = \"text/javascript\">\n <!-- \n //Browser Support Code\n function ajaxFunction() {\n var ajaxRequest; // The variable that makes Ajax possible!\n \n try { \n // Opera 8.0+, Firefox, Safari\n ajaxRequest = new XMLHttpRequest();\n } catch (e) {\n \n // Internet Explorer Browsers\n try {\n ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n \n try {\n ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {\n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n }\n }\n \n // Create a function that will receive data\n // sent from the server and will update\n // div section in the same page.\n ajaxRequest.onreadystatechange = function() {\n \n if(ajaxRequest.readyState == 4) {\n var ajaxDisplay = document.getElementById('ajaxDiv');\n ajaxDisplay.innerHTML = ajaxRequest.responseText;\n }\n }\n \n // Now get the value from user and pass it to\n // server script.\n var age = document.getElementById('age').value;\n var wpm = document.getElementById('wpm').value;\n var sex = document.getElementById('sex').value;\n var queryString = \"?age = \" + age ;\n \n queryString += \"&wpm = \" + wpm + \"&sex = \" + sex;\n ajaxRequest.open(\"GET\", \"ajax-example.php\" + queryString, true);\n ajaxRequest.send(null); \n }\n //-->\n </script>\n\n <form name = 'myForm'>\n Max Age: <input type = 'text' id = 'age' /> <br />\n Max WPM: <input type = 'text' id = 'wpm' /> <br />\n Sex: \n \n <select id = 'sex'>\n <option value = \"m\">m</option>\n <option value = \"f\">f</option>\n </select>\n \n <input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>\n </form>\n \n <div id = 'ajaxDiv'>Your result will display here</div>\n </body>\n</html>" }, { "code": null, "e": 22695, "s": 22600, "text": "NOTE − The way of passing variables in the Query is according to HTTP standard and have formA." }, { "code": null, "e": 22739, "s": 22695, "text": "URL?variable1 = value1;&variable2 = value2;" }, { "code": null, "e": 22794, "s": 22739, "text": "The above code will give you a screen as given below −" }, { "code": null, "e": 22805, "s": 22794, "text": "Max Age: " }, { "code": null, "e": 22815, "s": 22805, "text": "Max WPM: " }, { "code": null, "e": 22826, "s": 22815, "text": "Sex: \nm\nf\n" }, { "code": null, "e": 22904, "s": 22826, "text": "Your result will display here in this section after you have made your entry." }, { "code": null, "e": 22935, "s": 22904, "text": "NOTE − This is a dummy screen." }, { "code": null, "e": 23162, "s": 22935, "text": "Your client-side script is ready. Now, we have to write our server-side script, which will fetch age, wpm, and sex from the database and will send it back to the client. Put the following code into the file \"ajax-example.php\"." }, { "code": null, "e": 24614, "s": 23162, "text": "<?php\n$dbhost = \"localhost\";\n$dbuser = \"dbusername\";\n$dbpass = \"dbpassword\";\n$dbname = \"dbname\";\n\t\n//Connect to MySQL Server\nmysql_connect($dbhost, $dbuser, $dbpass);\n\t\n//Select Database\nmysql_select_db($dbname) or die(mysql_error());\n\t\n// Retrieve data from Query String\n$age = $_GET['age'];\n$sex = $_GET['sex'];\n$wpm = $_GET['wpm'];\n\t\n// Escape User Input to help prevent SQL Injection\n$age = mysql_real_escape_string($age);\n$sex = mysql_real_escape_string($sex);\n$wpm = mysql_real_escape_string($wpm);\n\t\n//build query\n$query = \"SELECT * FROM ajax_example WHERE sex = '$sex'\";\n\nif(is_numeric($age))\n $query .= \" AND age <= $age\";\n\nif(is_numeric($wpm))\n $query .= \" AND wpm <= $wpm\";\n\t\n//Execute query\n$qry_result = mysql_query($query) or die(mysql_error());\n\n//Build Result String\n$display_string = \"<table>\";\n$display_string .= \"<tr>\";\n$display_string .= \"<th>Name</th>\";\n$display_string .= \"<th>Age</th>\";\n$display_string .= \"<th>Sex</th>\";\n$display_string .= \"<th>WPM</th>\";\n$display_string .= \"</tr>\";\n\n// Insert a new row in the table for each person returned\nwhile($row = mysql_fetch_array($qry_result)) {\n $display_string .= \"<tr>\";\n $display_string .= \"<td>$row[name]</td>\";\n $display_string .= \"<td>$row[age]</td>\";\n $display_string .= \"<td>$row[sex]</td>\";\n $display_string .= \"<td>$row[wpm]</td>\";\n $display_string .= \"</tr>\";\n}\n\necho \"Query: \" . $query . \"<br />\";\n$display_string .= \"</table>\";\n\necho $display_string;\n?>" }, { "code": null, "e": 24723, "s": 24614, "text": "Now try by entering a valid value (e.g., 120) in Max Age or any other box and then click Query MySQL button." }, { "code": null, "e": 24734, "s": 24723, "text": "Max Age: " }, { "code": null, "e": 24744, "s": 24734, "text": "Max WPM: " }, { "code": null, "e": 24755, "s": 24744, "text": "Sex: \nm\nf\n" }, { "code": null, "e": 24833, "s": 24755, "text": "Your result will display here in this section after you have made your entry." }, { "code": null, "e": 24977, "s": 24833, "text": "If you have successfully completed this lesson, then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write AJAX applications." }, { "code": null, "e": 25076, "s": 24977, "text": "AJAX-based Web applications use the same server-side security schemes of regular Web applications." }, { "code": null, "e": 25175, "s": 25076, "text": "AJAX-based Web applications use the same server-side security schemes of regular Web applications." }, { "code": null, "e": 25321, "s": 25175, "text": "You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programmatic)." }, { "code": null, "e": 25467, "s": 25321, "text": "You specify authentication, authorization, and data protection requirements in your web.xml file (declarative) or in your program (programmatic)." }, { "code": null, "e": 25565, "s": 25467, "text": "AJAX-based Web applications are subject to the same security threats as regular Web applications." }, { "code": null, "e": 25663, "s": 25565, "text": "AJAX-based Web applications are subject to the same security threats as regular Web applications." }, { "code": null, "e": 25777, "s": 25663, "text": "JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-side weaknesses." }, { "code": null, "e": 25891, "s": 25777, "text": "JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-side weaknesses." }, { "code": null, "e": 26025, "s": 25891, "text": "JavaScript code is downloaded from the server and executed (\"eval\") at the client and can compromise the client by mal-intended code." }, { "code": null, "e": 26159, "s": 26025, "text": "JavaScript code is downloaded from the server and executed (\"eval\") at the client and can compromise the client by mal-intended code." }, { "code": null, "e": 26274, "s": 26159, "text": "Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for signed JavaScript." }, { "code": null, "e": 26389, "s": 26274, "text": "Downloaded JavaScript code is constrained by the sand-box security model and can be relaxed for signed JavaScript." }, { "code": null, "e": 26647, "s": 26389, "text": "AJAX is growing very fast and that is the reason that it contains many issues with it. We hope with the passes of time, they will be resolved and AJAX will become ideal for web applications. We are listing down a few issues that AJAX currently suffers from." }, { "code": null, "e": 26671, "s": 26647, "text": "Complexity is increased" }, { "code": null, "e": 26821, "s": 26671, "text": "Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic." }, { "code": null, "e": 26971, "s": 26821, "text": "Server-side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic." }, { "code": null, "e": 27027, "s": 26971, "text": "Page developers must have JavaScript technology skills." }, { "code": null, "e": 27083, "s": 27027, "text": "Page developers must have JavaScript technology skills." }, { "code": null, "e": 27153, "s": 27083, "text": "AJAX-based applications can be difficult to debug, test, and maintain" }, { "code": null, "e": 27209, "s": 27153, "text": "JavaScript is hard to test - automatic testing is hard." }, { "code": null, "e": 27240, "s": 27209, "text": "Weak modularity in JavaScript." }, { "code": null, "e": 27297, "s": 27240, "text": "Lack of design patterns or best practice guidelines yet." }, { "code": null, "e": 27336, "s": 27297, "text": "Toolkits/Frameworks are not mature yet" }, { "code": null, "e": 27368, "s": 27336, "text": "Most of them are in beta phase." }, { "code": null, "e": 27413, "s": 27368, "text": "No standardization of the XMLHttpRequest yet" }, { "code": null, "e": 27453, "s": 27413, "text": "Future version of IE will address this." }, { "code": null, "e": 27498, "s": 27453, "text": "No support of XMLHttpRequest in old browsers" }, { "code": null, "e": 27516, "s": 27498, "text": "Iframe will help." }, { "code": null, "e": 27569, "s": 27516, "text": "JavaScript technology dependency and incompatibility" }, { "code": null, "e": 27615, "s": 27569, "text": "Must be enabled for applications to function." }, { "code": null, "e": 27659, "s": 27615, "text": "Still some browser incompatibilities exist." }, { "code": null, "e": 27698, "s": 27659, "text": "JavaScript code is visible to a hacker" }, { "code": null, "e": 27760, "s": 27698, "text": "Poorly designed JavaScript code can invite security problems." }, { "code": null, "e": 27795, "s": 27760, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 27812, "s": 27795, "text": " Frahaan Hussain" }, { "code": null, "e": 27845, "s": 27812, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 27862, "s": 27845, "text": " Laurence Svekis" }, { "code": null, "e": 27895, "s": 27862, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 27905, "s": 27895, "text": " YouAccel" }, { "code": null, "e": 27940, "s": 27905, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 27950, "s": 27940, "text": " YouAccel" }, { "code": null, "e": 27985, "s": 27950, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 28008, "s": 27985, "text": " Stone River ELearning" }, { "code": null, "e": 28043, "s": 28008, "text": "\n 47 Lectures \n 5.5 hours \n" }, { "code": null, "e": 28061, "s": 28043, "text": " Packt Publishing" }, { "code": null, "e": 28068, "s": 28061, "text": " Print" }, { "code": null, "e": 28079, "s": 28068, "text": " Add Notes" } ]
How to create multi-column layout in HTML5 using tables?
Design your webpage to put your web content on multiple pages. You can keep your content in the middle column, you can use left column to use menu, and right column can be used to put an advertisement or some other stuff. <!DOCTYPE html> <html> <head> <title>Three Column HTML Layout</title> </head> <body> <table width = "100%" border = "0"> <tr valign = "top"> <td bgcolor = "#aaa" width = "20%"> <b>Main Menu</b><br /> HTML<br /> PHP<br /> PERL... </td> <td bgcolor = "#b5dcb3" height = "200" width = "60%"> Technical and Managerial Tutorials </td> <td bgcolor = "#aaa" width = "20%"> <b>Right Menu</b><br /> HTML<br /> PHP<br /> PERL... </td> </tr> <table> </body> </html>
[ { "code": null, "e": 1284, "s": 1062, "text": "Design your webpage to put your web content on multiple pages. You can keep your content in the middle column, you can use left column to use menu, and right column can be used to put an advertisement or some other stuff." }, { "code": null, "e": 1996, "s": 1284, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Three Column HTML Layout</title>\n </head>\n <body>\n <table width = \"100%\" border = \"0\">\n <tr valign = \"top\">\n <td bgcolor = \"#aaa\" width = \"20%\">\n <b>Main Menu</b><br />\n HTML<br />\n PHP<br />\n PERL...\n </td>\n\n <td bgcolor = \"#b5dcb3\" height = \"200\" width = \"60%\">\n Technical and Managerial Tutorials\n </td>\n\n <td bgcolor = \"#aaa\" width = \"20%\">\n <b>Right Menu</b><br />\n HTML<br />\n PHP<br />\n PERL...\n </td>\n </tr>\n <table>\n </body>\n</html>" } ]
How to include Social Media Icons in HTML ? - GeeksforGeeks
24 Jun, 2021 In this article, we will see how to add social media icons to any website using HTML and CSS Approach: If you want to attach an icons then you need a font-awesome CDN link. Social media could be very helpful in promoting and advertising your website. If your brand has social media accounts, it would be wise to give the website visitors an opportunity to join them and share your posts in their timelines. Note: You can either add Social Media icons as images( SVG, PNG ) or Font icon ( Font awesome ). In this article, explore both ways. Method 1: To use Font Awesome Icons, add the following CDN link inside <head> section. <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> Syntax: <a href="#" class="fa fa-facebook"></a> Example 1: In this example, we are using font awesome icon (Google Icons and Bootstrap Icons). HTML <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <style> .fa:hover { opacity: 0.9; } .fa-linkedin { background: #007bb5; color: white; } .fa-pinterest { background: #cb2027; color: white; } .fa-reddit { background: #ff5700; color: white; } .fa { padding: 20px; font-size: 40px; width: 60px; text-decoration: none; margin: 5px 80px; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Social Media Icons</h3> <!-- Add font awesome icons --> <a href="#" class="fa fa-linkedin"></a> <a href="#" class="fa fa-pinterest"></a> <a href="#" class="fa fa-reddit"></a> </center></body> </html> Output: Method 2: To use Google Icons, add the following link inside <head> section. <link rel=”stylesheet” href=”https://fonts.googleapis.com/icon?family=Material+Icons”> Syntax: <i class="material-icons">facebook</i> Example: HTML <!DOCTYPE><html> <head> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /></head> <style> h1 { color: green; } .material-icons { padding: 10px; font-size: 40px; width: 40px; text-decoration: none; margin: 5px 80px; } .android { background: #a4c639; color: white; } .facebook { background: #3b5998; color: white; }</style> <body> <center> <h1>GEEKSFORGEEKS</h1> <h3>Google Font Icon</h3> <i class="material-icons android">android </i> <i class="material-icons facebook">facebook</i> </center></body> </html> Output: Method 3: In this example, we are using SVG or PNG Images to an icon. Syntax: <svg class="bi bi-google" width="64" height="64" viewBox="0 0 16 16"> <path d=" "/> </svg> Note: You can select SVG icon through various websites like heroicons, bootstrap icons etc. Bootstrap icon is used in below example HTML <!DOCTYPE html><html><style> h1 { color: green; } .bi-twitter { color: #55acee; margin: 5px 20px; } .bi-google { color: #dd4b39; margin: 5px 20px; } .bi-youtube { color: #dd4b39; margin: 5px 20px; }</style> <body> <center> <h1>GEEKSFORGEEKS</h1> <!---- TWITTER ICON ---> <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" class="bi bi-twitter" viewBox="0 0 16 16"> <path d="M5.026 15c6.038 0 9.341-5.003 9.341-9.334 0-.14 0-.282-.006-.422A6.685 6.685 0 0 0 16 3.542a6.658 6.658 0 0 1-1.889.518 3.301 3.301 0 0 0 1.447-1.817 6.533 6.533 0 0 1-2.087.793A3.286 3.286 0 0 0 7.875 6.03a9.325 9.325 0 0 1-6.767-3.429 3.289 3.289 0 0 0 1.018 4.382A3.323 3.323 0 0 1 .64 6.575v.045a3.288 3.288 0 0 0 2.632 3.218 3.203 3.203 0 0 1-.865.115 3.23 3.23 0 0 1-.614-.057 3.283 3.283 0 0 0 3.067 2.277A6.588 6.588 0 0 1 .78 13.58a6.32 6.32 0 0 1-.78-.045A9.344 9.344 0 0 0 5.026 15z" /> </svg> <!---- GOOGLE ICON ---> <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" class="bi bi-google" viewBox="0 0 16 16"> <path d="M15.545 6.558a9.42 9.42 0 0 1 .139 1.626c0 2.434-.87 4.492-2.384 5.885h.002C11.978 15.292 10.158 16 8 16A8 8 0 1 1 8 0a7.689 7.689 0 0 1 5.352 2.082l-2.284 2.284A4.347 4.347 0 0 0 8 3.166c-2.087 0-3.86 1.408-4.492 3.304a4.792 4.792 0 0 0 0 3.063h.003c.635 1.893 2.405 3.301 4.492 3.301 1.078 0 2.004-.276 2.722-.764h-.003 a3.702 3.702 0 0 0 1.599-2.431H8v-3.08h7.545z" /> </svg> <!---- YOUTUBE ICON ---> <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="currentColor" class="bi bi-youtube" viewBox="0 0 16 16"> <path d="M8.051 1.999h.089c.822.003 4.987.033 6.11.335a2.01 2.01 0 0 1 1.415 1.42c.101.38.172 .883.22 1.402l.01.104.022.26.008.104c.065.914.073 1.77.074 1.957v.075c-.001.194-.01 1.108-.082 2.06l-.008.105-.009.104c-.05.572-.124 1.14-.235 1.558a2.007 2.007 0 0 1-1.415 1.42c-1.16.312 -5.569.334-6.18.335h-.142c-.309 0-1.587-.006 -2.927-.052l-.17-.006-.087-.004-.171-.007-.171 -.007c-1.11-.049 -2.167-.128-2.654-.26a2.007 2.007 0 0 1-1.415-1.419c-.111-.417-.185-.986 -.235-1.558L.09 9.82l-.008-.104A31.4 31.4 0 0 1 0 7.68v-.123c.002-.215.01-.958.064-1.778l .007-.103.003-.052.008-.104.022-.26.01-.104c .048-.519.119-1.023.22-1.402a2.007 2.007 0 0 1 1.415-1.42c.487-.13 1.544-.21 2.654-.26l.17 -.007.172-.006.086-.003.171-.007A99.788 99.788 0 0 1 7.858 2h.193zM6.4 5.209v4.818l4.157 -2.408L6.4 5.209z" /> </svg> </center></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions HTML-SVG icon resources Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Primer CSS Flexbox Flex Direction HTML Course | First Web Page | Printing Hello World Design a web page using HTML and CSS Search Bar using HTML, CSS and JavaScript How to wrap the text around an image using HTML and CSS ? REST API (Introduction) How to Insert Form Data into Database using PHP ? Form validation using HTML and JavaScript How to set input type date in dd-mm-yyyy format using HTML ? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 25009, "s": 24981, "text": "\n24 Jun, 2021" }, { "code": null, "e": 25102, "s": 25009, "text": "In this article, we will see how to add social media icons to any website using HTML and CSS" }, { "code": null, "e": 25112, "s": 25102, "text": "Approach:" }, { "code": null, "e": 25416, "s": 25112, "text": "If you want to attach an icons then you need a font-awesome CDN link. Social media could be very helpful in promoting and advertising your website. If your brand has social media accounts, it would be wise to give the website visitors an opportunity to join them and share your posts in their timelines." }, { "code": null, "e": 25549, "s": 25416, "text": "Note: You can either add Social Media icons as images( SVG, PNG ) or Font icon ( Font awesome ). In this article, explore both ways." }, { "code": null, "e": 25638, "s": 25551, "text": "Method 1: To use Font Awesome Icons, add the following CDN link inside <head> section." }, { "code": null, "e": 25752, "s": 25638, "text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>" }, { "code": null, "e": 25760, "s": 25752, "text": "Syntax:" }, { "code": null, "e": 25800, "s": 25760, "text": "<a href=\"#\" class=\"fa fa-facebook\"></a>" }, { "code": null, "e": 25895, "s": 25800, "text": "Example 1: In this example, we are using font awesome icon (Google Icons and Bootstrap Icons)." }, { "code": null, "e": 25900, "s": 25895, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <style> .fa:hover { opacity: 0.9; } .fa-linkedin { background: #007bb5; color: white; } .fa-pinterest { background: #cb2027; color: white; } .fa-reddit { background: #ff5700; color: white; } .fa { padding: 20px; font-size: 40px; width: 60px; text-decoration: none; margin: 5px 80px; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Social Media Icons</h3> <!-- Add font awesome icons --> <a href=\"#\" class=\"fa fa-linkedin\"></a> <a href=\"#\" class=\"fa fa-pinterest\"></a> <a href=\"#\" class=\"fa fa-reddit\"></a> </center></body> </html>", "e": 26993, "s": 25900, "text": null }, { "code": null, "e": 27001, "s": 26993, "text": "Output:" }, { "code": null, "e": 27079, "s": 27001, "text": " Method 2: To use Google Icons, add the following link inside <head> section." }, { "code": null, "e": 27166, "s": 27079, "text": "<link rel=”stylesheet” href=”https://fonts.googleapis.com/icon?family=Material+Icons”>" }, { "code": null, "e": 27174, "s": 27166, "text": "Syntax:" }, { "code": null, "e": 27213, "s": 27174, "text": "<i class=\"material-icons\">facebook</i>" }, { "code": null, "e": 27222, "s": 27213, "text": "Example:" }, { "code": null, "e": 27227, "s": 27222, "text": "HTML" }, { "code": "<!DOCTYPE><html> <head> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" /></head> <style> h1 { color: green; } .material-icons { padding: 10px; font-size: 40px; width: 40px; text-decoration: none; margin: 5px 80px; } .android { background: #a4c639; color: white; } .facebook { background: #3b5998; color: white; }</style> <body> <center> <h1>GEEKSFORGEEKS</h1> <h3>Google Font Icon</h3> <i class=\"material-icons android\">android </i> <i class=\"material-icons facebook\">facebook</i> </center></body> </html>", "e": 27913, "s": 27227, "text": null }, { "code": null, "e": 27921, "s": 27913, "text": "Output:" }, { "code": null, "e": 27991, "s": 27921, "text": "Method 3: In this example, we are using SVG or PNG Images to an icon." }, { "code": null, "e": 27999, "s": 27991, "text": "Syntax:" }, { "code": null, "e": 28093, "s": 27999, "text": "<svg class=\"bi bi-google\" width=\"64\" height=\"64\" viewBox=\"0 0 16 16\">\n <path d=\" \"/>\n</svg>" }, { "code": null, "e": 28225, "s": 28093, "text": "Note: You can select SVG icon through various websites like heroicons, bootstrap icons etc. Bootstrap icon is used in below example" }, { "code": null, "e": 28230, "s": 28225, "text": "HTML" }, { "code": "<!DOCTYPE html><html><style> h1 { color: green; } .bi-twitter { color: #55acee; margin: 5px 20px; } .bi-google { color: #dd4b39; margin: 5px 20px; } .bi-youtube { color: #dd4b39; margin: 5px 20px; }</style> <body> <center> <h1>GEEKSFORGEEKS</h1> <!---- TWITTER ICON ---> <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"64\" fill=\"currentColor\" class=\"bi bi-twitter\" viewBox=\"0 0 16 16\"> <path d=\"M5.026 15c6.038 0 9.341-5.003 9.341-9.334 0-.14 0-.282-.006-.422A6.685 6.685 0 0 0 16 3.542a6.658 6.658 0 0 1-1.889.518 3.301 3.301 0 0 0 1.447-1.817 6.533 6.533 0 0 1-2.087.793A3.286 3.286 0 0 0 7.875 6.03a9.325 9.325 0 0 1-6.767-3.429 3.289 3.289 0 0 0 1.018 4.382A3.323 3.323 0 0 1 .64 6.575v.045a3.288 3.288 0 0 0 2.632 3.218 3.203 3.203 0 0 1-.865.115 3.23 3.23 0 0 1-.614-.057 3.283 3.283 0 0 0 3.067 2.277A6.588 6.588 0 0 1 .78 13.58a6.32 6.32 0 0 1-.78-.045A9.344 9.344 0 0 0 5.026 15z\" /> </svg> <!---- GOOGLE ICON ---> <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"64\" fill=\"currentColor\" class=\"bi bi-google\" viewBox=\"0 0 16 16\"> <path d=\"M15.545 6.558a9.42 9.42 0 0 1 .139 1.626c0 2.434-.87 4.492-2.384 5.885h.002C11.978 15.292 10.158 16 8 16A8 8 0 1 1 8 0a7.689 7.689 0 0 1 5.352 2.082l-2.284 2.284A4.347 4.347 0 0 0 8 3.166c-2.087 0-3.86 1.408-4.492 3.304a4.792 4.792 0 0 0 0 3.063h.003c.635 1.893 2.405 3.301 4.492 3.301 1.078 0 2.004-.276 2.722-.764h-.003 a3.702 3.702 0 0 0 1.599-2.431H8v-3.08h7.545z\" /> </svg> <!---- YOUTUBE ICON ---> <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"64\" fill=\"currentColor\" class=\"bi bi-youtube\" viewBox=\"0 0 16 16\"> <path d=\"M8.051 1.999h.089c.822.003 4.987.033 6.11.335a2.01 2.01 0 0 1 1.415 1.42c.101.38.172 .883.22 1.402l.01.104.022.26.008.104c.065.914.073 1.77.074 1.957v.075c-.001.194-.01 1.108-.082 2.06l-.008.105-.009.104c-.05.572-.124 1.14-.235 1.558a2.007 2.007 0 0 1-1.415 1.42c-1.16.312 -5.569.334-6.18.335h-.142c-.309 0-1.587-.006 -2.927-.052l-.17-.006-.087-.004-.171-.007-.171 -.007c-1.11-.049 -2.167-.128-2.654-.26a2.007 2.007 0 0 1-1.415-1.419c-.111-.417-.185-.986 -.235-1.558L.09 9.82l-.008-.104A31.4 31.4 0 0 1 0 7.68v-.123c.002-.215.01-.958.064-1.778l .007-.103.003-.052.008-.104.022-.26.01-.104c .048-.519.119-1.023.22-1.402a2.007 2.007 0 0 1 1.415-1.42c.487-.13 1.544-.21 2.654-.26l.17 -.007.172-.006.086-.003.171-.007A99.788 99.788 0 0 1 7.858 2h.193zM6.4 5.209v4.818l4.157 -2.408L6.4 5.209z\" /> </svg> </center></body> </html>", "e": 31346, "s": 28230, "text": null }, { "code": null, "e": 31354, "s": 31346, "text": "Output:" }, { "code": null, "e": 31491, "s": 31354, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31506, "s": 31491, "text": "CSS-Properties" }, { "code": null, "e": 31520, "s": 31506, "text": "CSS-Questions" }, { "code": null, "e": 31535, "s": 31520, "text": "HTML-Questions" }, { "code": null, "e": 31544, "s": 31535, "text": "HTML-SVG" }, { "code": null, "e": 31559, "s": 31544, "text": "icon resources" }, { "code": null, "e": 31566, "s": 31559, "text": "Picked" }, { "code": null, "e": 31570, "s": 31566, "text": "CSS" }, { "code": null, "e": 31575, "s": 31570, "text": "HTML" }, { "code": null, "e": 31592, "s": 31575, "text": "Web Technologies" }, { "code": null, "e": 31597, "s": 31592, "text": "HTML" }, { "code": null, "e": 31695, "s": 31597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31704, "s": 31695, "text": "Comments" }, { "code": null, "e": 31717, "s": 31704, "text": "Old Comments" }, { "code": null, "e": 31751, "s": 31717, "text": "Primer CSS Flexbox Flex Direction" }, { "code": null, "e": 31803, "s": 31751, "text": "HTML Course | First Web Page | Printing Hello World" }, { "code": null, "e": 31840, "s": 31803, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31882, "s": 31840, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31940, "s": 31882, "text": "How to wrap the text around an image using HTML and CSS ?" }, { "code": null, "e": 31964, "s": 31940, "text": "REST API (Introduction)" }, { "code": null, "e": 32014, "s": 31964, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 32056, "s": 32014, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 32117, "s": 32056, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Machine Learning - Automatic Workflows
In order to execute and produce results successfully, a machine learning model must automate some standard workflows. The process of automate these standard workflows can be done with the help of Scikit-learn Pipelines. From a data scientist’s perspective, pipeline is a generalized, but very important concept. It basically allows data flow from its raw format to some useful information. The working of pipelines can be understood with the help of following diagram − The blocks of ML pipelines are as follows − Data ingestion − As the name suggests, it is the process of importing the data for use in ML project. The data can be extracted in real time or batches from single or multiple systems. It is one of the most challenging steps because the quality of data can affect the whole ML model. Data Preparation − After importing the data, we need to prepare data to be used for our ML model. Data preprocessing is one of the most important technique of data preparation. ML Model Training − Next step is to train our ML model. We have various ML algorithms like supervised, unsupervised, reinforcement to extract the features from data, and make predictions. Model Evaluation − Next, we need to evaluate the ML model. In case of AutoML pipeline, ML model can be evaluated with the help of various statistical methods and business rules. ML Model retraining − In case of AutoML pipeline, it is not necessary that the first model is best one. The first model is considered as a baseline model and we can train it repeatably to increase model’s accuracy. Deployment − At last, we need to deploy the model. This step involves applying and migrating the model to business operations for their use. In order to create ML pipelines, data scientists face many challenges. These challenges fall into the following three categories − The success of any ML model depends heavily on the quality of data. If the data we are providing to ML model is not accurate, reliable and robust, then we are going to end with wrong or misleading output. Another challenge associated with ML pipelines is the reliability of data we are providing to the ML model. As we know, there can be various sources from which data scientist can acquire data but to get the best results, it must be assured that the data sources are reliable and trusted. To get the best results out of ML pipelines, the data itself must be accessible which requires consolidation, cleansing and curation of data. As a result of data accessibility property, metadata will be updated with new tags. Data leakage, happening from training dataset to testing dataset, is an important issue for data scientist to deal with while preparing data for ML model. Generally, at the time of data preparation, data scientist uses techniques like standardization or normalization on entire dataset before learning. But these techniques cannot help us from the leakage of data because the training dataset would have been influenced by the scale of the data in the testing dataset. By using ML pipelines, we can prevent this data leakage because pipelines ensure that data preparation like standardization is constrained to each fold of our cross-validation procedure. The following is an example in Python that demonstrate data preparation and model evaluation workflow. For this purpose, we are using Pima Indian Diabetes dataset from Sklearn. First, we will be creating pipeline that standardized the data. Then a Linear Discriminative analysis model will be created and at last the pipeline will be evaluated using 10-fold cross validation. First, import the required packages as follows − from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.discriminant_analysis import LinearDiscriminantAnalysis Now, we need to load the Pima diabetes dataset as did in previous examples − path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names=headernames) array = data.values Next, we will create a pipeline with the help of the following code − estimators = [] estimators.append(('standardize', StandardScaler())) estimators.append(('lda', LinearDiscriminantAnalysis())) model = Pipeline(estimators) At last, we are going to evaluate this pipeline and output its accuracy as follows − kfold = KFold(n_splits=20, random_state=7) results = cross_val_score(model, X, Y, cv=kfold) print(results.mean()) 0.7790148448043184 The above output is the summary of accuracy of the setup on the dataset. Data leakage can also happen at feature extraction step of ML model. That is why feature extraction procedures should also be restricted to stop data leakage in our training dataset. As in the case of data preparation, by using ML pipelines, we can prevent this data leakage also. FeatureUnion, a tool provided by ML pipelines can be used for this purpose. The following is an example in Python that demonstrates feature extraction and model evaluation workflow. For this purpose, we are using Pima Indian Diabetes dataset from Sklearn. First, 3 features will be extracted with PCA (Principal Component Analysis). Then, 6 features will be extracted with Statistical Analysis. After feature extraction, result of multiple feature selection and extraction procedures will be combined by using FeatureUnion tool. At last, a Logistic Regression model will be created, and the pipeline will be evaluated using 10-fold cross validation. First, import the required packages as follows − from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.pipeline import Pipeline from sklearn.pipeline import FeatureUnion from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest Now, we need to load the Pima diabetes dataset as did in previous examples − path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names=headernames) array = data.values Next, feature union will be created as follows − features = [] features.append(('pca', PCA(n_components=3))) features.append(('select_best', SelectKBest(k=6))) feature_union = FeatureUnion(features) Next, pipeline will be creating with the help of following script lines − estimators = [] estimators.append(('feature_union', feature_union)) estimators.append(('logistic', LogisticRegression())) model = Pipeline(estimators) At last, we are going to evaluate this pipeline and output its accuracy as follows − kfold = KFold(n_splits=20, random_state=7) results = cross_val_score(model, X, Y, cv=kfold) print(results.mean()) 0.7789811066126855 The above output is the summary of accuracy of the setup on the dataset. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2774, "s": 2304, "text": "In order to execute and produce results successfully, a machine learning model must automate some standard workflows. The process of automate these standard workflows can be done with the help of Scikit-learn Pipelines. From a data scientist’s perspective, pipeline is a generalized, but very important concept. It basically allows data flow from its raw format to some useful information. The working of pipelines can be understood with the help of following diagram −" }, { "code": null, "e": 2818, "s": 2774, "text": "The blocks of ML pipelines are as follows −" }, { "code": null, "e": 3102, "s": 2818, "text": "Data ingestion − As the name suggests, it is the process of importing the data for use in ML project. The data can be extracted in real time or batches from single or multiple systems. It is one of the most challenging steps because the quality of data can affect the whole ML model." }, { "code": null, "e": 3279, "s": 3102, "text": "Data Preparation − After importing the data, we need to prepare data to be used for our ML model. Data preprocessing is one of the most important technique of data preparation." }, { "code": null, "e": 3467, "s": 3279, "text": "ML Model Training − Next step is to train our ML model. We have various ML algorithms like supervised, unsupervised, reinforcement to extract the features from data, and make predictions." }, { "code": null, "e": 3645, "s": 3467, "text": "Model Evaluation − Next, we need to evaluate the ML model. In case of AutoML pipeline, ML model can be evaluated with the help of various statistical methods and business rules." }, { "code": null, "e": 3860, "s": 3645, "text": "ML Model retraining − In case of AutoML pipeline, it is not necessary that the first model is best one. The first model is considered as a baseline model and we can train it repeatably to increase model’s accuracy." }, { "code": null, "e": 4001, "s": 3860, "text": "Deployment − At last, we need to deploy the model. This step involves applying and migrating the model to business operations for their use." }, { "code": null, "e": 4132, "s": 4001, "text": "In order to create ML pipelines, data scientists face many challenges. These challenges fall into the following three categories −" }, { "code": null, "e": 4337, "s": 4132, "text": "The success of any ML model depends heavily on the quality of data. If the data we are providing to ML model is not accurate, reliable and robust, then we are going to end with wrong or misleading output." }, { "code": null, "e": 4625, "s": 4337, "text": "Another challenge associated with ML pipelines is the reliability of data we are providing to the ML model. As we know, there can be various sources from which data scientist can acquire data but to get the best results, it must be assured that the data sources are reliable and trusted." }, { "code": null, "e": 4851, "s": 4625, "text": "To get the best results out of ML pipelines, the data itself must be accessible which requires consolidation, cleansing and curation of data. As a result of data accessibility property, metadata will be updated with new tags." }, { "code": null, "e": 5320, "s": 4851, "text": "Data leakage, happening from training dataset to testing dataset, is an important issue for data scientist to deal with while preparing data for ML model. Generally, at the time of data preparation, data scientist uses techniques like standardization or normalization on entire dataset before learning. But these techniques cannot help us from the leakage of data because the training dataset would have been influenced by the scale of the data in the testing dataset." }, { "code": null, "e": 5507, "s": 5320, "text": "By using ML pipelines, we can prevent this data leakage because pipelines ensure that data preparation like standardization is constrained to each fold of our cross-validation procedure." }, { "code": null, "e": 5883, "s": 5507, "text": "The following is an example in Python that demonstrate data preparation and model evaluation workflow. For this purpose, we are using Pima Indian Diabetes dataset from Sklearn. First, we will be creating pipeline that standardized the data. Then a Linear Discriminative analysis model will be created and at last the pipeline will be evaluated using 10-fold cross validation." }, { "code": null, "e": 5932, "s": 5883, "text": "First, import the required packages as follows −" }, { "code": null, "e": 6210, "s": 5932, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis" }, { "code": null, "e": 6287, "s": 6210, "text": "Now, we need to load the Pima diabetes dataset as did in previous examples −" }, { "code": null, "e": 6475, "s": 6287, "text": "path = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names=headernames)\narray = data.values\n" }, { "code": null, "e": 6545, "s": 6475, "text": "Next, we will create a pipeline with the help of the following code −" }, { "code": null, "e": 6701, "s": 6545, "text": "estimators = []\nestimators.append(('standardize', StandardScaler()))\nestimators.append(('lda', LinearDiscriminantAnalysis()))\nmodel = Pipeline(estimators)\n" }, { "code": null, "e": 6786, "s": 6701, "text": "At last, we are going to evaluate this pipeline and output its accuracy as follows −" }, { "code": null, "e": 6901, "s": 6786, "text": "kfold = KFold(n_splits=20, random_state=7)\nresults = cross_val_score(model, X, Y, cv=kfold)\nprint(results.mean())\n" }, { "code": null, "e": 6921, "s": 6901, "text": "0.7790148448043184\n" }, { "code": null, "e": 6994, "s": 6921, "text": "The above output is the summary of accuracy of the setup on the dataset." }, { "code": null, "e": 7351, "s": 6994, "text": "Data leakage can also happen at feature extraction step of ML model. That is why feature extraction procedures should also be restricted to stop data leakage in our training dataset. As in the case of data preparation, by using ML pipelines, we can prevent this data leakage also. FeatureUnion, a tool provided by ML pipelines can be used for this purpose." }, { "code": null, "e": 7531, "s": 7351, "text": "The following is an example in Python that demonstrates feature extraction and model evaluation workflow. For this purpose, we are using Pima Indian Diabetes dataset from Sklearn." }, { "code": null, "e": 7785, "s": 7531, "text": "First, 3 features will be extracted with PCA (Principal Component Analysis). Then, 6 features will be extracted with Statistical Analysis. After feature extraction, result of multiple feature selection and extraction procedures will be combined by using" }, { "code": null, "e": 7925, "s": 7785, "text": "FeatureUnion tool. At last, a Logistic Regression model will be created, and the pipeline will be evaluated using 10-fold cross validation." }, { "code": null, "e": 7974, "s": 7925, "text": "First, import the required packages as follows −" }, { "code": null, "e": 8316, "s": 7974, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.decomposition import PCA\nfrom sklearn.feature_selection import SelectKBest" }, { "code": null, "e": 8393, "s": 8316, "text": "Now, we need to load the Pima diabetes dataset as did in previous examples −" }, { "code": null, "e": 8581, "s": 8393, "text": "path = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names=headernames)\narray = data.values\n" }, { "code": null, "e": 8630, "s": 8581, "text": "Next, feature union will be created as follows −" }, { "code": null, "e": 8781, "s": 8630, "text": "features = []\nfeatures.append(('pca', PCA(n_components=3)))\nfeatures.append(('select_best', SelectKBest(k=6)))\nfeature_union = FeatureUnion(features)\n" }, { "code": null, "e": 8855, "s": 8781, "text": "Next, pipeline will be creating with the help of following script lines −" }, { "code": null, "e": 9007, "s": 8855, "text": "estimators = []\nestimators.append(('feature_union', feature_union))\nestimators.append(('logistic', LogisticRegression()))\nmodel = Pipeline(estimators)\n" }, { "code": null, "e": 9092, "s": 9007, "text": "At last, we are going to evaluate this pipeline and output its accuracy as follows −" }, { "code": null, "e": 9207, "s": 9092, "text": "kfold = KFold(n_splits=20, random_state=7)\nresults = cross_val_score(model, X, Y, cv=kfold)\nprint(results.mean())\n" }, { "code": null, "e": 9227, "s": 9207, "text": "0.7789811066126855\n" }, { "code": null, "e": 9300, "s": 9227, "text": "The above output is the summary of accuracy of the setup on the dataset." }, { "code": null, "e": 9337, "s": 9300, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 9360, "s": 9337, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 9396, "s": 9360, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 9424, "s": 9396, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9458, "s": 9424, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 9475, "s": 9458, "text": " Abhilash Nelson" }, { "code": null, "e": 9508, "s": 9475, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9530, "s": 9508, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9563, "s": 9530, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 9585, "s": 9563, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9618, "s": 9585, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 9640, "s": 9618, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9647, "s": 9640, "text": " Print" }, { "code": null, "e": 9658, "s": 9647, "text": " Add Notes" } ]
Print all odd numbers and their sum from 1 to n in PL/SQL
In this problem, we are given a number n and we have to print all odd numbers from 1 to n and also print the sum of numbers from 1 to n in PL/SQL. PL/SQL is a procedural language extension to SQL. The code is a sequence of instructions that are ground in a block with all related declarations and instructions. Let’s see an example of our problem − Input: 7 Output: odd numbers are: 1, 3, 5, 7 Sum of odd numbers is 16 To solve this problem, we will take a number and initialize it to 1 and a sum variable with initial value 0. And we will increase the number by 2 and add into the sum variable until its value is less than or equal to n. DECLARE number NUMBER(3) := 1; sumvar NUMBER(4) := 0; BEGIN dbms_output.Put_line('The odd numbers are : '); WHILE num <= 7 LOOP dbms_output.Put_line(number); sumvar := sumvar+num; num := num + 2; END LOOP; dbms_output.Put_line('Sum of odd numbers is '|| sum1); END; The odd numbers are − 1 3 5 7 Sum of odd numbers is 16
[ { "code": null, "e": 1209, "s": 1062, "text": "In this problem, we are given a number n and we have to print all odd numbers from 1 to n and also print the sum of numbers from 1 to n in PL/SQL." }, { "code": null, "e": 1373, "s": 1209, "text": "PL/SQL is a procedural language extension to SQL. The code is a sequence of instructions that are ground in a block with all related declarations and instructions." }, { "code": null, "e": 1411, "s": 1373, "text": "Let’s see an example of our problem −" }, { "code": null, "e": 1481, "s": 1411, "text": "Input: 7\nOutput: odd numbers are: 1, 3, 5, 7\nSum of odd numbers is 16" }, { "code": null, "e": 1701, "s": 1481, "text": "To solve this problem, we will take a number and initialize it to 1 and a sum variable with initial value 0. And we will increase the number by 2 and add into the sum variable until its value is less than or equal to n." }, { "code": null, "e": 2016, "s": 1701, "text": "DECLARE\n number NUMBER(3) := 1;\n sumvar NUMBER(4) := 0;\n\nBEGIN\n dbms_output.Put_line('The odd numbers are : ');\n WHILE num <= 7 LOOP\n dbms_output.Put_line(number);\n sumvar := sumvar+num;\n num := num + 2;\n END LOOP;\ndbms_output.Put_line('Sum of odd numbers is '|| sum1);\nEND;" }, { "code": null, "e": 2038, "s": 2016, "text": "The odd numbers are −" }, { "code": null, "e": 2071, "s": 2038, "text": "1\n3\n5\n7\nSum of odd numbers is 16" } ]
Animate CSS flex-grow property
To implement animation on flex-grow property with CSS, you can try to run the following code Live Demo <!DOCTYPE html> <html> <head> <style> .mycontainer { display: flex; background-color: red; align-content: space-between; } .mycontainer > div { background-color: white; text-align: center; line-height: 40px; font-size: 25px; width: 100px; margin: 5px; } div { animation: myanim 4s infinite; } @-webkit-keyframes myanim { 30% { flex-grow: 3; } } </style> </head> <body> <h1>Quiz</h1> <div class = "mycontainer"> <div style = "flex-grow: 1">A1</div> <div style = "flex-grow: 1">A2</div> <div style = "flex-grow: 20">A3</div> <div style = "flex-grow: 1">A4</div> <div style = "flex-grow: 1">A5</div> </div> </body> </html>
[ { "code": null, "e": 1155, "s": 1062, "text": "To implement animation on flex-grow property with CSS, you can try to run the following code" }, { "code": null, "e": 1165, "s": 1155, "text": "Live Demo" }, { "code": null, "e": 2103, "s": 1165, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .mycontainer {\n display: flex;\n background-color: red;\n align-content: space-between;\n }\n .mycontainer > div {\n background-color: white;\n text-align: center;\n line-height: 40px;\n font-size: 25px;\n width: 100px;\n margin: 5px;\n }\n div {\n animation: myanim 4s infinite;\n }\n @-webkit-keyframes myanim {\n 30% {\n flex-grow: 3;\n }\n }\n </style>\n </head>\n <body>\n <h1>Quiz</h1>\n <div class = \"mycontainer\">\n <div style = \"flex-grow: 1\">A1</div>\n <div style = \"flex-grow: 1\">A2</div>\n <div style = \"flex-grow: 20\">A3</div>\n <div style = \"flex-grow: 1\">A4</div>\n <div style = \"flex-grow: 1\">A5</div>\n </div>\n </body>\n</html>" } ]
Game with String | Practice | GeeksforGeeks
Given a string s of lowercase alphabets and a number k, the task is to print the minimum value of the string after removal of ‘k’ characters. The value of a string is defined as the sum of squares of the count of each distinct character. Example 1: Input: s = abccc, k = 1 Output: 6 Explaination: We remove c to get the value as 12 + 12 + 22 Example 2: Input: s = aabcbcbcabcc, k = 3 Output: 27 Explaination: We remove two 'c' and one 'b'. Now we get the value as 32 + 32 + 32. Your Task: You do not need to read input or print anything. Your task is to complete the function minValue() which takes s and k as input parameters and returns the minimum possible required value. Expected Time Complexity: O(N*logN) where N is the length of string Expected Auxiliary Space: O(N) Constraints: 1 ≤ k ≤ |string length| ≤ 100 0 rawatchirag7123 weeks ago int minValue(string s, int k){ // code here map<int,int>mp; vector<int>v; //count the value for(int i=0;i<s.size();i++) { if(mp.find(s[i])==mp.end()) { mp[s[i]]=1; } else mp[s[i]]++; } //push frequence in vector for (auto& it : mp) { v.push_back(it.second); } int n=v.size()-1; //minus the highest value by one //so sort the vector in descending order //then minus the first index of vector by one while(k--) { sort(v.begin(),v.end(),greater<>()); v[0]=v[0]-1; } int sum=0; //finally calculate squares of the count for(int i=0;i<=n;i++) { sum+=v[i]*v[i]; } return sum; } 0 kartikeykabdwal863 weeks ago :) C++ || EASY TO UNDERSTAND class Solution{ public: int minValue(string s, int k){ vector<int>v(26,0); priority_queue<int>pq; for(int i=0;i<s.size();i++) { v[s[i]-97]++; } for(int i=0;i<26;i++) { pq.push(v[i]); } while(k--) { int x=pq.top(); x-=1; pq.pop(); pq.push(x); } int ans=0; while(!pq.empty()) { ans+=pq.top()*pq.top(); pq.pop(); } return ans; } }; 0 akbhobhiya4 weeks ago class Solution{ public: int minValue(string s, int k){ // code here vector<int>alfa(26,0); for(int i=0;i<s.length();i++)alfa[s[i]-'a']++; sort(alfa.begin(),alfa.end(),greater<int>()); priority_queue<int>pq; for(int i=0;i<26;i++){ if(alfa[i]>0)pq.push(alfa[i]); else break; } for(int i=0;i<k;i++){ int top = pq.top();pq.pop(); top--; pq.push(top); } int sum = 0; while(!pq.empty()){ sum += pq.top()*pq.top(); pq.pop(); } return sum; } }; 0 harrypotter04 weeks ago from collections import Counterimport heapqclass Solution: def minValue(self, s, k): d = Counter(s) c = list(d.values()) # c.sort(reverse=True) c = [i*-1 for i in c] heapq.heapify(c) while k>0: temp = heapq.heappop(c) temp +=1 heapq.heappush(c, temp) k-=1 summ = 0 for i in c: summ+=i**2 return summ 0 jyoti2804mishra1 month ago #JAVA SOLUTION class Solution{ static int minValue(String s, int k){ // code here Map<Character, Integer> map = new HashMap<>(); for(char c: s.toCharArray()) { if (map.containsKey(c)) { map.put(c, map.get(c)+1); }else { map.put(c, 1); } } Queue<CharCount> queue = new PriorityQueue<>((a, b) -> b.count-a.count); for (Map.Entry<Character, Integer> es:map.entrySet()) { queue.offer(new CharCount(es.getKey(), es.getValue())); } while (!queue.isEmpty() && k-- > 0) { CharCount c = queue.poll(); c.count--; queue.offer(c); } int res = 0; while (!queue.isEmpty()) { int count = queue.poll().count; res += count*count; } return res; }} class CharCount { char c; int count; CharCount(char c, int count) { this.c = c; this.count = count; } public String toString() { return "char: "+c+" count: "+count; }} +1 shirurrohit1 month ago PYTHON - O(26) Space class Solution: def minValue(self, s, k): char_set = [0] * 26 smallest_freq = float("inf") for i in s: char_set[ord(i)-97] += 1 char_set.sort(reverse = True) i = 0 while k: char_set[i] -= 1 k -= 1 bound = char_set[i] for j in range(26): if char_set[j] >= bound: bound = char_set[j] i = j ans = 0 for i in char_set: if i > 0: ans += i*i return ans 0 kiransaisk4481 month ago Python Solution: from collections import Counter class Solution: def minValue(self, s, k): # code here d = Counter(s) c = list(d.values()) c.sort(reverse=True) tot = 0 max_ = c[0] i = 0 while k > 0: c[i] -= 1 k -= 1 max_ = max(c) i = c.index(max_) for i in range(len(c)): tot = tot + c[i] ** 2 +2 rohanyt741 month ago int minValue(string s, int k){ // code here int sum=0; priority_queue<int>pq; unordered_map<char,int>um; for(int i=0;i<s.length();i++){ um[s[i]]++; } for(auto x:um){ pq.push(x.second); } while(k){ int x=pq.top(); pq.pop(); x--; pq.push(x); k--; } while(!pq.empty()){ int d=pq.top(); sum=sum+(d*d); pq.pop(); } return sum; } 0 himanshu201912 months ago int minValue(string s, int k){ // code here long long res=0; int arr[26]={0}; int min=INT_MAX; for(auto a:s){ arr[a-97]++; } priority_queue<int> p; for(auto a:arr){ if(a!=0 && a<min) min=a; if(a!=0) p.push(a); } while(k--){ int a=p.top(); a--; p.pop(); if(a==0){ continue; } p.push(a); } while(p.empty()==false){ int val=p.top(); p.pop(); res+=val*val; } return res; } +1 aloksinghbais022 months ago C++ solution having time complexity as O(N+26*log(26)+k*log(26)+26) and space complexity as O(26) is as follows :- Execution Time :- 0.0 / 1.1 sec int minValue(string s, int k){ int freq[26] = {0}; for(int i = 0; i < s.length(); i++){ freq[s[i]-'a']++; } priority_queue<pair<int,int>> pq; for(int i = 0; i < 26; i++){ if(freq[i]){ pq.push({freq[i],i}); } } while(!pq.empty() && k){ auto p = pq.top(); pq.pop(); int f = p.first; int i = p.second; freq[i]--; f--; k--; if(f){ pq.push({f,i}); } } int ans = 0; for(int i = 0; i < 26; i++){ if(freq[i]){ ans += freq[i] * freq[i]; } } return (ans); } 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": 478, "s": 238, "text": "Given a string s of lowercase alphabets and a number k, the task is to print the minimum value of the string after removal of ‘k’ characters. The value of a string is defined as the sum of squares of the count of each distinct character.\n " }, { "code": null, "e": 489, "s": 478, "text": "Example 1:" }, { "code": null, "e": 583, "s": 489, "text": "Input: s = abccc, k = 1\nOutput: 6\nExplaination:\nWe remove c to get the value as 12 + 12 + 22\n" }, { "code": null, "e": 596, "s": 585, "text": "Example 2:" }, { "code": null, "e": 722, "s": 596, "text": "Input: s = aabcbcbcabcc, k = 3\nOutput: 27\nExplaination: We remove two 'c' and one 'b'. \nNow we get the value as 32 + 32 + 32." }, { "code": null, "e": 921, "s": 722, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minValue() which takes s and k as input parameters and returns the minimum possible required value." }, { "code": null, "e": 1023, "s": 923, "text": "Expected Time Complexity: O(N*logN) where N is the length of string\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1068, "s": 1025, "text": "Constraints:\n1 ≤ k ≤ |string length| ≤ 100" }, { "code": null, "e": 1070, "s": 1068, "text": "0" }, { "code": null, "e": 1096, "s": 1070, "text": "rawatchirag7123 weeks ago" }, { "code": null, "e": 1857, "s": 1096, "text": "int minValue(string s, int k){ // code here map<int,int>mp; vector<int>v; //count the value for(int i=0;i<s.size();i++) { if(mp.find(s[i])==mp.end()) { mp[s[i]]=1; } else mp[s[i]]++; } //push frequence in vector for (auto& it : mp) { v.push_back(it.second); } int n=v.size()-1; //minus the highest value by one //so sort the vector in descending order //then minus the first index of vector by one while(k--) { sort(v.begin(),v.end(),greater<>()); v[0]=v[0]-1; } int sum=0; //finally calculate squares of the count for(int i=0;i<=n;i++) { sum+=v[i]*v[i]; } return sum; }" }, { "code": null, "e": 1859, "s": 1857, "text": "0" }, { "code": null, "e": 1888, "s": 1859, "text": "kartikeykabdwal863 weeks ago" }, { "code": null, "e": 1943, "s": 1888, "text": " :) C++ || EASY TO UNDERSTAND " }, { "code": null, "e": 2481, "s": 1945, "text": "class Solution{\npublic:\n int minValue(string s, int k){\n vector<int>v(26,0);\n priority_queue<int>pq;\n for(int i=0;i<s.size();i++)\n {\n v[s[i]-97]++;\n \n }\n for(int i=0;i<26;i++)\n {\n pq.push(v[i]);\n }\n while(k--)\n {\n int x=pq.top();\n x-=1;\n pq.pop();\n pq.push(x);\n }\n int ans=0;\n \n while(!pq.empty())\n {\n ans+=pq.top()*pq.top();\n pq.pop();\n }\n \n return ans;\n }\n};" }, { "code": null, "e": 2483, "s": 2481, "text": "0" }, { "code": null, "e": 2505, "s": 2483, "text": "akbhobhiya4 weeks ago" }, { "code": null, "e": 3138, "s": 2505, "text": "class Solution{\npublic:\n int minValue(string s, int k){\n // code here\n vector<int>alfa(26,0);\n for(int i=0;i<s.length();i++)alfa[s[i]-'a']++;\n sort(alfa.begin(),alfa.end(),greater<int>());\n priority_queue<int>pq;\n for(int i=0;i<26;i++){\n if(alfa[i]>0)pq.push(alfa[i]);\n else break;\n }\n for(int i=0;i<k;i++){\n int top = pq.top();pq.pop();\n top--;\n pq.push(top);\n }\n int sum = 0;\n while(!pq.empty()){\n sum += pq.top()*pq.top();\n pq.pop();\n }\n return sum;\n }\n};" }, { "code": null, "e": 3140, "s": 3138, "text": "0" }, { "code": null, "e": 3164, "s": 3140, "text": "harrypotter04 weeks ago" }, { "code": null, "e": 3571, "s": 3164, "text": "from collections import Counterimport heapqclass Solution: def minValue(self, s, k): d = Counter(s) c = list(d.values()) # c.sort(reverse=True) c = [i*-1 for i in c] heapq.heapify(c) while k>0: temp = heapq.heappop(c) temp +=1 heapq.heappush(c, temp) k-=1 summ = 0 for i in c: summ+=i**2 return summ " }, { "code": null, "e": 3573, "s": 3571, "text": "0" }, { "code": null, "e": 3600, "s": 3573, "text": "jyoti2804mishra1 month ago" }, { "code": null, "e": 3615, "s": 3600, "text": "#JAVA SOLUTION" }, { "code": null, "e": 3937, "s": 3615, "text": "class Solution{ static int minValue(String s, int k){ // code here Map<Character, Integer> map = new HashMap<>(); for(char c: s.toCharArray()) { if (map.containsKey(c)) { map.put(c, map.get(c)+1); }else { map.put(c, 1); } } " }, { "code": null, "e": 4304, "s": 3937, "text": " Queue<CharCount> queue = new PriorityQueue<>((a, b) -> b.count-a.count); for (Map.Entry<Character, Integer> es:map.entrySet()) { queue.offer(new CharCount(es.getKey(), es.getValue())); } while (!queue.isEmpty() && k-- > 0) { CharCount c = queue.poll(); c.count--; queue.offer(c); } " }, { "code": null, "e": 4488, "s": 4304, "text": " int res = 0; while (!queue.isEmpty()) { int count = queue.poll().count; res += count*count; } return res; }}" }, { "code": null, "e": 4692, "s": 4488, "text": "class CharCount { char c; int count; CharCount(char c, int count) { this.c = c; this.count = count; } public String toString() { return \"char: \"+c+\" count: \"+count; }}" }, { "code": null, "e": 4695, "s": 4692, "text": "+1" }, { "code": null, "e": 4718, "s": 4695, "text": "shirurrohit1 month ago" }, { "code": null, "e": 4739, "s": 4718, "text": "PYTHON - O(26) Space" }, { "code": null, "e": 5356, "s": 4741, "text": "class Solution:\n def minValue(self, s, k):\n char_set = [0] * 26\n smallest_freq = float(\"inf\")\n \n for i in s:\n char_set[ord(i)-97] += 1\n char_set.sort(reverse = True)\n \n i = 0\n while k:\n char_set[i] -= 1\n k -= 1\n bound = char_set[i]\n for j in range(26):\n if char_set[j] >= bound:\n bound = char_set[j]\n i = j\n \n ans = 0 \n for i in char_set:\n if i > 0:\n ans += i*i\n return ans" }, { "code": null, "e": 5358, "s": 5356, "text": "0" }, { "code": null, "e": 5383, "s": 5358, "text": "kiransaisk4481 month ago" }, { "code": null, "e": 5400, "s": 5383, "text": "Python Solution:" }, { "code": null, "e": 5813, "s": 5400, "text": "from collections import Counter\nclass Solution:\n def minValue(self, s, k):\n # code here\n d = Counter(s)\n c = list(d.values())\n c.sort(reverse=True)\n tot = 0\n max_ = c[0]\n i = 0\n while k > 0:\n c[i] -= 1\n k -= 1\n max_ = max(c)\n i = c.index(max_)\n for i in range(len(c)):\n tot = tot + c[i] ** 2" }, { "code": null, "e": 5816, "s": 5813, "text": "+2" }, { "code": null, "e": 5837, "s": 5816, "text": "rohanyt741 month ago" }, { "code": null, "e": 6335, "s": 5837, "text": "int minValue(string s, int k){ // code here int sum=0; priority_queue<int>pq; unordered_map<char,int>um; for(int i=0;i<s.length();i++){ um[s[i]]++; } for(auto x:um){ pq.push(x.second); } while(k){ int x=pq.top(); pq.pop(); x--; pq.push(x); k--; } while(!pq.empty()){ int d=pq.top(); sum=sum+(d*d); pq.pop(); } return sum; }" }, { "code": null, "e": 6337, "s": 6335, "text": "0" }, { "code": null, "e": 6363, "s": 6337, "text": "himanshu201912 months ago" }, { "code": null, "e": 6952, "s": 6363, "text": "int minValue(string s, int k){ // code here long long res=0; int arr[26]={0}; int min=INT_MAX; for(auto a:s){ arr[a-97]++; } priority_queue<int> p; for(auto a:arr){ if(a!=0 && a<min) min=a; if(a!=0) p.push(a); } while(k--){ int a=p.top(); a--; p.pop(); if(a==0){ continue; } p.push(a); } while(p.empty()==false){ int val=p.top(); p.pop(); res+=val*val; } return res; }" }, { "code": null, "e": 6955, "s": 6952, "text": "+1" }, { "code": null, "e": 6983, "s": 6955, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 7099, "s": 6983, "text": "C++ solution having time complexity as O(N+26*log(26)+k*log(26)+26) and space complexity as O(26) is as follows :- " }, { "code": null, "e": 7133, "s": 7101, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 7900, "s": 7135, "text": "int minValue(string s, int k){ int freq[26] = {0}; for(int i = 0; i < s.length(); i++){ freq[s[i]-'a']++; } priority_queue<pair<int,int>> pq; for(int i = 0; i < 26; i++){ if(freq[i]){ pq.push({freq[i],i}); } } while(!pq.empty() && k){ auto p = pq.top(); pq.pop(); int f = p.first; int i = p.second; freq[i]--; f--; k--; if(f){ pq.push({f,i}); } } int ans = 0; for(int i = 0; i < 26; i++){ if(freq[i]){ ans += freq[i] * freq[i]; } } return (ans); }" }, { "code": null, "e": 8046, "s": 7900, "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": 8082, "s": 8046, "text": " Login to access your submissions. " }, { "code": null, "e": 8092, "s": 8082, "text": "\nProblem\n" }, { "code": null, "e": 8102, "s": 8092, "text": "\nContest\n" }, { "code": null, "e": 8165, "s": 8102, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8313, "s": 8165, "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": 8521, "s": 8313, "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": 8627, "s": 8521, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to convert a string to a list of words in python?
To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters. >>> "Please split this string".split() ['Please', 'split', 'this', 'string'] Regex can also be used to solve this problem. You can call the re.split() method using the regex '\s+' as delimiter. Note that this method is slower than the above method. >>> import re >>> re.split('\s+', 'Please split this string') ['Please', 'split', 'this', 'string']
[ { "code": null, "e": 1320, "s": 1062, "text": "To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters." }, { "code": null, "e": 1397, "s": 1320, "text": ">>> \"Please split this string\".split()\n['Please', 'split', 'this', 'string']" }, { "code": null, "e": 1569, "s": 1397, "text": "Regex can also be used to solve this problem. You can call the re.split() method using the regex '\\s+' as delimiter. Note that this method is slower than the above method." }, { "code": null, "e": 1669, "s": 1569, "text": ">>> import re\n>>> re.split('\\s+', 'Please split this string')\n['Please', 'split', 'this', 'string']" } ]
VBScript Number Formatting Functions
variablename = Format_function_Name(Expression[,NumberDigAfterDec[,LeadingDig[,UseParForNegNum[,GroupDigits]]]]) The Required parameter Format_function_Name corresponds to any of the below listed number formatting functions. The Required parameter Format_function_Name corresponds to any of the below listed number formatting functions. The Optional parameter Expression corresponds to any numerical expression, which would result in a number. The Optional parameter Expression corresponds to any numerical expression, which would result in a number. The Optional parameter NumberDigAfterDec corresponds to the number of digits after the decimal place. The Optional parameter NumberDigAfterDec corresponds to the number of digits after the decimal place. The Optional parameter LeadingDig corresponds to whether or not a leading zero is displayed for fractional values. It takes one of the three values based on the below settings parameter. The Optional parameter LeadingDig corresponds to whether or not a leading zero is displayed for fractional values. It takes one of the three values based on the below settings parameter. The Optional parameter UseParForNegNum corresponds to whether or not to place negative values within parentheses. It takes one of the three values based on the below settings parameter. The Optional parameter UseParForNegNum corresponds to whether or not to place negative values within parentheses. It takes one of the three values based on the below settings parameter. The Optional parameter GroupDigits corresponds to whether or not numbers are grouped using the group delimiter. It takes one of the three values based on the below settings parameter. The Optional parameter GroupDigits corresponds to whether or not numbers are grouped using the group delimiter. It takes one of the three values based on the below settings parameter. The above parameters LeadingDig, UseParForNegNum and GroupDigits arguments can have any of the following settings − -2 = vbUseDefault − Use the computer's regional settings -1 = vbTrue − True 0 = vbFalse − False Try the following example to understand all the Number Formatting Functions available in VBScript. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim num : num = -645.998651 document.write("Line 1 : " & FormatNumber(num, 3))& "<br/>" ' The UseParensForNegativeNumbers parameter is set to true. document.write("Line 2 : " & FormatNumber (num, 3, , vbTrue))&" <br/> " ' The GroupDigits parameter is set to false. document.write("Line 3 : " & FormatNumber (num, 3, , , vbFalse)) & "<br/>" document.write("Line 4 : " & FormatPercent(num, 3))& "<br/>" ' The UseParensForNegativeNumbers parameter is set to true. document.write("Line 5 : " & FormatPercent (num, 3, , vbTrue))&" <br/> " ' The GroupDigits parameter is set to false. document.write("Line 6 : " & FormatPercent (num, 3, , , vbFalse)) & "<br/>" </script> </body> </html> When executed the above script, following is the output − Line 1 : -645.999 Line 2 : (645.999) Line 3 : -645.999 Line 4 : -64,599.865% Line 5 : (64,599.865%) Line 6 : -64599.865% 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2195, "s": 2080, "text": "variablename = Format_function_Name(Expression[,NumberDigAfterDec[,LeadingDig[,UseParForNegNum[,GroupDigits]]]]) \n" }, { "code": null, "e": 2307, "s": 2195, "text": "The Required parameter Format_function_Name corresponds to any of the below listed number formatting functions." }, { "code": null, "e": 2419, "s": 2307, "text": "The Required parameter Format_function_Name corresponds to any of the below listed number formatting functions." }, { "code": null, "e": 2526, "s": 2419, "text": "The Optional parameter Expression corresponds to any numerical expression, which would result in a number." }, { "code": null, "e": 2633, "s": 2526, "text": "The Optional parameter Expression corresponds to any numerical expression, which would result in a number." }, { "code": null, "e": 2735, "s": 2633, "text": "The Optional parameter NumberDigAfterDec corresponds to the number of digits after the decimal place." }, { "code": null, "e": 2837, "s": 2735, "text": "The Optional parameter NumberDigAfterDec corresponds to the number of digits after the decimal place." }, { "code": null, "e": 3024, "s": 2837, "text": "The Optional parameter LeadingDig corresponds to whether or not a leading zero is displayed for fractional values. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 3211, "s": 3024, "text": "The Optional parameter LeadingDig corresponds to whether or not a leading zero is displayed for fractional values. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 3397, "s": 3211, "text": "The Optional parameter UseParForNegNum corresponds to whether or not to place negative values within parentheses. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 3583, "s": 3397, "text": "The Optional parameter UseParForNegNum corresponds to whether or not to place negative values within parentheses. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 3767, "s": 3583, "text": "The Optional parameter GroupDigits corresponds to whether or not numbers are grouped using the group delimiter. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 3951, "s": 3767, "text": "The Optional parameter GroupDigits corresponds to whether or not numbers are grouped using the group delimiter. It takes one of the three values based on the below settings parameter." }, { "code": null, "e": 4067, "s": 3951, "text": "The above parameters LeadingDig, UseParForNegNum and GroupDigits arguments can have any of the following settings −" }, { "code": null, "e": 4124, "s": 4067, "text": "-2 = vbUseDefault − Use the computer's regional settings" }, { "code": null, "e": 4143, "s": 4124, "text": "-1 = vbTrue − True" }, { "code": null, "e": 4163, "s": 4143, "text": "0 = vbFalse − False" }, { "code": null, "e": 4262, "s": 4163, "text": "Try the following example to understand all the Number Formatting Functions available in VBScript." }, { "code": null, "e": 5152, "s": 4262, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n\n Dim num : num = -645.998651\n\n document.write(\"Line 1 : \" & FormatNumber(num, 3))& \"<br/>\"\n\n ' The UseParensForNegativeNumbers parameter is set to true.\n document.write(\"Line 2 : \" & FormatNumber (num, 3, , vbTrue))&\" <br/> \"\n\n ' The GroupDigits parameter is set to false.\n document.write(\"Line 3 : \" & FormatNumber (num, 3, , , vbFalse)) & \"<br/>\"\n\n document.write(\"Line 4 : \" & FormatPercent(num, 3))& \"<br/>\"\n\n ' The UseParensForNegativeNumbers parameter is set to true.\n document.write(\"Line 5 : \" & FormatPercent (num, 3, , vbTrue))&\" <br/> \"\n\n ' The GroupDigits parameter is set to false.\n document.write(\"Line 6 : \" & FormatPercent (num, 3, , , vbFalse)) & \"<br/>\"\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 5210, "s": 5152, "text": "When executed the above script, following is the output −" }, { "code": null, "e": 5334, "s": 5210, "text": "Line 1 : -645.999\nLine 2 : (645.999) \nLine 3 : -645.999\nLine 4 : -64,599.865%\nLine 5 : (64,599.865%) \nLine 6 : -64599.865%\n" }, { "code": null, "e": 5367, "s": 5334, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 5384, "s": 5367, "text": " Frahaan Hussain" }, { "code": null, "e": 5391, "s": 5384, "text": " Print" }, { "code": null, "e": 5402, "s": 5391, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML input elements
[]
How to Create an Interactive Dropdown in Jupyter | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. Libraries2. Data Setup for the Dropdown3. Multiple Plot Function4. Interactive Dropdown Menu5. All the Code6. Using for Other DatasetsConclusion In the last article, I wrote about how to create a bubble map using Plotly.express and Mapbox. The bubble map can show all the data with different sizes on a map. In this article, I am going to write about an interactive graph using a dropdown menu. When you have a series of datasets and want to separate one dataset from others, this method is useful. I am using CSSEGISandData’s COVID-19 Github repo for this article. import pandas as pdimport numpy as npimport plotly.graph_objects as go pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool. Numpy is the fundamental package for scientific computing with Python. Plotly is an interactive, open-source Python graphing library. Let’s start preparing our dataset. We are going to use the time-series data and you can find the raw data here. Create a variable confirmed_global , and store the data into covid19_confirmed using Panda’s read_csv. We set the index column to Country/Region and display the dataframe. # confirmed_globalconfirmed_global='https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'covid19_confirmed=pd.read_csv(confirmed_global,index_col='Country/Region')display(covid19_confirmed) There are 266 rows. This has Country/Region in index and Lat , Long, and dates on the label. We are going to extract the latest date from the dataframe. We transpose the dataset, covid19_confirmed (Fig 1), using T and display the last 5 rows. Pandas’ transpose reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa. display(covid19_confirmed.T.tail()) The transposed dataframe has dates in the index and country names in the label. We find the latest date at the end of the index column. We can use index.values[-1] to extract the latest date. confirmed_latest = covid19_confirmed.T.index.values[-1]display(confirmed_latest) Output: ‘6/9/20’ There are multiple rows that have the same Country/Region. We can find 8 rows with Australia in fig 3, above. We group them together by Country/Region and calculate the sum. df_grouped_conf=covid19_confirmed.groupby('Country/Region').sum()display(df_grouped_conf.head(10)) Here are the first 10 rows. Before we had 266 rows and now we have 142 rows. Australia has one row. The df_grouped_conf (Fig 4) has the latest date (6/9/20 for this case) at the end. We are going to sort the dataframe by this value, confirmed_latest with using ascending=False. We select the top 10 countries using head(10) and drop Lat and Long columns. We transpose the dataframe using T at the end. df_confirmed=df_grouped_conf.sort_values(confirmed_latest,ascending=False).head(10).drop(['Lat', 'Long'],axis=1).T towardsdatascience.com towardsdatascience.com We can find out other Plotly dropdown examples here. We create a function called multi_plot. This requires two variables: df: dataframe with countries as columns and rows as date addAll: boolean. True display ALL in the dropdown button. ALL displays all countries at once. We set the default True. We create a plotly.graph_objects’s Figure instance. We use a for loop to iterate county names obtained by df.columns.to_list(). df.columns.to_list() returns a list, [‘US’, ‘Brazil’, ‘Russia’, ...]. In the iteration, we add a trace to the figure. You can use plotly.graph_objects.Scatter or plotly.graph_objects.Bar for the trace, and we are going to use Scatter. We define the x, y, and name. The name parameter sets a trace name. The trace name appears as the legend item and on hover. def multi_plot(df, title, addAll = True): fig = go.Figure() for column in df.columns.to_list(): fig.add_trace( go.Scatter( x = df.index, y = df[column], name = column ) ) // continue We define a dictionary button_all and function create_layout_button, which are used in update_layout. update_layout updates the properties of the figure’s layout and returns the Figure object. In fig.update_layout() method, we use updatemenus, which is a tuple of plotly.graph_objects.layout.Updatemenu instance. We also set yaxis_type="log" to show the logarithmic scale on the y-axis and height to 400px. // continue button_all = dict(label = 'All', method = 'update', args = [{'visible': df.columns.isin(df.columns), 'title': 'All', 'showlegend':True}]) def create_layout_button(column): return dict(label = column, method = 'update', args = [{'visible': df.columns.isin([column]), 'title': column, 'showlegend': True}]) fig.update_layout( updatemenus=[go.layout.Updatemenu( active = 0, buttons = ([button_all] * addAll) + list(df.columns.map(lambda column: create_layout_button(column))) ) ], yaxis_type="log" ) # Update remaining layout properties fig.update_layout( title_text=title, height=800 ) fig.show() The final part is using this multi_plot function. multi_plot(df_confirmed, title="Logarithmic COVID-19 time series total confirmed by country") The CSSEGISandData’s COVID-19 Github repo has two more datasets. You can use the same code to create other graphs. You can see it live here. https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv You may find Plotly has too many parameters and sometimes confusing. But sample codes provide various examples, which you can use for your data science project. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 349, "s": 172, "text": "Table of ContentsIntroduction1. Libraries2. Data Setup for the Dropdown3. Multiple Plot Function4. Interactive Dropdown Menu5. All the Code6. Using for Other DatasetsConclusion" }, { "code": null, "e": 512, "s": 349, "text": "In the last article, I wrote about how to create a bubble map using Plotly.express and Mapbox. The bubble map can show all the data with different sizes on a map." }, { "code": null, "e": 599, "s": 512, "text": "In this article, I am going to write about an interactive graph using a dropdown menu." }, { "code": null, "e": 703, "s": 599, "text": "When you have a series of datasets and want to separate one dataset from others, this method is useful." }, { "code": null, "e": 770, "s": 703, "text": "I am using CSSEGISandData’s COVID-19 Github repo for this article." }, { "code": null, "e": 841, "s": 770, "text": "import pandas as pdimport numpy as npimport plotly.graph_objects as go" }, { "code": null, "e": 1078, "s": 841, "text": "pandas is a fast, powerful, flexible, and easy to use open-source data analysis and manipulation tool. Numpy is the fundamental package for scientific computing with Python. Plotly is an interactive, open-source Python graphing library." }, { "code": null, "e": 1190, "s": 1078, "text": "Let’s start preparing our dataset. We are going to use the time-series data and you can find the raw data here." }, { "code": null, "e": 1362, "s": 1190, "text": "Create a variable confirmed_global , and store the data into covid19_confirmed using Panda’s read_csv. We set the index column to Country/Region and display the dataframe." }, { "code": null, "e": 1650, "s": 1362, "text": "# confirmed_globalconfirmed_global='https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'covid19_confirmed=pd.read_csv(confirmed_global,index_col='Country/Region')display(covid19_confirmed)" }, { "code": null, "e": 1743, "s": 1650, "text": "There are 266 rows. This has Country/Region in index and Lat , Long, and dates on the label." }, { "code": null, "e": 2000, "s": 1743, "text": "We are going to extract the latest date from the dataframe. We transpose the dataset, covid19_confirmed (Fig 1), using T and display the last 5 rows. Pandas’ transpose reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa." }, { "code": null, "e": 2036, "s": 2000, "text": "display(covid19_confirmed.T.tail())" }, { "code": null, "e": 2116, "s": 2036, "text": "The transposed dataframe has dates in the index and country names in the label." }, { "code": null, "e": 2228, "s": 2116, "text": "We find the latest date at the end of the index column. We can use index.values[-1] to extract the latest date." }, { "code": null, "e": 2309, "s": 2228, "text": "confirmed_latest = covid19_confirmed.T.index.values[-1]display(confirmed_latest)" }, { "code": null, "e": 2326, "s": 2309, "text": "Output: ‘6/9/20’" }, { "code": null, "e": 2385, "s": 2326, "text": "There are multiple rows that have the same Country/Region." }, { "code": null, "e": 2436, "s": 2385, "text": "We can find 8 rows with Australia in fig 3, above." }, { "code": null, "e": 2500, "s": 2436, "text": "We group them together by Country/Region and calculate the sum." }, { "code": null, "e": 2599, "s": 2500, "text": "df_grouped_conf=covid19_confirmed.groupby('Country/Region').sum()display(df_grouped_conf.head(10))" }, { "code": null, "e": 2627, "s": 2599, "text": "Here are the first 10 rows." }, { "code": null, "e": 2699, "s": 2627, "text": "Before we had 266 rows and now we have 142 rows. Australia has one row." }, { "code": null, "e": 2782, "s": 2699, "text": "The df_grouped_conf (Fig 4) has the latest date (6/9/20 for this case) at the end." }, { "code": null, "e": 3001, "s": 2782, "text": "We are going to sort the dataframe by this value, confirmed_latest with using ascending=False. We select the top 10 countries using head(10) and drop Lat and Long columns. We transpose the dataframe using T at the end." }, { "code": null, "e": 3116, "s": 3001, "text": "df_confirmed=df_grouped_conf.sort_values(confirmed_latest,ascending=False).head(10).drop(['Lat', 'Long'],axis=1).T" }, { "code": null, "e": 3139, "s": 3116, "text": "towardsdatascience.com" }, { "code": null, "e": 3162, "s": 3139, "text": "towardsdatascience.com" }, { "code": null, "e": 3215, "s": 3162, "text": "We can find out other Plotly dropdown examples here." }, { "code": null, "e": 3284, "s": 3215, "text": "We create a function called multi_plot. This requires two variables:" }, { "code": null, "e": 3341, "s": 3284, "text": "df: dataframe with countries as columns and rows as date" }, { "code": null, "e": 3460, "s": 3341, "text": "addAll: boolean. True display ALL in the dropdown button. ALL displays all countries at once. We set the default True." }, { "code": null, "e": 3512, "s": 3460, "text": "We create a plotly.graph_objects’s Figure instance." }, { "code": null, "e": 3588, "s": 3512, "text": "We use a for loop to iterate county names obtained by df.columns.to_list()." }, { "code": null, "e": 3658, "s": 3588, "text": "df.columns.to_list() returns a list, [‘US’, ‘Brazil’, ‘Russia’, ...]." }, { "code": null, "e": 3823, "s": 3658, "text": "In the iteration, we add a trace to the figure. You can use plotly.graph_objects.Scatter or plotly.graph_objects.Bar for the trace, and we are going to use Scatter." }, { "code": null, "e": 3947, "s": 3823, "text": "We define the x, y, and name. The name parameter sets a trace name. The trace name appears as the legend item and on hover." }, { "code": null, "e": 4220, "s": 3947, "text": "def multi_plot(df, title, addAll = True): fig = go.Figure() for column in df.columns.to_list(): fig.add_trace( go.Scatter( x = df.index, y = df[column], name = column ) ) // continue" }, { "code": null, "e": 4413, "s": 4220, "text": "We define a dictionary button_all and function create_layout_button, which are used in update_layout. update_layout updates the properties of the figure’s layout and returns the Figure object." }, { "code": null, "e": 4533, "s": 4413, "text": "In fig.update_layout() method, we use updatemenus, which is a tuple of plotly.graph_objects.layout.Updatemenu instance." }, { "code": null, "e": 4627, "s": 4533, "text": "We also set yaxis_type=\"log\" to show the logarithmic scale on the y-axis and height to 400px." }, { "code": null, "e": 5570, "s": 4627, "text": " // continue button_all = dict(label = 'All', method = 'update', args = [{'visible': df.columns.isin(df.columns), 'title': 'All', 'showlegend':True}]) def create_layout_button(column): return dict(label = column, method = 'update', args = [{'visible': df.columns.isin([column]), 'title': column, 'showlegend': True}]) fig.update_layout( updatemenus=[go.layout.Updatemenu( active = 0, buttons = ([button_all] * addAll) + list(df.columns.map(lambda column: create_layout_button(column))) ) ], yaxis_type=\"log\" ) # Update remaining layout properties fig.update_layout( title_text=title, height=800 ) fig.show()" }, { "code": null, "e": 5620, "s": 5570, "text": "The final part is using this multi_plot function." }, { "code": null, "e": 5714, "s": 5620, "text": "multi_plot(df_confirmed, title=\"Logarithmic COVID-19 time series total confirmed by country\")" }, { "code": null, "e": 5829, "s": 5714, "text": "The CSSEGISandData’s COVID-19 Github repo has two more datasets. You can use the same code to create other graphs." }, { "code": null, "e": 5855, "s": 5829, "text": "You can see it live here." }, { "code": null, "e": 6003, "s": 5855, "text": "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv" }, { "code": null, "e": 6154, "s": 6003, "text": "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv" }, { "code": null, "e": 6315, "s": 6154, "text": "You may find Plotly has too many parameters and sometimes confusing. But sample codes provide various examples, which you can use for your data science project." } ]
Design a Student Grade Calculator using JavaScript - GeeksforGeeks
26 Aug, 2021 Student Grade Calculator (SGC) can be used to calculate a percentage based on the marks of students. (SGC) is a fairly reliable indicator of student results. Formula: percentage = ( totalgrades / 400 ) * 100 ; Approach: SGC is a percentage calculator from a student’s marks. To find out SGC we will take input from the user (for the four subjects) stored in Chemistry, Hindi, and Math variables for further calculation. The calculation process is simple, we will simply First we will add all the input marks and store them in the total grades variable after that we will divide it by the sum of maximum marks of each subject. and later on we will let one more variable named as grades which will store the grades. Now as per the percentage calculated, it will execute the respective if-else statement. Printing in the result is a percentage and the grade of the student. Using HTML we are giving desired structure, option for the input, and submit button. With the help of CSS, we are beautifying our structure by giving colors and desired font, etc. In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed. Steps to create the calculator: First, we will make a function named as calculate. Initializing all the variables and storing the values input by the user. Now converting the values in float data type. Then we use simple mathematics to perform the calculation. Then we have implemented the if-else condition. Then we check the condition for empty inputs and if it is not empty then we will execute our output. Example: Now let’s start the implementation of the student’s grades calculator. index.html <!DOCTYPE html> <html> <head> <title>student calculate</title> <!-- link for font --> <link href= "https://fonts.googleapis.com/css?family=Righteous&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="style.css" /> </head> <body> <!-- main html --> <div class="container"> <h1>Student grade calculator</h1> <div class="screen-body-item"> <div class="app"> <div class="form-group"> <!-- option for taking the input --> <input type="text" class="form-control" placeholder="CHEMISTRY" id="chemistry" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="HINDI" id="hindi" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="MATHS" id="maths" /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="PHYSICS" id="phy" /> </div> <div> <input type="button" value="show Percentage" class="form-button" onclick="calculate()" /> </div> </div> </div> <!-- for showing the result--> <div class="form-group showdata"> <p id="showdata"></p> </div> </div> <!--adding external javascript file--> <script src="script.js"></script> </body> </html> style.css style.css * { margin: 0; padding: 0; box-sizing: border-box; } body { background: #006600; font-size: 12px; } .container { flex: 0 1 700px; margin: auto; padding: 10px; } .screen-body-item { flex: 1; padding: 50px; } input { margin: 10px 10px 10px; } .showdata { color: black; font-size: 1.2rem; padding-top: 10px; padding-bottom: 10px; } script.js // Function for calculating grades const calculate = () => { // Getting input from user into height variable. let chemistry = document.querySelector("#chemistry").value; let hindi = document.querySelector("#hindi").value; let maths = document.querySelector("#maths").value; let phy = document.querySelector("#phy").value; let grades = ""; // Input is string so typecasting is necessary. */ let totalgrades = parseFloat(chemistry) + parseFloat(hindi) + parseFloat(maths) + parseFloat(phy); // Checking the condition for the providing the // grade to student based on percentage let percentage = (totalgrades / 400) * 100; if (percentage <= 100 && percentage >= 80) { grades = "A"; } else if (percentage <= 79 && percentage >= 60) { grades = "B"; } else if (percentage <= 59 && percentage >= 40) { grades = "C"; } else { grades = "F"; } // Checking the values are empty if empty than // show please fill them if (chemistry == "" || hindi == "" || maths == "" || phy == "") { document.querySelector("#showdata").innerHTML = "Please enter all the fields"; } else { // Checking the condition for the fail and pass if (percentage >= 39.5) { document.querySelector( "#showdata" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Pass. `; } else { document.querySelector( "#showdata" ).innerHTML = ` Out of 400 your total is ${totalgrades} and percentage is ${percentage}%. <br> Your grade is ${grades}. You are Fail. `; } } }; Output: surindertarika1234 CSS-Properties CSS-Questions HTML-Basics HTML-Questions HTML-Tags JavaScript-Methods JavaScript-Questions CSS HTML JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set input type date in dd-mm-yyyy format using HTML ? Form validation using HTML and JavaScript HTML | <img> align Attribute How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 25057, "s": 25026, "text": " \n26 Aug, 2021\n" }, { "code": null, "e": 25215, "s": 25057, "text": "Student Grade Calculator (SGC) can be used to calculate a percentage based on the marks of students. (SGC) is a fairly reliable indicator of student results." }, { "code": null, "e": 25224, "s": 25215, "text": "Formula:" }, { "code": null, "e": 25269, "s": 25224, "text": "percentage = ( totalgrades / 400 ) * 100 ;" }, { "code": null, "e": 26228, "s": 25269, "text": "Approach: SGC is a percentage calculator from a student’s marks. To find out SGC we will take input from the user (for the four subjects) stored in Chemistry, Hindi, and Math variables for further calculation. The calculation process is simple, we will simply First we will add all the input marks and store them in the total grades variable after that we will divide it by the sum of maximum marks of each subject. and later on we will let one more variable named as grades which will store the grades. Now as per the percentage calculated, it will execute the respective if-else statement. Printing in the result is a percentage and the grade of the student. Using HTML we are giving desired structure, option for the input, and submit button. With the help of CSS, we are beautifying our structure by giving colors and desired font, etc. In the JavaScript section, we are processing the taken input and after calculating, the respective output is printed." }, { "code": null, "e": 26260, "s": 26228, "text": "Steps to create the calculator:" }, { "code": null, "e": 26311, "s": 26260, "text": "First, we will make a function named as calculate." }, { "code": null, "e": 26384, "s": 26311, "text": "Initializing all the variables and storing the values input by the user." }, { "code": null, "e": 26430, "s": 26384, "text": "Now converting the values in float data type." }, { "code": null, "e": 26489, "s": 26430, "text": "Then we use simple mathematics to perform the calculation." }, { "code": null, "e": 26537, "s": 26489, "text": "Then we have implemented the if-else condition." }, { "code": null, "e": 26638, "s": 26537, "text": "Then we check the condition for empty inputs and if it is not empty then we will execute our output." }, { "code": null, "e": 26720, "s": 26640, "text": "Example: Now let’s start the implementation of the student’s grades calculator." }, { "code": null, "e": 26731, "s": 26720, "text": "index.html" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n <head> \n <title>student calculate</title> \n <!-- link for font -->\n <link\n href= \n\"https://fonts.googleapis.com/css?family=Righteous&display=swap\"\n rel=\"stylesheet\"\n /> \n <link rel=\"stylesheet\" href=\"style.css\" /> \n </head> \n <body> \n <!-- main html -->\n <div class=\"container\"> \n <h1>Student grade calculator</h1> \n <div class=\"screen-body-item\"> \n <div class=\"app\"> \n <div class=\"form-group\"> \n <!-- option for taking the input -->\n <input\n type=\"text\"\n class=\"form-control\"\n placeholder=\"CHEMISTRY\"\n id=\"chemistry\"\n /> \n </div> \n <div class=\"form-group\"> \n <input\n type=\"text\"\n class=\"form-control\"\n placeholder=\"HINDI\"\n id=\"hindi\"\n /> \n </div> \n <div class=\"form-group\"> \n <input\n type=\"text\"\n class=\"form-control\"\n placeholder=\"MATHS\"\n id=\"maths\"\n /> \n </div> \n <div class=\"form-group\"> \n <input\n type=\"text\"\n class=\"form-control\"\n placeholder=\"PHYSICS\"\n id=\"phy\"\n /> \n </div> \n <div> \n <input\n type=\"button\"\n value=\"show Percentage\"\n class=\"form-button\"\n onclick=\"calculate()\"\n /> \n </div> \n </div> \n </div> \n <!-- for showing the result-->\n <div class=\"form-group showdata\"> \n <p id=\"showdata\"></p> \n </div> \n </div> \n <!--adding external javascript file-->\n <script src=\"script.js\"></script> \n </body> \n</html> \n\n\n\n\n\n", "e": 28568, "s": 26741, "text": null }, { "code": null, "e": 28578, "s": 28568, "text": "style.css" }, { "code": null, "e": 28588, "s": 28578, "text": "style.css" }, { "code": "\n\n\n\n\n\n\n* { \n margin: 0; \n padding: 0; \n box-sizing: border-box; \n} \nbody { \n background: #006600; \n font-size: 12px; \n} \n \n.container { \n flex: 0 1 700px; \n margin: auto; \n padding: 10px; \n} \n \n.screen-body-item { \n flex: 1; \n padding: 50px; \n} \ninput { \n margin: 10px 10px 10px; \n} \n.showdata { \n color: black; \n font-size: 1.2rem; \n padding-top: 10px; \n padding-bottom: 10px; \n} \n\n\n\n\n\n", "e": 29003, "s": 28598, "text": null }, { "code": null, "e": 29013, "s": 29003, "text": "script.js" }, { "code": "\n\n\n\n\n\n\n// Function for calculating grades \nconst calculate = () => { \n \n // Getting input from user into height variable. \n let chemistry = document.querySelector(\"#chemistry\").value; \n let hindi = document.querySelector(\"#hindi\").value; \n let maths = document.querySelector(\"#maths\").value; \n let phy = document.querySelector(\"#phy\").value; \n let grades = \"\"; \n \n // Input is string so typecasting is necessary. */ \n let totalgrades = \n parseFloat(chemistry) + \n parseFloat(hindi) + \n parseFloat(maths) + \n parseFloat(phy); \n \n // Checking the condition for the providing the \n // grade to student based on percentage \n let percentage = (totalgrades / 400) * 100; \n if (percentage <= 100 && percentage >= 80) { \n grades = \"A\"; \n } else if (percentage <= 79 && percentage >= 60) { \n grades = \"B\"; \n } else if (percentage <= 59 && percentage >= 40) { \n grades = \"C\"; \n } else { \n grades = \"F\"; \n } \n // Checking the values are empty if empty than \n // show please fill them \n if (chemistry == \"\" || hindi == \"\" \n || maths == \"\" || phy == \"\") { \n document.querySelector(\"#showdata\").innerHTML \n = \"Please enter all the fields\"; \n } else { \n \n // Checking the condition for the fail and pass \n if (percentage >= 39.5) { \n document.querySelector( \n \"#showdata\"\n ).innerHTML = \n ` Out of 400 your total is ${totalgrades} \n and percentage is ${percentage}%. <br> \n Your grade is ${grades}. You are Pass. `; \n } else { \n document.querySelector( \n \"#showdata\"\n ).innerHTML = \n ` Out of 400 your total is ${totalgrades} \n and percentage is ${percentage}%. <br> \n Your grade is ${grades}. You are Fail. `; \n } \n } \n}; \n\n\n\n\n\n", "e": 30806, "s": 29023, "text": null }, { "code": null, "e": 30814, "s": 30806, "text": "Output:" }, { "code": null, "e": 30833, "s": 30814, "text": "surindertarika1234" }, { "code": null, "e": 30850, "s": 30833, "text": "\nCSS-Properties\n" }, { "code": null, "e": 30866, "s": 30850, "text": "\nCSS-Questions\n" }, { "code": null, "e": 30880, "s": 30866, "text": "\nHTML-Basics\n" }, { "code": null, "e": 30897, "s": 30880, "text": "\nHTML-Questions\n" }, { "code": null, "e": 30909, "s": 30897, "text": "\nHTML-Tags\n" }, { "code": null, "e": 30930, "s": 30909, "text": "\nJavaScript-Methods\n" }, { "code": null, "e": 30953, "s": 30930, "text": "\nJavaScript-Questions\n" }, { "code": null, "e": 30959, "s": 30953, "text": "\nCSS\n" }, { "code": null, "e": 30966, "s": 30959, "text": "\nHTML\n" }, { "code": null, "e": 30979, "s": 30966, "text": "\nJavaScript\n" }, { "code": null, "e": 30998, "s": 30979, "text": "\nWeb Technologies\n" }, { "code": null, "e": 31203, "s": 30998, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31240, "s": 31203, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31269, "s": 31240, "text": "Form validation using jQuery" }, { "code": null, "e": 31308, "s": 31269, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31350, "s": 31308, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31385, "s": 31350, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31446, "s": 31385, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31488, "s": 31446, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 31517, "s": 31488, "text": "HTML | <img> align Attribute" } ]
Building recommender systems with Surprise. | Towards Data Science
If you’ve ever worked on a data science project, you probably have a default library that you use for standard tasks. Most people will probably use Pandas for data manipulation, Scikit-learn for general-purpose machine learning applications, and TensorFlow or PyTorch for deep learning. But what would you use to build a recommender system? This is where Surprise comes into play. Surprise is an open-source Python library that makes it easy for developers to build recommender systems with explicit rating data. In this article, I will show you how you can use Surprise to build a book recommendation system using the goodbooks-10k dataset available on Kaggle under the CC BY-SA 4.0 license. You can install Surprise with pip using the following command. pip install scikit-surprise If you would prefer to use Anaconda for package management, you can use the following command to install Surprise with Anaconda. conda install -c conda-forge scikit-surprise If you want to install the latest version of the library directly from GitHub, you should use the following commands (you will need Numpy and Cython). pip install numpy cythongit clone https://github.com/NicolasHug/surprise.gitcd surprisepython setup.py install You can find the entire code for this practical example on GitHub. To get started, I just imported some basic libraries for data manipulation and visualization. import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline I used two CSV files from the goodbooks-10k dataset available on Kaggle. The first one contains rating data for 10,000 books rated by over 53,000 users. The second file contains the metadata (title, author, ISBN, etc.) for each of the 10,000 books. ratings_data = pd.read_csv('./data/ratings.csv.zip')books_metadata = pd.read_csv('./data/books.csv.zip')ratings_data.head(10) In order to train recommender systems with Surprise, we need to create a Dataset object. A Surprise Dataset object is a dataset that contains the following fields in this order: The user IDsThe item IDs (in this case the IDs for each book)The corresponding rating (usually on a scale such as 1–5) The user IDs The item IDs (in this case the IDs for each book) The corresponding rating (usually on a scale such as 1–5) from surprise import Datasetfrom surprise import Readerreader = Reader(rating_scale=(1, 5))data = Dataset.load_from_df(ratings_data[['user_id', 'book_id', 'rating']], reader) We can train and cross-validate a model that performs SVD (singular value decomposition) in order to build a recommendation system in just a few lines of code. SVD is a popular matrix factorization algorithm that can be used for recommender systems. Recommender systems that use matrix factorization generally follow a pattern where a matrix of ratings is factored into a product of matrices representing latent factors for the items (in this case books) and the users. Considering the figure above, notice how the rating matrix, R, has missing values in some places. The matrix factorization algorithm uses a procedure such as gradient descent to minimize the error when predicting existing ratings using the matrix factors. Thus, an algorithm like SVD builds a recommendation system by allowing us to “fill in the gaps” in the rating matrix, predicting the ratings that each user would assign to each item in the dataset. Starting with an input matrix A, SVD actually factorizes the original matrix into three matrices as demonstrated in the equation below. We can map these new matrices to the rating matrix R and the item and user factors Q and P as follows: In the case of our book recommendation system, the SVD algorithm will represent the rating matrix as a product of matrices representing the book factors and user factors respectively. Of course, this is a very brief explanation of the SVD algorithm without all of the mathematical details but if you want a more detailed explanation of this algorithm, you should check out the Stanford CS 246 lecture notes. In the code below, I cross-validated an SVD model using three-fold cross-validation. from surprise import SVDfrom surprise.model_selection import cross_validatesvd = SVD(verbose=True, n_epochs=10)cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=3, verbose=True) Running the code above produced the following output. Fold 1 Fold 2 Fold 3 Mean Std RMSE (testset) 0.8561 0.8577 0.8551 0.8563 0.0011 MAE (testset) 0.6753 0.6764 0.6746 0.6754 0.0007 Fit time 20.21 22.62 23.25 22.03 1.31 Test time 3.18 4.68 4.79 4.22 0.74 We can also train the model on the entire dataset using the fit method after converting the dataset for cross-validation into a Surprise Trainset object using the build_full_trainset method. trainset = data.build_full_trainset()svd.fit(trainset) Now that we have a trained SVD model, we can use it to predict the rating a user would assign to a book given an ID for the user (UID) and an ID for the item/book (IID). The code below demonstrates how to do this with the predict method. svd.predict(uid=10, iid=100) The predict method returns the Prediction shown below, which contains a field called est that indicates the estimated book rating for this specific user. Prediction(uid=10, iid=100, r_ui=None, est=4.051206489275292, details={'was_impossible': False}) Based on the output above, we can see that the model predicted that this specific user would give a four-star rating (roughly) to the book corresponding to an IID of 100. The model doesn’t directly recommend books, but we can use this rating prediction utility to identify what books a user would likely enjoy, which allows us to justify recommending them to a user. Using this rating prediction utility, I defined the following utility functions below for generating book recommendations. The generate_recommendation function generates a book recommendation for a user by iterating through the shuffled list of book titles and predicting the user ratings for each title until it finds a book with a rating at or above the specified threshold that qualifies it for being recommended to a user. Shuffling the book titles at the beginning adds some randomness to the book recommendation. generate_recommendation(1000, svd, books_metadata) Running the function as demonstrated above produced the output below (note that due to the randomness of the function, you may get a different recommendation). [{'id': 7034, 'isbn': '1402792808', 'authors': 'Corban Addison', 'title': 'A Walk Across the Sun', 'original_title': 'A Walk Across the Sun'}] Based on the output above, we can see that the function returns a dictionary with metadata about the book that was recommended. Running this function multiple times will produce multiple book recommendations. After a user reviews a book, we can add that data to the rating data and retrain the model to produce an even better recommender system. We can take this project a step further and actually visualize the similarity between books based on the book factor matrix, referred to as Q in the previous diagram used to explain matrix factorization models. This 10,000 x 100 matrix has a 100-dimensional vector for each book, which is too many dimensions for us to visualize intuitively, but we can use a dimensionality reduction technique to represent each book as a two-dimensional point in space. In the code below, I used a technique called t-SNE (t-Distributed Stochastic Neighbors Embedding) to represent each book as a two-dimensional point and stored the results in a data frame. from sklearn.manifold import TSNEtsne = TSNE(n_components=2, n_iter=500, verbose=3, random_state=1)books_embedding = tsne.fit_transform(svd.qi)projection = pd.DataFrame(columns=['x', 'y'], data=books_embedding)projection['title'] = books_metadata['original_title'] After creating this data frame with two-dimensional points for each book, I used Plotly to create a visualization with each point corresponding to a book in the original dataset. import plotly.express as pxfig = px.scatter( projection, x='x', y='y')fig.show() Based on the plot produced above by the Plotly code, we can see that the points representing the 10,000 books seem to follow a two-dimensional normal distribution. We can explain this distribution with the following theories about the books in the dataset: Some books may be generally popular among a wide range of audiences and thus correspond to points in the center of this scatterplot. Other books may fall into very specific genres such as vampire novels, mystery novels, and romance that are popular among specific audiences. These books may correspond to points away from the center of the plot. To actually look at the book titles associated with each point, I defined a specific function for plotting a list of books given their titles. Note that I used Datapane to display the visualizations embedded in this article. In the code below, I added a function argument for publishing the resulting plot as a Datapane report. import datapane as dpdef plot_books(titles, plot_name): book_indices = [] for book in titles: book_indices.append(get_book_id(book, books_metadata)-1) book_vector_df = projection.iloc[book_indices] fig = px.scatter( book_vector_df, x='x', y='y', text='title', ) fig.show() report = dp.Report(dp.Plot(fig) ) #Create a report report.publish(name=plot_name, open=True, visibility='PUBLIC') Using the code below, I plotted the points associated with the first 30 books in the dataset. books = list(books_metadata['title'][:30])plot_books(books, plot_name='books_embedding') This visualization allows us to see the similarities between different books. Books located closer to each other tend to perform similarly when it comes to ratings provided by similar users. For example, we can see that Catching Fire and Divergent, two novels from the Hunger Games and Divergent series respectively, were popular among similar users. Surprise is an easy-to-use Python library that allows us to quickly build rating-based recommender systems without reinventing the wheel. Surprise also gives us access to the matrix factors when using models such as SVD, which allows us to visualize the similarities between the items in our dataset. As mentioned earlier, I have included the code for all of the examples in this article on GitHub. Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community? Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up! N. Hug, Surprise: A Python library for recommender systems, (2020), Journal of Open Source Software.Z. Zajac, Goodbooks-10k dataset, (2017), Kaggle.J. Leskovec, Stanford CS 246 Mining Massive Datasets Lecture Notes, (2015), Stanford Network Analysis Project. N. Hug, Surprise: A Python library for recommender systems, (2020), Journal of Open Source Software. Z. Zajac, Goodbooks-10k dataset, (2017), Kaggle. J. Leskovec, Stanford CS 246 Mining Massive Datasets Lecture Notes, (2015), Stanford Network Analysis Project.
[ { "code": null, "e": 553, "s": 172, "text": "If you’ve ever worked on a data science project, you probably have a default library that you use for standard tasks. Most people will probably use Pandas for data manipulation, Scikit-learn for general-purpose machine learning applications, and TensorFlow or PyTorch for deep learning. But what would you use to build a recommender system? This is where Surprise comes into play." }, { "code": null, "e": 865, "s": 553, "text": "Surprise is an open-source Python library that makes it easy for developers to build recommender systems with explicit rating data. In this article, I will show you how you can use Surprise to build a book recommendation system using the goodbooks-10k dataset available on Kaggle under the CC BY-SA 4.0 license." }, { "code": null, "e": 928, "s": 865, "text": "You can install Surprise with pip using the following command." }, { "code": null, "e": 956, "s": 928, "text": "pip install scikit-surprise" }, { "code": null, "e": 1085, "s": 956, "text": "If you would prefer to use Anaconda for package management, you can use the following command to install Surprise with Anaconda." }, { "code": null, "e": 1130, "s": 1085, "text": "conda install -c conda-forge scikit-surprise" }, { "code": null, "e": 1281, "s": 1130, "text": "If you want to install the latest version of the library directly from GitHub, you should use the following commands (you will need Numpy and Cython)." }, { "code": null, "e": 1392, "s": 1281, "text": "pip install numpy cythongit clone https://github.com/NicolasHug/surprise.gitcd surprisepython setup.py install" }, { "code": null, "e": 1459, "s": 1392, "text": "You can find the entire code for this practical example on GitHub." }, { "code": null, "e": 1553, "s": 1459, "text": "To get started, I just imported some basic libraries for data manipulation and visualization." }, { "code": null, "e": 1640, "s": 1553, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 1889, "s": 1640, "text": "I used two CSV files from the goodbooks-10k dataset available on Kaggle. The first one contains rating data for 10,000 books rated by over 53,000 users. The second file contains the metadata (title, author, ISBN, etc.) for each of the 10,000 books." }, { "code": null, "e": 2015, "s": 1889, "text": "ratings_data = pd.read_csv('./data/ratings.csv.zip')books_metadata = pd.read_csv('./data/books.csv.zip')ratings_data.head(10)" }, { "code": null, "e": 2193, "s": 2015, "text": "In order to train recommender systems with Surprise, we need to create a Dataset object. A Surprise Dataset object is a dataset that contains the following fields in this order:" }, { "code": null, "e": 2312, "s": 2193, "text": "The user IDsThe item IDs (in this case the IDs for each book)The corresponding rating (usually on a scale such as 1–5)" }, { "code": null, "e": 2325, "s": 2312, "text": "The user IDs" }, { "code": null, "e": 2375, "s": 2325, "text": "The item IDs (in this case the IDs for each book)" }, { "code": null, "e": 2433, "s": 2375, "text": "The corresponding rating (usually on a scale such as 1–5)" }, { "code": null, "e": 2608, "s": 2433, "text": "from surprise import Datasetfrom surprise import Readerreader = Reader(rating_scale=(1, 5))data = Dataset.load_from_df(ratings_data[['user_id', 'book_id', 'rating']], reader)" }, { "code": null, "e": 2858, "s": 2608, "text": "We can train and cross-validate a model that performs SVD (singular value decomposition) in order to build a recommendation system in just a few lines of code. SVD is a popular matrix factorization algorithm that can be used for recommender systems." }, { "code": null, "e": 3078, "s": 2858, "text": "Recommender systems that use matrix factorization generally follow a pattern where a matrix of ratings is factored into a product of matrices representing latent factors for the items (in this case books) and the users." }, { "code": null, "e": 3532, "s": 3078, "text": "Considering the figure above, notice how the rating matrix, R, has missing values in some places. The matrix factorization algorithm uses a procedure such as gradient descent to minimize the error when predicting existing ratings using the matrix factors. Thus, an algorithm like SVD builds a recommendation system by allowing us to “fill in the gaps” in the rating matrix, predicting the ratings that each user would assign to each item in the dataset." }, { "code": null, "e": 3668, "s": 3532, "text": "Starting with an input matrix A, SVD actually factorizes the original matrix into three matrices as demonstrated in the equation below." }, { "code": null, "e": 3771, "s": 3668, "text": "We can map these new matrices to the rating matrix R and the item and user factors Q and P as follows:" }, { "code": null, "e": 4179, "s": 3771, "text": "In the case of our book recommendation system, the SVD algorithm will represent the rating matrix as a product of matrices representing the book factors and user factors respectively. Of course, this is a very brief explanation of the SVD algorithm without all of the mathematical details but if you want a more detailed explanation of this algorithm, you should check out the Stanford CS 246 lecture notes." }, { "code": null, "e": 4264, "s": 4179, "text": "In the code below, I cross-validated an SVD model using three-fold cross-validation." }, { "code": null, "e": 4447, "s": 4264, "text": "from surprise import SVDfrom surprise.model_selection import cross_validatesvd = SVD(verbose=True, n_epochs=10)cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=3, verbose=True)" }, { "code": null, "e": 4501, "s": 4447, "text": "Running the code above produced the following output." }, { "code": null, "e": 4770, "s": 4501, "text": "Fold 1 Fold 2 Fold 3 Mean Std RMSE (testset) 0.8561 0.8577 0.8551 0.8563 0.0011 MAE (testset) 0.6753 0.6764 0.6746 0.6754 0.0007 Fit time 20.21 22.62 23.25 22.03 1.31 Test time 3.18 4.68 4.79 4.22 0.74" }, { "code": null, "e": 4961, "s": 4770, "text": "We can also train the model on the entire dataset using the fit method after converting the dataset for cross-validation into a Surprise Trainset object using the build_full_trainset method." }, { "code": null, "e": 5016, "s": 4961, "text": "trainset = data.build_full_trainset()svd.fit(trainset)" }, { "code": null, "e": 5254, "s": 5016, "text": "Now that we have a trained SVD model, we can use it to predict the rating a user would assign to a book given an ID for the user (UID) and an ID for the item/book (IID). The code below demonstrates how to do this with the predict method." }, { "code": null, "e": 5283, "s": 5254, "text": "svd.predict(uid=10, iid=100)" }, { "code": null, "e": 5437, "s": 5283, "text": "The predict method returns the Prediction shown below, which contains a field called est that indicates the estimated book rating for this specific user." }, { "code": null, "e": 5534, "s": 5437, "text": "Prediction(uid=10, iid=100, r_ui=None, est=4.051206489275292, details={'was_impossible': False})" }, { "code": null, "e": 5901, "s": 5534, "text": "Based on the output above, we can see that the model predicted that this specific user would give a four-star rating (roughly) to the book corresponding to an IID of 100. The model doesn’t directly recommend books, but we can use this rating prediction utility to identify what books a user would likely enjoy, which allows us to justify recommending them to a user." }, { "code": null, "e": 6024, "s": 5901, "text": "Using this rating prediction utility, I defined the following utility functions below for generating book recommendations." }, { "code": null, "e": 6420, "s": 6024, "text": "The generate_recommendation function generates a book recommendation for a user by iterating through the shuffled list of book titles and predicting the user ratings for each title until it finds a book with a rating at or above the specified threshold that qualifies it for being recommended to a user. Shuffling the book titles at the beginning adds some randomness to the book recommendation." }, { "code": null, "e": 6471, "s": 6420, "text": "generate_recommendation(1000, svd, books_metadata)" }, { "code": null, "e": 6631, "s": 6471, "text": "Running the function as demonstrated above produced the output below (note that due to the randomness of the function, you may get a different recommendation)." }, { "code": null, "e": 6778, "s": 6631, "text": "[{'id': 7034, 'isbn': '1402792808', 'authors': 'Corban Addison', 'title': 'A Walk Across the Sun', 'original_title': 'A Walk Across the Sun'}]" }, { "code": null, "e": 7124, "s": 6778, "text": "Based on the output above, we can see that the function returns a dictionary with metadata about the book that was recommended. Running this function multiple times will produce multiple book recommendations. After a user reviews a book, we can add that data to the rating data and retrain the model to produce an even better recommender system." }, { "code": null, "e": 7335, "s": 7124, "text": "We can take this project a step further and actually visualize the similarity between books based on the book factor matrix, referred to as Q in the previous diagram used to explain matrix factorization models." }, { "code": null, "e": 7766, "s": 7335, "text": "This 10,000 x 100 matrix has a 100-dimensional vector for each book, which is too many dimensions for us to visualize intuitively, but we can use a dimensionality reduction technique to represent each book as a two-dimensional point in space. In the code below, I used a technique called t-SNE (t-Distributed Stochastic Neighbors Embedding) to represent each book as a two-dimensional point and stored the results in a data frame." }, { "code": null, "e": 8031, "s": 7766, "text": "from sklearn.manifold import TSNEtsne = TSNE(n_components=2, n_iter=500, verbose=3, random_state=1)books_embedding = tsne.fit_transform(svd.qi)projection = pd.DataFrame(columns=['x', 'y'], data=books_embedding)projection['title'] = books_metadata['original_title']" }, { "code": null, "e": 8210, "s": 8031, "text": "After creating this data frame with two-dimensional points for each book, I used Plotly to create a visualization with each point corresponding to a book in the original dataset." }, { "code": null, "e": 8294, "s": 8210, "text": "import plotly.express as pxfig = px.scatter( projection, x='x', y='y')fig.show()" }, { "code": null, "e": 8551, "s": 8294, "text": "Based on the plot produced above by the Plotly code, we can see that the points representing the 10,000 books seem to follow a two-dimensional normal distribution. We can explain this distribution with the following theories about the books in the dataset:" }, { "code": null, "e": 8684, "s": 8551, "text": "Some books may be generally popular among a wide range of audiences and thus correspond to points in the center of this scatterplot." }, { "code": null, "e": 8897, "s": 8684, "text": "Other books may fall into very specific genres such as vampire novels, mystery novels, and romance that are popular among specific audiences. These books may correspond to points away from the center of the plot." }, { "code": null, "e": 9225, "s": 8897, "text": "To actually look at the book titles associated with each point, I defined a specific function for plotting a list of books given their titles. Note that I used Datapane to display the visualizations embedded in this article. In the code below, I added a function argument for publishing the resulting plot as a Datapane report." }, { "code": null, "e": 9666, "s": 9225, "text": "import datapane as dpdef plot_books(titles, plot_name): book_indices = [] for book in titles: book_indices.append(get_book_id(book, books_metadata)-1) book_vector_df = projection.iloc[book_indices] fig = px.scatter( book_vector_df, x='x', y='y', text='title', ) fig.show() report = dp.Report(dp.Plot(fig) ) #Create a report report.publish(name=plot_name, open=True, visibility='PUBLIC')" }, { "code": null, "e": 9760, "s": 9666, "text": "Using the code below, I plotted the points associated with the first 30 books in the dataset." }, { "code": null, "e": 9849, "s": 9760, "text": "books = list(books_metadata['title'][:30])plot_books(books, plot_name='books_embedding')" }, { "code": null, "e": 10200, "s": 9849, "text": "This visualization allows us to see the similarities between different books. Books located closer to each other tend to perform similarly when it comes to ratings provided by similar users. For example, we can see that Catching Fire and Divergent, two novels from the Hunger Games and Divergent series respectively, were popular among similar users." }, { "code": null, "e": 10338, "s": 10200, "text": "Surprise is an easy-to-use Python library that allows us to quickly build rating-based recommender systems without reinventing the wheel." }, { "code": null, "e": 10501, "s": 10338, "text": "Surprise also gives us access to the matrix factors when using models such as SVD, which allows us to visualize the similarities between the items in our dataset." }, { "code": null, "e": 10599, "s": 10501, "text": "As mentioned earlier, I have included the code for all of the examples in this article on GitHub." }, { "code": null, "e": 10800, "s": 10599, "text": "Do you want to get better at data science and machine learning? Do you want to stay up to date with the latest libraries, developments, and research in the data science and machine learning community?" }, { "code": null, "e": 10962, "s": 10800, "text": "Join my mailing list to get updates on my data science content. You’ll also get my free Step-By-Step Guide to Solving Machine Learning Problems when you sign up!" }, { "code": null, "e": 11221, "s": 10962, "text": "N. Hug, Surprise: A Python library for recommender systems, (2020), Journal of Open Source Software.Z. Zajac, Goodbooks-10k dataset, (2017), Kaggle.J. Leskovec, Stanford CS 246 Mining Massive Datasets Lecture Notes, (2015), Stanford Network Analysis Project." }, { "code": null, "e": 11322, "s": 11221, "text": "N. Hug, Surprise: A Python library for recommender systems, (2020), Journal of Open Source Software." }, { "code": null, "e": 11371, "s": 11322, "text": "Z. Zajac, Goodbooks-10k dataset, (2017), Kaggle." } ]
JSF - h:inputSecret
The h:inputSecret tag renders an HTML input element of the type "password". <h:inputSecret value = "password" /> <input type = "password" name = "j_idt12:j_idt16" value = "password" /> id Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that’s created and attached to a component required A boolean; if true, requires a value to be entered in the associated field accesskey A key, typically combined with a system-defined metakey, that gives focus to an element accept Comma-separated list of content types for a form accept-charset Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset alt Alternative text for nontextual elements such as images or applets border Pixel value for an element’s border width charset Character encoding for a linked resource coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left). disabled Disabled state of an input element or button hreflang Base language of a resource specified with the href attribute; hreflang may only be used with href lang Base language of an element’s attributes and text maxlength Maximum number of characters for text fields readonly Read-only state of an input field; text can be selected in a readonly field but not edited style Inline style information tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value type Type of a link; for example, stylesheet width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field immediate Process validation early in the life cycle redisplay when true, the input field’s value is redisplayed when the web page is reloaded Let us create a test JSF application to test the above tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> <h2>h:inputSecret example</h2> <hr /> <h:form> <h3>Read-Only input password box</h3> <h:inputSecret value = "password" readonly = "true"/> <h3>Read-Only input text box</h3> <h:inputText value = "password"/> </h:form> </body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2028, "s": 1952, "text": "The h:inputSecret tag renders an HTML input element of the type \"password\"." }, { "code": null, "e": 2066, "s": 2028, "text": "<h:inputSecret value = \"password\" />\n" }, { "code": null, "e": 2139, "s": 2066, "text": "<input type = \"password\" name = \"j_idt12:j_idt16\" value = \"password\" />\n" }, { "code": null, "e": 2142, "s": 2139, "text": "id" }, { "code": null, "e": 2169, "s": 2142, "text": "Identifier for a component" }, { "code": null, "e": 2177, "s": 2169, "text": "binding" }, { "code": null, "e": 2239, "s": 2177, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2248, "s": 2239, "text": "rendered" }, { "code": null, "e": 2286, "s": 2248, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2297, "s": 2286, "text": "styleClass" }, { "code": null, "e": 2335, "s": 2297, "text": "Cascading stylesheet (CSS) class name" }, { "code": null, "e": 2341, "s": 2335, "text": "value" }, { "code": null, "e": 2388, "s": 2341, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 2408, "s": 2388, "text": "valueChangeListener" }, { "code": null, "e": 2468, "s": 2408, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 2478, "s": 2468, "text": "converter" }, { "code": null, "e": 2499, "s": 2478, "text": "Converter class name" }, { "code": null, "e": 2509, "s": 2499, "text": "validator" }, { "code": null, "e": 2578, "s": 2509, "text": "Class name of a validator that’s created and attached to a component" }, { "code": null, "e": 2587, "s": 2578, "text": "required" }, { "code": null, "e": 2662, "s": 2587, "text": "A boolean; if true, requires a value to be entered in the associated field" }, { "code": null, "e": 2672, "s": 2662, "text": "accesskey" }, { "code": null, "e": 2760, "s": 2672, "text": "A key, typically combined with a system-defined metakey, that gives focus to an element" }, { "code": null, "e": 2767, "s": 2760, "text": "accept" }, { "code": null, "e": 2816, "s": 2767, "text": "Comma-separated list of content types for a form" }, { "code": null, "e": 2831, "s": 2816, "text": "accept-charset" }, { "code": null, "e": 2987, "s": 2831, "text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset" }, { "code": null, "e": 2991, "s": 2987, "text": "alt" }, { "code": null, "e": 3058, "s": 2991, "text": "Alternative text for nontextual elements such as images or applets" }, { "code": null, "e": 3065, "s": 3058, "text": "border" }, { "code": null, "e": 3107, "s": 3065, "text": "Pixel value for an element’s border width" }, { "code": null, "e": 3115, "s": 3107, "text": "charset" }, { "code": null, "e": 3156, "s": 3115, "text": "Character encoding for a linked resource" }, { "code": null, "e": 3163, "s": 3156, "text": "coords" }, { "code": null, "e": 3237, "s": 3163, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 3241, "s": 3237, "text": "dir" }, { "code": null, "e": 3323, "s": 3241, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)." }, { "code": null, "e": 3332, "s": 3323, "text": "disabled" }, { "code": null, "e": 3377, "s": 3332, "text": "Disabled state of an input element or button" }, { "code": null, "e": 3386, "s": 3377, "text": "hreflang" }, { "code": null, "e": 3485, "s": 3386, "text": "Base language of a resource specified with the href attribute; hreflang may only be used with href" }, { "code": null, "e": 3490, "s": 3485, "text": "lang" }, { "code": null, "e": 3540, "s": 3490, "text": "Base language of an element’s attributes and text" }, { "code": null, "e": 3550, "s": 3540, "text": "maxlength" }, { "code": null, "e": 3595, "s": 3550, "text": "Maximum number of characters for text fields" }, { "code": null, "e": 3604, "s": 3595, "text": "readonly" }, { "code": null, "e": 3695, "s": 3604, "text": "Read-only state of an input field; text can be selected in a readonly field but not edited" }, { "code": null, "e": 3701, "s": 3695, "text": "style" }, { "code": null, "e": 3726, "s": 3701, "text": "Inline style information" }, { "code": null, "e": 3735, "s": 3726, "text": "tabindex" }, { "code": null, "e": 3774, "s": 3735, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 3781, "s": 3774, "text": "target" }, { "code": null, "e": 3831, "s": 3781, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 3837, "s": 3831, "text": "title" }, { "code": null, "e": 3961, "s": 3837, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 3966, "s": 3961, "text": "type" }, { "code": null, "e": 4006, "s": 3966, "text": "Type of a link; for example, stylesheet" }, { "code": null, "e": 4012, "s": 4006, "text": "width" }, { "code": null, "e": 4032, "s": 4012, "text": "Width of an element" }, { "code": null, "e": 4039, "s": 4032, "text": "onblur" }, { "code": null, "e": 4059, "s": 4039, "text": "Element loses focus" }, { "code": null, "e": 4068, "s": 4059, "text": "onchange" }, { "code": null, "e": 4092, "s": 4068, "text": "Element’s value changes" }, { "code": null, "e": 4100, "s": 4092, "text": "onclick" }, { "code": null, "e": 4141, "s": 4100, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 4152, "s": 4141, "text": "ondblclick" }, { "code": null, "e": 4200, "s": 4152, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 4208, "s": 4200, "text": "onfocus" }, { "code": null, "e": 4231, "s": 4208, "text": "Element receives focus" }, { "code": null, "e": 4241, "s": 4231, "text": "onkeydown" }, { "code": null, "e": 4256, "s": 4241, "text": "Key is pressed" }, { "code": null, "e": 4267, "s": 4256, "text": "onkeypress" }, { "code": null, "e": 4308, "s": 4267, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 4316, "s": 4308, "text": "onkeyup" }, { "code": null, "e": 4332, "s": 4316, "text": "Key is released" }, { "code": null, "e": 4344, "s": 4332, "text": "onmousedown" }, { "code": null, "e": 4385, "s": 4344, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 4397, "s": 4385, "text": "onmousemove" }, { "code": null, "e": 4426, "s": 4397, "text": "Mouse moves over the element" }, { "code": null, "e": 4437, "s": 4426, "text": "onmouseout" }, { "code": null, "e": 4469, "s": 4437, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 4481, "s": 4469, "text": "onmouseover" }, { "code": null, "e": 4509, "s": 4481, "text": "Mouse moves onto an element" }, { "code": null, "e": 4519, "s": 4509, "text": "onmouseup" }, { "code": null, "e": 4544, "s": 4519, "text": "Mouse button is released" }, { "code": null, "e": 4552, "s": 4544, "text": "onreset" }, { "code": null, "e": 4566, "s": 4552, "text": "Form is reset" }, { "code": null, "e": 4575, "s": 4566, "text": "onselect" }, { "code": null, "e": 4610, "s": 4575, "text": "Text is selected in an input field" }, { "code": null, "e": 4620, "s": 4610, "text": "immediate" }, { "code": null, "e": 4663, "s": 4620, "text": "Process validation early in the life cycle" }, { "code": null, "e": 4673, "s": 4663, "text": "redisplay" }, { "code": null, "e": 4753, "s": 4673, "text": "when true, the input field’s value is redisplayed when the web page is reloaded" }, { "code": null, "e": 4813, "s": 4753, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 5362, "s": 4813, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>h:inputSecret example</h2>\n <hr />\n \n <h:form>\n <h3>Read-Only input password box</h3>\n <h:inputSecret value = \"password\" readonly = \"true\"/>\n <h3>Read-Only input text box</h3>\n <h:inputText value = \"password\"/>\n </h:form>\n \n </body>\n</html>" }, { "code": null, "e": 5578, "s": 5362, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 5613, "s": 5578, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5628, "s": 5613, "text": " Chaand Sheikh" }, { "code": null, "e": 5635, "s": 5628, "text": " Print" }, { "code": null, "e": 5646, "s": 5635, "text": " Add Notes" } ]
How do I use Selenium with Ruby?
We can use Selenium with Ruby. First of all we have to install Ruby in the system. For installation in Windows, we have to take the help of the RubyInstaller package by navigating to the link − https://rubyinstaller.org/ Click on Download. The various versions of Ruby Installers links get displayed. Select the latest version and click on it. Click on the Save File button to download the corresponding rubyinstaller.exe file. Once the download is completed, accept the license agreement and proceed to the next steps till installation is completed. To have Selenium webdriver package for Ruby, run the command − gem install selenium−webdriver To have Rest−Client package for Ruby, run the command − gem install rest−client To have test−unit package for Ruby, run the command − gem install test−unit #set webdriver gem for Selenium require "selenium−webdriver" require "rubygems" #driver object creation driver = Selenium::WebDriver.for :chrome #launch browser driver.navigate.to "https://www.tutorialspoint.com/index.htm" #close browser driver.close
[ { "code": null, "e": 1256, "s": 1062, "text": "We can use Selenium with Ruby. First of all we have to install Ruby in the system. For installation in Windows, we have to take the help of the RubyInstaller package by navigating to the link −" }, { "code": null, "e": 1283, "s": 1256, "text": "https://rubyinstaller.org/" }, { "code": null, "e": 1302, "s": 1283, "text": "Click on Download." }, { "code": null, "e": 1406, "s": 1302, "text": "The various versions of Ruby Installers links get displayed. Select the latest\nversion and click on it." }, { "code": null, "e": 1490, "s": 1406, "text": "Click on the Save File button to download the corresponding rubyinstaller.exe file." }, { "code": null, "e": 1613, "s": 1490, "text": "Once the download is completed, accept the license agreement and proceed to the next steps till installation is completed." }, { "code": null, "e": 1676, "s": 1613, "text": "To have Selenium webdriver package for Ruby, run the command −" }, { "code": null, "e": 1707, "s": 1676, "text": "gem install selenium−webdriver" }, { "code": null, "e": 1763, "s": 1707, "text": "To have Rest−Client package for Ruby, run the command −" }, { "code": null, "e": 1787, "s": 1763, "text": "gem install rest−client" }, { "code": null, "e": 1841, "s": 1787, "text": "To have test−unit package for Ruby, run the command −" }, { "code": null, "e": 1863, "s": 1841, "text": "gem install test−unit" }, { "code": null, "e": 2114, "s": 1863, "text": "#set webdriver gem for Selenium\nrequire \"selenium−webdriver\"\nrequire \"rubygems\"\n#driver object creation\ndriver = Selenium::WebDriver.for :chrome\n#launch browser\ndriver.navigate.to \"https://www.tutorialspoint.com/index.htm\"\n#close browser\ndriver.close" } ]
Node.js slice() function
14 Oct, 2021 The slice() function is a string function of Node.js which is used to extract sub-string from a string. Syntax: string.slice( start, end ) Parameters: This function uses thress parameters as mentioned above and described below: string: It holds the string content. The substring is extracted from this string. start: This parameter holds the starting index of sub-string. end: This parameter holds the ending index od sub-string. Return type: The function returns the substring. The program below demonstrates the working of the function: Program 1: function findsubstr(str) { var index = str.slice(12, 25); console.log(index);} var str = "Welcome to GeeksforGeeks"; findsubstr(str); Output: GeeksforGeeks Program 2: function findsubstr(str, start, end) { var index = str.slice(start, end); console.log(index);} var str = "Welcome to GeeksforGeeks"; var start = 0;var end = 6; findsubstr(str, start, end); Output: Welcome NodeJS-function Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 132, "s": 28, "text": "The slice() function is a string function of Node.js which is used to extract sub-string from a string." }, { "code": null, "e": 140, "s": 132, "text": "Syntax:" }, { "code": null, "e": 173, "s": 140, "text": " \nstring.slice( start, end )\n" }, { "code": null, "e": 262, "s": 173, "text": "Parameters: This function uses thress parameters as mentioned above and described below:" }, { "code": null, "e": 344, "s": 262, "text": "string: It holds the string content. The substring is extracted from this string." }, { "code": null, "e": 406, "s": 344, "text": "start: This parameter holds the starting index of sub-string." }, { "code": null, "e": 464, "s": 406, "text": "end: This parameter holds the ending index od sub-string." }, { "code": null, "e": 513, "s": 464, "text": "Return type: The function returns the substring." }, { "code": null, "e": 573, "s": 513, "text": "The program below demonstrates the working of the function:" }, { "code": null, "e": 584, "s": 573, "text": "Program 1:" }, { "code": "function findsubstr(str) { var index = str.slice(12, 25); console.log(index);} var str = \"Welcome to GeeksforGeeks\"; findsubstr(str);", "e": 738, "s": 584, "text": null }, { "code": null, "e": 746, "s": 738, "text": "Output:" }, { "code": null, "e": 760, "s": 746, "text": "GeeksforGeeks" }, { "code": null, "e": 771, "s": 760, "text": "Program 2:" }, { "code": "function findsubstr(str, start, end) { var index = str.slice(start, end); console.log(index);} var str = \"Welcome to GeeksforGeeks\"; var start = 0;var end = 6; findsubstr(str, start, end);", "e": 981, "s": 771, "text": null }, { "code": null, "e": 989, "s": 981, "text": "Output:" }, { "code": null, "e": 997, "s": 989, "text": "Welcome" }, { "code": null, "e": 1013, "s": 997, "text": "NodeJS-function" }, { "code": null, "e": 1021, "s": 1013, "text": "Node.js" }, { "code": null, "e": 1038, "s": 1021, "text": "Web Technologies" }, { "code": null, "e": 1136, "s": 1038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1166, "s": 1136, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1220, "s": 1166, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1260, "s": 1220, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1295, "s": 1260, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1327, "s": 1295, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1389, "s": 1327, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1450, "s": 1389, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1500, "s": 1450, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1543, "s": 1500, "text": "How to fetch data from an API in ReactJS ?" } ]
Pass by reference vs value in Python
23 Jun, 2022 Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment is the cause behind the confusion at the fundamental level. In the article, we will be discussing the concept of how to pass a value by reference in Python and try to understand pass-by-reference examples. You might want to punch something after reading ahead, so brace yourself. Python’s argument passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”. The paradigms of “Pass by value”, “Pass by Reference” and “Pass by object Reference” can be understood by exploring the below example functions. Look into the two functions defined below: Python3 def set_list(list): list = ["A", "B", "C"] return list def add(list): list.append("D") return list my_list = ["E"] print(set_list(my_list)) print(add(my_list)) Output: ['A', 'B', 'C'] ['E', 'D'] Now, let’s explore the above code, What if I tell you The Ramayana was not written by Tulsi Das but The Ramayana was written by a man named Tulsi Das. Does that distinction make any sense? No right?!. But according to Python, it does and it makes a crucial distinction. So, in Python and its PKD’s, there is a big difference between the thing and the label we use to refer to that thing. “A man named Tulsi Das ” is just a man and “Tulsi Das” is a name used to refer to that man. So, consider a list a = ["X", "Y"] Here “a” is a variable that points to a list containing the element “X” and “Y”. But “a” itself is not the list. Consider “a” to be a bucket that contains the object “X” and “Y”. Defining Pass by Reference, the variable( the bucket) is passed into the function directly. The variable acts as a Package that comes with its contents(the objects). In the above code image both “list” and “my_list” are the same container variable and therefore refer to the exact same object in the memory. Any operation performed by the function on the variable or the object will be directly reflected by the function caller. For instance, the function could completely change the variable’s content, and point it at a completely different object: Also, the function can reassign the contents of the variable with the same effect as below: To summarize, in pass-by-reference the function and the caller use the same variable and object. Defining Pass by Reference, the function is provided with a copy of the argument object passed to it by the caller. That means the original object stays intact and all changes made are to a copy of the same and stored at different memory locations. The same is true for any operation performed by the function on the variable or the object To summarize the copies of the variables and the objects in the context of the caller of the function are completely isolated. As python is different in this context, the functions in python receive the reference of the same object in the memory as referred by the caller. However, the function does not receive the variable(the bucket) that the caller is storing the same object in; like in pass-by-value, the function provides its own bucket and creates an entirely new variable for itself. The same object in the memory is referred to by both the caller and the function, so when the append function adds an extra element to the list, the caller object gets updated too. They have different names but are the same thing. Both the variables contain the same object. This is the meaning behind pass-by object reference. The function and caller use the same object in memory, but get them through different variables. Any changes made to the function variable(bucket) won’t change the nature of the caller variable (bucket), only the content gets updated. akshaysingh98088 surajkumarguptaintern python-basics Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 470, "s": 54, "text": "Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment is the cause behind the confusion at the fundamental level. In the article, we will be discussing the concept of how to pass a value by reference in Python and try to understand pass-by-reference examples." }, { "code": null, "e": 666, "s": 470, "text": "You might want to punch something after reading ahead, so brace yourself. Python’s argument passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”. " }, { "code": null, "e": 854, "s": 666, "text": "The paradigms of “Pass by value”, “Pass by Reference” and “Pass by object Reference” can be understood by exploring the below example functions. Look into the two functions defined below:" }, { "code": null, "e": 862, "s": 854, "text": "Python3" }, { "code": "def set_list(list): list = [\"A\", \"B\", \"C\"] return list def add(list): list.append(\"D\") return list my_list = [\"E\"] print(set_list(my_list)) print(add(my_list))", "e": 1034, "s": 862, "text": null }, { "code": null, "e": 1042, "s": 1034, "text": "Output:" }, { "code": null, "e": 1069, "s": 1042, "text": "['A', 'B', 'C']\n['E', 'D']" }, { "code": null, "e": 1105, "s": 1069, "text": "Now, let’s explore the above code, " }, { "code": null, "e": 1570, "s": 1105, "text": "What if I tell you The Ramayana was not written by Tulsi Das but The Ramayana was written by a man named Tulsi Das. Does that distinction make any sense? No right?!. But according to Python, it does and it makes a crucial distinction. So, in Python and its PKD’s, there is a big difference between the thing and the label we use to refer to that thing. “A man named Tulsi Das ” is just a man and “Tulsi Das” is a name used to refer to that man. So, consider a list" }, { "code": null, "e": 1586, "s": 1570, "text": " a = [\"X\", \"Y\"]" }, { "code": null, "e": 1766, "s": 1586, "text": "Here “a” is a variable that points to a list containing the element “X” and “Y”. But “a” itself is not the list. Consider “a” to be a bucket that contains the object “X” and “Y”. " }, { "code": null, "e": 1934, "s": 1768, "text": "Defining Pass by Reference, the variable( the bucket) is passed into the function directly. The variable acts as a Package that comes with its contents(the objects)." }, { "code": null, "e": 2322, "s": 1936, "text": "In the above code image both “list” and “my_list” are the same container variable and therefore refer to the exact same object in the memory. Any operation performed by the function on the variable or the object will be directly reflected by the function caller. For instance, the function could completely change the variable’s content, and point it at a completely different object: " }, { "code": null, "e": 2418, "s": 2324, "text": " Also, the function can reassign the contents of the variable with the same effect as below: " }, { "code": null, "e": 2517, "s": 2420, "text": "To summarize, in pass-by-reference the function and the caller use the same variable and object." }, { "code": null, "e": 2767, "s": 2517, "text": "Defining Pass by Reference, the function is provided with a copy of the argument object passed to it by the caller. That means the original object stays intact and all changes made are to a copy of the same and stored at different memory locations. " }, { "code": null, "e": 2861, "s": 2769, "text": "The same is true for any operation performed by the function on the variable or the object " }, { "code": null, "e": 2990, "s": 2863, "text": "To summarize the copies of the variables and the objects in the context of the caller of the function are completely isolated." }, { "code": null, "e": 3357, "s": 2990, "text": "As python is different in this context, the functions in python receive the reference of the same object in the memory as referred by the caller. However, the function does not receive the variable(the bucket) that the caller is storing the same object in; like in pass-by-value, the function provides its own bucket and creates an entirely new variable for itself. " }, { "code": null, "e": 3923, "s": 3359, "text": "The same object in the memory is referred to by both the caller and the function, so when the append function adds an extra element to the list, the caller object gets updated too. They have different names but are the same thing. Both the variables contain the same object. This is the meaning behind pass-by object reference. The function and caller use the same object in memory, but get them through different variables. Any changes made to the function variable(bucket) won’t change the nature of the caller variable (bucket), only the content gets updated. " }, { "code": null, "e": 3940, "s": 3923, "text": "akshaysingh98088" }, { "code": null, "e": 3962, "s": 3940, "text": "surajkumarguptaintern" }, { "code": null, "e": 3976, "s": 3962, "text": "python-basics" }, { "code": null, "e": 3993, "s": 3976, "text": "Python-Functions" }, { "code": null, "e": 4000, "s": 3993, "text": "Python" }, { "code": null, "e": 4098, "s": 4000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4140, "s": 4098, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4162, "s": 4140, "text": "Enumerate() in Python" }, { "code": null, "e": 4188, "s": 4162, "text": "Python String | replace()" }, { "code": null, "e": 4220, "s": 4188, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4249, "s": 4220, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4276, "s": 4249, "text": "Python Classes and Objects" }, { "code": null, "e": 4312, "s": 4276, "text": "Convert integer to string in Python" }, { "code": null, "e": 4333, "s": 4312, "text": "Python OOPs Concepts" }, { "code": null, "e": 4364, "s": 4333, "text": "Python | os.path.join() method" } ]
How to Implement Press Back Again to Exit in Android?
01 Sep, 2020 The ‘Back‘ button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app’s previous activity. Many apps require the user to press the ‘Back’ button two times within an interval to successfully close the application, which is considered the best practice. Why implement this in the app? It adds a better UX to the app providing the user with a satisfying experience. It acts as a confirmation in case the user presses the ‘Back’ button by mistake. Step 1: Create a new Android Studio project Please refer to this article How to create a new project in Android Studio to see in detail how to create a new Android Studio project. Note that choose Java as the programming language. Step 2: Working with activity_main.xml file In this example, we will have only a single layout, activity_main.xml which will contain an ImageView and a TextView. This is how our activity_main.xml looks like: 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" tools:context=".MainActivity" android:background="#388e3c" android:orientation="vertical"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gfglog"/> <TextView android:padding="15dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This was written at GeeksforGeeks" android:textColor="#f5f5f5" android:textSize="30sp" android:gravity="center_horizontal"/> </LinearLayout> The above layout looks like this: Layout Output Step 3: Working with MainActivity.java file Now comes the main part of the app. In order to check when the ‘BACK’ button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the ‘BACK’ button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don’t exit. Here’s how the MainActivity.java looks like: MainActivity.java package org.geeksforgeeks.pressbackexit; import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private long pressedTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onBackPressed() { if (pressedTime + 2000 > System.currentTimeMillis()) { super.onBackPressed(); finish(); } else { Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show(); } pressedTime = System.currentTimeMillis(); }} In the above code, when the user presses the ‘BACK’ button once, they are greeted with a toast asking them to press it again to exit. If the user then presses ‘BACK’ again within 2 seconds(2000ms), then the app is closed, otherwise, we remain there. android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2020" }, { "code": null, "e": 378, "s": 28, "text": "The ‘Back‘ button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app’s previous activity. Many apps require the user to press the ‘Back’ button two times within an interval to successfully close the application, which is considered the best practice." }, { "code": null, "e": 409, "s": 378, "text": "Why implement this in the app?" }, { "code": null, "e": 489, "s": 409, "text": "It adds a better UX to the app providing the user with a satisfying experience." }, { "code": null, "e": 570, "s": 489, "text": "It acts as a confirmation in case the user presses the ‘Back’ button by mistake." }, { "code": null, "e": 614, "s": 570, "text": "Step 1: Create a new Android Studio project" }, { "code": null, "e": 801, "s": 614, "text": "Please refer to this article How to create a new project in Android Studio to see in detail how to create a new Android Studio project. Note that choose Java as the programming language." }, { "code": null, "e": 845, "s": 801, "text": "Step 2: Working with activity_main.xml file" }, { "code": null, "e": 1009, "s": 845, "text": "In this example, we will have only a single layout, activity_main.xml which will contain an ImageView and a TextView. This is how our activity_main.xml looks like:" }, { "code": null, "e": 1027, "s": 1009, "text": "activity_main.xml" }, { "code": "<?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\" tools:context=\".MainActivity\" android:background=\"#388e3c\" android:orientation=\"vertical\"> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/gfglog\"/> <TextView android:padding=\"15dp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"This was written at GeeksforGeeks\" android:textColor=\"#f5f5f5\" android:textSize=\"30sp\" android:gravity=\"center_horizontal\"/> </LinearLayout>", "e": 1887, "s": 1027, "text": null }, { "code": null, "e": 1921, "s": 1887, "text": "The above layout looks like this:" }, { "code": null, "e": 1935, "s": 1921, "text": "Layout Output" }, { "code": null, "e": 1979, "s": 1935, "text": "Step 3: Working with MainActivity.java file" }, { "code": null, "e": 2310, "s": 1979, "text": "Now comes the main part of the app. In order to check when the ‘BACK’ button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the ‘BACK’ button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don’t exit. Here’s how the MainActivity.java looks like:" }, { "code": null, "e": 2328, "s": 2310, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.pressbackexit; import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private long pressedTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onBackPressed() { if (pressedTime + 2000 > System.currentTimeMillis()) { super.onBackPressed(); finish(); } else { Toast.makeText(getBaseContext(), \"Press back again to exit\", Toast.LENGTH_SHORT).show(); } pressedTime = System.currentTimeMillis(); }}", "e": 3069, "s": 2328, "text": null }, { "code": null, "e": 3319, "s": 3069, "text": "In the above code, when the user presses the ‘BACK’ button once, they are greeted with a toast asking them to press it again to exit. If the user then presses ‘BACK’ again within 2 seconds(2000ms), then the app is closed, otherwise, we remain there." }, { "code": null, "e": 3327, "s": 3319, "text": "android" }, { "code": null, "e": 3335, "s": 3327, "text": "Android" }, { "code": null, "e": 3340, "s": 3335, "text": "Java" }, { "code": null, "e": 3345, "s": 3340, "text": "Java" }, { "code": null, "e": 3353, "s": 3345, "text": "Android" }, { "code": null, "e": 3451, "s": 3353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3520, "s": 3451, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3551, "s": 3520, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3594, "s": 3551, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 3626, "s": 3594, "text": "Android SDK and it's Components" }, { "code": null, "e": 3665, "s": 3626, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3680, "s": 3665, "text": "Arrays in Java" }, { "code": null, "e": 3716, "s": 3680, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3760, "s": 3716, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3785, "s": 3760, "text": "Reverse a string in Java" } ]
Python Bitwise Operators Example
There are following Bitwise operators supported by Python language. #!/usr/bin/python a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b; # 12 = 0000 1100 print "Line 1 - Value of c is ", c c = a | b; # 61 = 0011 1101 print "Line 2 - Value of c is ", c c = a ^ b; # 49 = 0011 0001 print "Line 3 - Value of c is ", c c = ~a; # -61 = 1100 0011 print "Line 4 - Value of c is ", c c = a << 2; # 240 = 1111 0000 print "Line 5 - Value of c is ", c c = a >> 2; # 15 = 0000 1111 print "Line 6 - Value of c is ", c When you execute the above program it produces the following result − Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15
[ { "code": null, "e": 2446, "s": 2378, "text": "There are following Bitwise operators supported by Python language." }, { "code": null, "e": 2972, "s": 2446, "text": "#!/usr/bin/python\n\na = 60 # 60 = 0011 1100 \nb = 13 # 13 = 0000 1101 \nc = 0\n\nc = a & b; # 12 = 0000 1100\nprint \"Line 1 - Value of c is \", c\n\nc = a | b; # 61 = 0011 1101 \nprint \"Line 2 - Value of c is \", c\n\nc = a ^ b; # 49 = 0011 0001\nprint \"Line 3 - Value of c is \", c\n\nc = ~a; # -61 = 1100 0011\nprint \"Line 4 - Value of c is \", c\n\nc = a << 2; # 240 = 1111 0000\nprint \"Line 5 - Value of c is \", c\n\nc = a >> 2; # 15 = 0000 1111\nprint \"Line 6 - Value of c is \", c" }, { "code": null, "e": 3042, "s": 2972, "text": "When you execute the above program it produces the following result −" } ]
Merge Sort with O(1) extra space merge and O(n lg n) time [Unsigned Integers Only]
06 Jul, 2021 We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only. Examples: Input : 5 4 3 2 1 Output : 1 2 3 4 5 Input : 999 612 589 856 56 945 243 Output : 56 243 589 612 856 945 999 For integer types, merge sort can be made inplace using some mathematics trick of modulus and division. That means storing two elements value at one index and can be extracted using modulus and division. First we have to find a value greater than all the elements of the array. Now we can store the original value as modulus and the second value as division. Suppose we want to store arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value of arr[j]. So below is the implementation on merge sort. Approach: (Euclidean Division) dividend = divisor * quotient +remainder ex: 5/3 = q:1, r:2 applying euclidean: 3*1+2 =>5 (dividend) divisor = maxele (absolute max element in the array)+1 (so that we always get non zero remainder)quotient = min(first, second)remainder = original element Note: (when getting current element, assume the current container already has encoded element hence using % divisor)first = arr[i] % divisorsecond = arr[j] % divisor encoded element = remainder + quotient*divisor Possible issues in Merging: 1. If current number is Integer.MAX then new encoded value which is usually greater than current element will cause integer overflow and data corruption (In python there is no limit to number size so this issue will not occur). 2. Doesn’t handle negative numbers (ie, when encoding a -ve number(current) with another -ve number(chosen smallest) the sign can’t be preserved since both numbers have -ve sign. Also absolute values must be used when computing dividend = divisor*quotient+remainder (divisor = maxele, quotient = smallest, remainder = original) and sign must be restored, still it might not work due to sign preservation issue. 3. Only applicable to Unsigned integers, like indexes which are usually non-negative. 4. AUX = O(n) in worst case, assuming in a language like python where there is no limit to word/integer size, when input array elements are almost at Integer.MAX, then encoded value will require possibly 2x bits space to represent new number, the 2x bit space on whole can become +1x array size, which is almost like creating an AUX array but in an indirect way. 5. mod and division operations are the costliest, hence reduces overall performance(upto some extent). C++ Java Python3 C# Javascript // C++ program to sort an array using merge sort such// that merge operation takes O(1) extra space.#include <bits/stdc++.h>using namespace std;void merge(int arr[], int beg, int mid, int end, int maxele){ int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (int i = beg; i <= end; i++) arr[i] = arr[i] / maxele;} // Recursive merge sort with extra parameter, naxelevoid mergeSortRec(int arr[], int beg, int end, int maxele){ if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); }} // This functions finds max element and calls recursive// merge sort.void mergeSort(int arr[], int n){ int maxele = *max_element(arr, arr+n) + 1; mergeSortRec(arr, 0, n-1, maxele);} int main(){ int arr[] = { 999, 612, 589, 856, 56, 945, 243 }; int n = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, n); cout << "Sorted array \n"; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.import java.util.Arrays; class GFG{ static void merge(int[] arr, int beg, int mid, int end, int maxele) { int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (i = beg; i <= end; i++) { arr[i] = arr[i] / maxele; } } // Recursive merge sort // with extra parameter, naxele static void mergeSortRec(int[] arr, int beg, int end, int maxele) { if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); } } // This functions finds // max element and calls // recursive merge sort. static void mergeSort(int[] arr, int n) { int maxele = Arrays.stream(arr).max().getAsInt() + 1; mergeSortRec(arr, 0, n - 1, maxele); } // Driver code public static void main(String[] args) { int[] arr = {999, 612, 589, 856, 56, 945, 243}; int n = arr.length; mergeSort(arr, n); System.out.println("Sorted array "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }} // This code is contributed by 29AjayKumar # Python3 program to sort an array using# merge sort such that merge operation# takes O(1) extra space.def merge(arr, beg, mid, end, maxele): i = beg j = mid + 1 k = beg while (i <= mid and j <= end): if (arr[i] % maxele <= arr[j] % maxele): arr[k] = arr[k] + (arr[i] % maxele) * maxele k += 1 i += 1 else: arr[k] = arr[k] + (arr[j] % maxele) * maxele k += 1 j += 1 while (i <= mid): arr[k] = arr[k] + (arr[i] % maxele) * maxele k += 1 i += 1 while (j <= end): arr[k] = arr[k] + (arr[j] % maxele) * maxele k += 1 j += 1 # Obtaining actual values for i in range(beg, end + 1): arr[i] = arr[i] // maxele # Recursive merge sort with extra# parameter, naxeledef mergeSortRec(arr, beg, end, maxele): if (beg < end): mid = (beg + end) // 2 mergeSortRec(arr, beg, mid, maxele) mergeSortRec(arr, mid + 1, end, maxele) merge(arr, beg, mid, end, maxele) # This functions finds max element and# calls recursive merge sort.def mergeSort(arr, n): maxele = max(arr) + 1 mergeSortRec(arr, 0, n - 1, maxele) # Driver Codeif __name__ == '__main__': arr = [ 999, 612, 589, 856, 56, 945, 243 ] n = len(arr) mergeSort(arr, n) print("Sorted array") for i in range(n): print(arr[i], end = " ") # This code is contributed by mohit kumar 29 // C# program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.using System;using System.Linq; class GFG{static void merge(int []arr, int beg, int mid, int end, int maxele){ int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for ( i = beg; i <= end; i++) arr[i] = arr[i] / maxele;} // Recursive merge sort// with extra parameter, naxelestatic void mergeSortRec(int []arr, int beg, int end, int maxele){ if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); }} // This functions finds// max element and calls// recursive merge sort.static void mergeSort(int []arr, int n){ int maxele = arr.Max() + 1; mergeSortRec(arr, 0, n - 1, maxele);} //Driver codepublic static void Main (){ int []arr = {999, 612, 589, 856, 56, 945, 243}; int n = arr.Length; mergeSort(arr, n); Console.WriteLine("Sorted array "); for (int i = 0; i < n; i++) Console.Write( arr[i] + " ");}} // This code is contributed// by inder_verma. <script>// Javascript program to sort an array// using merge sort such that// merge operation takes O(1)// extra space. function merge(arr,beg,mid,end,maxele) { let i = beg; let j = mid + 1; let k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (i = beg; i <= end; i++) { arr[i] = Math.floor(arr[i] / maxele); } } // Recursive merge sort // with extra parameter, naxele function mergeSortRec(arr,beg,end,maxele) { if (beg < end) { let mid = Math.floor((beg + end) / 2); mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); } } // This functions finds // max element and calls // recursive merge sort. function mergeSort(arr,n) { let maxele = Math.max(...arr) + 1; mergeSortRec(arr, 0, n - 1, maxele); } // Driver code let arr=[999, 612, 589, 856, 56, 945, 243]; let n = arr.length; mergeSort(arr, n); document.write("Sorted array <br>"); for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } // This code is contributed by patel2127</script> Sorted array 56 243 589 612 856 945 999 inderDuMCA 29AjayKumar mohit kumar 29 patel2127 mahee96 Merge Sort Modular Arithmetic Divide and Conquer Mathematical Sorting Mathematical Divide and Conquer Sorting Modular Arithmetic Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2021" }, { "code": null, "e": 251, "s": 52, "text": "We have discussed Merge sort. How to modify the algorithm so that merge works in O(1) extra space and algorithm still works in O(n Log n) time. We may assume that the input values are integers only." }, { "code": null, "e": 262, "s": 251, "text": "Examples: " }, { "code": null, "e": 371, "s": 262, "text": "Input : 5 4 3 2 1\nOutput : 1 2 3 4 5\n\nInput : 999 612 589 856 56 945 243\nOutput : 56 243 589 612 856 945 999" }, { "code": null, "e": 576, "s": 371, "text": "For integer types, merge sort can be made inplace using some mathematics trick of modulus and division. That means storing two elements value at one index and can be extracted using modulus and division. " }, { "code": null, "e": 1083, "s": 576, "text": "First we have to find a value greater than all the elements of the array. Now we can store the original value as modulus and the second value as division. Suppose we want to store arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value of arr[j]. So below is the implementation on merge sort." }, { "code": null, "e": 1114, "s": 1083, "text": "Approach: (Euclidean Division)" }, { "code": null, "e": 1198, "s": 1114, "text": " dividend = divisor * quotient +remainder" }, { "code": null, "e": 1261, "s": 1198, "text": "ex: 5/3 = q:1, r:2 applying euclidean: 3*1+2 =>5 (dividend)" }, { "code": null, "e": 1416, "s": 1261, "text": "divisor = maxele (absolute max element in the array)+1 (so that we always get non zero remainder)quotient = min(first, second)remainder = original element" }, { "code": null, "e": 1583, "s": 1416, "text": "Note: (when getting current element, assume the current container already has encoded element hence using % divisor)first = arr[i] % divisorsecond = arr[j] % divisor " }, { "code": null, "e": 1630, "s": 1583, "text": "encoded element = remainder + quotient*divisor" }, { "code": null, "e": 1658, "s": 1630, "text": "Possible issues in Merging:" }, { "code": null, "e": 1886, "s": 1658, "text": "1. If current number is Integer.MAX then new encoded value which is usually greater than current element will cause integer overflow and data corruption (In python there is no limit to number size so this issue will not occur)." }, { "code": null, "e": 2297, "s": 1886, "text": "2. Doesn’t handle negative numbers (ie, when encoding a -ve number(current) with another -ve number(chosen smallest) the sign can’t be preserved since both numbers have -ve sign. Also absolute values must be used when computing dividend = divisor*quotient+remainder (divisor = maxele, quotient = smallest, remainder = original) and sign must be restored, still it might not work due to sign preservation issue." }, { "code": null, "e": 2383, "s": 2297, "text": "3. Only applicable to Unsigned integers, like indexes which are usually non-negative." }, { "code": null, "e": 2746, "s": 2383, "text": "4. AUX = O(n) in worst case, assuming in a language like python where there is no limit to word/integer size, when input array elements are almost at Integer.MAX, then encoded value will require possibly 2x bits space to represent new number, the 2x bit space on whole can become +1x array size, which is almost like creating an AUX array but in an indirect way." }, { "code": null, "e": 2849, "s": 2746, "text": "5. mod and division operations are the costliest, hence reduces overall performance(upto some extent)." }, { "code": null, "e": 2853, "s": 2849, "text": "C++" }, { "code": null, "e": 2858, "s": 2853, "text": "Java" }, { "code": null, "e": 2866, "s": 2858, "text": "Python3" }, { "code": null, "e": 2869, "s": 2866, "text": "C#" }, { "code": null, "e": 2880, "s": 2869, "text": "Javascript" }, { "code": "// C++ program to sort an array using merge sort such// that merge operation takes O(1) extra space.#include <bits/stdc++.h>using namespace std;void merge(int arr[], int beg, int mid, int end, int maxele){ int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (int i = beg; i <= end; i++) arr[i] = arr[i] / maxele;} // Recursive merge sort with extra parameter, naxelevoid mergeSortRec(int arr[], int beg, int end, int maxele){ if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); }} // This functions finds max element and calls recursive// merge sort.void mergeSort(int arr[], int n){ int maxele = *max_element(arr, arr+n) + 1; mergeSortRec(arr, 0, n-1, maxele);} int main(){ int arr[] = { 999, 612, 589, 856, 56, 945, 243 }; int n = sizeof(arr) / sizeof(arr[0]); mergeSort(arr, n); cout << \"Sorted array \\n\"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 4476, "s": 2880, "text": null }, { "code": "// Java program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.import java.util.Arrays; class GFG{ static void merge(int[] arr, int beg, int mid, int end, int maxele) { int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (i = beg; i <= end; i++) { arr[i] = arr[i] / maxele; } } // Recursive merge sort // with extra parameter, naxele static void mergeSortRec(int[] arr, int beg, int end, int maxele) { if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); } } // This functions finds // max element and calls // recursive merge sort. static void mergeSort(int[] arr, int n) { int maxele = Arrays.stream(arr).max().getAsInt() + 1; mergeSortRec(arr, 0, n - 1, maxele); } // Driver code public static void main(String[] args) { int[] arr = {999, 612, 589, 856, 56, 945, 243}; int n = arr.length; mergeSort(arr, n); System.out.println(\"Sorted array \"); for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }} // This code is contributed by 29AjayKumar", "e": 6763, "s": 4476, "text": null }, { "code": "# Python3 program to sort an array using# merge sort such that merge operation# takes O(1) extra space.def merge(arr, beg, mid, end, maxele): i = beg j = mid + 1 k = beg while (i <= mid and j <= end): if (arr[i] % maxele <= arr[j] % maxele): arr[k] = arr[k] + (arr[i] % maxele) * maxele k += 1 i += 1 else: arr[k] = arr[k] + (arr[j] % maxele) * maxele k += 1 j += 1 while (i <= mid): arr[k] = arr[k] + (arr[i] % maxele) * maxele k += 1 i += 1 while (j <= end): arr[k] = arr[k] + (arr[j] % maxele) * maxele k += 1 j += 1 # Obtaining actual values for i in range(beg, end + 1): arr[i] = arr[i] // maxele # Recursive merge sort with extra# parameter, naxeledef mergeSortRec(arr, beg, end, maxele): if (beg < end): mid = (beg + end) // 2 mergeSortRec(arr, beg, mid, maxele) mergeSortRec(arr, mid + 1, end, maxele) merge(arr, beg, mid, end, maxele) # This functions finds max element and# calls recursive merge sort.def mergeSort(arr, n): maxele = max(arr) + 1 mergeSortRec(arr, 0, n - 1, maxele) # Driver Codeif __name__ == '__main__': arr = [ 999, 612, 589, 856, 56, 945, 243 ] n = len(arr) mergeSort(arr, n) print(\"Sorted array\") for i in range(n): print(arr[i], end = \" \") # This code is contributed by mohit kumar 29", "e": 8300, "s": 6763, "text": null }, { "code": "// C# program to sort an array// using merge sort such that// merge operation takes O(1)// extra space.using System;using System.Linq; class GFG{static void merge(int []arr, int beg, int mid, int end, int maxele){ int i = beg; int j = mid + 1; int k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for ( i = beg; i <= end; i++) arr[i] = arr[i] / maxele;} // Recursive merge sort// with extra parameter, naxelestatic void mergeSortRec(int []arr, int beg, int end, int maxele){ if (beg < end) { int mid = (beg + end) / 2; mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); }} // This functions finds// max element and calls// recursive merge sort.static void mergeSort(int []arr, int n){ int maxele = arr.Max() + 1; mergeSortRec(arr, 0, n - 1, maxele);} //Driver codepublic static void Main (){ int []arr = {999, 612, 589, 856, 56, 945, 243}; int n = arr.Length; mergeSort(arr, n); Console.WriteLine(\"Sorted array \"); for (int i = 0; i < n; i++) Console.Write( arr[i] + \" \");}} // This code is contributed// by inder_verma.", "e": 10227, "s": 8300, "text": null }, { "code": "<script>// Javascript program to sort an array// using merge sort such that// merge operation takes O(1)// extra space. function merge(arr,beg,mid,end,maxele) { let i = beg; let j = mid + 1; let k = beg; while (i <= mid && j <= end) { if (arr[i] % maxele <= arr[j] % maxele) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } else { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } } while (i <= mid) { arr[k] = arr[k] + (arr[i] % maxele) * maxele; k++; i++; } while (j <= end) { arr[k] = arr[k] + (arr[j] % maxele) * maxele; k++; j++; } // Obtaining actual values for (i = beg; i <= end; i++) { arr[i] = Math.floor(arr[i] / maxele); } } // Recursive merge sort // with extra parameter, naxele function mergeSortRec(arr,beg,end,maxele) { if (beg < end) { let mid = Math.floor((beg + end) / 2); mergeSortRec(arr, beg, mid, maxele); mergeSortRec(arr, mid + 1, end, maxele); merge(arr, beg, mid, end, maxele); } } // This functions finds // max element and calls // recursive merge sort. function mergeSort(arr,n) { let maxele = Math.max(...arr) + 1; mergeSortRec(arr, 0, n - 1, maxele); } // Driver code let arr=[999, 612, 589, 856, 56, 945, 243]; let n = arr.length; mergeSort(arr, n); document.write(\"Sorted array <br>\"); for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } // This code is contributed by patel2127</script>", "e": 12355, "s": 10227, "text": null }, { "code": null, "e": 12396, "s": 12355, "text": "Sorted array \n56 243 589 612 856 945 999" }, { "code": null, "e": 12409, "s": 12398, "text": "inderDuMCA" }, { "code": null, "e": 12421, "s": 12409, "text": "29AjayKumar" }, { "code": null, "e": 12436, "s": 12421, "text": "mohit kumar 29" }, { "code": null, "e": 12446, "s": 12436, "text": "patel2127" }, { "code": null, "e": 12454, "s": 12446, "text": "mahee96" }, { "code": null, "e": 12465, "s": 12454, "text": "Merge Sort" }, { "code": null, "e": 12484, "s": 12465, "text": "Modular Arithmetic" }, { "code": null, "e": 12503, "s": 12484, "text": "Divide and Conquer" }, { "code": null, "e": 12516, "s": 12503, "text": "Mathematical" }, { "code": null, "e": 12524, "s": 12516, "text": "Sorting" }, { "code": null, "e": 12537, "s": 12524, "text": "Mathematical" }, { "code": null, "e": 12556, "s": 12537, "text": "Divide and Conquer" }, { "code": null, "e": 12564, "s": 12556, "text": "Sorting" }, { "code": null, "e": 12583, "s": 12564, "text": "Modular Arithmetic" }, { "code": null, "e": 12594, "s": 12583, "text": "Merge Sort" } ]
How Does Back-Propagation in Artificial Neural Networks Work? | by Anas Al-Masri | Towards Data Science
Ever since the world of Machine Learning was introduced to non-linear functions that work recursively (i.e. Artificial Neural Networks), the applications of which boomed noticeably. In this context, proper training of a Neural Network is the most important aspect of making a reliable model. This training is usually associated with the term “Back-propagation”, which is highly vague to most people getting into Deep Learning. Heck, most people in the industry don’t even know how it works — they just know it does! Back-propagation is the essence of neural net training. It is the practice of fine-tuning the weights of a neural net based on the error rate (i.e. loss) obtained in the previous epoch (i.e. iteration). Proper tuning of the weights ensures lower error rates, making the model reliable by increasing its generalization. So how does this process work, with the vast simultaneous mini-executions involved? Let’s learn by example! In order to make this example as subjective as possible, we’re just going to touch on related concepts (e.g. loss functions, optimization functions, etc.) without explaining them, as these topics deserve their own series. Imagine that we have a deep neural network that we need to train. The purpose of training is to build a model that performs the XOR (exclusive OR) functionality with two inputs and three hidden units, such that the training set (truth table) looks something like the following: X1 | X2 | Y0 | 0 | 00 | 1 | 11 | 0 | 1 1 | 1 | 0 Moreover, we need an activation function that determines the activation value at every node in the neural net. For simplicity, let’s choose an identity activation function: f(a) = a We also need a hypothesis function that determines what the input to the activation function is. This function is going to be the typical, ever-famous: h(X) = W0.X0 + W1.X1 + W2.X2 orh(X) = sigma(W.X) for all (W, X) Let’s also choose the loss function to be the usual cost function of logistic regression, which looks a bit complicated but is actually fairly simple: Furthermore, we’re going to use the Batch Gradient Descent optimization function to determine in what direction we should adjust the weights to get a lower loss than the one we currently have. Finally, the learning rate will be 0.1 and all the weights will be initialized to 1. Let’s finally draw a diagram of our long-awaited neural net. It should look something like this: The leftmost layer is the input layer, which takes X0 as the bias term of value 1, and X1 and X2 as input features. The layer in the middle is the first hidden layer, which also takes a bias term Z0 of value 1. Finally, the output layer has only one output unit D0 whose activation value is the actual output of the model (i.e. h(x)). It is now the time to feed-forward the information from one layer to the next. This goes through two steps that happen at every node/unit in the network: 1- Getting the weighted sum of inputs of a particular unit using the h(x) function we defined earlier. 2- Plugging the value we get from step 1 into the activation function we have (f(a)=a in this example) and using the activation value we get (i.e. the output of the activation function) as the input feature for the connected nodes in the next layer. Note that units X0, X1, X2 and Z0 do not have any units connected to them and providing inputs. Therefore, the steps mentioned above do not occur in those nodes. However, for the rest of the nodes/units, this is how it all happens throughout the neural net for the first input sample in the training set: Unit Z1: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1 and same goes for the rest of the units: Unit Z2: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1Unit Z3: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1Unit D0: h(x) = W0.Z0 + W1.Z1 + W2.Z2 + W3.Z3 = 1 . 1 + 1 . 1 + 1 . 1 + 1 . 1 = 4 = a z = f(a) = a => z = f(4) = 4 As we mentioned earlier, the activation value (z) of the final unit (D0) is that of the whole model. Therefore, our model predicted an output of 1 for the set of inputs {0, 0}. Calculating the loss/cost of the current iteration would follow: Loss = actual_y - predicted_y = 0 - 4 = -4 The actual_y value comes from the training set, while the predicted_y value is what our model yielded. So the cost at this iteration is equal to -4. According to our example, we now have a model that does not give accurate predictions (it gave us the value 4 instead of 1) and that is attributed to the fact that its weights have not been tuned yet (they are all equal to 1). We also have the loss, that is equal to -4. Back-propagation is all about feeding this loss backwards in such a way that we can fine-tune the weights based on which. The optimization function (Gradient Descent in our example) will help us find the weights that will — hopefully — yield a smaller loss in the next iteration. So let’s get to it! If feeding forward happened using the following functions: f(a) = a Then feeding backward will happen through the partial derivatives of those functions. There is no need to go through the working of arriving at these derivatives. All we need to know is that the above functions will follow: f'(a) = 1J'(w) = Z . delta where Z is just the z value we obtained from the activation function calculations in the feed-forward step, while delta is the loss of the unit in the layer. I know it’s a lot of information to absorb in one sitting, but I suggest you take your time and really understand what is going on at every step before going further. Now we need to find the loss at every unit/node in the neural net. Why is that? Well, think about it this way, every loss the the deep learning model arrives to is actually the mess that was caused by all the nodes accumulated into one number. Therefore, we need to find out which node is responsible for most of the loss in every layer, so that we can penalize it in a sense by giving it a smaller weight value and thus lessening the total loss of the model. Calculating the delta of every unit can be problematic. However, thanks to Mr. Andrew Ng, he gave us the shortcut formula for the whole thing: delta_0 = w . delta_1 . f'(z) where values delta_0, w and f’(z) are those of the same unit’s, while delta_1 is the loss of the unit on the other side of the weighted link. For example: You can think of it this way, in order to get the loss of a node (e.g. Z0), we multiply the value of its corresponding f’(z) by the loss of the node it is connected to in the next layer (delta_1), by the weight of the link connecting both nodes. This is exactly how back-propagation works. We do the delta calculation step at every unit, back-propagating the loss into the neural net, and finding out what loss every node/unit is responsible for. Let’s calculate those deltas and get it over with! delta_D0 = total_loss = -4delta_Z0 = W . delta_D0 . f'(Z0) = 1 . (-4) . 1 = -4delta_Z1 = W . delta_D0 . f'(Z1) = 1 . (-4) . 1 = -4delta_Z2 = W . delta_D0 . f'(Z2) = 1 . (-4) . 1 = -4delta_Z3 = W . delta_D0 . f'(Z3) = 1 . (-4) . 1 = -4 There are a few things to notice here: The loss of the final unit (i.e. D0) is equal to the loss of the whole model. This is because it is the output unit, and its loss is the accumulated loss of all the units together, like we said earlier. The function f’(z) will always give the value 1, no matter what the input (i.e. z) is equal to. This is because the partial derivative, as we said earlier, follows: f’(a) = 1 The input nodes/units (X0, X1 and X2) do not have delta values, as there is nothing those nodes control in the neural net. They are only there as a link between the data set and the neural net. This is merely why the whole layer is usually not included in the layer count. All that is left now is to update all the weights we have in the neural net. This follows the Batch Gradient Descent formula: W := W - alpha . J'(W) Where W is the weight at hand, alpha is the learning rate (i.e. 0.1 in our example) and J’(W) is the partial derivative of the cost function J(W) with respect to W. Again, there’s no need for us to get into the math. Therefore, let’s use Mr. Andrew Ng’s partial derivative of the function: J'(W) = Z . delta Where Z is the Z value obtained through forward-propagation, and delta is the loss at the unit on the other end of the weighted link: Now we use the Batch Gradient Descent weight update on all the weights, utilizing our partial derivative values that we obtain at every step. It is worth emphasizing on that the Z values of the input nodes (X0, X1, and X2) are equal to 1, 0, 0, respectively. The 1 is the value of the bias unit, while the zeroes are actually the feature input values coming from the data set. One last note is that there is no particular order to updating the weights. You can update them in any order you want, as long as you don’t make the mistake of updating any weight twice in the same iteration. In order to calculate the new weights, let’s give the links in our neural nets names: New weight calculations will happen as follows: W10 := W10 - alpha . Z_X0 . delta_Z1 = 1 - 0.1 . 1 . (-4) = 1.4W20 := W20 - alpha . Z_X0 . delta_Z2 = 1 - 0.1 . 1 . (-4) = 1.4. . . . .. . . . .. . . . .W30 := 1.4W11 := 1.4W21 := 1.4W31 := 1.4W12 := 1.4W22 := 1.4W32 := 1.4V00 := V00 - alpha . Z_Z0 . delta_D0 = 1 - 0.1 . 1 . (-4) = 1.4V01 := 1.4V02 := 1.4V03 := 1.4 It is important to note here that the model is not trained properly yet, as we only back-propagated through one sample from the training set. Doing all we did all over again for all the samples will yield a model with better accuracy as we go, trying to get closer to the minimum loss/cost at every step. It might not make sense to you that all the weights have the same value again. However, training the model on different samples over and over again will result in nodes having different weights based on their contributions to the total loss. The theory behind Machine Learning can be really difficult to grasp if not tackled the right way. One example of this would be Back-propagation, whose effectiveness is visible in most real-world Deep Learning applications, but it is never examined. Back-propagation is just a way of propagating the total loss back into the neural network to know how much of the loss every node is responsible for, and subsequently updating the weights in such a way that minimizes the loss by giving the nodes with higher error rates lower weights and vice versa.
[ { "code": null, "e": 688, "s": 172, "text": "Ever since the world of Machine Learning was introduced to non-linear functions that work recursively (i.e. Artificial Neural Networks), the applications of which boomed noticeably. In this context, proper training of a Neural Network is the most important aspect of making a reliable model. This training is usually associated with the term “Back-propagation”, which is highly vague to most people getting into Deep Learning. Heck, most people in the industry don’t even know how it works — they just know it does!" }, { "code": null, "e": 1007, "s": 688, "text": "Back-propagation is the essence of neural net training. It is the practice of fine-tuning the weights of a neural net based on the error rate (i.e. loss) obtained in the previous epoch (i.e. iteration). Proper tuning of the weights ensures lower error rates, making the model reliable by increasing its generalization." }, { "code": null, "e": 1115, "s": 1007, "text": "So how does this process work, with the vast simultaneous mini-executions involved? Let’s learn by example!" }, { "code": null, "e": 1337, "s": 1115, "text": "In order to make this example as subjective as possible, we’re just going to touch on related concepts (e.g. loss functions, optimization functions, etc.) without explaining them, as these topics deserve their own series." }, { "code": null, "e": 1615, "s": 1337, "text": "Imagine that we have a deep neural network that we need to train. The purpose of training is to build a model that performs the XOR (exclusive OR) functionality with two inputs and three hidden units, such that the training set (truth table) looks something like the following:" }, { "code": null, "e": 1672, "s": 1615, "text": "X1 | X2 | Y0 | 0 | 00 | 1 | 11 | 0 | 1 1 | 1 | 0" }, { "code": null, "e": 1845, "s": 1672, "text": "Moreover, we need an activation function that determines the activation value at every node in the neural net. For simplicity, let’s choose an identity activation function:" }, { "code": null, "e": 1854, "s": 1845, "text": "f(a) = a" }, { "code": null, "e": 2006, "s": 1854, "text": "We also need a hypothesis function that determines what the input to the activation function is. This function is going to be the typical, ever-famous:" }, { "code": null, "e": 2082, "s": 2006, "text": "h(X) = W0.X0 + W1.X1 + W2.X2 orh(X) = sigma(W.X) for all (W, X)" }, { "code": null, "e": 2233, "s": 2082, "text": "Let’s also choose the loss function to be the usual cost function of logistic regression, which looks a bit complicated but is actually fairly simple:" }, { "code": null, "e": 2511, "s": 2233, "text": "Furthermore, we’re going to use the Batch Gradient Descent optimization function to determine in what direction we should adjust the weights to get a lower loss than the one we currently have. Finally, the learning rate will be 0.1 and all the weights will be initialized to 1." }, { "code": null, "e": 2608, "s": 2511, "text": "Let’s finally draw a diagram of our long-awaited neural net. It should look something like this:" }, { "code": null, "e": 2943, "s": 2608, "text": "The leftmost layer is the input layer, which takes X0 as the bias term of value 1, and X1 and X2 as input features. The layer in the middle is the first hidden layer, which also takes a bias term Z0 of value 1. Finally, the output layer has only one output unit D0 whose activation value is the actual output of the model (i.e. h(x))." }, { "code": null, "e": 3097, "s": 2943, "text": "It is now the time to feed-forward the information from one layer to the next. This goes through two steps that happen at every node/unit in the network:" }, { "code": null, "e": 3200, "s": 3097, "text": "1- Getting the weighted sum of inputs of a particular unit using the h(x) function we defined earlier." }, { "code": null, "e": 3450, "s": 3200, "text": "2- Plugging the value we get from step 1 into the activation function we have (f(a)=a in this example) and using the activation value we get (i.e. the output of the activation function) as the input feature for the connected nodes in the next layer." }, { "code": null, "e": 3755, "s": 3450, "text": "Note that units X0, X1, X2 and Z0 do not have any units connected to them and providing inputs. Therefore, the steps mentioned above do not occur in those nodes. However, for the rest of the nodes/units, this is how it all happens throughout the neural net for the first input sample in the training set:" }, { "code": null, "e": 3892, "s": 3755, "text": "Unit Z1: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1" }, { "code": null, "e": 3933, "s": 3892, "text": "and same goes for the rest of the units:" }, { "code": null, "e": 4358, "s": 3933, "text": "Unit Z2: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1Unit Z3: h(x) = W0.X0 + W1.X1 + W2.X2 = 1 . 1 + 1 . 0 + 1 . 0 = 1 = a z = f(a) = a => z = f(1) = 1Unit D0: h(x) = W0.Z0 + W1.Z1 + W2.Z2 + W3.Z3 = 1 . 1 + 1 . 1 + 1 . 1 + 1 . 1 = 4 = a z = f(a) = a => z = f(4) = 4" }, { "code": null, "e": 4600, "s": 4358, "text": "As we mentioned earlier, the activation value (z) of the final unit (D0) is that of the whole model. Therefore, our model predicted an output of 1 for the set of inputs {0, 0}. Calculating the loss/cost of the current iteration would follow:" }, { "code": null, "e": 4665, "s": 4600, "text": "Loss = actual_y - predicted_y = 0 - 4 = -4" }, { "code": null, "e": 4814, "s": 4665, "text": "The actual_y value comes from the training set, while the predicted_y value is what our model yielded. So the cost at this iteration is equal to -4." }, { "code": null, "e": 5385, "s": 4814, "text": "According to our example, we now have a model that does not give accurate predictions (it gave us the value 4 instead of 1) and that is attributed to the fact that its weights have not been tuned yet (they are all equal to 1). We also have the loss, that is equal to -4. Back-propagation is all about feeding this loss backwards in such a way that we can fine-tune the weights based on which. The optimization function (Gradient Descent in our example) will help us find the weights that will — hopefully — yield a smaller loss in the next iteration. So let’s get to it!" }, { "code": null, "e": 5444, "s": 5385, "text": "If feeding forward happened using the following functions:" }, { "code": null, "e": 5453, "s": 5444, "text": "f(a) = a" }, { "code": null, "e": 5677, "s": 5453, "text": "Then feeding backward will happen through the partial derivatives of those functions. There is no need to go through the working of arriving at these derivatives. All we need to know is that the above functions will follow:" }, { "code": null, "e": 5704, "s": 5677, "text": "f'(a) = 1J'(w) = Z . delta" }, { "code": null, "e": 5862, "s": 5704, "text": "where Z is just the z value we obtained from the activation function calculations in the feed-forward step, while delta is the loss of the unit in the layer." }, { "code": null, "e": 6029, "s": 5862, "text": "I know it’s a lot of information to absorb in one sitting, but I suggest you take your time and really understand what is going on at every step before going further." }, { "code": null, "e": 6489, "s": 6029, "text": "Now we need to find the loss at every unit/node in the neural net. Why is that? Well, think about it this way, every loss the the deep learning model arrives to is actually the mess that was caused by all the nodes accumulated into one number. Therefore, we need to find out which node is responsible for most of the loss in every layer, so that we can penalize it in a sense by giving it a smaller weight value and thus lessening the total loss of the model." }, { "code": null, "e": 6632, "s": 6489, "text": "Calculating the delta of every unit can be problematic. However, thanks to Mr. Andrew Ng, he gave us the shortcut formula for the whole thing:" }, { "code": null, "e": 6662, "s": 6632, "text": "delta_0 = w . delta_1 . f'(z)" }, { "code": null, "e": 6817, "s": 6662, "text": "where values delta_0, w and f’(z) are those of the same unit’s, while delta_1 is the loss of the unit on the other side of the weighted link. For example:" }, { "code": null, "e": 7063, "s": 6817, "text": "You can think of it this way, in order to get the loss of a node (e.g. Z0), we multiply the value of its corresponding f’(z) by the loss of the node it is connected to in the next layer (delta_1), by the weight of the link connecting both nodes." }, { "code": null, "e": 7264, "s": 7063, "text": "This is exactly how back-propagation works. We do the delta calculation step at every unit, back-propagating the loss into the neural net, and finding out what loss every node/unit is responsible for." }, { "code": null, "e": 7315, "s": 7264, "text": "Let’s calculate those deltas and get it over with!" }, { "code": null, "e": 7550, "s": 7315, "text": "delta_D0 = total_loss = -4delta_Z0 = W . delta_D0 . f'(Z0) = 1 . (-4) . 1 = -4delta_Z1 = W . delta_D0 . f'(Z1) = 1 . (-4) . 1 = -4delta_Z2 = W . delta_D0 . f'(Z2) = 1 . (-4) . 1 = -4delta_Z3 = W . delta_D0 . f'(Z3) = 1 . (-4) . 1 = -4" }, { "code": null, "e": 7589, "s": 7550, "text": "There are a few things to notice here:" }, { "code": null, "e": 7792, "s": 7589, "text": "The loss of the final unit (i.e. D0) is equal to the loss of the whole model. This is because it is the output unit, and its loss is the accumulated loss of all the units together, like we said earlier." }, { "code": null, "e": 7967, "s": 7792, "text": "The function f’(z) will always give the value 1, no matter what the input (i.e. z) is equal to. This is because the partial derivative, as we said earlier, follows: f’(a) = 1" }, { "code": null, "e": 8240, "s": 7967, "text": "The input nodes/units (X0, X1 and X2) do not have delta values, as there is nothing those nodes control in the neural net. They are only there as a link between the data set and the neural net. This is merely why the whole layer is usually not included in the layer count." }, { "code": null, "e": 8366, "s": 8240, "text": "All that is left now is to update all the weights we have in the neural net. This follows the Batch Gradient Descent formula:" }, { "code": null, "e": 8389, "s": 8366, "text": "W := W - alpha . J'(W)" }, { "code": null, "e": 8679, "s": 8389, "text": "Where W is the weight at hand, alpha is the learning rate (i.e. 0.1 in our example) and J’(W) is the partial derivative of the cost function J(W) with respect to W. Again, there’s no need for us to get into the math. Therefore, let’s use Mr. Andrew Ng’s partial derivative of the function:" }, { "code": null, "e": 8697, "s": 8679, "text": "J'(W) = Z . delta" }, { "code": null, "e": 8831, "s": 8697, "text": "Where Z is the Z value obtained through forward-propagation, and delta is the loss at the unit on the other end of the weighted link:" }, { "code": null, "e": 9417, "s": 8831, "text": "Now we use the Batch Gradient Descent weight update on all the weights, utilizing our partial derivative values that we obtain at every step. It is worth emphasizing on that the Z values of the input nodes (X0, X1, and X2) are equal to 1, 0, 0, respectively. The 1 is the value of the bias unit, while the zeroes are actually the feature input values coming from the data set. One last note is that there is no particular order to updating the weights. You can update them in any order you want, as long as you don’t make the mistake of updating any weight twice in the same iteration." }, { "code": null, "e": 9503, "s": 9417, "text": "In order to calculate the new weights, let’s give the links in our neural nets names:" }, { "code": null, "e": 9551, "s": 9503, "text": "New weight calculations will happen as follows:" }, { "code": null, "e": 9982, "s": 9551, "text": "W10 := W10 - alpha . Z_X0 . delta_Z1 = 1 - 0.1 . 1 . (-4) = 1.4W20 := W20 - alpha . Z_X0 . delta_Z2 = 1 - 0.1 . 1 . (-4) = 1.4. . . . .. . . . .. . . . .W30 := 1.4W11 := 1.4W21 := 1.4W31 := 1.4W12 := 1.4W22 := 1.4W32 := 1.4V00 := V00 - alpha . Z_Z0 . delta_D0 = 1 - 0.1 . 1 . (-4) = 1.4V01 := 1.4V02 := 1.4V03 := 1.4" }, { "code": null, "e": 10287, "s": 9982, "text": "It is important to note here that the model is not trained properly yet, as we only back-propagated through one sample from the training set. Doing all we did all over again for all the samples will yield a model with better accuracy as we go, trying to get closer to the minimum loss/cost at every step." }, { "code": null, "e": 10529, "s": 10287, "text": "It might not make sense to you that all the weights have the same value again. However, training the model on different samples over and over again will result in nodes having different weights based on their contributions to the total loss." } ]
How to add NOT NULL constraint to an already created MySQL column?
Achieve this using ALTER TABLE. Let us first create a table − mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.86 sec) Let us check the description of the table − mysql> desc DemoTable; This will produce the following output − +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 2 rows in set (0.01 sec) Here is the query to add a NOT NULL constraint to the other column “StudentName”, which wasn’t set NOT NULL initially − mysql> alter table DemoTable modify StudentName varchar(100) NOT NULL; Query OK, 0 rows affected (1.57 sec) Records: 0 Duplicates: 0 Warnings: 0 Let us check the description of the table once again − mysql> desc DemoTable; This will produce the following output − +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1124, "s": 1062, "text": "Achieve this using ALTER TABLE. Let us first create a table −" }, { "code": null, "e": 1296, "s": 1124, "text": "mysql> create table DemoTable\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.86 sec)" }, { "code": null, "e": 1340, "s": 1296, "text": "Let us check the description of the table −" }, { "code": null, "e": 1363, "s": 1340, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 1404, "s": 1363, "text": "This will produce the following output −" }, { "code": null, "e": 1855, "s": 1404, "text": "+-------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | YES | | NULL | |\n+-------------+--------------+------+-----+---------+----------------+\n2 rows in set (0.01 sec)" }, { "code": null, "e": 1975, "s": 1855, "text": "Here is the query to add a NOT NULL constraint to the other column “StudentName”, which wasn’t set NOT NULL initially −" }, { "code": null, "e": 2120, "s": 1975, "text": "mysql> alter table DemoTable modify StudentName varchar(100) NOT NULL;\nQuery OK, 0 rows affected (1.57 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2175, "s": 2120, "text": "Let us check the description of the table once again −" }, { "code": null, "e": 2198, "s": 2175, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 2239, "s": 2198, "text": "This will produce the following output −" }, { "code": null, "e": 2690, "s": 2239, "text": "+-------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentName | varchar(100) | NO | | NULL | |\n+-------------+--------------+------+-----+---------+----------------+\n2 rows in set (0.00 sec)" } ]
CSS Variables - GeeksforGeeks
21 Oct, 2021 The variables in CSS are just like simple variables of any other programming language. These variables are used to store values and have a scope in which the variables can be used. A variable is defined by using two dashes(–) at the beginning and then the name which is case-sensitive. The benefit of variables is that it allows the same values to be reused at multiple places and updated/modified from one place. Also, the variable names are easier to understand and use, as compared to the values of colors, as it avoids of being copying & pasting the value of the colors over and over again. Syntax: var( --custom-name, value ); The var() function can be used to take the values of the variables in CSS. Parameters: The variable var() accepts two parameters which are listed below: –custom-name: It is a required parameter that accepts the custom property name starting with two dashes. value: It is an optional parameter. It accepts a fallback value which is used when a custom property is invalid. Working of CSS var() function: The scope of the variables in CSS can either be local or global. We can utilize the global variables in the entire document whereas the local variable can only be used inside the selector where the variable is declared, within the scope. For creating the variables with global scope, we need to declare the variable inside the :root selector, where it compares for the document’s root element. For creating the variable in the local scope, we can declare the variable inside the selector where it can be used within the scope. We will understand the above concepts through the examples. Example 1: This example illustrates the use of the var() function to declare & access the variable globally, inside the :root selector. HTML <!DOCTYPE html><html><head> <title>CSS Variables</title> <style> :root { --bg-color: green; --txt-color: white; } /* var() function used here */ body { background-color: var(--bg-color); } h1 { color: var(--txt-color); } div { color: var(--txt-color); } </style></head> <body> <h1>GeeksforGeeks</h1> <div> A computer science portal for geeks </div></body></html> Output: Example 2: This example illustrates the use of the CSS variables for declaring the variable name, instead of copying and pasting the same colors multiple times. HTML <!DOCTYPE html><html><head> <title>CSS Variables</title> <style> :root { --bg-color: green; } /* var() function used here */ body { background-color: var(--bg-color); } h1 { color: var(--txt-color, white); } div { color: var(--txt-color, white); } </style></head> <body> <h1>GeeksforGeeks</h1> <div> A computer science portal for geeks </div></body></html> Output: Supported Browsers: The browser supported by CSS variables are listed below: Google Chrome 49.0 Microsoft Edge 15.0 Firefox 31.0 Safari 9.1 opera 36.0 bhaskargeeksforgeeks CSS-Basics Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28046, "s": 28018, "text": "\n21 Oct, 2021" }, { "code": null, "e": 28641, "s": 28046, "text": "The variables in CSS are just like simple variables of any other programming language. These variables are used to store values and have a scope in which the variables can be used. A variable is defined by using two dashes(–) at the beginning and then the name which is case-sensitive. The benefit of variables is that it allows the same values to be reused at multiple places and updated/modified from one place. Also, the variable names are easier to understand and use, as compared to the values of colors, as it avoids of being copying & pasting the value of the colors over and over again." }, { "code": null, "e": 28649, "s": 28641, "text": "Syntax:" }, { "code": null, "e": 28678, "s": 28649, "text": "var( --custom-name, value );" }, { "code": null, "e": 28753, "s": 28678, "text": "The var() function can be used to take the values of the variables in CSS." }, { "code": null, "e": 28831, "s": 28753, "text": "Parameters: The variable var() accepts two parameters which are listed below:" }, { "code": null, "e": 28936, "s": 28831, "text": "–custom-name: It is a required parameter that accepts the custom property name starting with two dashes." }, { "code": null, "e": 29049, "s": 28936, "text": "value: It is an optional parameter. It accepts a fallback value which is used when a custom property is invalid." }, { "code": null, "e": 29607, "s": 29049, "text": "Working of CSS var() function: The scope of the variables in CSS can either be local or global. We can utilize the global variables in the entire document whereas the local variable can only be used inside the selector where the variable is declared, within the scope. For creating the variables with global scope, we need to declare the variable inside the :root selector, where it compares for the document’s root element. For creating the variable in the local scope, we can declare the variable inside the selector where it can be used within the scope." }, { "code": null, "e": 29667, "s": 29607, "text": "We will understand the above concepts through the examples." }, { "code": null, "e": 29803, "s": 29667, "text": "Example 1: This example illustrates the use of the var() function to declare & access the variable globally, inside the :root selector." }, { "code": null, "e": 29808, "s": 29803, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>CSS Variables</title> <style> :root { --bg-color: green; --txt-color: white; } /* var() function used here */ body { background-color: var(--bg-color); } h1 { color: var(--txt-color); } div { color: var(--txt-color); } </style></head> <body> <h1>GeeksforGeeks</h1> <div> A computer science portal for geeks </div></body></html>", "e": 30263, "s": 29808, "text": null }, { "code": null, "e": 30271, "s": 30263, "text": "Output:" }, { "code": null, "e": 30432, "s": 30271, "text": "Example 2: This example illustrates the use of the CSS variables for declaring the variable name, instead of copying and pasting the same colors multiple times." }, { "code": null, "e": 30437, "s": 30432, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>CSS Variables</title> <style> :root { --bg-color: green; } /* var() function used here */ body { background-color: var(--bg-color); } h1 { color: var(--txt-color, white); } div { color: var(--txt-color, white); } </style></head> <body> <h1>GeeksforGeeks</h1> <div> A computer science portal for geeks </div></body></html>", "e": 30879, "s": 30437, "text": null }, { "code": null, "e": 30887, "s": 30879, "text": "Output:" }, { "code": null, "e": 30964, "s": 30887, "text": "Supported Browsers: The browser supported by CSS variables are listed below:" }, { "code": null, "e": 30983, "s": 30964, "text": "Google Chrome 49.0" }, { "code": null, "e": 31003, "s": 30983, "text": "Microsoft Edge 15.0" }, { "code": null, "e": 31016, "s": 31003, "text": "Firefox 31.0" }, { "code": null, "e": 31027, "s": 31016, "text": "Safari 9.1" }, { "code": null, "e": 31038, "s": 31027, "text": "opera 36.0" }, { "code": null, "e": 31059, "s": 31038, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31070, "s": 31059, "text": "CSS-Basics" }, { "code": null, "e": 31077, "s": 31070, "text": "Picked" }, { "code": null, "e": 31081, "s": 31077, "text": "CSS" }, { "code": null, "e": 31098, "s": 31081, "text": "Web Technologies" }, { "code": null, "e": 31196, "s": 31098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31205, "s": 31196, "text": "Comments" }, { "code": null, "e": 31218, "s": 31205, "text": "Old Comments" }, { "code": null, "e": 31268, "s": 31218, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31330, "s": 31268, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31388, "s": 31330, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31436, "s": 31388, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31486, "s": 31436, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 31528, "s": 31486, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31561, "s": 31528, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31611, "s": 31561, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31673, "s": 31611, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Download City Scapes Dataset with script | by Cem Sazara | Towards Data Science
City Scapes dataset is a very popular dataset that consists of labeled street images (from video sequence). There are 5000 high-quality labeled frames and 20000 weakly annotated frames. The website for this dataset is www.cityscapes-dataset.com When I was working with this dataset, I quickly realized the dataset can only be downloaded from the website after logging in. So, there is no direct download link. This means when you need to deploy a deep learning model to a cloud machine or to another linux machine, you need to get the data from another source: Dropbox etc. Some of the data files are really large: 44GB, 11GB, 6.6GB !!! . A solution to this problem is to login and download the data without a browser. First, you need to create an account in the web page. You will use your username and password in the first line of the script to login to the page. Here is the two line script: wget --keep-session-cookies --save-cookies=cookies.txt --post-data 'username=myusername&password=mypassword&submit=Login' https://www.cityscapes-dataset.com/login/wget --load-cookies cookies.txt --content-disposition https://www.cityscapes-dataset.com/file-handling/?packageID=1 In the first line, put your username and password. This will login with your credentials and keep the associated cookies. In the second line, you need to provide the packageID paramater and it downloads the file. packageIDs map like this in the website: 1 -> gtFine_trainvaltest.zip (241MB) 2 -> gtCoarse.zip (1.3GB) 3 -> leftImg8bit_trainvaltest.zip (11GB) 4 -> leftImg8bit_trainextra.zip (44GB) 8 -> camera_trainvaltest.zip (2MB) 9 -> camera_trainextra.zip (8MB) 10 -> vehicle_trainvaltest.zip (2MB) 11 -> vehicle_trainextra.zip (7MB) 12 -> leftImg8bit_demoVideo.zip (6.6GB) 28 -> gtBbox_cityPersons_trainval.zip (2.2MB) A screenshot from the download page: You can see the GitHub repository for this script here.
[ { "code": null, "e": 417, "s": 172, "text": "City Scapes dataset is a very popular dataset that consists of labeled street images (from video sequence). There are 5000 high-quality labeled frames and 20000 weakly annotated frames. The website for this dataset is www.cityscapes-dataset.com" }, { "code": null, "e": 891, "s": 417, "text": "When I was working with this dataset, I quickly realized the dataset can only be downloaded from the website after logging in. So, there is no direct download link. This means when you need to deploy a deep learning model to a cloud machine or to another linux machine, you need to get the data from another source: Dropbox etc. Some of the data files are really large: 44GB, 11GB, 6.6GB !!! . A solution to this problem is to login and download the data without a browser." }, { "code": null, "e": 1039, "s": 891, "text": "First, you need to create an account in the web page. You will use your username and password in the first line of the script to login to the page." }, { "code": null, "e": 1068, "s": 1039, "text": "Here is the two line script:" }, { "code": null, "e": 1347, "s": 1068, "text": "wget --keep-session-cookies --save-cookies=cookies.txt --post-data 'username=myusername&password=mypassword&submit=Login' https://www.cityscapes-dataset.com/login/wget --load-cookies cookies.txt --content-disposition https://www.cityscapes-dataset.com/file-handling/?packageID=1" }, { "code": null, "e": 1469, "s": 1347, "text": "In the first line, put your username and password. This will login with your credentials and keep the associated cookies." }, { "code": null, "e": 1560, "s": 1469, "text": "In the second line, you need to provide the packageID paramater and it downloads the file." }, { "code": null, "e": 1601, "s": 1560, "text": "packageIDs map like this in the website:" }, { "code": null, "e": 1979, "s": 1601, "text": "1 -> gtFine_trainvaltest.zip (241MB) 2 -> gtCoarse.zip (1.3GB) 3 -> leftImg8bit_trainvaltest.zip (11GB) 4 -> leftImg8bit_trainextra.zip (44GB) 8 -> camera_trainvaltest.zip (2MB) 9 -> camera_trainextra.zip (8MB) 10 -> vehicle_trainvaltest.zip (2MB) 11 -> vehicle_trainextra.zip (7MB) 12 -> leftImg8bit_demoVideo.zip (6.6GB) 28 -> gtBbox_cityPersons_trainval.zip (2.2MB)" }, { "code": null, "e": 2016, "s": 1979, "text": "A screenshot from the download page:" } ]
Stop Using CSVs for Storage — Here Are the Top 5 Alternatives | by Dario Radečić | Towards Data Science
Everyone and their grandmother know what a CSV file is. But is it the optimal way to store data? Heck no. It’s probably the worst storage format if you don’t plan to view or edit data on the fly. If you’re storing large volumes of data, opting for CSVs will cost you both time and money. Today you’ll learn about five CSV alternatives. Each provides an advantage, either in read/write time or in file size. Some are even better in all areas. Let’s set up the environment before going over the file formats. You’ll need a couple of libraries to follow along. The best practice is to install them inside a virtual environment, so that’s exactly what you’ll do. The following code snippet creates a new virtual environment through Anaconda and installs every required library: conda create --name file_formats python=3.8conda activate file_formatsconda install -c conda forge numpy pandas fastavro pyarrow feather-format jupyter jupyterlab Once the installation finishes, you can execute the following command to start a JupyterLab session: jupyter lab The next step is to import the libraries and create an arbitrary dataset. You’ll make one with 5 columns and 10M rows: import numpy as npimport pandas as pdimport featherimport pickleimport pyarrow as paimport pyarrow.orc as orc from fastavro import writer, reader, parse_schemanp.random.seed = 42df_size = 10_000_000df = pd.DataFrame({ 'a': np.random.rand(df_size), 'b': np.random.rand(df_size), 'c': np.random.rand(df_size), 'd': np.random.rand(df_size), 'e': np.random.rand(df_size)})df.head() Here’s how it looks like: You now have everything needed to start experimenting with different data formats. Let’s cover ORC first. ORC stands for Optimized Row Columnar. It’s a data format optimized for reads and writes in Hive. As Hive is painfully slow, folks at Hortonworks decided to develop the ORC file format to speed it up. In Python, you can use the read_orc() function from Pandas to read ORC files. Unfortunately, there’s no alternative function for writing ORC files, so you’ll have to use PyArrow. Here’s an example of writing Pandas DataFrames: table = pa.Table.from_pandas(df, preserve_index=False)orc.write_table(table, '10M.orc') And here’s the command for reading ORC files: df = pd.read_orc('10M.orc') You can learn more about ORC here: towardsdatascience.com Avro is an open-source project which provides services of data serialization and exchange for Apache Hadoop. It stores a JSON-like schema with the data, so the correct data types are known in advance. That’s where the compression happens. Avro has an API for every major programming language, but it doesn’t support Pandas by default. Here’s the set of commands for saving a Pandas DataFrame to an Avro file: # 1. Define the schemaschema = { 'doc': 'Float data', 'name': 'Data', 'namespace': 'data', 'type': 'record', 'fields': [ {'name': 'a', 'type': 'float'}, {'name': 'b', 'type': 'float'}, {'name': 'c', 'type': 'float'}, {'name': 'd', 'type': 'float'}, {'name': 'e', 'type': 'float'}, ]}parsed_schema = parse_schema(schema)# 2. Convert pd.DataFrame to records - list of dictionariesrecords = df.to_dict('records')# 3. Write to Avro filewith open('10M.avro', 'wb') as out: writer(out, parsed_schema, records) Reading Avro files is no picnic either: # 1. List to store the recordsavro_records = []# 2. Read the Avro filewith open('10M.avro', 'rb') as fo: avro_reader = reader(fo) for record in avro_reader: avro_records.append(record) # 3. Convert to pd.DataFramedf = pd.DataFrame(avro_records) You can learn more about Avro here: towardsdatascience.com Apache Parquet is a data storage format designed for efficiency. The reason behind this is the column storage architecture, as it allows you to skip data that isn’t relevant quickly. This way, both queries and aggregations are faster, resulting in hardware savings. The best news is — Pandas has full support for Parquet files. Here’s the command for writing a Pandas DataFrame to a Parquet file: df.to_parquet('10M.parquet') And here’s the equivalent for reading: df = pd.read_parquet('10M.parquet') You can learn more about Parquet here: towardsdatascience.com You can use the pickle module to serialize objects and save them to a file. Likewise, you can then deserialize the serialized file to load them back when needed. Pickle has one major advantage over other formats — you can use it to store any Python object. One of the most widely used functionalities is saving machine learning models after the training is complete. The biggest downside is that Pickle is Python-specific, so cross-language support isn’t guaranteed. It could be a deal-breaker for any project requiring data communication between Python and R, for example. Here’s how to write a Pandas DataFrame to a Pickle file: with open('10M.pkl', 'wb') as f: pickle.dump(df, f) You’ll only have to change the file mode when reading a Pickle file: with open('10M.pkl', 'rb') as f: df = pickle.load(f) You can learn more about Pickle here: towardsdatascience.com Feather is a data format for storing data frames. It’s designed around a simple premise — to push data frames in and out of memory as efficiently as possible. It was initially designed for fast communication between Python and R, but you’re not limited to this use case. You can use the feather library to work with Feather files in Python. It’s the fastest available option currently. Here’s the command for saving Pandas DataFrames to a Feather file: feather.write_dataframe(df, '10M.feather') And here’s the command for reading: df = feather.read_dataframe('10M.feather') You can learn more about Feather here: towardsdatascience.com Many highly optimized file formats are useless if you need to change or even view the data on the fly. If that’s not the case, you should generally avoid CSVs. Below is a comparison between CSV and every other mentioned data format in write time. The goal was to save previously created 10Mx5 dataset locally: The differences are astronomical. Feather is about 115 times faster than CSV for storing identical datasets. Even if you decide to go with something more compatible such as Parquet, there’s still a 17 times decrease in write time. Let’s talk about the read times next. The goal is to compare how much time it takes to read identical datasets in different formats: CSVs aren’t so terrible here. Apache Avro is the absolute worse due to required parsing. Pickle is the fastest one, so it looks like the most promising option if you’re working only in Python. And finally, let’s compare the file sizes on the disk: Things don’t look good for CSVs. The file size reduction goes from 2.4x to 4.8x, depending on the file format. To summarize, if you store gigabytes of data daily, choosing the correct file format is crucial. If you’re working only in Python, you can’t go wrong with Pickle. If you need something a bit more versatile, go with any other mentioned format. What are your thoughts on these CSV alternatives? Which one(s) do you use if viewing and editing data on the fly isn’t required? Let me know in the comments below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Follow me on Medium for more stories like this Sign up for my newsletter Connect on LinkedIn
[ { "code": null, "e": 243, "s": 47, "text": "Everyone and their grandmother know what a CSV file is. But is it the optimal way to store data? Heck no. It’s probably the worst storage format if you don’t plan to view or edit data on the fly." }, { "code": null, "e": 335, "s": 243, "text": "If you’re storing large volumes of data, opting for CSVs will cost you both time and money." }, { "code": null, "e": 489, "s": 335, "text": "Today you’ll learn about five CSV alternatives. Each provides an advantage, either in read/write time or in file size. Some are even better in all areas." }, { "code": null, "e": 554, "s": 489, "text": "Let’s set up the environment before going over the file formats." }, { "code": null, "e": 821, "s": 554, "text": "You’ll need a couple of libraries to follow along. The best practice is to install them inside a virtual environment, so that’s exactly what you’ll do. The following code snippet creates a new virtual environment through Anaconda and installs every required library:" }, { "code": null, "e": 984, "s": 821, "text": "conda create --name file_formats python=3.8conda activate file_formatsconda install -c conda forge numpy pandas fastavro pyarrow feather-format jupyter jupyterlab" }, { "code": null, "e": 1085, "s": 984, "text": "Once the installation finishes, you can execute the following command to start a JupyterLab session:" }, { "code": null, "e": 1097, "s": 1085, "text": "jupyter lab" }, { "code": null, "e": 1216, "s": 1097, "text": "The next step is to import the libraries and create an arbitrary dataset. You’ll make one with 5 columns and 10M rows:" }, { "code": null, "e": 1609, "s": 1216, "text": "import numpy as npimport pandas as pdimport featherimport pickleimport pyarrow as paimport pyarrow.orc as orc from fastavro import writer, reader, parse_schemanp.random.seed = 42df_size = 10_000_000df = pd.DataFrame({ 'a': np.random.rand(df_size), 'b': np.random.rand(df_size), 'c': np.random.rand(df_size), 'd': np.random.rand(df_size), 'e': np.random.rand(df_size)})df.head()" }, { "code": null, "e": 1635, "s": 1609, "text": "Here’s how it looks like:" }, { "code": null, "e": 1741, "s": 1635, "text": "You now have everything needed to start experimenting with different data formats. Let’s cover ORC first." }, { "code": null, "e": 1942, "s": 1741, "text": "ORC stands for Optimized Row Columnar. It’s a data format optimized for reads and writes in Hive. As Hive is painfully slow, folks at Hortonworks decided to develop the ORC file format to speed it up." }, { "code": null, "e": 2121, "s": 1942, "text": "In Python, you can use the read_orc() function from Pandas to read ORC files. Unfortunately, there’s no alternative function for writing ORC files, so you’ll have to use PyArrow." }, { "code": null, "e": 2169, "s": 2121, "text": "Here’s an example of writing Pandas DataFrames:" }, { "code": null, "e": 2257, "s": 2169, "text": "table = pa.Table.from_pandas(df, preserve_index=False)orc.write_table(table, '10M.orc')" }, { "code": null, "e": 2303, "s": 2257, "text": "And here’s the command for reading ORC files:" }, { "code": null, "e": 2331, "s": 2303, "text": "df = pd.read_orc('10M.orc')" }, { "code": null, "e": 2366, "s": 2331, "text": "You can learn more about ORC here:" }, { "code": null, "e": 2389, "s": 2366, "text": "towardsdatascience.com" }, { "code": null, "e": 2628, "s": 2389, "text": "Avro is an open-source project which provides services of data serialization and exchange for Apache Hadoop. It stores a JSON-like schema with the data, so the correct data types are known in advance. That’s where the compression happens." }, { "code": null, "e": 2724, "s": 2628, "text": "Avro has an API for every major programming language, but it doesn’t support Pandas by default." }, { "code": null, "e": 2798, "s": 2724, "text": "Here’s the set of commands for saving a Pandas DataFrame to an Avro file:" }, { "code": null, "e": 3358, "s": 2798, "text": "# 1. Define the schemaschema = { 'doc': 'Float data', 'name': 'Data', 'namespace': 'data', 'type': 'record', 'fields': [ {'name': 'a', 'type': 'float'}, {'name': 'b', 'type': 'float'}, {'name': 'c', 'type': 'float'}, {'name': 'd', 'type': 'float'}, {'name': 'e', 'type': 'float'}, ]}parsed_schema = parse_schema(schema)# 2. Convert pd.DataFrame to records - list of dictionariesrecords = df.to_dict('records')# 3. Write to Avro filewith open('10M.avro', 'wb') as out: writer(out, parsed_schema, records)" }, { "code": null, "e": 3398, "s": 3358, "text": "Reading Avro files is no picnic either:" }, { "code": null, "e": 3663, "s": 3398, "text": "# 1. List to store the recordsavro_records = []# 2. Read the Avro filewith open('10M.avro', 'rb') as fo: avro_reader = reader(fo) for record in avro_reader: avro_records.append(record) # 3. Convert to pd.DataFramedf = pd.DataFrame(avro_records)" }, { "code": null, "e": 3699, "s": 3663, "text": "You can learn more about Avro here:" }, { "code": null, "e": 3722, "s": 3699, "text": "towardsdatascience.com" }, { "code": null, "e": 3988, "s": 3722, "text": "Apache Parquet is a data storage format designed for efficiency. The reason behind this is the column storage architecture, as it allows you to skip data that isn’t relevant quickly. This way, both queries and aggregations are faster, resulting in hardware savings." }, { "code": null, "e": 4050, "s": 3988, "text": "The best news is — Pandas has full support for Parquet files." }, { "code": null, "e": 4119, "s": 4050, "text": "Here’s the command for writing a Pandas DataFrame to a Parquet file:" }, { "code": null, "e": 4148, "s": 4119, "text": "df.to_parquet('10M.parquet')" }, { "code": null, "e": 4187, "s": 4148, "text": "And here’s the equivalent for reading:" }, { "code": null, "e": 4223, "s": 4187, "text": "df = pd.read_parquet('10M.parquet')" }, { "code": null, "e": 4262, "s": 4223, "text": "You can learn more about Parquet here:" }, { "code": null, "e": 4285, "s": 4262, "text": "towardsdatascience.com" }, { "code": null, "e": 4652, "s": 4285, "text": "You can use the pickle module to serialize objects and save them to a file. Likewise, you can then deserialize the serialized file to load them back when needed. Pickle has one major advantage over other formats — you can use it to store any Python object. One of the most widely used functionalities is saving machine learning models after the training is complete." }, { "code": null, "e": 4859, "s": 4652, "text": "The biggest downside is that Pickle is Python-specific, so cross-language support isn’t guaranteed. It could be a deal-breaker for any project requiring data communication between Python and R, for example." }, { "code": null, "e": 4916, "s": 4859, "text": "Here’s how to write a Pandas DataFrame to a Pickle file:" }, { "code": null, "e": 4971, "s": 4916, "text": "with open('10M.pkl', 'wb') as f: pickle.dump(df, f)" }, { "code": null, "e": 5040, "s": 4971, "text": "You’ll only have to change the file mode when reading a Pickle file:" }, { "code": null, "e": 5096, "s": 5040, "text": "with open('10M.pkl', 'rb') as f: df = pickle.load(f)" }, { "code": null, "e": 5134, "s": 5096, "text": "You can learn more about Pickle here:" }, { "code": null, "e": 5157, "s": 5134, "text": "towardsdatascience.com" }, { "code": null, "e": 5428, "s": 5157, "text": "Feather is a data format for storing data frames. It’s designed around a simple premise — to push data frames in and out of memory as efficiently as possible. It was initially designed for fast communication between Python and R, but you’re not limited to this use case." }, { "code": null, "e": 5543, "s": 5428, "text": "You can use the feather library to work with Feather files in Python. It’s the fastest available option currently." }, { "code": null, "e": 5610, "s": 5543, "text": "Here’s the command for saving Pandas DataFrames to a Feather file:" }, { "code": null, "e": 5653, "s": 5610, "text": "feather.write_dataframe(df, '10M.feather')" }, { "code": null, "e": 5689, "s": 5653, "text": "And here’s the command for reading:" }, { "code": null, "e": 5732, "s": 5689, "text": "df = feather.read_dataframe('10M.feather')" }, { "code": null, "e": 5771, "s": 5732, "text": "You can learn more about Feather here:" }, { "code": null, "e": 5794, "s": 5771, "text": "towardsdatascience.com" }, { "code": null, "e": 5954, "s": 5794, "text": "Many highly optimized file formats are useless if you need to change or even view the data on the fly. If that’s not the case, you should generally avoid CSVs." }, { "code": null, "e": 6104, "s": 5954, "text": "Below is a comparison between CSV and every other mentioned data format in write time. The goal was to save previously created 10Mx5 dataset locally:" }, { "code": null, "e": 6335, "s": 6104, "text": "The differences are astronomical. Feather is about 115 times faster than CSV for storing identical datasets. Even if you decide to go with something more compatible such as Parquet, there’s still a 17 times decrease in write time." }, { "code": null, "e": 6468, "s": 6335, "text": "Let’s talk about the read times next. The goal is to compare how much time it takes to read identical datasets in different formats:" }, { "code": null, "e": 6661, "s": 6468, "text": "CSVs aren’t so terrible here. Apache Avro is the absolute worse due to required parsing. Pickle is the fastest one, so it looks like the most promising option if you’re working only in Python." }, { "code": null, "e": 6716, "s": 6661, "text": "And finally, let’s compare the file sizes on the disk:" }, { "code": null, "e": 6827, "s": 6716, "text": "Things don’t look good for CSVs. The file size reduction goes from 2.4x to 4.8x, depending on the file format." }, { "code": null, "e": 7070, "s": 6827, "text": "To summarize, if you store gigabytes of data daily, choosing the correct file format is crucial. If you’re working only in Python, you can’t go wrong with Pickle. If you need something a bit more versatile, go with any other mentioned format." }, { "code": null, "e": 7234, "s": 7070, "text": "What are your thoughts on these CSV alternatives? Which one(s) do you use if viewing and editing data on the fly isn’t required? Let me know in the comments below." }, { "code": null, "e": 7417, "s": 7234, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 7428, "s": 7417, "text": "medium.com" }, { "code": null, "e": 7475, "s": 7428, "text": "Follow me on Medium for more stories like this" }, { "code": null, "e": 7501, "s": 7475, "text": "Sign up for my newsletter" } ]
How to create and release a save point in JDBC?
When you set a save point you define a logical rollback point within a transaction. If an error occurs past a save point, you can use the rollback method to undo either all the changes or only the changes made after the save point. Savepoint interface gives you the additional transactional control. Most modern DBMS, support save points within their environments such as Oracle's PL/SQL. You can set a save point in a database using the setSavepoint(String savepointName) method of the Connection interface, this method accepts a string value representing the name of the save point and returns a Savepoint object. You can release a save point using the releaseSavepoint(Savepoint savepointName) method of the Connection interface, this method accepts the name of the savepoint and releases/deletes the specified save point. Assume we have a table named customers in the database with 5 records as shown below: +----+-----------+------+---------+----------------+ | ID | NAME | AGE | SALARY | ADDRESS | +----+-----------+------+---------+----------------+ | 1 | Amit | 25 | 3000.00 | Hyderabad | | 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam | | 3 | Renuka | 30 | 5000.00 | Delhi | | 4 | Archana | 24 | 1500.00 | Mumbai | | 5 | Koushik | 30 | 9000.00 | Kota | +----+-----------+------+---------+----------------+ Following JDBC program Inserts 7 more records to it, sets a save point, removes some records and roll backs to the save point. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Savepoint; public class SavepointExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Setting auto-commit false con.setAutoCommit(false); System.out.println(" "); //Creating the Statement PreparedStatement pstmt = con.prepareStatement("INSERT into customers VALUES (?, ?, ?, ?, ?) "); pstmt.setInt(1, 6); pstmt.setString(2, "Hardik"); pstmt.setInt(3, 45); pstmt.setInt(4, 6400); pstmt.setString(5, "Bhopal"); pstmt.executeUpdate(); pstmt.setInt(1, 7); pstmt.setString(2, "Trupti"); pstmt.setInt(3, 33); pstmt.setInt(4, 4360); pstmt.setString(5, "Ahmedabad"); pstmt.executeUpdate(); pstmt.setInt(1, 8); pstmt.setString(2, "Mithili"); pstmt.setInt(3, 26); pstmt.setInt(4, 4100); pstmt.setString(5, "Vijayawada"); pstmt.executeUpdate(); pstmt.setInt(1, 9); pstmt.setString(2, "Maneesh"); pstmt.setInt(3, 39); pstmt.setInt(4, 4000); pstmt.setString(5, "Hyderabad"); pstmt.executeUpdate(); pstmt.setInt(1, 10); pstmt.setString(2, "Rajaneesh"); pstmt.setInt(3, 30); pstmt.setInt(4, 6400); pstmt.setString(5, "Delhi"); pstmt.executeUpdate(); pstmt.setInt(1, 11); pstmt.setString(2, "Komal"); pstmt.setInt(3, 29); pstmt.setInt(4, 8000); pstmt.setString(5, "Ahmedabad"); pstmt.executeUpdate(); pstmt.setInt(1, 12); pstmt.setString(2, "Manyata"); pstmt.setInt(3, 25); pstmt.setInt(4, 5000); pstmt.setString(5, "Vijayawada"); pstmt.executeUpdate(); //Setting save point Savepoint savePoint = con.setSavepoint("mysavepoint"); System.out.println(" "); System.out.println("Contents of the customers table after inserting the records: "); Statement stmt = con.createStatement(); //Retrieving data ResultSet rs = stmt.executeQuery("Select * from customers"); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Age: "+rs.getInt("Age")+", "); System.out.print("Salary: "+rs.getInt("Salary")+", "); System.out.print("Address: "+rs.getString("Address")); System.out.println(); } //Deleting the records stmt.execute("Delete from customers where id > 5"); System.out.println(" "); System.out.println("Contents of the customers table after deleting the records: "); //Retrieving data rs = stmt.executeQuery("Select * from customers"); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Age: "+rs.getInt("Age")+", "); System.out.print("Salary: "+rs.getInt("Salary")+", "); System.out.print("Address: "+rs.getString("Address")); System.out.println(); } //Rolling back to the save point con.rollback(savePoint); System.out.println(" "); System.out.println("Contents of the table at the save point: "); //Retrieving data rs = stmt.executeQuery("Select * from customers"); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Age: "+rs.getInt("Age")+", "); System.out.print("Salary: "+rs.getInt("Salary")+", "); System.out.print("Address: "+rs.getString("Address")); System.out.println(); } } } Connection established...... Contents of the customers table after inserting the records: ID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad ID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam ID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi ID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai ID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota ID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal ID: 7, Name: Trupti, Age: 33, Salary: 4360, Address: Ahmedabad ID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada ID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad ID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi ID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad ID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada Contents of the customers table after deleting the records: ID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad ID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam ID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi ID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai ID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota Contents of the table at the save point: ID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad ID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam ID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi ID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai ID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota ID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal ID: 7, Name: Trupti, Age: 33, Salary: 4360, Address: Ahmedabad ID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada ID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad ID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi ID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad ID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada
[ { "code": null, "e": 1294, "s": 1062, "text": "When you set a save point you define a logical rollback point within a transaction. If an error occurs past a save point, you can use the rollback method to undo either all the changes or only the changes made after the save point." }, { "code": null, "e": 1451, "s": 1294, "text": "Savepoint interface gives you the additional transactional control. Most modern DBMS, support save points within their environments such as Oracle's PL/SQL." }, { "code": null, "e": 1678, "s": 1451, "text": "You can set a save point in a database using the setSavepoint(String savepointName) method of the Connection interface, this method accepts a string value representing the name of the save point and returns a Savepoint object." }, { "code": null, "e": 1888, "s": 1678, "text": "You can release a save point using the releaseSavepoint(Savepoint savepointName) method of the Connection interface, this method accepts the name of the savepoint and releases/deletes the specified save point." }, { "code": null, "e": 1974, "s": 1888, "text": "Assume we have a table named customers in the database with 5 records as shown below:" }, { "code": null, "e": 2451, "s": 1974, "text": "+----+-----------+------+---------+----------------+\n| ID | NAME | AGE | SALARY | ADDRESS |\n+----+-----------+------+---------+----------------+\n| 1 | Amit | 25 | 3000.00 | Hyderabad |\n| 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam |\n| 3 | Renuka | 30 | 5000.00 | Delhi |\n| 4 | Archana | 24 | 1500.00 | Mumbai |\n| 5 | Koushik | 30 | 9000.00 | Kota |\n+----+-----------+------+---------+----------------+" }, { "code": null, "e": 2578, "s": 2451, "text": "Following JDBC program Inserts 7 more records to it, sets a save point, removes some records and roll backs to the save point." }, { "code": null, "e": 6760, "s": 2578, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Savepoint;\npublic class SavepointExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Setting auto-commit false\n con.setAutoCommit(false);\n System.out.println(\" \");\n //Creating the Statement\n PreparedStatement pstmt = con.prepareStatement(\"INSERT into customers VALUES (?, ?, ?, ?, ?) \");\n pstmt.setInt(1, 6);\n pstmt.setString(2, \"Hardik\");\n pstmt.setInt(3, 45);\n pstmt.setInt(4, 6400);\n pstmt.setString(5, \"Bhopal\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 7);\n pstmt.setString(2, \"Trupti\");\n pstmt.setInt(3, 33);\n pstmt.setInt(4, 4360);\n pstmt.setString(5, \"Ahmedabad\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 8);\n pstmt.setString(2, \"Mithili\");\n pstmt.setInt(3, 26);\n pstmt.setInt(4, 4100);\n pstmt.setString(5, \"Vijayawada\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 9);\n pstmt.setString(2, \"Maneesh\");\n pstmt.setInt(3, 39);\n pstmt.setInt(4, 4000);\n pstmt.setString(5, \"Hyderabad\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 10);\n pstmt.setString(2, \"Rajaneesh\");\n pstmt.setInt(3, 30);\n pstmt.setInt(4, 6400);\n pstmt.setString(5, \"Delhi\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 11);\n pstmt.setString(2, \"Komal\");\n pstmt.setInt(3, 29);\n pstmt.setInt(4, 8000);\n pstmt.setString(5, \"Ahmedabad\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 12);\n pstmt.setString(2, \"Manyata\");\n pstmt.setInt(3, 25);\n pstmt.setInt(4, 5000);\n pstmt.setString(5, \"Vijayawada\");\n pstmt.executeUpdate();\n\n //Setting save point\n Savepoint savePoint = con.setSavepoint(\"mysavepoint\");\n System.out.println(\" \");\n\n System.out.println(\"Contents of the customers table after inserting the records: \");\n Statement stmt = con.createStatement();\n\n //Retrieving data\n ResultSet rs = stmt.executeQuery(\"Select * from customers\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Age: \"+rs.getInt(\"Age\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Address\"));\n System.out.println();\n }\n //Deleting the records\n stmt.execute(\"Delete from customers where id > 5\");\n\n System.out.println(\" \");\n System.out.println(\"Contents of the customers table after deleting the records: \");\n\n //Retrieving data\n rs = stmt.executeQuery(\"Select * from customers\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Age: \"+rs.getInt(\"Age\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Address\"));\n System.out.println();\n }\n\n //Rolling back to the save point\n con.rollback(savePoint);\n\n System.out.println(\" \");\n System.out.println(\"Contents of the table at the save point: \");\n\n //Retrieving data\n rs = stmt.executeQuery(\"Select * from customers\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Age: \"+rs.getInt(\"Age\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Address\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 8766, "s": 6760, "text": "Connection established......\n\nContents of the customers table after inserting the records:\nID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad\nID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam\nID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi\nID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai\nID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota\nID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal\nID: 7, Name: Trupti, Age: 33, Salary: 4360, Address: Ahmedabad\nID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada\nID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad\nID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi\nID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad\nID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada\n\nContents of the customers table after deleting the records:\nID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad\nID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam\nID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi\nID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai\nID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota\n\nContents of the table at the save point:\nID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad\nID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam\nID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi\nID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai\nID: 5, Name: Koushik, Age: 30, Salary: 9000, Address: Kota\nID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal\nID: 7, Name: Trupti, Age: 33, Salary: 4360, Address: Ahmedabad\nID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada\nID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad\nID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi\nID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad\nID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada" } ]
Get Interactive plots directly with pandas. | by Parul Pandey | Towards Data Science
Data exploration is by far one of the most important aspects of any data analysis task. The initial probing and preliminary checks that we perform, using the vast catalog of visualization tools, give us actionable insights into the nature of data. However, the choice of visualization tool at times is more complicated than the task itself. On the one hand, we have libraries that are easier to use but are not so helpful in showing complex relationships in data. Then there are others that render interactivity but have a considerable learning curve. Fortunately, some open-source libraries have been created that try to address this pain point effectively. In this article, we’ll look at two such libraries, namely pandas_bokeh and cufflinks. We’ll learn how to create plotly and bokeh charts with the basic pandas plotting syntax, which we all are comfortable with. Since the article's emphasis is on the syntax rather than the types of plots, we’ll limit ourselves to the five basic charts, i.e., line charts, bar charts, histograms, scatter plots, and pie charts. We’ll create each of these charts first with pandas plotting library and then recreate them in plotly and bokeh, albeit with a twist. Importing the Dataset Plotting with Pandas directly Bokeh Backend for Pandas — plotting with Pandas-Bokeh. Plotly Backend for Pandas — plotting with Cufflinks Conclusion We’ll work with the NIFTY-50 dataset. The NIFTY 50 index is the National Stock Exchange of India’s benchmark for the Indian equity market. The dataset is openly available on Kaggle, but we’ll be using a subset of the data containing the stock value of only four sectors, i.e., bank, pharma, IT, and FMCG. You can download the sample dataset from here. Let’s import the necessary libraries and dataset required for the visualization purpose: # Importing required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline# Reading in the datanifty_data = pd.read_csv('NIFTY_data_2020.csv',parse_dates=["Date"],index_col='Date')nifty_data.head() We can also resample/ aggregate the data by month-end. The pandas’ library has a resample() function, which resamples the time series data. nifty_data_resample = nifty_data.resample(rule = 'M').mean()nifty_data_resample Now that we have our dataframes ready, it is time to visualize them via different plots. Let’s begin with the most straightforward plotting technique — pandas’ plotting functions. To plot a graph using pandas, we’ll call the .plot()method on the dataframe. Syntax: dataframe.plot() The plot method is just a simple wrapper around matplotlib’s plt.plot(). We can also specify some additional parameters like the ones mentioned below: Some of the important Parameters--------------------------------x : label or position, default None Only used if data is a DataFrame.y : label, position or list of label, positions, default Nonetitle: title to be used for the plotX and y label: Name to use for the label on the x-axis and y-axis.figsize : specifies the size of the figure object. kind : str The kind of plot to produce: - 'line' : line plot (default) - 'bar' : vertical bar plot - 'barh' : horizontal bar plot - 'hist' : histogram - 'box' : boxplot - 'kde' : Kernel Density Estimation plot - 'density' : same as 'kde' - 'area' : area plot - 'pie' : pie plot - 'scatter' : scatter plot - 'hexbin' : hexbin plot. For a complete list of the parameters and their usage, please refer to the documentation. Let’s now look at ways to create different plots. In this article, we’ll not go into detail explaining each plot. We’ll only focus on the syntax, which is self-explanatory if you have some experience in pandas. For a detailed understanding of the pandas’ plots, the below article will be helpful: In this article, we’ll look at how to explore and visualize your data with pandas, and then we’ll dive deeper into some of the advanced capabilities for visualization with pandas. nifty_data.plot(title='Nifty Index values in 2020', xlabel = 'Values', figsize=(10,6); nifty_data.plot(kind='scatter', x='NIFTY FMCG index', y='NIFTY Bank index', title = 'Scatter Plot for NIFTY Index values in 2020', figsize=(10,6)); nifty_data[['NIFTY FMCG index','NIFTY Bank index']].plot(kind='hist',figsize=(9,6), bins=30); nifty_data_resample.plot(kind='bar',figsize=(10,6)); 4.1 Stacked bar plots nifty_data_resample.plot(kind='barh',figsize=(10,6)); nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample['NIFTY Bank index'].plot.pie(legend=False, figsize=(10,6),autopct='%.1f'); These were some of the charts that can be directly created with pandas’ dataframes. However, these charts lack interactivity and capabilities like zoom and pan. Let’s now change these existing charts in syntax into their fully interactive counterparts with just a slight change in the syntax. The bokeh library clearly stands out when it comes to data visualizations. The Pandas-Bokeh provides a bokeh plotting backend for Pandas, GeoPandas, and Pyspark DataFrames. This backend adds a plot_bokeh() method to the DataFrames and Series. Pandas-Bokeh can be installed from PyPI via pip or conda pip install pandas-bokehorconda install -c patrikhlobil pandas-bokeh The Pandas-Bokeh library should be imported after Pandas, GeoPandas, and/or Pyspark. import pandas as pdimport pandas_bokeh Then one needs to define the plotting output, which can be either of the two: pandas_bokeh.output_notebook(): for embedding plots in Jupyter Notebooks.pandas_bokeh.output_file(filename): for exporting plots as HTML. Syntax Now, the plotting API is accessible for a Pandas DataFrame via the dataframe.plot_bokeh(). For more details about the plotting outputs, see the reference here or the Bokeh documentation. Let’s now plot all the five kinds of plots as plotted in the above section. We’ll be using the same datasets as used above. import pandas as pdimport pandas_bokehpandas_bokeh.output_notebook() nifty_data.plot_bokeh(kind='line') #equivalent to nifty_data.plot_bokeh.line() nifty_data.plot_bokeh.scatter(x='NIFTY FMCG index', y='NIFTY Bank index'); nifty_data[['NIFTY FMCG index','NIFTY Bank index']].plot_bokeh(kind='hist', bins=30); nifty_data_resample.plot_bokeh(kind='bar',figsize=(10,6)); 4.1 Stacked bar plots nifty_data_resample.plot_bokeh(kind='barh',stacked=True); nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample.plot_bokeh.pie(y ='NIFTY Bank index') Additionally, you can also create multiple nested pie plots within the same plot: nifty_data_resample.plot_bokeh.pie() This section saw how we could seamlessly create bokeh plots without any significant change in the pandas plotting syntax. Now we can have the best of both worlds without having to learn any new format. Another commonly used library for data visualization is Plotly. With plotly, you can make interactive charts in Python, R, and JavaScript. As of version 4.8, Plotly came out with a Plotly Express-powered backend for Pandas plotting, which meant that one even does not need to import plotly to create plotly like visualizations. However, the library I want to mention here is not plotly express, but an independent third-party wrapper library around Plotly called Cufflinks. The beauty of cufflinks is that it is more versatile, has more functionalities, and has an API similar to pandas plotting. This means you only need to add a .iplot() method to Pandas dataframes for plotting graphs. Make sure you have plotly installed before installing cufflinks. Read this guide for instructions. pip install cufflinks The repository has a lot of useful examples and notebooks to get started. import pandas as pdimport cufflinks as cffrom IPython.display import display,HTML#making all charts public and setting a global themecf.set_config_file(sharing='public',theme='white',offline=True) That is all. We can now create visualizations with the power of plotly but with the ease of pandas. The only change in the syntax is dataframe.iplot(). nifty_data.iplot(kind='line') You need to mention the plotting mode for scatter trace while creating a scatterplot. The mode could be lines, markers, text, or a combination of either of them. nifty_data.iplot(kind='scatter',x='NIFTY FMCG index', y='NIFTY Bank index',mode='markers'); nifty_data[['NIFTY FMCG index','NIFTY Bank index']].iplot(kind='hist', bins=30); nifty_data_resample.iplot(kind='bar'); 4.1 Stacked bar plots nifty_data_resample.iplot(kind='barh',barmode = 'stack'); nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample.reset_index().iplot(kind='pie',labels='index',values='NIFTY Bank index') The Cufflinks library provides an easy way to get the power of plotly within plotly. The similarity in syntax is another point of advantage. The Bokeh or a Plotly plot is self-sufficient in conveying the entire information. Based on your choice and preference, you can choose both or either of them; The primary purpose is to make the visualizations more intuitive and interactive at the same time. After going through this article, you should be able to convert the static visualizations into their interactive counterparts and take your analysis a notch higher. 👉 Interested in reading other articles by myself. This repo contains all the articles written by me category-wise.
[ { "code": null, "e": 831, "s": 172, "text": "Data exploration is by far one of the most important aspects of any data analysis task. The initial probing and preliminary checks that we perform, using the vast catalog of visualization tools, give us actionable insights into the nature of data. However, the choice of visualization tool at times is more complicated than the task itself. On the one hand, we have libraries that are easier to use but are not so helpful in showing complex relationships in data. Then there are others that render interactivity but have a considerable learning curve. Fortunately, some open-source libraries have been created that try to address this pain point effectively." }, { "code": null, "e": 1375, "s": 831, "text": "In this article, we’ll look at two such libraries, namely pandas_bokeh and cufflinks. We’ll learn how to create plotly and bokeh charts with the basic pandas plotting syntax, which we all are comfortable with. Since the article's emphasis is on the syntax rather than the types of plots, we’ll limit ourselves to the five basic charts, i.e., line charts, bar charts, histograms, scatter plots, and pie charts. We’ll create each of these charts first with pandas plotting library and then recreate them in plotly and bokeh, albeit with a twist." }, { "code": null, "e": 1397, "s": 1375, "text": "Importing the Dataset" }, { "code": null, "e": 1427, "s": 1397, "text": "Plotting with Pandas directly" }, { "code": null, "e": 1482, "s": 1427, "text": "Bokeh Backend for Pandas — plotting with Pandas-Bokeh." }, { "code": null, "e": 1534, "s": 1482, "text": "Plotly Backend for Pandas — plotting with Cufflinks" }, { "code": null, "e": 1545, "s": 1534, "text": "Conclusion" }, { "code": null, "e": 1850, "s": 1545, "text": "We’ll work with the NIFTY-50 dataset. The NIFTY 50 index is the National Stock Exchange of India’s benchmark for the Indian equity market. The dataset is openly available on Kaggle, but we’ll be using a subset of the data containing the stock value of only four sectors, i.e., bank, pharma, IT, and FMCG." }, { "code": null, "e": 1897, "s": 1850, "text": "You can download the sample dataset from here." }, { "code": null, "e": 1986, "s": 1897, "text": "Let’s import the necessary libraries and dataset required for the visualization purpose:" }, { "code": null, "e": 2224, "s": 1986, "text": "# Importing required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline# Reading in the datanifty_data = pd.read_csv('NIFTY_data_2020.csv',parse_dates=[\"Date\"],index_col='Date')nifty_data.head()" }, { "code": null, "e": 2364, "s": 2224, "text": "We can also resample/ aggregate the data by month-end. The pandas’ library has a resample() function, which resamples the time series data." }, { "code": null, "e": 2444, "s": 2364, "text": "nifty_data_resample = nifty_data.resample(rule = 'M').mean()nifty_data_resample" }, { "code": null, "e": 2533, "s": 2444, "text": "Now that we have our dataframes ready, it is time to visualize them via different plots." }, { "code": null, "e": 2701, "s": 2533, "text": "Let’s begin with the most straightforward plotting technique — pandas’ plotting functions. To plot a graph using pandas, we’ll call the .plot()method on the dataframe." }, { "code": null, "e": 2726, "s": 2701, "text": "Syntax: dataframe.plot()" }, { "code": null, "e": 2877, "s": 2726, "text": "The plot method is just a simple wrapper around matplotlib’s plt.plot(). We can also specify some additional parameters like the ones mentioned below:" }, { "code": null, "e": 3597, "s": 2877, "text": "Some of the important Parameters--------------------------------x : label or position, default None Only used if data is a DataFrame.y : label, position or list of label, positions, default Nonetitle: title to be used for the plotX and y label: Name to use for the label on the x-axis and y-axis.figsize : specifies the size of the figure object. kind : str The kind of plot to produce: - 'line' : line plot (default) - 'bar' : vertical bar plot - 'barh' : horizontal bar plot - 'hist' : histogram - 'box' : boxplot - 'kde' : Kernel Density Estimation plot - 'density' : same as 'kde' - 'area' : area plot - 'pie' : pie plot - 'scatter' : scatter plot - 'hexbin' : hexbin plot." }, { "code": null, "e": 3984, "s": 3597, "text": "For a complete list of the parameters and their usage, please refer to the documentation. Let’s now look at ways to create different plots. In this article, we’ll not go into detail explaining each plot. We’ll only focus on the syntax, which is self-explanatory if you have some experience in pandas. For a detailed understanding of the pandas’ plots, the below article will be helpful:" }, { "code": null, "e": 4164, "s": 3984, "text": "In this article, we’ll look at how to explore and visualize your data with pandas, and then we’ll dive deeper into some of the advanced capabilities for visualization with pandas." }, { "code": null, "e": 4282, "s": 4164, "text": "nifty_data.plot(title='Nifty Index values in 2020', xlabel = 'Values', figsize=(10,6);" }, { "code": null, "e": 4459, "s": 4282, "text": "nifty_data.plot(kind='scatter', x='NIFTY FMCG index', y='NIFTY Bank index', title = 'Scatter Plot for NIFTY Index values in 2020', figsize=(10,6));" }, { "code": null, "e": 4553, "s": 4459, "text": "nifty_data[['NIFTY FMCG index','NIFTY Bank index']].plot(kind='hist',figsize=(9,6), bins=30);" }, { "code": null, "e": 4606, "s": 4553, "text": "nifty_data_resample.plot(kind='bar',figsize=(10,6));" }, { "code": null, "e": 4628, "s": 4606, "text": "4.1 Stacked bar plots" }, { "code": null, "e": 4682, "s": 4628, "text": "nifty_data_resample.plot(kind='barh',figsize=(10,6));" }, { "code": null, "e": 4850, "s": 4682, "text": "nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample['NIFTY Bank index'].plot.pie(legend=False, figsize=(10,6),autopct='%.1f');" }, { "code": null, "e": 5143, "s": 4850, "text": "These were some of the charts that can be directly created with pandas’ dataframes. However, these charts lack interactivity and capabilities like zoom and pan. Let’s now change these existing charts in syntax into their fully interactive counterparts with just a slight change in the syntax." }, { "code": null, "e": 5386, "s": 5143, "text": "The bokeh library clearly stands out when it comes to data visualizations. The Pandas-Bokeh provides a bokeh plotting backend for Pandas, GeoPandas, and Pyspark DataFrames. This backend adds a plot_bokeh() method to the DataFrames and Series." }, { "code": null, "e": 5443, "s": 5386, "text": "Pandas-Bokeh can be installed from PyPI via pip or conda" }, { "code": null, "e": 5512, "s": 5443, "text": "pip install pandas-bokehorconda install -c patrikhlobil pandas-bokeh" }, { "code": null, "e": 5597, "s": 5512, "text": "The Pandas-Bokeh library should be imported after Pandas, GeoPandas, and/or Pyspark." }, { "code": null, "e": 5636, "s": 5597, "text": "import pandas as pdimport pandas_bokeh" }, { "code": null, "e": 5714, "s": 5636, "text": "Then one needs to define the plotting output, which can be either of the two:" }, { "code": null, "e": 5852, "s": 5714, "text": "pandas_bokeh.output_notebook(): for embedding plots in Jupyter Notebooks.pandas_bokeh.output_file(filename): for exporting plots as HTML." }, { "code": null, "e": 5859, "s": 5852, "text": "Syntax" }, { "code": null, "e": 5950, "s": 5859, "text": "Now, the plotting API is accessible for a Pandas DataFrame via the dataframe.plot_bokeh()." }, { "code": null, "e": 6170, "s": 5950, "text": "For more details about the plotting outputs, see the reference here or the Bokeh documentation. Let’s now plot all the five kinds of plots as plotted in the above section. We’ll be using the same datasets as used above." }, { "code": null, "e": 6239, "s": 6170, "text": "import pandas as pdimport pandas_bokehpandas_bokeh.output_notebook()" }, { "code": null, "e": 6318, "s": 6239, "text": "nifty_data.plot_bokeh(kind='line') #equivalent to nifty_data.plot_bokeh.line()" }, { "code": null, "e": 6393, "s": 6318, "text": "nifty_data.plot_bokeh.scatter(x='NIFTY FMCG index', y='NIFTY Bank index');" }, { "code": null, "e": 6479, "s": 6393, "text": "nifty_data[['NIFTY FMCG index','NIFTY Bank index']].plot_bokeh(kind='hist', bins=30);" }, { "code": null, "e": 6538, "s": 6479, "text": "nifty_data_resample.plot_bokeh(kind='bar',figsize=(10,6));" }, { "code": null, "e": 6560, "s": 6538, "text": "4.1 Stacked bar plots" }, { "code": null, "e": 6618, "s": 6560, "text": "nifty_data_resample.plot_bokeh(kind='barh',stacked=True);" }, { "code": null, "e": 6749, "s": 6618, "text": "nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample.plot_bokeh.pie(y ='NIFTY Bank index')" }, { "code": null, "e": 6831, "s": 6749, "text": "Additionally, you can also create multiple nested pie plots within the same plot:" }, { "code": null, "e": 6868, "s": 6831, "text": "nifty_data_resample.plot_bokeh.pie()" }, { "code": null, "e": 7070, "s": 6868, "text": "This section saw how we could seamlessly create bokeh plots without any significant change in the pandas plotting syntax. Now we can have the best of both worlds without having to learn any new format." }, { "code": null, "e": 7398, "s": 7070, "text": "Another commonly used library for data visualization is Plotly. With plotly, you can make interactive charts in Python, R, and JavaScript. As of version 4.8, Plotly came out with a Plotly Express-powered backend for Pandas plotting, which meant that one even does not need to import plotly to create plotly like visualizations." }, { "code": null, "e": 7759, "s": 7398, "text": "However, the library I want to mention here is not plotly express, but an independent third-party wrapper library around Plotly called Cufflinks. The beauty of cufflinks is that it is more versatile, has more functionalities, and has an API similar to pandas plotting. This means you only need to add a .iplot() method to Pandas dataframes for plotting graphs." }, { "code": null, "e": 7858, "s": 7759, "text": "Make sure you have plotly installed before installing cufflinks. Read this guide for instructions." }, { "code": null, "e": 7880, "s": 7858, "text": "pip install cufflinks" }, { "code": null, "e": 7954, "s": 7880, "text": "The repository has a lot of useful examples and notebooks to get started." }, { "code": null, "e": 8151, "s": 7954, "text": "import pandas as pdimport cufflinks as cffrom IPython.display import display,HTML#making all charts public and setting a global themecf.set_config_file(sharing='public',theme='white',offline=True)" }, { "code": null, "e": 8303, "s": 8151, "text": "That is all. We can now create visualizations with the power of plotly but with the ease of pandas. The only change in the syntax is dataframe.iplot()." }, { "code": null, "e": 8333, "s": 8303, "text": "nifty_data.iplot(kind='line')" }, { "code": null, "e": 8495, "s": 8333, "text": "You need to mention the plotting mode for scatter trace while creating a scatterplot. The mode could be lines, markers, text, or a combination of either of them." }, { "code": null, "e": 8587, "s": 8495, "text": "nifty_data.iplot(kind='scatter',x='NIFTY FMCG index', y='NIFTY Bank index',mode='markers');" }, { "code": null, "e": 8668, "s": 8587, "text": "nifty_data[['NIFTY FMCG index','NIFTY Bank index']].iplot(kind='hist', bins=30);" }, { "code": null, "e": 8707, "s": 8668, "text": "nifty_data_resample.iplot(kind='bar');" }, { "code": null, "e": 8729, "s": 8707, "text": "4.1 Stacked bar plots" }, { "code": null, "e": 8787, "s": 8729, "text": "nifty_data_resample.iplot(kind='barh',barmode = 'stack');" }, { "code": null, "e": 8953, "s": 8787, "text": "nifty_data_resample.index=['Jan','Feb','March','Apr','May','June','July']nifty_data_resample.reset_index().iplot(kind='pie',labels='index',values='NIFTY Bank index')" }, { "code": null, "e": 9094, "s": 8953, "text": "The Cufflinks library provides an easy way to get the power of plotly within plotly. The similarity in syntax is another point of advantage." }, { "code": null, "e": 9517, "s": 9094, "text": "The Bokeh or a Plotly plot is self-sufficient in conveying the entire information. Based on your choice and preference, you can choose both or either of them; The primary purpose is to make the visualizations more intuitive and interactive at the same time. After going through this article, you should be able to convert the static visualizations into their interactive counterparts and take your analysis a notch higher." } ]
Solve the Crossword Puzzle - GeeksforGeeks
26 May, 2018 A 10 x 10 Crossword grid is provided, along with a set of words (or names of places) which need to be filled into the grid. The cells in the grid are initially, either + signs or – signs. Cells marked with a ‘+’ have to be left as they are. Cells marked with a ‘-‘ need to be filled up with an appropriate character.You are also given an array of words that need to be filled in Crossword grid. Example : Input : +++++++++- -++++++++- -------++- -++++++++- -++++++++- -++++----- ------+++- -++++++++- +--------- ++++++++++ Output : +++++++++C P++++++++H HISTORY++E Y++++++++M S++++++++I I++++MATHS CIVICS+++T S++++++++R +GEOGRAPHY ++++++++++ The approach behind this is to recursively check for each word in the vertical position and in the horizontal position. Then fill the word in the matrix that can be the best fit in the corresponding position of the grid, then update the crossword grid by filling the gap with that word. // CPP code to fill the crossword puzzle#include <bits/stdc++.h>using namespace std; // ways are to calculate the number of// possible ways to fill the gridint ways = 0; // this function is used to print// the resultant matrixvoid printMatrix(vector<string>& matrix, int n){ for (int i = 0; i < n; i++) cout << matrix[i] << endl;} // this function checks for the current word// if it can be placed horizontally or not// x -> it represent index of row// y -> it represent index of column// currentWord -> it represent the// current word in word arrayvector<string> checkHorizontal(int x, int y, vector<string> matrix, string currentWord){ int n = currentWord.length(); for (int i = 0; i < n; i++) { if (matrix[x][y + i] == '#' || matrix[x][y + i] == currentWord[i]) { matrix[x][y + i] = currentWord[i]; } else { // this shows that word cannot // be placed horizontally matrix[0][0] = '@'; return matrix; } } return matrix;} // this function checks for the current word// if it can be placed vertically or not// x -> it represent index of row// y -> it represent index of column// currentWord -> it represent the// current word in word arrayvector<string> checkVertical(int x, int y, vector<string> matrix, string currentWord){ int n = currentWord.length(); for (int i = 0; i < n; i++) { if (matrix[x + i][y] == '#' || matrix[x + i][y] == currentWord[i]) { matrix[x + i][y] = currentWord[i]; } else { // this shows that word // cannot be placed vertically matrix[0][0] = '@'; return matrix; } } return matrix;} // this function recursively checks for every// word that can align vertically in one loop// and in another loop it checks for those words// that can align horizontally words -> it// contains all the words to fill in a crossword// puzzle matrix -> it contain the current// state of crossword index -> it represent// the index of current word n -> it represent// the length of row or column of the square matrixvoid solvePuzzle(vector<string>& words, vector<string> matrix, int index, int n){ if (index < words.size()) { string currentWord = words[index]; int maxLen = n - currentWord.length(); // loop to check the words that can align vertically. for (int i = 0; i < n; i++) { for (int j = 0; j <= maxLen; j++) { vector<string> temp = checkVertical(j, i, matrix, currentWord); if (temp[0][0] != '@') { solvePuzzle(words, temp, index + 1, n); } } } // loop to check the words that can align horizontally. for (int i = 0; i < n; i++) { for (int j = 0; j <= maxLen; j++) { vector<string> temp = checkHorizontal(i, j, matrix, currentWord); if (temp[0][0] != '@') { solvePuzzle(words, temp, index + 1, n); } } } } else { // calling of print function to // print the crossword puzzle cout << (ways + 1) << " way to solve the puzzle " << endl; printMatrix(matrix, n); cout << endl; // increase the ways ways++; return; }} // Driver Codeint main(){ // length of grid int n1 = 10; // matrix to hold the grid of puzzle vector<string> matrix; // take input of puzzle in matrix // input of grid of size n1 x n1 matrix.push_back("*#********"); matrix.push_back("*#********"); matrix.push_back("*#****#***"); matrix.push_back("*##***##**"); matrix.push_back("*#****#***"); matrix.push_back("*#****#***"); matrix.push_back("*#****#***"); matrix.push_back("*#*######*"); matrix.push_back("*#********"); matrix.push_back("***#######"); vector<string> words; // the words matrix will hold all // the words need to be filled in the grid words.push_back("PUNJAB"); words.push_back("JHARKHAND"); words.push_back("MIZORAM"); words.push_back("MUMBAI"); // initialize the number of ways // to solve the puzzle to zero ways = 0; // recursive function to solve the puzzle // Here 0 is the initial index of words array // n1 is length of grid solvePuzzle(words, matrix, 0, n1); cout << "Number of ways to fill the grid is " << ways << endl; return 0;} 1 way to solve the puzzle *J******** *H******** *A****P*** *R#***U#** *K****N*** *H****J*** *A****A*** *N*MUMBAI* *D******** ***MIZORAM Number of ways to fill the grid is 1 cpp-string programming-puzzle Matrix Recursion Recursion Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find the Sum of each Row and each Column of a Matrix Python program to add two Matrices Flood fill Algorithm - how to implement fill() in paint? Mathematics | L U Decomposition of a System of Linear Equations Multiplication of Matrix using threads Write a program to print all permutations of a given string Program for Tower of Hanoi Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Sum of the digits of a given number
[ { "code": null, "e": 24920, "s": 24892, "text": "\n26 May, 2018" }, { "code": null, "e": 25315, "s": 24920, "text": "A 10 x 10 Crossword grid is provided, along with a set of words (or names of places) which need to be filled into the grid. The cells in the grid are initially, either + signs or – signs. Cells marked with a ‘+’ have to be left as they are. Cells marked with a ‘-‘ need to be filled up with an appropriate character.You are also given an array of words that need to be filled in Crossword grid." }, { "code": null, "e": 25325, "s": 25315, "text": "Example :" }, { "code": null, "e": 25564, "s": 25325, "text": "Input :\n+++++++++-\n-++++++++-\n-------++-\n-++++++++-\n-++++++++-\n-++++-----\n------+++-\n-++++++++-\n+---------\n++++++++++\n\nOutput :\n+++++++++C\nP++++++++H\nHISTORY++E\nY++++++++M\nS++++++++I\nI++++MATHS\nCIVICS+++T\nS++++++++R\n+GEOGRAPHY\n++++++++++\n" }, { "code": null, "e": 25851, "s": 25564, "text": "The approach behind this is to recursively check for each word in the vertical position and in the horizontal position. Then fill the word in the matrix that can be the best fit in the corresponding position of the grid, then update the crossword grid by filling the gap with that word." }, { "code": "// CPP code to fill the crossword puzzle#include <bits/stdc++.h>using namespace std; // ways are to calculate the number of// possible ways to fill the gridint ways = 0; // this function is used to print// the resultant matrixvoid printMatrix(vector<string>& matrix, int n){ for (int i = 0; i < n; i++) cout << matrix[i] << endl;} // this function checks for the current word// if it can be placed horizontally or not// x -> it represent index of row// y -> it represent index of column// currentWord -> it represent the// current word in word arrayvector<string> checkHorizontal(int x, int y, vector<string> matrix, string currentWord){ int n = currentWord.length(); for (int i = 0; i < n; i++) { if (matrix[x][y + i] == '#' || matrix[x][y + i] == currentWord[i]) { matrix[x][y + i] = currentWord[i]; } else { // this shows that word cannot // be placed horizontally matrix[0][0] = '@'; return matrix; } } return matrix;} // this function checks for the current word// if it can be placed vertically or not// x -> it represent index of row// y -> it represent index of column// currentWord -> it represent the// current word in word arrayvector<string> checkVertical(int x, int y, vector<string> matrix, string currentWord){ int n = currentWord.length(); for (int i = 0; i < n; i++) { if (matrix[x + i][y] == '#' || matrix[x + i][y] == currentWord[i]) { matrix[x + i][y] = currentWord[i]; } else { // this shows that word // cannot be placed vertically matrix[0][0] = '@'; return matrix; } } return matrix;} // this function recursively checks for every// word that can align vertically in one loop// and in another loop it checks for those words// that can align horizontally words -> it// contains all the words to fill in a crossword// puzzle matrix -> it contain the current// state of crossword index -> it represent// the index of current word n -> it represent// the length of row or column of the square matrixvoid solvePuzzle(vector<string>& words, vector<string> matrix, int index, int n){ if (index < words.size()) { string currentWord = words[index]; int maxLen = n - currentWord.length(); // loop to check the words that can align vertically. for (int i = 0; i < n; i++) { for (int j = 0; j <= maxLen; j++) { vector<string> temp = checkVertical(j, i, matrix, currentWord); if (temp[0][0] != '@') { solvePuzzle(words, temp, index + 1, n); } } } // loop to check the words that can align horizontally. for (int i = 0; i < n; i++) { for (int j = 0; j <= maxLen; j++) { vector<string> temp = checkHorizontal(i, j, matrix, currentWord); if (temp[0][0] != '@') { solvePuzzle(words, temp, index + 1, n); } } } } else { // calling of print function to // print the crossword puzzle cout << (ways + 1) << \" way to solve the puzzle \" << endl; printMatrix(matrix, n); cout << endl; // increase the ways ways++; return; }} // Driver Codeint main(){ // length of grid int n1 = 10; // matrix to hold the grid of puzzle vector<string> matrix; // take input of puzzle in matrix // input of grid of size n1 x n1 matrix.push_back(\"*#********\"); matrix.push_back(\"*#********\"); matrix.push_back(\"*#****#***\"); matrix.push_back(\"*##***##**\"); matrix.push_back(\"*#****#***\"); matrix.push_back(\"*#****#***\"); matrix.push_back(\"*#****#***\"); matrix.push_back(\"*#*######*\"); matrix.push_back(\"*#********\"); matrix.push_back(\"***#######\"); vector<string> words; // the words matrix will hold all // the words need to be filled in the grid words.push_back(\"PUNJAB\"); words.push_back(\"JHARKHAND\"); words.push_back(\"MIZORAM\"); words.push_back(\"MUMBAI\"); // initialize the number of ways // to solve the puzzle to zero ways = 0; // recursive function to solve the puzzle // Here 0 is the initial index of words array // n1 is length of grid solvePuzzle(words, matrix, 0, n1); cout << \"Number of ways to fill the grid is \" << ways << endl; return 0;}", "e": 30587, "s": 25851, "text": null }, { "code": null, "e": 30763, "s": 30587, "text": "1 way to solve the puzzle \n*J********\n*H********\n*A****P***\n*R#***U#**\n*K****N***\n*H****J***\n*A****A***\n*N*MUMBAI*\n*D********\n***MIZORAM\n\nNumber of ways to fill the grid is 1\n" }, { "code": null, "e": 30774, "s": 30763, "text": "cpp-string" }, { "code": null, "e": 30793, "s": 30774, "text": "programming-puzzle" }, { "code": null, "e": 30800, "s": 30793, "text": "Matrix" }, { "code": null, "e": 30810, "s": 30800, "text": "Recursion" }, { "code": null, "e": 30820, "s": 30810, "text": "Recursion" }, { "code": null, "e": 30827, "s": 30820, "text": "Matrix" }, { "code": null, "e": 30925, "s": 30827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30934, "s": 30925, "text": "Comments" }, { "code": null, "e": 30947, "s": 30934, "text": "Old Comments" }, { "code": null, "e": 31011, "s": 30947, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 31046, "s": 31011, "text": "Python program to add two Matrices" }, { "code": null, "e": 31103, "s": 31046, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 31167, "s": 31103, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 31206, "s": 31167, "text": "Multiplication of Matrix using threads" }, { "code": null, "e": 31266, "s": 31206, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31293, "s": 31266, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 31378, "s": 31293, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 31388, "s": 31378, "text": "Recursion" } ]
Ubuntu - Installing MySQL and Python
MySQL and Python are famous database and development software respectively. These are normally installed on Linux-based systems. Let’s see how we can get them installed on Ubuntu server environments. The first thing to do is to find out what is the version of Python installed on the system. We can find this issuing the following command. Python –v Where the –v option specifies to show what is the version of Python installed. The following screenshot shows a sample of the output of the above command. From the above output, we can see that the version of Python installed is version 2.7. There is another way to see if Python is installed via the following commands. Python –V Python3 –V The later command is used to see the version 3 of Python installed. If we want to have the latest version of Python installed, then we need to issue the following statement. sudo apt-get install python3 The above command will download the necessary packages for Python and have it installed. To install MySQL, the following steps need to be followed. Step 1 − Issue the apt-get command to ensure all operating system packages are up to date. sudo apt-get update Step 2 − Once all the packages have been updated, it is time to get the packages for MySQL. sudo apt-get install mysql-server The above command will start the download of all the relevant packages for MySQL. Once the download completes and the installation starts, the installer will first ask to configure a root password. Step 3 − Enter the required password and click the OK button. It will also prompt to re-enter the password. Step 4 − To see the MySQL process running, run the following command. ps –ef | grep mysql The following screenshot shows mysqld which is the daemon process for mysql running in the background. Step 5 − To configure mysql, run the following command. /usr/bin/mysql_secure_installation It prompts to enter the root password which was entered during the installation process. Step 6 − Enter the password and hit Enter. Now, it prompts on whether we want to change the root password. Step 7 − Enter ‘N’ for No and proceed. Again, it prompts on whether we want to remove the Anonymous access. Step 8 − When connecting from other machines on this database, it is advised to keep the default options as ‘N’ for both anonymous users and disallow root login remotely. Step 9 − It is advised to provide the option as No for the options of Remove test database as well. We can enter ‘Y’ to reload the privileges table. Finally, the configuration of MySQL will be complete. 8 Lectures 31 mins Musab Zayadneh 14 Lectures 1.5 hours Satish 26 Lectures 1.5 hours YouAccel Print Add Notes Bookmark this page
[ { "code": null, "e": 2333, "s": 2133, "text": "MySQL and Python are famous database and development software respectively. These are normally installed on Linux-based systems. Let’s see how we can get them installed on Ubuntu server environments." }, { "code": null, "e": 2473, "s": 2333, "text": "The first thing to do is to find out what is the version of Python installed on the system. We can find this issuing the following command." }, { "code": null, "e": 2484, "s": 2473, "text": "Python –v\n" }, { "code": null, "e": 2639, "s": 2484, "text": "Where the –v option specifies to show what is the version of Python installed. The following screenshot shows a sample of the output of the above command." }, { "code": null, "e": 2726, "s": 2639, "text": "From the above output, we can see that the version of Python installed is version 2.7." }, { "code": null, "e": 2805, "s": 2726, "text": "There is another way to see if Python is installed via the following commands." }, { "code": null, "e": 2816, "s": 2805, "text": "Python –V\n" }, { "code": null, "e": 2828, "s": 2816, "text": "Python3 –V\n" }, { "code": null, "e": 2896, "s": 2828, "text": "The later command is used to see the version 3 of Python installed." }, { "code": null, "e": 3002, "s": 2896, "text": "If we want to have the latest version of Python installed, then we need to issue the following statement." }, { "code": null, "e": 3032, "s": 3002, "text": "sudo apt-get install python3\n" }, { "code": null, "e": 3121, "s": 3032, "text": "The above command will download the necessary packages for Python and have it installed." }, { "code": null, "e": 3180, "s": 3121, "text": "To install MySQL, the following steps need to be followed." }, { "code": null, "e": 3271, "s": 3180, "text": "Step 1 − Issue the apt-get command to ensure all operating system packages are up to date." }, { "code": null, "e": 3294, "s": 3271, "text": "sudo apt-get update \n" }, { "code": null, "e": 3386, "s": 3294, "text": "Step 2 − Once all the packages have been updated, it is time to get the packages for MySQL." }, { "code": null, "e": 3421, "s": 3386, "text": "sudo apt-get install mysql-server\n" }, { "code": null, "e": 3503, "s": 3421, "text": "The above command will start the download of all the relevant packages for MySQL." }, { "code": null, "e": 3619, "s": 3503, "text": "Once the download completes and the installation starts, the installer will first ask to configure a root password." }, { "code": null, "e": 3727, "s": 3619, "text": "Step 3 − Enter the required password and click the OK button. It will also prompt to re-enter the password." }, { "code": null, "e": 3797, "s": 3727, "text": "Step 4 − To see the MySQL process running, run the following command." }, { "code": null, "e": 3818, "s": 3797, "text": "ps –ef | grep mysql\n" }, { "code": null, "e": 3921, "s": 3818, "text": "The following screenshot shows mysqld which is the daemon process for mysql running in the background." }, { "code": null, "e": 3977, "s": 3921, "text": "Step 5 − To configure mysql, run the following command." }, { "code": null, "e": 4013, "s": 3977, "text": "/usr/bin/mysql_secure_installation\n" }, { "code": null, "e": 4102, "s": 4013, "text": "It prompts to enter the root password which was entered during the installation process." }, { "code": null, "e": 4145, "s": 4102, "text": "Step 6 − Enter the password and hit Enter." }, { "code": null, "e": 4209, "s": 4145, "text": "Now, it prompts on whether we want to change the root password." }, { "code": null, "e": 4248, "s": 4209, "text": "Step 7 − Enter ‘N’ for No and proceed." }, { "code": null, "e": 4317, "s": 4248, "text": "Again, it prompts on whether we want to remove the Anonymous access." }, { "code": null, "e": 4488, "s": 4317, "text": "Step 8 − When connecting from other machines on this database, it is advised to keep the default options as ‘N’ for both anonymous users and disallow root login remotely." }, { "code": null, "e": 4637, "s": 4488, "text": "Step 9 − It is advised to provide the option as No for the options of Remove test database as well. We can enter ‘Y’ to reload the privileges table." }, { "code": null, "e": 4691, "s": 4637, "text": "Finally, the configuration of MySQL will be complete." }, { "code": null, "e": 4722, "s": 4691, "text": "\n 8 Lectures \n 31 mins\n" }, { "code": null, "e": 4738, "s": 4722, "text": " Musab Zayadneh" }, { "code": null, "e": 4773, "s": 4738, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4781, "s": 4773, "text": " Satish" }, { "code": null, "e": 4816, "s": 4781, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4826, "s": 4816, "text": " YouAccel" }, { "code": null, "e": 4833, "s": 4826, "text": " Print" }, { "code": null, "e": 4844, "s": 4833, "text": " Add Notes" } ]
LESS - Parametric Mixins
Parametric mixins use one or more parameters that extend functionality of LESS by taking arguments and its properties to customize the mixin output when mixed into another block. For instance, consider a simple LESS code snippet − .border(@width; @style; @color) { border: @width @style @color; } .myheader { .border(2px; dashed; green); } Here we are using the parametric mixin as .border with three parameters - width, style and color. Using these parameters, you can customize the mixin output with the passed parameters value. The following table describes the different types of parametric mixins along with description. Parameters can be separated using commas or semicolon. Mixins provide parameter values instead of positions by using their names. When a mixin is called, the @arguments include all the passed arguments. Mixin takes variable number of arguments by using ..... Change the behavior of mixin by passing parameters to it. 20 Lectures 1 hours Anadi Sharma 44 Lectures 7.5 hours Eduonix Learning Solutions 17 Lectures 2 hours Zach Miller 23 Lectures 1.5 hours Zach Miller 34 Lectures 4 hours Syed Raza 31 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2729, "s": 2550, "text": "Parametric mixins use one or more parameters that extend functionality of LESS by taking arguments and its properties to customize the mixin output when mixed into another block." }, { "code": null, "e": 2781, "s": 2729, "text": "For instance, consider a simple LESS code snippet −" }, { "code": null, "e": 2897, "s": 2781, "text": ".border(@width; @style; @color) {\n border: @width @style @color;\n}\n\n.myheader {\n .border(2px; dashed; green);\n}" }, { "code": null, "e": 3088, "s": 2897, "text": "Here we are using the parametric mixin as .border with three parameters - width, style and color. Using these parameters, you can customize the mixin output with the passed parameters value." }, { "code": null, "e": 3183, "s": 3088, "text": "The following table describes the different types of parametric mixins along with description." }, { "code": null, "e": 3238, "s": 3183, "text": "Parameters can be separated using commas or semicolon." }, { "code": null, "e": 3313, "s": 3238, "text": "Mixins provide parameter values instead of positions by using their names." }, { "code": null, "e": 3386, "s": 3313, "text": "When a mixin is called, the @arguments include all the passed arguments." }, { "code": null, "e": 3442, "s": 3386, "text": "Mixin takes variable number of arguments by using ....." }, { "code": null, "e": 3500, "s": 3442, "text": "Change the behavior of mixin by passing parameters to it." }, { "code": null, "e": 3533, "s": 3500, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 3547, "s": 3533, "text": " Anadi Sharma" }, { "code": null, "e": 3582, "s": 3547, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3610, "s": 3582, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3643, "s": 3610, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 3656, "s": 3643, "text": " Zach Miller" }, { "code": null, "e": 3691, "s": 3656, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3704, "s": 3691, "text": " Zach Miller" }, { "code": null, "e": 3737, "s": 3704, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3748, "s": 3737, "text": " Syed Raza" }, { "code": null, "e": 3781, "s": 3748, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 3801, "s": 3781, "text": " Harshit Srivastava" }, { "code": null, "e": 3808, "s": 3801, "text": " Print" }, { "code": null, "e": 3819, "s": 3808, "text": " Add Notes" } ]
Windows 10 Development - XAML Controls
XAML Stands for Extensible Application Markup Language. It is a User Interface framework and it offers an extensive library of controls that support UI development for Windows. Some of them have a visual representation such as a Button, Textbox and TextBlock etc; while other controls are used as the containers for other controls or content, such as images etc. All the XAML controls are inherited from “System.Windows.Controls.Control”. XAML is used in many important Microsoft platforms such as the Windows Presentation Foundation (WPF), the Silverlight and now, Windows apps. Now, Microsoft Office 2016 is also a family of UWP apps. XAML is a rich Platform, which provides very cool features and controls that can be used in UWP applications. The complete inheritance hierarchy of controls is shown below. Layout of Controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting the layout panels − Positions of the child elements. Sizes of the child elements. Layering of overlapping child elements on top of each other. A list of Layout Controls is given below − StackPanel StackPanel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line either horizontally or vertically based on orientation property. WrapPanel In WrapPanel, child elements are positioned in sequential order from left to right or from top to bottom based on the orientation property. The only difference between StackPanel and WrapPanel is that it does not stack all the child elements into a single line but it wraps the remaining elements to another line if there is no space left. DockPanel DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel you can easily dock child elements to top, bottom, right, left and center with Dock property. With LastChildFill property, the last child element fill the remaining space regardless of any other dock value when set for that element. Canvas Canvas is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to any side such as left, right, top and bottom. Typically Canvas is used for 2D graphic elements (such as Ellipse, Rectangle etc.) but not for UI elements because specifying absolute coordinates give trouble while resizing, localizing or scaling in an XAML application. Grid Grid provides a flexible area, which consists of rows and columns. In Grid, child elements can be arranged in a tabular form. Elements can be added to any specific row and column by using Grid.Row and Grid.Column properties. SplitView SplitView represents a container with two views; one view for the main content and another view that is typically used for navigation commands. RelativePanel RelativePanel defines an area within which you can position and align child objects in relation to each other or the parent panel. ViewBox ViewBox defines a content decorator that can stretch and scale a single child to fill the available space. FlipView FlipView represents an item’s control that displays one item at a time, and enables "flip" behavior for traversing its collection of items. GridView GridView is a control that presents a collection of items in rows and columns and can be scrolled horizontally. Here is a list of UI Controls, which are visible to the end users. Button A control that responds to user input Calendar Represents a control that enables a user to select a date by using a visual calendar display. CheckBox A control that a user can select or clear. ComboBox A drop-down list of items, a user can select from. ContextMenu Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. DataGrid Represents a control that displays data in a customizable grid. DatePicker A control that lets a user select a date. Dialogs An application may also display additional windows to do the user to gather or display important information. Flyout Represents a control that displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping outside of it, pressing the device’s back button, or pressing the ‘Esc’ key. Image A control that presents an image. ListBox A control that presents an inline list of items that the user can select from. Menus Represents a Windows menu control that enables you to hierarchically organize the elements associated with commands and event handlers. MenuFlyout Represents a flyout that displays a menu of commands. PasswordBox A control for entering passwords. Popup Displays content on top of the existing content, within the bounds of the application window. ProgressBar A control that indicates the progress by displaying a bar. ProgressRing A control that indicates the indeterminate progress by displaying a ring. RadioButton A control that allows a user to select a single option from a group of options. RichEditBox A control that lets a user edit rich text documents with content like formatted text, hyperlinks, and images. ScrollViewer A container control that lets the user pan and zoom its content. SearchBox A control that lets a user enter search queries. Slider A control that lets the user select from a range of values by moving a Thumb control along a track. TextBlock A control that displays the text. TimePicker A control that lets a user set a time value. ToggleButton A button that can be toggled between 2 states. ToolTip A pop-up window that displays information for an element. Window The root window which provides minimize/maximize option, Title bar, border and close button. Given below is an example, which contains different types of controls in a SplitView. In XAML file, different controls are created with some properties and events. <Page x:Class = "UWPControlsDemo.MainPage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "using:UWPControlsDemo" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable = "d"> <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> <StackPanel Margin = "20"> <StackPanel Orientation = "Horizontal"> <ToggleButton x:Name = "HamburgerButton" FontFamily = "Segoe MDL2 Assets" Content = "" Checked = "HandleCheck" Unchecked = "HandleUnchecked" HorizontalAlignment = "Center"/> <AppBarButton Icon = "Like" /> <AppBarButton Icon = "Dislike" /> <AppBarSeparator/> <AppBarButton Icon = "Accept" /> <AppBarButton Icon = "Add" /> </StackPanel> <SplitView x:Name = "splitView" DisplayMode = "Inline" OpenPaneLength = "296"> <SplitView.Pane> <StackPanel> <TextBlock Text = "SplitView Pane" FontSize = "36" VerticalAlignment = "Center" HorizontalAlignment = "Center" Margin = "10"/> <Button Content = "Options" Margin = "10"> <Button.Flyout> <MenuFlyout> <MenuFlyoutItem Text = "Reset"/> <MenuFlyoutSeparator/> <MenuFlyoutItem Text = "Repeat"/> <MenuFlyoutItem Text = "Shuffle"/> </MenuFlyout> </Button.Flyout> </Button> </StackPanel> </SplitView.Pane> <StackPanel> <TextBlock Text = "SplitView Content" FontSize = "36" VerticalAlignment = "Center" HorizontalAlignment = "Center" Margin = "10"/> <Border BorderThickness = "3" BorderBrush = "Red" Margin = "5"> <StackPanel Orientation = "Horizontal"> <TextBlock Text = "Hyperlink example" Margin = "5"/> <HyperlinkButton Content = "www.microsoft.com" NavigateUri = "http://www.microsoft.com"/> </StackPanel> </Border> <RelativePanel BorderBrush = "Red" BorderThickness = "2" CornerRadius = "10" Padding = "12" Margin = "5"> <TextBlock x:Name = "txt" Text = "Relative Panel example" RelativePanel.AlignLeftWithPanel = "True" Margin = "5,0,0,0"/> <TextBox x:Name = "textBox1" RelativePanel.RightOf = "btn" Margin = "5,0,0,0"/> <Button x:Name = "btn" Content = "Name" RelativePanel.RightOf = "txt" Margin = "5,0,0,0"/> </RelativePanel> <FlipView Height = "400" Margin = "10" Width = "400"> <Image Source = "Images/DSC_0104.JPG"/> <Image Source = "Images/DSC_0080.JPG"/> <Image Source = "Images/DSC_0076.JPG"/> <Image Source = "Images/thGTF7BWGW.jpg"/> </FlipView> </StackPanel> </SplitView> </StackPanel> </Grid> </Page> Given below is the Events implementation in C#. using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPControlsDemo { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void HandleCheck(object sender, RoutedEventArgs e) { splitView.IsPaneOpen = true; } private void HandleUnchecked(object sender, RoutedEventArgs e) { splitView.IsPaneOpen = false; } } } When the above code is compiled and executed, you will see the following window − When you click on the hamburger button on the top left side, it will open/close the SplitView pane. In the SplitView Pane, you can see the Flyout, MenuFlyout and FlipView controls. In the SplitView Content, you can see the Hyperlink, Relative Panel, ViewBox and other buttons and textbox controls. 23 Lectures 2 hours Pavan Lalwani 37 Lectures 13 hours Trevoir Williams 46 Lectures 3.5 hours Fettah Ben 55 Lectures 6 hours Total Seminars 20 Lectures 2.5 hours Brandon Dennis 52 Lectures 9 hours Fabrice Chrzanowski Print Add Notes Bookmark this page
[ { "code": null, "e": 2723, "s": 2284, "text": "XAML Stands for Extensible Application Markup Language. It is a User Interface framework and it offers an extensive library of controls that support UI development for Windows. Some of them have a visual representation such as a Button, Textbox and TextBlock etc; while other controls are used as the containers for other controls or content, such as images etc. All the XAML controls are inherited from “System.Windows.Controls.Control”." }, { "code": null, "e": 3031, "s": 2723, "text": "XAML is used in many important Microsoft platforms such as the Windows Presentation Foundation (WPF), the Silverlight and now, Windows apps. Now, Microsoft Office 2016 is also a family of UWP apps. XAML is a rich Platform, which provides very cool features and controls that can be used in UWP applications." }, { "code": null, "e": 3094, "s": 3031, "text": "The complete inheritance hierarchy of controls is shown below." }, { "code": null, "e": 3321, "s": 3094, "text": "Layout of Controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting the layout panels −" }, { "code": null, "e": 3354, "s": 3321, "text": "Positions of the child elements." }, { "code": null, "e": 3383, "s": 3354, "text": "Sizes of the child elements." }, { "code": null, "e": 3444, "s": 3383, "text": "Layering of overlapping child elements on top of each other." }, { "code": null, "e": 3487, "s": 3444, "text": "A list of Layout Controls is given below −" }, { "code": null, "e": 3498, "s": 3487, "text": "StackPanel" }, { "code": null, "e": 3683, "s": 3498, "text": "StackPanel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line either horizontally or vertically based on orientation property." }, { "code": null, "e": 3693, "s": 3683, "text": "WrapPanel" }, { "code": null, "e": 4034, "s": 3693, "text": "In WrapPanel, child elements are positioned in sequential order from left to right or from top to bottom based on the orientation property. The only difference between StackPanel and WrapPanel is that it does not stack all the child elements into a single line but it wraps the remaining elements to another line if there is no space left." }, { "code": null, "e": 4044, "s": 4034, "text": "DockPanel" }, { "code": null, "e": 4264, "s": 4044, "text": "DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel you can easily dock child elements to top, bottom, right, left and center with Dock property." }, { "code": null, "e": 4403, "s": 4264, "text": "With LastChildFill property, the last child element fill the remaining space regardless of any other dock value when set for that element." }, { "code": null, "e": 4410, "s": 4403, "text": "Canvas" }, { "code": null, "e": 4803, "s": 4410, "text": "Canvas is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to any side such as left, right, top and bottom. Typically Canvas is used for 2D graphic elements (such as Ellipse, Rectangle etc.) but not for UI elements because specifying absolute coordinates give trouble while resizing, localizing or scaling in an XAML application." }, { "code": null, "e": 4808, "s": 4803, "text": "Grid" }, { "code": null, "e": 5033, "s": 4808, "text": "Grid provides a flexible area, which consists of rows and columns. In Grid, child elements can be arranged in a tabular form. Elements can be added to any specific row and column by using Grid.Row and Grid.Column properties." }, { "code": null, "e": 5043, "s": 5033, "text": "SplitView" }, { "code": null, "e": 5187, "s": 5043, "text": "SplitView represents a container with two views; one view for the main content and another view that is typically used for navigation commands." }, { "code": null, "e": 5201, "s": 5187, "text": "RelativePanel" }, { "code": null, "e": 5332, "s": 5201, "text": "RelativePanel defines an area within which you can position and align child objects in relation to each other or the parent panel." }, { "code": null, "e": 5340, "s": 5332, "text": "ViewBox" }, { "code": null, "e": 5447, "s": 5340, "text": "ViewBox defines a content decorator that can stretch and scale a single child to fill the available space." }, { "code": null, "e": 5456, "s": 5447, "text": "FlipView" }, { "code": null, "e": 5596, "s": 5456, "text": "FlipView represents an item’s control that displays one item at a time, and enables \"flip\" behavior for traversing its collection of items." }, { "code": null, "e": 5605, "s": 5596, "text": "GridView" }, { "code": null, "e": 5717, "s": 5605, "text": "GridView is a control that presents a collection of items in rows and columns and can be scrolled horizontally." }, { "code": null, "e": 5784, "s": 5717, "text": "Here is a list of UI Controls, which are visible to the end users." }, { "code": null, "e": 5791, "s": 5784, "text": "Button" }, { "code": null, "e": 5829, "s": 5791, "text": "A control that responds to user input" }, { "code": null, "e": 5838, "s": 5829, "text": "Calendar" }, { "code": null, "e": 5932, "s": 5838, "text": "Represents a control that enables a user to select a date by using a visual calendar display." }, { "code": null, "e": 5941, "s": 5932, "text": "CheckBox" }, { "code": null, "e": 5984, "s": 5941, "text": "A control that a user can select or clear." }, { "code": null, "e": 5993, "s": 5984, "text": "ComboBox" }, { "code": null, "e": 6044, "s": 5993, "text": "A drop-down list of items, a user can select from." }, { "code": null, "e": 6056, "s": 6044, "text": "ContextMenu" }, { "code": null, "e": 6206, "s": 6056, "text": "Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element." }, { "code": null, "e": 6215, "s": 6206, "text": "DataGrid" }, { "code": null, "e": 6279, "s": 6215, "text": "Represents a control that displays data in a customizable grid." }, { "code": null, "e": 6290, "s": 6279, "text": "DatePicker" }, { "code": null, "e": 6332, "s": 6290, "text": "A control that lets a user select a date." }, { "code": null, "e": 6340, "s": 6332, "text": "Dialogs" }, { "code": null, "e": 6450, "s": 6340, "text": "An application may also display additional windows to do the user to gather or display important information." }, { "code": null, "e": 6457, "s": 6450, "text": "Flyout" }, { "code": null, "e": 6714, "s": 6457, "text": "Represents a control that displays lightweight UI that is either information, or requires user interaction. Unlike a dialog, a Flyout can be light dismissed by clicking or tapping outside of it, pressing the device’s back button, or pressing the ‘Esc’ key." }, { "code": null, "e": 6720, "s": 6714, "text": "Image" }, { "code": null, "e": 6754, "s": 6720, "text": "A control that presents an image." }, { "code": null, "e": 6762, "s": 6754, "text": "ListBox" }, { "code": null, "e": 6841, "s": 6762, "text": "A control that presents an inline list of items that the user can select from." }, { "code": null, "e": 6847, "s": 6841, "text": "Menus" }, { "code": null, "e": 6983, "s": 6847, "text": "Represents a Windows menu control that enables you to hierarchically organize the elements associated with commands and event handlers." }, { "code": null, "e": 6994, "s": 6983, "text": "MenuFlyout" }, { "code": null, "e": 7048, "s": 6994, "text": "Represents a flyout that displays a menu of commands." }, { "code": null, "e": 7060, "s": 7048, "text": "PasswordBox" }, { "code": null, "e": 7094, "s": 7060, "text": "A control for entering passwords." }, { "code": null, "e": 7100, "s": 7094, "text": "Popup" }, { "code": null, "e": 7194, "s": 7100, "text": "Displays content on top of the existing content, within the bounds of the application window." }, { "code": null, "e": 7206, "s": 7194, "text": "ProgressBar" }, { "code": null, "e": 7265, "s": 7206, "text": "A control that indicates the progress by displaying a bar." }, { "code": null, "e": 7278, "s": 7265, "text": "ProgressRing" }, { "code": null, "e": 7352, "s": 7278, "text": "A control that indicates the indeterminate progress by displaying a ring." }, { "code": null, "e": 7364, "s": 7352, "text": "RadioButton" }, { "code": null, "e": 7444, "s": 7364, "text": "A control that allows a user to select a single option from a group of options." }, { "code": null, "e": 7456, "s": 7444, "text": "RichEditBox" }, { "code": null, "e": 7566, "s": 7456, "text": "A control that lets a user edit rich text documents with content like formatted text, hyperlinks, and images." }, { "code": null, "e": 7579, "s": 7566, "text": "ScrollViewer" }, { "code": null, "e": 7644, "s": 7579, "text": "A container control that lets the user pan and zoom its content." }, { "code": null, "e": 7654, "s": 7644, "text": "SearchBox" }, { "code": null, "e": 7703, "s": 7654, "text": "A control that lets a user enter search queries." }, { "code": null, "e": 7710, "s": 7703, "text": "Slider" }, { "code": null, "e": 7810, "s": 7710, "text": "A control that lets the user select from a range of values by moving a Thumb control along a track." }, { "code": null, "e": 7820, "s": 7810, "text": "TextBlock" }, { "code": null, "e": 7854, "s": 7820, "text": "A control that displays the text." }, { "code": null, "e": 7865, "s": 7854, "text": "TimePicker" }, { "code": null, "e": 7910, "s": 7865, "text": "A control that lets a user set a time value." }, { "code": null, "e": 7923, "s": 7910, "text": "ToggleButton" }, { "code": null, "e": 7970, "s": 7923, "text": "A button that can be toggled between 2 states." }, { "code": null, "e": 7978, "s": 7970, "text": "ToolTip" }, { "code": null, "e": 8036, "s": 7978, "text": "A pop-up window that displays information for an element." }, { "code": null, "e": 8043, "s": 8036, "text": "Window" }, { "code": null, "e": 8136, "s": 8043, "text": "The root window which provides minimize/maximize option, Title bar, border and close button." }, { "code": null, "e": 8300, "s": 8136, "text": "Given below is an example, which contains different types of controls in a SplitView. In XAML file, different controls are created with some properties and events." }, { "code": null, "e": 12000, "s": 8300, "text": "<Page \n x:Class = \"UWPControlsDemo.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:local = \"using:UWPControlsDemo\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n mc:Ignorable = \"d\">\n \n <Grid Background = \"{ThemeResource ApplicationPageBackgroundThemeBrush}\"> \n <StackPanel Margin = \"20\"> \n\t\t\n <StackPanel Orientation = \"Horizontal\"> \n\t\t\t\n <ToggleButton x:Name = \"HamburgerButton\" FontFamily = \"Segoe MDL2 Assets\"\n Content = \"\" Checked = \"HandleCheck\" Unchecked = \"HandleUnchecked\" \n HorizontalAlignment = \"Center\"/> \n\t\t\t\t\t\n <AppBarButton Icon = \"Like\" />\n <AppBarButton Icon = \"Dislike\" /> \n <AppBarSeparator/> \n <AppBarButton Icon = \"Accept\" /> \n <AppBarButton Icon = \"Add\" /> \n\t\t\t\t\n </StackPanel> \n\t\t\t\n <SplitView x:Name = \"splitView\" DisplayMode = \"Inline\" \n OpenPaneLength = \"296\"> \n\t\t\t\t\n <SplitView.Pane> \n <StackPanel> \n <TextBlock Text = \"SplitView Pane\" FontSize = \"36\" \n VerticalAlignment = \"Center\" HorizontalAlignment = \"Center\" \n Margin = \"10\"/> \n\t\t\t\t\t\t\t\n <Button Content = \"Options\" Margin = \"10\"> \n\t\t\t\t\t\t\n <Button.Flyout> \n <MenuFlyout> \n <MenuFlyoutItem Text = \"Reset\"/> \n <MenuFlyoutSeparator/> \n <MenuFlyoutItem Text = \"Repeat\"/> \n <MenuFlyoutItem Text = \"Shuffle\"/> \n </MenuFlyout> \n </Button.Flyout> \n\t\t\t\t\t\t\t\n </Button> \n\t\t\t\t\t\t\n </StackPanel> \n </SplitView.Pane> \n\t\t\t\t\t\n <StackPanel>\n\t\t\t\t\n <TextBlock Text = \"SplitView Content\" FontSize = \"36\" \n VerticalAlignment = \"Center\" HorizontalAlignment = \"Center\" \n Margin = \"10\"/>\n\t\t\t\t\t\t\n <Border BorderThickness = \"3\" BorderBrush = \"Red\" Margin = \"5\"> \n <StackPanel Orientation = \"Horizontal\"> \n <TextBlock Text = \"Hyperlink example\" Margin = \"5\"/> \n <HyperlinkButton Content = \"www.microsoft.com\" \n NavigateUri = \"http://www.microsoft.com\"/> \n </StackPanel> \n </Border> \n\t\t\t\t\t\n <RelativePanel BorderBrush = \"Red\" BorderThickness = \"2\" \n CornerRadius = \"10\" Padding = \"12\" Margin = \"5\"> \n\t\t\t\t\t\t\n <TextBlock x:Name = \"txt\" Text = \"Relative Panel example\" \n RelativePanel.AlignLeftWithPanel = \"True\" \n Margin = \"5,0,0,0\"/> \n\t\t\t\t\t\t\t\n <TextBox x:Name = \"textBox1\" RelativePanel.RightOf = \"btn\" \n Margin = \"5,0,0,0\"/> \n\t\t\t\t\t\t\t\n <Button x:Name = \"btn\" Content = \"Name\" \n RelativePanel.RightOf = \"txt\" Margin = \"5,0,0,0\"/> \n\t\t\t\t\t\t\t\n </RelativePanel> \n\t\t\t\t\t\n <FlipView Height = \"400\" Margin = \"10\" Width = \"400\"> \n <Image Source = \"Images/DSC_0104.JPG\"/> \n <Image Source = \"Images/DSC_0080.JPG\"/> \n <Image Source = \"Images/DSC_0076.JPG\"/> \n <Image Source = \"Images/thGTF7BWGW.jpg\"/> \n </FlipView>\n\t\t\t\t\t\n </StackPanel> \n\t\t\t\t\n </SplitView> \n\t\t\t\n </StackPanel> \n\t\t\n </Grid> \n\t\n</Page> " }, { "code": null, "e": 12048, "s": 12000, "text": "Given below is the Events implementation in C#." }, { "code": null, "e": 12783, "s": 12048, "text": "using Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Media;\n \n// The Blank Page item template is documented at\n http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409\n \nnamespace UWPControlsDemo {\n \n /// <summary> \n /// An empty page that can be used on its own or navigated to within a Frame. \n /// </summary> \n\t\n public sealed partial class MainPage : Page {\n \n public MainPage() {\n this.InitializeComponent(); \n } \n\t\t\n private void HandleCheck(object sender, RoutedEventArgs e) { \n splitView.IsPaneOpen = true; \n }\n\t\t\n private void HandleUnchecked(object sender, RoutedEventArgs e) {\n splitView.IsPaneOpen = false; \n }\n\t\t\n }\n\t\n} " }, { "code": null, "e": 12865, "s": 12783, "text": "When the above code is compiled and executed, you will see the following window −" }, { "code": null, "e": 12965, "s": 12865, "text": "When you click on the hamburger button on the top left side, it will open/close the SplitView pane." }, { "code": null, "e": 13046, "s": 12965, "text": "In the SplitView Pane, you can see the Flyout, MenuFlyout and FlipView controls." }, { "code": null, "e": 13163, "s": 13046, "text": "In the SplitView Content, you can see the Hyperlink, Relative Panel, ViewBox and other buttons and textbox controls." }, { "code": null, "e": 13196, "s": 13163, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 13211, "s": 13196, "text": " Pavan Lalwani" }, { "code": null, "e": 13245, "s": 13211, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 13263, "s": 13245, "text": " Trevoir Williams" }, { "code": null, "e": 13298, "s": 13263, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 13310, "s": 13298, "text": " Fettah Ben" }, { "code": null, "e": 13343, "s": 13310, "text": "\n 55 Lectures \n 6 hours \n" }, { "code": null, "e": 13359, "s": 13343, "text": " Total Seminars" }, { "code": null, "e": 13394, "s": 13359, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13410, "s": 13394, "text": " Brandon Dennis" }, { "code": null, "e": 13443, "s": 13410, "text": "\n 52 Lectures \n 9 hours \n" }, { "code": null, "e": 13464, "s": 13443, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 13471, "s": 13464, "text": " Print" }, { "code": null, "e": 13482, "s": 13471, "text": " Add Notes" } ]
C library function - setbuf()
The C library function void setbuf(FILE *stream, char *buffer) defines how a stream should be buffered. This function should be called once the file associated with the stream has already been opened, but before any input or output operation has taken place. Following is the declaration for setbuf() function. void setbuf(FILE *stream, char *buffer) stream − This is the pointer to a FILE object that identifies an open stream. stream − This is the pointer to a FILE object that identifies an open stream. buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array. buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array. This function does not return any value. The following example shows the usage of setbuf() function. #include <stdio.h> int main () { char buf[BUFSIZ]; setbuf(stdout, buf); puts("This is tutorialspoint"); fflush(stdout); return(0); } Let us compile and run the above program to produce the following result. Here program sends output to the STDOUT just before it comes out, otherwise it keeps buffering the output. You can also use fflush() function to flush the output. This is tutorialspoint 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2266, "s": 2007, "text": "The C library function void setbuf(FILE *stream, char *buffer) defines how a stream should be buffered. This function should be called once the file associated with the stream has already been opened, but before any input or output operation has taken place." }, { "code": null, "e": 2318, "s": 2266, "text": "Following is the declaration for setbuf() function." }, { "code": null, "e": 2358, "s": 2318, "text": "void setbuf(FILE *stream, char *buffer)" }, { "code": null, "e": 2436, "s": 2358, "text": "stream − This is the pointer to a FILE object that identifies an open stream." }, { "code": null, "e": 2514, "s": 2436, "text": "stream − This is the pointer to a FILE object that identifies an open stream." }, { "code": null, "e": 2676, "s": 2514, "text": "buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array." }, { "code": null, "e": 2838, "s": 2676, "text": "buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array." }, { "code": null, "e": 2879, "s": 2838, "text": "This function does not return any value." }, { "code": null, "e": 2939, "s": 2879, "text": "The following example shows the usage of setbuf() function." }, { "code": null, "e": 3090, "s": 2939, "text": "#include <stdio.h>\n\nint main () {\n char buf[BUFSIZ];\n\n setbuf(stdout, buf);\n puts(\"This is tutorialspoint\");\n\n fflush(stdout);\n return(0);\n}" }, { "code": null, "e": 3327, "s": 3090, "text": "Let us compile and run the above program to produce the following result. Here program sends output to the STDOUT just before it comes out, otherwise it keeps buffering the output. You can also use fflush() function to flush the output." }, { "code": null, "e": 3351, "s": 3327, "text": "This is tutorialspoint\n" }, { "code": null, "e": 3384, "s": 3351, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3399, "s": 3384, "text": " Nishant Malik" }, { "code": null, "e": 3434, "s": 3399, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3449, "s": 3434, "text": " Nishant Malik" }, { "code": null, "e": 3484, "s": 3449, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3498, "s": 3484, "text": " Asif Hussain" }, { "code": null, "e": 3531, "s": 3498, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3549, "s": 3531, "text": " Richa Maheshwari" }, { "code": null, "e": 3584, "s": 3549, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3603, "s": 3584, "text": " Vandana Annavaram" }, { "code": null, "e": 3636, "s": 3603, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3648, "s": 3636, "text": " Amit Diwan" }, { "code": null, "e": 3655, "s": 3648, "text": " Print" }, { "code": null, "e": 3666, "s": 3655, "text": " Add Notes" } ]
Java Generics - Type Inference
Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters. Compiler generates unchecked conversion warning in-case type inference is not used. Box<Integer> integerBox = new Box<>(); Where Box − Box is a generic class. Box − Box is a generic class. <> − The diamond operator denotes type inference. <> − The diamond operator denotes type inference. Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards. Create the following java program using any editor of your choice. GenericsTester.java package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { //type inference Box<Integer> integerBox = new Box<>(); //unchecked conversion warning Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } } class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } This will produce the following result. Integer Value :10 String Value :Hello World 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2999, "s": 2640, "text": "Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters." }, { "code": null, "e": 3083, "s": 2999, "text": "Compiler generates unchecked conversion warning in-case type inference is not used." }, { "code": null, "e": 3123, "s": 3083, "text": "Box<Integer> integerBox = new Box<>();\n" }, { "code": null, "e": 3129, "s": 3123, "text": "Where" }, { "code": null, "e": 3159, "s": 3129, "text": "Box − Box is a generic class." }, { "code": null, "e": 3189, "s": 3159, "text": "Box − Box is a generic class." }, { "code": null, "e": 3239, "s": 3189, "text": "<> − The diamond operator denotes type inference." }, { "code": null, "e": 3289, "s": 3239, "text": "<> − The diamond operator denotes type inference." }, { "code": null, "e": 3420, "s": 3289, "text": "Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards." }, { "code": null, "e": 3487, "s": 3420, "text": "Create the following java program using any editor of your choice." }, { "code": null, "e": 3507, "s": 3487, "text": "GenericsTester.java" }, { "code": null, "e": 4122, "s": 3507, "text": "package com.tutorialspoint;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n //type inference \n Box<Integer> integerBox = new Box<>();\n //unchecked conversion warning\n Box<String> stringBox = new Box<String>();\n\n integerBox.add(new Integer(10));\n stringBox.add(new String(\"Hello World\"));\n\n System.out.printf(\"Integer Value :%d\\n\", integerBox.get());\n System.out.printf(\"String Value :%s\\n\", stringBox.get());\n }\n}\n\nclass Box<T> {\n private T t;\n\n public void add(T t) {\n this.t = t;\n }\n\n public T get() {\n return t;\n } \n}" }, { "code": null, "e": 4162, "s": 4122, "text": "This will produce the following result." }, { "code": null, "e": 4207, "s": 4162, "text": "Integer Value :10\nString Value :Hello World\n" }, { "code": null, "e": 4240, "s": 4207, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4256, "s": 4240, "text": " Malhar Lathkar" }, { "code": null, "e": 4289, "s": 4256, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4305, "s": 4289, "text": " Malhar Lathkar" }, { "code": null, "e": 4340, "s": 4305, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4354, "s": 4340, "text": " Anadi Sharma" }, { "code": null, "e": 4388, "s": 4354, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4402, "s": 4388, "text": " Tushar Kale" }, { "code": null, "e": 4439, "s": 4402, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4454, "s": 4439, "text": " Monica Mittal" }, { "code": null, "e": 4487, "s": 4454, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4506, "s": 4487, "text": " Arnab Chakraborty" }, { "code": null, "e": 4513, "s": 4506, "text": " Print" }, { "code": null, "e": 4524, "s": 4513, "text": " Add Notes" } ]
A simple News app with Tkinter and Newsapi - GeeksforGeeks
06 Jul, 2021 Prerequisites: Tkinter Tkinter is a very famous python library for building a desktop app for windows and UNIX based OS. The idea here is to generate a python code to build a news app with Tkinter. You can very easily get yourself an API key from newsapi.org . Import modules Create a screen with a title Add labels Add buttons Create a textarea for news to be displayed. Bind buttons to functions such that on being clicked news is displayed in the textarea Program: Python3 from tkinter import *from tkinter import messageboximport requestsimport jsontype = 'sports'apiKey = 'YOUR_API_KEY_HERE'BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey class NewsApp: global apiKey, type def __init__(self, root): self.root = root self.root.geometry('1350x700+0+0') self.root.title("eNewsPaper") #====variables========# self.newsCatButton = [] self.newsCat = ["general", "entertainment", "business", "sports", "technology", "health"] #========title frame===========# bg_color = "#404040" text_area_bg = "#b8e0c4" basic_font_color = "#ccc4c4" title = Label(self.root, text="NewsPaper Software", font=("times new roman", 30, "bold"), pady=2, bd=12, relief=GROOVE, bg=bg_color, fg=basic_font_color).pack(fill=X) F1 = LabelFrame(self.root, text="Category", font=( "times new roman", 20, "bold"), bg=bg_color, fg=basic_font_color, bd=10, relief=GROOVE) F1.place(x=0, y=80, width=300, relheight=0.88) for i in range(len(self.newsCat)): b = Button(F1, text=self.newsCat[i].upper( ), width=20, bd=7, font="arial 15 bold") b.grid(row=i, column=0, padx=10, pady=5) b.bind('<Button-1>', self.Newsarea) self.newsCatButton.append(b) #=======news frame=======# F2 = Frame(self.root, bd=7, relief=GROOVE) F2.place(x=320, y=80, relwidth=0.7, relheight=0.8) news_title = Label(F2, text="News Area", font=( "arial", 20, "bold"), bd=7, relief=GROOVE).pack(fill=X) scroll_y = Scrollbar(F2, orient=VERTICAL) self.txtarea = Text(F2, yscrollcommand=scroll_y.set, font=( "times new roman", 15, "bold"), bg=text_area_bg, fg="#3206b8") scroll_y.pack(side=RIGHT, fill=Y) scroll_y.config(command=self.txtarea.yview) self.txtarea.insert( END, "PLEASE SELECT ANY CATEGORY TO SHOW HEADLINES AND PLEASE BE PATIENT IT DEPENDS ON UR INTERNET CONNECTIONS!!!!") self.txtarea.pack(fill=BOTH, expand=1) def Newsarea(self, event): type = event.widget.cget('text').lower() BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey self.txtarea.delete("1.0", END) self.txtarea.insert(END, f"\n Welcome to GFG news paper\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") try: articles = (requests.get(BASE_URL).json())['articles'] if(articles != 0): for i in range(len(articles)): self.txtarea.insert(END, f"{articles[i]['title']}\n") self.txtarea.insert( END, f"{articles[i]['description']}\n\n") self.txtarea.insert(END, f"{articles[i]['content']}\n\n") self.txtarea.insert( END, f"read more...{articles[i]['url']}\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") else: self.txtarea.insert(END, "Sorry no news available") except Exception as e: messagebox.showerror( 'ERROR', "Sorry cant connect to internet or some issues with newsapp :'(") root = Tk()obj = NewsApp(root)root.mainloop() Output: Python3 from tkinter import *from tkinter import messageboximport requestsimport jsontype = 'sports'apiKey = 'YOUR_API_KEY_HERE'BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey class NewsApp: global apiKey, type def __init__(self, root): self.root = root self.root.geometry('1350x700+0+0') self.root.title("eNewsPaper") #====variables========# self.newsCatButton = [] self.newsCat = ["general", "entertainment", "business", "sports", "technology", "health"] #========title frame===========# bg_color = "#404040" text_area_bg = "#b8e0c4" basic_font_color = "#ccc4c4" title = Label(self.root, text="NewsPaper Software", font=("times new roman", 30, "bold"), pady=2, bd=12, relief=GROOVE, bg=bg_color, fg=basic_font_color).pack(fill=X) F1 = LabelFrame(self.root, text="Category", font=( "times new roman", 20, "bold"), bg=bg_color, fg=basic_font_color, bd=10, relief=GROOVE) F1.place(x=0, y=80, width=300, relheight=0.88) for i in range(len(self.newsCat)): b = Button(F1, text=self.newsCat[i].upper( ), width=20, bd=7, font="arial 15 bold") b.grid(row=i, column=0, padx=10, pady=5) b.bind('<Button-1>', self.Newsarea) self.newsCatButton.append(b) #=======news frame=======# F2 = Frame(self.root, bd=7, relief=GROOVE) F2.place(x=320, y=80, relwidth=0.7, relheight=0.8) news_title = Label(F2, text="News Area", font=( "arial", 20, "bold"), bd=7, relief=GROOVE).pack(fill=X) scroll_y = Scrollbar(F2, orient=VERTICAL) self.txtarea = Text(F2, yscrollcommand=scroll_y.set, font=( "times new roman", 15, "bold"), bg=text_area_bg, fg="#3206b8") scroll_y.pack(side=RIGHT, fill=Y) scroll_y.config(command=self.txtarea.yview) self.txtarea.insert( END, "PLEASE SELECT ANY CATEGORY TO SHOW HEADLINES AND PLEASE BE PATIENT IT DEPENDS ON UR INTERNET CONNECTIONS!!!!") self.txtarea.pack(fill=BOTH, expand=1) def Newsarea(self, event): type = event.widget.cget('text').lower() BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey self.txtarea.delete("1.0", END) self.txtarea.insert(END, f"\n Welcome to GFG news paper\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") try: articles = (requests.get(BASE_URL).json())['articles'] if(articles != 0): for i in range(len(articles)): self.txtarea.insert(END, f"{articles[i]['title']}\n") self.txtarea.insert( END, f"{articles[i]['description']}\n\n") self.txtarea.insert(END, f"{articles[i]['content']}\n\n") self.txtarea.insert( END, f"read more...{articles[i]['url']}\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") self.txtarea.insert( END, "--------------------------------------------------------------------\n") else: self.txtarea.insert(END, "Sorry no news available") except Exception as e: messagebox.showerror( 'ERROR', "Sorry cant connect to internet or some issues with newsapp :'(") root = Tk()obj = NewsApp(root)root.mainloop() FINAL APP saurabh1990aror Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25578, "s": 25555, "text": "Prerequisites: Tkinter" }, { "code": null, "e": 25816, "s": 25578, "text": "Tkinter is a very famous python library for building a desktop app for windows and UNIX based OS. The idea here is to generate a python code to build a news app with Tkinter. You can very easily get yourself an API key from newsapi.org ." }, { "code": null, "e": 25831, "s": 25816, "text": "Import modules" }, { "code": null, "e": 25860, "s": 25831, "text": "Create a screen with a title" }, { "code": null, "e": 25871, "s": 25860, "text": "Add labels" }, { "code": null, "e": 25883, "s": 25871, "text": "Add buttons" }, { "code": null, "e": 25927, "s": 25883, "text": "Create a textarea for news to be displayed." }, { "code": null, "e": 26014, "s": 25927, "text": "Bind buttons to functions such that on being clicked news is displayed in the textarea" }, { "code": null, "e": 26023, "s": 26014, "text": "Program:" }, { "code": null, "e": 26031, "s": 26023, "text": "Python3" }, { "code": "from tkinter import *from tkinter import messageboximport requestsimport jsontype = 'sports'apiKey = 'YOUR_API_KEY_HERE'BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey class NewsApp: global apiKey, type def __init__(self, root): self.root = root self.root.geometry('1350x700+0+0') self.root.title(\"eNewsPaper\") #====variables========# self.newsCatButton = [] self.newsCat = [\"general\", \"entertainment\", \"business\", \"sports\", \"technology\", \"health\"] #========title frame===========# bg_color = \"#404040\" text_area_bg = \"#b8e0c4\" basic_font_color = \"#ccc4c4\" title = Label(self.root, text=\"NewsPaper Software\", font=(\"times new roman\", 30, \"bold\"), pady=2, bd=12, relief=GROOVE, bg=bg_color, fg=basic_font_color).pack(fill=X) F1 = LabelFrame(self.root, text=\"Category\", font=( \"times new roman\", 20, \"bold\"), bg=bg_color, fg=basic_font_color, bd=10, relief=GROOVE) F1.place(x=0, y=80, width=300, relheight=0.88) for i in range(len(self.newsCat)): b = Button(F1, text=self.newsCat[i].upper( ), width=20, bd=7, font=\"arial 15 bold\") b.grid(row=i, column=0, padx=10, pady=5) b.bind('<Button-1>', self.Newsarea) self.newsCatButton.append(b) #=======news frame=======# F2 = Frame(self.root, bd=7, relief=GROOVE) F2.place(x=320, y=80, relwidth=0.7, relheight=0.8) news_title = Label(F2, text=\"News Area\", font=( \"arial\", 20, \"bold\"), bd=7, relief=GROOVE).pack(fill=X) scroll_y = Scrollbar(F2, orient=VERTICAL) self.txtarea = Text(F2, yscrollcommand=scroll_y.set, font=( \"times new roman\", 15, \"bold\"), bg=text_area_bg, fg=\"#3206b8\") scroll_y.pack(side=RIGHT, fill=Y) scroll_y.config(command=self.txtarea.yview) self.txtarea.insert( END, \"PLEASE SELECT ANY CATEGORY TO SHOW HEADLINES AND PLEASE BE PATIENT IT DEPENDS ON UR INTERNET CONNECTIONS!!!!\") self.txtarea.pack(fill=BOTH, expand=1) def Newsarea(self, event): type = event.widget.cget('text').lower() BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey self.txtarea.delete(\"1.0\", END) self.txtarea.insert(END, f\"\\n Welcome to GFG news paper\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") try: articles = (requests.get(BASE_URL).json())['articles'] if(articles != 0): for i in range(len(articles)): self.txtarea.insert(END, f\"{articles[i]['title']}\\n\") self.txtarea.insert( END, f\"{articles[i]['description']}\\n\\n\") self.txtarea.insert(END, f\"{articles[i]['content']}\\n\\n\") self.txtarea.insert( END, f\"read more...{articles[i]['url']}\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") else: self.txtarea.insert(END, \"Sorry no news available\") except Exception as e: messagebox.showerror( 'ERROR', \"Sorry cant connect to internet or some issues with newsapp :'(\") root = Tk()obj = NewsApp(root)root.mainloop()", "e": 29665, "s": 26031, "text": null }, { "code": null, "e": 29673, "s": 29665, "text": "Output:" }, { "code": null, "e": 29681, "s": 29673, "text": "Python3" }, { "code": "from tkinter import *from tkinter import messageboximport requestsimport jsontype = 'sports'apiKey = 'YOUR_API_KEY_HERE'BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey class NewsApp: global apiKey, type def __init__(self, root): self.root = root self.root.geometry('1350x700+0+0') self.root.title(\"eNewsPaper\") #====variables========# self.newsCatButton = [] self.newsCat = [\"general\", \"entertainment\", \"business\", \"sports\", \"technology\", \"health\"] #========title frame===========# bg_color = \"#404040\" text_area_bg = \"#b8e0c4\" basic_font_color = \"#ccc4c4\" title = Label(self.root, text=\"NewsPaper Software\", font=(\"times new roman\", 30, \"bold\"), pady=2, bd=12, relief=GROOVE, bg=bg_color, fg=basic_font_color).pack(fill=X) F1 = LabelFrame(self.root, text=\"Category\", font=( \"times new roman\", 20, \"bold\"), bg=bg_color, fg=basic_font_color, bd=10, relief=GROOVE) F1.place(x=0, y=80, width=300, relheight=0.88) for i in range(len(self.newsCat)): b = Button(F1, text=self.newsCat[i].upper( ), width=20, bd=7, font=\"arial 15 bold\") b.grid(row=i, column=0, padx=10, pady=5) b.bind('<Button-1>', self.Newsarea) self.newsCatButton.append(b) #=======news frame=======# F2 = Frame(self.root, bd=7, relief=GROOVE) F2.place(x=320, y=80, relwidth=0.7, relheight=0.8) news_title = Label(F2, text=\"News Area\", font=( \"arial\", 20, \"bold\"), bd=7, relief=GROOVE).pack(fill=X) scroll_y = Scrollbar(F2, orient=VERTICAL) self.txtarea = Text(F2, yscrollcommand=scroll_y.set, font=( \"times new roman\", 15, \"bold\"), bg=text_area_bg, fg=\"#3206b8\") scroll_y.pack(side=RIGHT, fill=Y) scroll_y.config(command=self.txtarea.yview) self.txtarea.insert( END, \"PLEASE SELECT ANY CATEGORY TO SHOW HEADLINES AND PLEASE BE PATIENT IT DEPENDS ON UR INTERNET CONNECTIONS!!!!\") self.txtarea.pack(fill=BOTH, expand=1) def Newsarea(self, event): type = event.widget.cget('text').lower() BASE_URL = f'http://newsapi.org/v2/top-headlines?country=in&category={type}&apiKey='+apiKey self.txtarea.delete(\"1.0\", END) self.txtarea.insert(END, f\"\\n Welcome to GFG news paper\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") try: articles = (requests.get(BASE_URL).json())['articles'] if(articles != 0): for i in range(len(articles)): self.txtarea.insert(END, f\"{articles[i]['title']}\\n\") self.txtarea.insert( END, f\"{articles[i]['description']}\\n\\n\") self.txtarea.insert(END, f\"{articles[i]['content']}\\n\\n\") self.txtarea.insert( END, f\"read more...{articles[i]['url']}\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") self.txtarea.insert( END, \"--------------------------------------------------------------------\\n\") else: self.txtarea.insert(END, \"Sorry no news available\") except Exception as e: messagebox.showerror( 'ERROR', \"Sorry cant connect to internet or some issues with newsapp :'(\") root = Tk()obj = NewsApp(root)root.mainloop()", "e": 33315, "s": 29681, "text": null }, { "code": null, "e": 33325, "s": 33315, "text": "FINAL APP" }, { "code": null, "e": 33341, "s": 33325, "text": "saurabh1990aror" }, { "code": null, "e": 33366, "s": 33341, "text": "Python Tkinter-exercises" }, { "code": null, "e": 33381, "s": 33366, "text": "Python-tkinter" }, { "code": null, "e": 33388, "s": 33381, "text": "Python" }, { "code": null, "e": 33486, "s": 33388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33518, "s": 33486, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33560, "s": 33518, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33602, "s": 33560, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33658, "s": 33602, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33685, "s": 33658, "text": "Python Classes and Objects" }, { "code": null, "e": 33716, "s": 33685, "text": "Python | os.path.join() method" }, { "code": null, "e": 33745, "s": 33716, "text": "Create a directory in Python" }, { "code": null, "e": 33784, "s": 33745, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33820, "s": 33784, "text": "Python | Pandas dataframe.groupby()" } ]
C program that does not suspend when Ctrl+Z is pressed - GeeksforGeeks
26 Sep, 2017 Write a C program that doesn’t terminate when Ctrl+Z is pressed. It prints a message “Cannot be suspended using Ctrl+Z” and continues execution. We can use Unix signal for this. When Ctrl+Z is pressed, SIGTSTP signal is generated. SIGTSTP signal is sent to a process by its controlling terminal to request it to stop (terminal stop). We can catch this signal and run our own defined signal.The standard C library function signal() can be used to set up a handler for any of the above signals. // C program that does not suspend when// Ctrl+Z is pressed#include <stdio.h>#include <signal.h> // Signal Handler for SIGTSTPvoid sighandler(int sig_num){ // Reset handler to catch SIGTSTP next time signal(SIGTSTP, sighandler); printf("Cannot execute Ctrl+Z\n");} int main(){ // Set the SIGTSTP (Ctrl-Z) signal handler // to sigHandler signal(SIGTSTP, sighandler); while(1) { } return 0;} Output: Cannot execute Ctrl+Z This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. system-programming C Language Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 25477, "s": 25449, "text": "\n26 Sep, 2017" }, { "code": null, "e": 25622, "s": 25477, "text": "Write a C program that doesn’t terminate when Ctrl+Z is pressed. It prints a message “Cannot be suspended using Ctrl+Z” and continues execution." }, { "code": null, "e": 25708, "s": 25622, "text": "We can use Unix signal for this. When Ctrl+Z is pressed, SIGTSTP signal is generated." }, { "code": null, "e": 25970, "s": 25708, "text": "SIGTSTP signal is sent to a process by its controlling terminal to request it to stop (terminal stop). We can catch this signal and run our own defined signal.The standard C library function signal() can be used to set up a handler for any of the above signals." }, { "code": "// C program that does not suspend when// Ctrl+Z is pressed#include <stdio.h>#include <signal.h> // Signal Handler for SIGTSTPvoid sighandler(int sig_num){ // Reset handler to catch SIGTSTP next time signal(SIGTSTP, sighandler); printf(\"Cannot execute Ctrl+Z\\n\");} int main(){ // Set the SIGTSTP (Ctrl-Z) signal handler // to sigHandler signal(SIGTSTP, sighandler); while(1) { } return 0;}", "e": 26392, "s": 25970, "text": null }, { "code": null, "e": 26400, "s": 26392, "text": "Output:" }, { "code": null, "e": 26423, "s": 26400, "text": "Cannot execute Ctrl+Z\n" }, { "code": null, "e": 26723, "s": 26423, "text": "This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26848, "s": 26723, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26867, "s": 26848, "text": "system-programming" }, { "code": null, "e": 26878, "s": 26867, "text": "C Language" }, { "code": null, "e": 26889, "s": 26878, "text": "Linux-Unix" }, { "code": null, "e": 26987, "s": 26889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27025, "s": 26987, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27051, "s": 27025, "text": "Exception Handling in C++" }, { "code": null, "e": 27071, "s": 27051, "text": "Multithreading in C" }, { "code": null, "e": 27093, "s": 27071, "text": "'this' pointer in C++" }, { "code": null, "e": 27134, "s": 27093, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27174, "s": 27134, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27214, "s": 27174, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27241, "s": 27214, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27276, "s": 27241, "text": "cut command in Linux with examples" } ]
PHP - DOM Parser Example
A HTML Dom parser written in PHP5.X versions. Dom Parser is very good at dealing with XML as well as HTML. Dom parser travels based on tree based and before access the data, it will load the data into dom object and it will update the data to the web browser. Below Example shows how to get access to the HTML data in web browser. <?php $html = ' <head> <title>Tutorialspoint</title> </head> <body> <h2>Course details</h2> <table border = "0"> <tbody> <tr> <td>Android</td> <td>Gopal</td> <td>Sairam</td> </tr> <tr> <td>Hadoop</td> <td>Gopal</td> <td>Satish</td> </tr> <tr> <td>HTML</td> <td>Gopal</td> <td>Raju</td> </tr> <tr> <td>Web technologies</td> <td>Gopal</td> <td>Javed</td> </tr> <tr> <td>Graphic</td> <td>Gopal</td> <td>Satish</td> </tr> <tr> <td>Writer</td> <td>Kiran</td> <td>Amith</td> </tr> <tr> <td>Writer</td> <td>Kiran</td> <td>Vineeth</td> </tr> </tbody> </table> </body> </html> '; /*** a new dom object ***/ $dom = new domDocument; /*** load the html into the object ***/ $dom->loadHTML($html); /*** discard white space ***/ $dom->preserveWhiteSpace = false; /*** the table by its tag name ***/ $tables = $dom->getElementsByTagName('table'); /*** get all rows from the table ***/ $rows = $tables->item(0)->getElementsByTagName('tr'); /*** loop over the table rows ***/ foreach ($rows as $row) { /*** get each column by tag name ***/ $cols = $row->getElementsByTagName('td'); /*** echo the values ***/ echo 'Designation: '.$cols->item(0)->nodeValue.'<br />'; echo 'Manager: '.$cols->item(1)->nodeValue.'<br />'; echo 'Team: '.$cols->item(2)->nodeValue; echo '<hr />'; } ?> It will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 3088, "s": 2757, "text": "A HTML Dom parser written in PHP5.X versions. Dom Parser is very good at dealing with XML as well as HTML. Dom parser travels based on tree based and before access the data, it will load the data into dom object and it will update the data to the web browser. Below Example shows how to get access to the HTML data in web browser." }, { "code": null, "e": 5277, "s": 3088, "text": "<?php \n $html = ' \n <head> \n <title>Tutorialspoint</title>\n </head> \n \n <body> \n <h2>Course details</h2> \n \n <table border = \"0\"> \n <tbody> \n <tr> \n <td>Android</td> \n <td>Gopal</td> \n <td>Sairam</td> \n </tr> \n \n <tr> \n <td>Hadoop</td> \n <td>Gopal</td> \n <td>Satish</td> \n </tr> \n \n <tr> \n <td>HTML</td> \n <td>Gopal</td> \n <td>Raju</td> \n </tr> \n \n <tr> \n <td>Web technologies</td> \n <td>Gopal</td> \n <td>Javed</td> \n </tr> \n \n <tr> \n <td>Graphic</td> \n <td>Gopal</td> \n <td>Satish</td> \n </tr> \n \n <tr> \n <td>Writer</td> \n <td>Kiran</td> \n <td>Amith</td> \n </tr> \n \n <tr> \n <td>Writer</td> \n <td>Kiran</td> \n <td>Vineeth</td> \n </tr> \n </tbody> \n </table> \n </body> \n </html> \n '; \n /*** a new dom object ***/ \n $dom = new domDocument; \n \n /*** load the html into the object ***/ \n $dom->loadHTML($html); \n \n /*** discard white space ***/ \n $dom->preserveWhiteSpace = false; \n \n /*** the table by its tag name ***/ \n $tables = $dom->getElementsByTagName('table'); \n \n /*** get all rows from the table ***/ \n $rows = $tables->item(0)->getElementsByTagName('tr'); \n \n /*** loop over the table rows ***/ \n foreach ($rows as $row) {\n /*** get each column by tag name ***/ \n $cols = $row->getElementsByTagName('td'); \n \n /*** echo the values ***/ \n echo 'Designation: '.$cols->item(0)->nodeValue.'<br />'; \n echo 'Manager: '.$cols->item(1)->nodeValue.'<br />'; \n echo 'Team: '.$cols->item(2)->nodeValue; \n echo '<hr />'; \n }\n?> " }, { "code": null, "e": 5316, "s": 5277, "text": "It will produce the following result −" }, { "code": null, "e": 5349, "s": 5316, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5365, "s": 5349, "text": " Malhar Lathkar" }, { "code": null, "e": 5398, "s": 5365, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5409, "s": 5398, "text": " Syed Raza" }, { "code": null, "e": 5444, "s": 5409, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5461, "s": 5444, "text": " Frahaan Hussain" }, { "code": null, "e": 5494, "s": 5461, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5509, "s": 5494, "text": " Nivedita Jain" }, { "code": null, "e": 5544, "s": 5509, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5556, "s": 5544, "text": " Azaz Patel" }, { "code": null, "e": 5591, "s": 5556, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5619, "s": 5591, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5626, "s": 5619, "text": " Print" }, { "code": null, "e": 5637, "s": 5626, "text": " Add Notes" } ]
bokeh.plotting.figure.arc() function in Python - GeeksforGeeks
17 Jun, 2020 Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc. The arc() function in plotting module of bokeh library is used to Configure and add Arc glyphs to this Figure. Syntax: arc(x, y, radius, start_angle, end_angle, direction=’anticlock’, *, end_angle_units=’rad’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, radius_units=’data’, start_angle_units=’rad’, tags=[], **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter is the x-coordinates for the center of the arcs. y: This parameter is the y-coordinates for the center of the arcs. start_angle: This parameter is the angles to start the arcs. end_angle: This parameter is the angles to end the arcs. direction: This parameter is the direction to stroke between the start and end angles. fill_alpha: This parameter is the fill alpha values for the arcs. fill_color: This parameter is the fill color values for the arcs. line_alpha: This parameter is the line alpha values for the steps with default value of 1.0 . line_cap: This parameter is the line cap values for the steps with default value of butt. line_color: This parameter is the line color values for the steps with default value of black. line_dash: This parameter is the line dash values for the steps with default value of []. line_dash_offset: This parameter is the line dash offset values for the steps with default value of 0. line_join: This parameter is the line join values for the steps with default value of bevel. line_width: This parameter is the line width values for the steps with default value of 1. mode: This parameter can be one of three values : [“before”, “after”, “center”]. name: This parameter is the user-supplied name for this model. tags: This parameter is the user-supplied values for this model. Other Parameters: These parameters are **kwargs that are described below: alpha: This parameter is used to set all alpha keyword arguments at once. color: This parameter is used to to set all color keyword arguments at once. legend_field: This parameter is the name of a column in the data source that should be used or the grouping. legend_group: This parameter is the name of a column in the data source that should be used or the grouping. legend_label: This parameter is the legend entry is labeled with exactly the text supplied here. muted: This parameter contains the bool value. name: This parameter is the optional user-supplied name to attach to the renderer. source: This parameter is the user-supplied data source. view: This parameter is the view for filtering the data source. visible: This parameter contains the bool value. x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates. y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates. level: This parameter specify the render level order for this glyph. Return: This method return the GlyphRenderer value. Below examples illustrate the bokeh.plotting.figure.arc() function in bokeh.plotting:Example 1: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300)plot.arc(x =[1, 2, 3], y =[3, 2, 1], radius = 0.3, start_angle = 0.4, end_angle = 4.8, color ="green", alpha = 0.6) show(plot) Output: Example 2: # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show N = 9x = np.linspace(-2, 2, N)y = x**2r = x / 15.0 + 0.3 plot = figure(plot_width = 300, plot_height = 300)plot.arc(x = x, y = y, radius = r, start_angle = 0.6, end_angle = 4.8, color ="green", alpha = 0.6, line_width = 3) show(plot) Output: Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n17 Jun, 2020" }, { "code": null, "e": 25981, "s": 25647, "text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc." }, { "code": null, "e": 26092, "s": 25981, "text": "The arc() function in plotting module of bokeh library is used to Configure and add Arc glyphs to this Figure." }, { "code": null, "e": 26387, "s": 26092, "text": "Syntax: arc(x, y, radius, start_angle, end_angle, direction=’anticlock’, *, end_angle_units=’rad’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, radius_units=’data’, start_angle_units=’rad’, tags=[], **kwargs)" }, { "code": null, "e": 26469, "s": 26387, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26536, "s": 26469, "text": "x: This parameter is the x-coordinates for the center of the arcs." }, { "code": null, "e": 26603, "s": 26536, "text": "y: This parameter is the y-coordinates for the center of the arcs." }, { "code": null, "e": 26664, "s": 26603, "text": "start_angle: This parameter is the angles to start the arcs." }, { "code": null, "e": 26721, "s": 26664, "text": "end_angle: This parameter is the angles to end the arcs." }, { "code": null, "e": 26808, "s": 26721, "text": "direction: This parameter is the direction to stroke between the start and end angles." }, { "code": null, "e": 26874, "s": 26808, "text": "fill_alpha: This parameter is the fill alpha values for the arcs." }, { "code": null, "e": 26940, "s": 26874, "text": "fill_color: This parameter is the fill color values for the arcs." }, { "code": null, "e": 27034, "s": 26940, "text": "line_alpha: This parameter is the line alpha values for the steps with default value of 1.0 ." }, { "code": null, "e": 27124, "s": 27034, "text": "line_cap: This parameter is the line cap values for the steps with default value of butt." }, { "code": null, "e": 27219, "s": 27124, "text": "line_color: This parameter is the line color values for the steps with default value of black." }, { "code": null, "e": 27309, "s": 27219, "text": "line_dash: This parameter is the line dash values for the steps with default value of []." }, { "code": null, "e": 27412, "s": 27309, "text": "line_dash_offset: This parameter is the line dash offset values for the steps with default value of 0." }, { "code": null, "e": 27505, "s": 27412, "text": "line_join: This parameter is the line join values for the steps with default value of bevel." }, { "code": null, "e": 27596, "s": 27505, "text": "line_width: This parameter is the line width values for the steps with default value of 1." }, { "code": null, "e": 27677, "s": 27596, "text": "mode: This parameter can be one of three values : [“before”, “after”, “center”]." }, { "code": null, "e": 27740, "s": 27677, "text": "name: This parameter is the user-supplied name for this model." }, { "code": null, "e": 27805, "s": 27740, "text": "tags: This parameter is the user-supplied values for this model." }, { "code": null, "e": 27879, "s": 27805, "text": "Other Parameters: These parameters are **kwargs that are described below:" }, { "code": null, "e": 27953, "s": 27879, "text": "alpha: This parameter is used to set all alpha keyword arguments at once." }, { "code": null, "e": 28030, "s": 27953, "text": "color: This parameter is used to to set all color keyword arguments at once." }, { "code": null, "e": 28139, "s": 28030, "text": "legend_field: This parameter is the name of a column in the data source that should be used or the grouping." }, { "code": null, "e": 28248, "s": 28139, "text": "legend_group: This parameter is the name of a column in the data source that should be used or the grouping." }, { "code": null, "e": 28345, "s": 28248, "text": "legend_label: This parameter is the legend entry is labeled with exactly the text supplied here." }, { "code": null, "e": 28392, "s": 28345, "text": "muted: This parameter contains the bool value." }, { "code": null, "e": 28475, "s": 28392, "text": "name: This parameter is the optional user-supplied name to attach to the renderer." }, { "code": null, "e": 28532, "s": 28475, "text": "source: This parameter is the user-supplied data source." }, { "code": null, "e": 28596, "s": 28532, "text": "view: This parameter is the view for filtering the data source." }, { "code": null, "e": 28645, "s": 28596, "text": "visible: This parameter contains the bool value." }, { "code": null, "e": 28738, "s": 28645, "text": "x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates." }, { "code": null, "e": 28831, "s": 28738, "text": "y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates." }, { "code": null, "e": 28900, "s": 28831, "text": "level: This parameter specify the render level order for this glyph." }, { "code": null, "e": 28952, "s": 28900, "text": "Return: This method return the GlyphRenderer value." }, { "code": null, "e": 29048, "s": 28952, "text": "Below examples illustrate the bokeh.plotting.figure.arc() function in bokeh.plotting:Example 1:" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300)plot.arc(x =[1, 2, 3], y =[3, 2, 1], radius = 0.3, start_angle = 0.4, end_angle = 4.8, color =\"green\", alpha = 0.6) show(plot)", "e": 29351, "s": 29048, "text": null }, { "code": null, "e": 29359, "s": 29351, "text": "Output:" }, { "code": null, "e": 29370, "s": 29359, "text": "Example 2:" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show N = 9x = np.linspace(-2, 2, N)y = x**2r = x / 15.0 + 0.3 plot = figure(plot_width = 300, plot_height = 300)plot.arc(x = x, y = y, radius = r, start_angle = 0.6, end_angle = 4.8, color =\"green\", alpha = 0.6, line_width = 3) show(plot)", "e": 29731, "s": 29370, "text": null }, { "code": null, "e": 29739, "s": 29731, "text": "Output:" }, { "code": null, "e": 29752, "s": 29739, "text": "Python-Bokeh" }, { "code": null, "e": 29759, "s": 29752, "text": "Python" }, { "code": null, "e": 29857, "s": 29759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29889, "s": 29857, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29931, "s": 29889, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29973, "s": 29931, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30029, "s": 29973, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30056, "s": 30029, "text": "Python Classes and Objects" }, { "code": null, "e": 30087, "s": 30056, "text": "Python | os.path.join() method" }, { "code": null, "e": 30116, "s": 30087, "text": "Create a directory in Python" }, { "code": null, "e": 30138, "s": 30116, "text": "Defaultdict in Python" }, { "code": null, "e": 30174, "s": 30138, "text": "Python | Pandas dataframe.groupby()" } ]
How to increase the spacing between subplots in Matplotlib with subplot2grid?
To increase the spacing between subplots with subplot2grid, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Add a grid layout to place subplots within a figure. Add a grid layout to place subplots within a figure. Update the subplot parameters of the grid. Update the subplot parameters of the grid. Add a subplot to the current figure. Add a subplot to the current figure. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True ax = plt.GridSpec(2, 2) ax.update(wspace=0.5, hspace=0.5) ax1 = plt.subplot(ax[0, :]) ax2 = plt.subplot(ax[1, 0]) ax3 = plt.subplot(ax[1, 1]) plt.show()
[ { "code": null, "e": 1156, "s": 1062, "text": "To increase the spacing between subplots with subplot2grid, we can take the following steps −" }, { "code": null, "e": 1232, "s": 1156, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1308, "s": 1232, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1361, "s": 1308, "text": "Add a grid layout to place subplots within a figure." }, { "code": null, "e": 1414, "s": 1361, "text": "Add a grid layout to place subplots within a figure." }, { "code": null, "e": 1457, "s": 1414, "text": "Update the subplot parameters of the grid." }, { "code": null, "e": 1500, "s": 1457, "text": "Update the subplot parameters of the grid." }, { "code": null, "e": 1537, "s": 1500, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1574, "s": 1537, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1616, "s": 1574, "text": "To display the figure, use show() method." }, { "code": null, "e": 1658, "s": 1616, "text": "To display the figure, use show() method." }, { "code": null, "e": 1939, "s": 1658, "text": "from matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nax = plt.GridSpec(2, 2)\nax.update(wspace=0.5, hspace=0.5)\n\nax1 = plt.subplot(ax[0, :])\nax2 = plt.subplot(ax[1, 0])\nax3 = plt.subplot(ax[1, 1])\n\nplt.show()" } ]
H2 Database - Quick Guide
H2 is an open-source lightweight Java database. It can be embedded in Java applications or run in the client-server mode. Mainly, H2 database can be configured to run as inmemory database, which means that data will not persist on the disk. Because of embedded database it is not used for production development, but mostly used for development and testing. This database can be used in embedded mode or in server mode. Following are the main features of H2 database − Extremely fast, open source, JDBC API Available in embedded and server modes; in-memory databases Browser-based Console application Small footprint − Around 1.5MB jar file size The main features of H2 Database are as follows − It is an extremely fast database engine. It is an extremely fast database engine. H2 is open source and written in Java. H2 is open source and written in Java. It supports standard SQL and JDBC API. It can use PostgreSQL ODBC driver too. It supports standard SQL and JDBC API. It can use PostgreSQL ODBC driver too. It has embedded and Server mode. It has embedded and Server mode. H2 supports clustering and multi-version concurrency. H2 supports clustering and multi-version concurrency. It has strong security features. It has strong security features. Following are some additional features of H2 Database − H2 is a disk-based or in-memory databases and tables, read-only database support, temporary tables. H2 is a disk-based or in-memory databases and tables, read-only database support, temporary tables. H2 provides transaction support (read committed), 2-phase-commit multiple connections, table level locking. H2 provides transaction support (read committed), 2-phase-commit multiple connections, table level locking. H2 is a cost-based optimizer, using a genetic algorithm for complex queries, zeroadministration. H2 is a cost-based optimizer, using a genetic algorithm for complex queries, zeroadministration. H2 contains scrollable and updatable result set support, large result set, external result sorting, functions can return a result set. H2 contains scrollable and updatable result set support, large result set, external result sorting, functions can return a result set. H2 supports encrypted database (AES), SHA-256 password encryption, encryption functions, and SSL. H2 supports encrypted database (AES), SHA-256 password encryption, encryption functions, and SSL. In order to use H2 Database, you need to have the following components − A web browser A H2 console server This is a client/server application, so both server and client (a browser) are required to run it. H2 is a database written in Java. We can easily embed this database to our application by using JDBC. We can run this on many different platforms or any version of Java Runtime Environment. However, before installing the database, there should be Java installed in the system. If JDK is installed in the system, try the following command to verify the Java version. java –version If JDk is successfully installed in the system, then we will get the following output. java version "1.8.0_91" Java(TM) SE Runtime Environment (build 1.8.0_91-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode) If JDK is not installed in the system, then visit the following link to Install JDK. We can run this database on many different platforms. In this chapter, we will learn about H2 Database installation on Windows. Following are the steps to install H2 Database on Windows operating system. Download the latest version of H2 Database from the given link. In this link, you will get the latest version of H2 database in two types. One is Windows Installer type (that is .exe file) and second is Platform-Independent zip file for other operating systems. Click the Windows installer for downloading the Windows supportable H2 database after downloading the .exe file. In this case, we are using H2 Database with the version 1.4.192. After downloading we get the H2 Windows installer file (i.e. h2-setup-yyyy-mm-dd.exe) in the Downloads directory. To start the installation process of H2 Database, double click on the installer file. The following screen is the first step in the installation process. Provide a path where we want to install the H2 database server as shown in the following screenshot. As seen in the above screenshot, by default it will take C:\ProgramFiles (x86)\H2 as the destination folder. Click next to proceed to the next step. The following screen pops up. In the above screenshot, click the Install button to start the installation process. After installation, we get the following screenshot. Click Finish to complete the installation process. After installation, let us verify the database installation in the system. Click Windows → type H2 Console → Click H2 console icon. Connect to the URL http://localhost:8082. At the time of connecting, the H2 database will ask for database registration as shown in the following screenshot. Fill all the details in the above dialog box such as Saved Settings, Settings Name, Driver Class, JDBC URL, User Name, and Password. In the JDBC URL, specify the database is located and the database name. User Name and Password are the fields for user name and password of the database. Click Connect. The Database welcome page pops up as shown in the following screenshot. Select command is used to fetch record data from a table or multiple tables. If we design a select query, then it returns data in the form of result table called result sets. The basic syntax of SELECT statement is as follows − SELECT [ TOP term ] [ DISTINCT | ALL ] selectExpression [,...] FROM tableExpression [,...] [ WHERE expression ] [ GROUP BY expression [,...] ] [ HAVING expression ] [ { UNION [ ALL ] | MINUS | EXCEPT | INTERSECT } select ] [ ORDER BY order [,...] ] [ [ LIMIT expression ] [ OFFSET expression ] [ SAMPLE_SIZE rowCountInt ] ] [ FOR UPDATE ] To fetch all the available fields, use the following syntax. SELECT * FROM table_name; Consider the CUSTOMER table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ To get the customer table along with the given data, execute the following queries. CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20), salary number); INSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000); INSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500); INSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000); INSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500); INSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500); INSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500); INSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000); The following command is an example, which would fetch ID, Name and Salary fields of the customers available in the CUSTOMER table. SELECT ID, NAME, SALARY FROM CUSTOMERS; The above command produces the following result. +----+----------+----------+ | ID | NAME | SALARY | +----+----------+----------+ | 1 | Ramesh | 2000.00 | | 2 | Khilan | 1500.00 | | 3 | kaushik | 2000.00 | | 4 | Chaitali | 6500.00 | | 5 | Hardik | 8500.00 | | 6 | Komal | 4500.00 | | 7 | Muffy | 10000.00 | +----+----------+----------+ Use the following query to fetch all the fields of CUSTOMERS table. SQL> SELECT * FROM CUSTOMERS; The above query produces the following result − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The SQL INSERT statement is used to add new rows of data to a table in the database. Following is the basic syntax of INSERT INTO statement. INSERT INTO tableName { [ ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | [ DIRECT ] [ SORTED ] select } } | { SET { columnName = { DEFAULT | expression } } [,...] } Using this INSERT statement, we can insert a new record or new rows into a table. When using DIRECT clause, the results are directly affected to the target table without any intermediate step. However, while adding values for all the columns of the table, make sure the order of the values is in the same order as the columns in the table. Let us take an example and try to insert the following given records into the Customer table. We can get all the given records into the customer table by executing the following commands. INSERT INTO CUSTOMER VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000); INSERT INTO CUSTOMER VALUES (2, 'Khilan', 25, 'Delhi', 1500); INSERT INTO CUSTOMER VALUES (3, 'kaushik', 23, 'Kota', 2000); INSERT INTO CUSTOMER VALUES (4, 'Chaitali', 25, 'Mumbai', 6500); INSERT INTO CUSTOMER VALUES (5, 'Hardik', 27, 'Bhopal', 8500); INSERT INTO CUSTOMER VALUES (6, 'Komal', 22, 'MP', 4500); INSERT INTO CUSTOMER VALUES (7, 'Muffy', 24, 'Indore', 10000); The UPDATE query is used to update or modify the existing records in a table. We can use WHERE clause with UPDATE query to update the selected rows, otherwise all the rows would be affected. Following is the basic syntax of the UPDATE query. UPDATE tableName [ [ AS ] newTableAlias ] SET { { columnName = { DEFAULT | expression } } [,...] } | { ( columnName [,...] ) = ( select ) } [ WHERE expression ] [ ORDER BY order [,...] ] [ LIMIT expression ] In this UPDATE syntax, we can combine more than one condition by using AND or OR clauses. Consider the CUSTOMER table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to get the customer table along with the given data, execute the following queries. CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20), salary number); INSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000); INSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500); INSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000); INSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500); INSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500); INSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500); INSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000); The following command is an example, which would update ADDRESS for a customer whose ID is 6 − UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6; Now, CUSTOMERS table would have the following records. We can check the customer table records by executing the following query. SELECT * FROM CUSTOMERS; The above query produces the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | Pune | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ To modify all ADDRESS and SALARY column values in CUSTOMERS table, we need not use the WHERE clause. The UPDATE query would be as follows − UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00; Now, CUSTOMERS table would have the following records. We can check the customer table records by executing the following query. SELECT * FROM CUSTOMERS; The above query produces the following result − +----+----------+-----+---------+---------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+---------+ | 1 | Ramesh | 32 | Pune | 1000.00 | | 2 | Khilan | 25 | Pune | 1000.00 | | 3 | kaushik | 23 | Pune | 1000.00 | | 4 | Chaitali | 25 | Pune | 1000.00 | | 5 | Hardik | 27 | Pune | 1000.00 | | 6 | Komal | 22 | Pune | 1000.00 | | 7 | Muffy | 24 | Pune | 1000.00 | +----+----------+-----+---------+---------+ The SQL DELETE query is used to delete the existing records from a table. We can use WHERE clause with DELETE query to delete selected records, otherwise all the records will be deleted. Following is the generic query syntax of the delete command. DELETE [ TOP term ] FROM tableName [ WHERE expression ] [ LIMIT term ] The above syntax deletes the rows from a table. If TOP or LIMIT is specified, at most the specified number of rows are deleted (no limit if null or smaller than zero). Consider the CUSTOMER table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following command will delete the details of the customer, whose ID is 6. DELETE FROM CUSTOMERS WHERE ID = 6; After execution of the above command, check the Customer table by executing the following command. SELECT * FROM CUSTOMERS; The above command produces the following output − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If we want to DELETE all the records from CUSTOMERS table, we do not use WHERE clause. The DELETE query would be as follows. DELETE FROM CUSTOMER; After executing the above command, no records will be available in the Customer table. BACKUP is the command used to take database backup into a separate .zip file. Objects are not locked, and when it takes backup the transaction log is also copied. Admin rights are required to execute this command. Following is the generic syntax of the Backup command. BACKUP TO fileNameString; In this example, let us take a backup of the current database into backup.zip file. Use the following command for the same. BACKUP TO 'backup.zip'; On executing the above command, you will get the backup.zip file in your local file system. CALL is a SQL command which belongs to H2 database server. This command is used to calculate a simple expression. It returns the result of the given expression in a single column field. When it returns an array of results, then each element in the array is displayed as a column value. Following is the generic syntax of the CALL command. CALL expression; We can use the arithmetic expression in this syntax. Let us take an example and execute an arithmetic expression (15 * 25) using call command. CALL 15*25; The above command produces the following output. EXPLAIN command displays the execution plan for a statement. When we execute a statement using EXPLAIN ANALYZE command, the query plan will include the actual row scan count for each table. Following is the generic syntax of the EXPLAIN command. EXPLAIN { [ PLAN FOR ] | ANALYZE } { select | insert | update | delete | merge} Along with this syntax we can use select, insert, delete, and merge. This example explains the query plan details of the customer with ID 1. EXPLAIN SELECT * FROM CUSTOMER WHERE ID = 1; The above command produces the following output − MERGE command is used to update the existing rows and insert new rows into a table. The primary key column plays an important role while using this command; it is used to find the row. Following is the generic syntax of the MERGE command. MERGE INTO tableName [ ( columnName [,...] ) ] [ KEY ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | select } In the above syntax, the KEY clause is used to specify the primary key column name. Along with VALUES clause, we can use primitive values to insert or we can retrieve and store another table values into this table using the select command. In this example, let us try to add a new record into Customers table. Following are the details of the new record in the table. Using the following query, let us insert the given record into the H2 database query. MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Lokesh', 32, 'Hyderabad', 2500); The above query produces the following output. Update count: 1 Let us verify the records of the Customer table by executing the following query. SELECT * FROM CUSTOMER; The above query produces the following output. Now let us try to update the record using the Merge command. Following are the details of the record to be updated. Use the following query to insert the given record into the H2 database query. MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Loki', 32, 'Hyderabad', 3000); The above query produces the following output. Update count: 1 Let us verify the records of the Customer table by executing the following query. SELECT * FROM CUSTOMER; The above query produces the following output − SHOW is a command used to display the list of Schemas, Tables, or Columns of the table. Following is the generic syntax of the SHOW command. SHOW { SCHEMAS | TABLES [ FROM schemaName ] | COLUMNS FROM tableName [ FROM schemaName ] } The following command can be used to get the list of tables in the current database. SHOW TABLES; The above command produces the following output. CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views, and Users in H2 Database server. Create Table is a command used to create a user-defined table in the current database. Following is the generic syntax for the Create Table command. CREATE [ CACHED | MEMORY ] [ TEMP | [ GLOBAL | LOCAL ] TEMPORARY ] TABLE [ IF NOT EXISTS ] name [ ( { columnDefinition | constraint } [,...] ) ] [ ENGINE tableEngineName [ WITH tableEngineParamName [,...] ] ] [ NOT PERSISTENT ] [ TRANSACTIONAL ] [ AS select ] By using the generic syntax of the Create Table command, we can create different types of tables such as cached tables, memory tables, and temporary tables. Following is the list to describe different clauses from the given syntax. CACHED − The cached tables are the default type for regular tables. This means the number of rows is not limited by the main memory. CACHED − The cached tables are the default type for regular tables. This means the number of rows is not limited by the main memory. MEMORY − The memory tables are the default type for temporary tables. This means the memory tables should not get too large and the index data is kept in the main memory. MEMORY − The memory tables are the default type for temporary tables. This means the memory tables should not get too large and the index data is kept in the main memory. TEMPORARY − Temporary tables are deleted while closing or opening a database. Basically, temporary tables are of two types − GLOBAL type − Accessible by all connections. LOCAL type − Accessible by the current connection. The default type for temporary tables is global type. Indexes of temporary tables are kept in the main memory, unless the temporary table is created using CREATE CACHED TABLE. TEMPORARY − Temporary tables are deleted while closing or opening a database. Basically, temporary tables are of two types − GLOBAL type − Accessible by all connections. GLOBAL type − Accessible by all connections. LOCAL type − Accessible by the current connection. LOCAL type − Accessible by the current connection. The default type for temporary tables is global type. Indexes of temporary tables are kept in the main memory, unless the temporary table is created using CREATE CACHED TABLE. ENGINE − The ENGINE option is only required when custom table implementations are used. ENGINE − The ENGINE option is only required when custom table implementations are used. NOT PERSISTENT − It is a modifier to keep the complete table data in-memory and all rows are lost when the database is closed. NOT PERSISTENT − It is a modifier to keep the complete table data in-memory and all rows are lost when the database is closed. TRANSACTIONAL − It is a keyword that commits an open transaction and this command supports only temporary tables. TRANSACTIONAL − It is a keyword that commits an open transaction and this command supports only temporary tables. In this example, let us create a table named tutorials_tbl using the following given data. The following query is used to create a table tutorials_tbl along with the given column data. CREATE TABLE tutorials_tbl ( id INT NOT NULL, title VARCHAR(50) NOT NULL, author VARCHAR(20) NOT NULL, submission_date DATE ); The above query produces the following output. (0) rows effected Create Schema is a command used to create a user-dependent schema under a particular authorization (under the currently registered user). Following is the generic syntax of the Create Schema command. CREATE SCHEMA [ IF NOT EXISTS ] name [ AUTHORIZATION ownerUserName ] In the above generic syntax, AUTHORIZATION is a keyword used to provide the respective user name. This command is optional which means if we are not providing the user name, then it will consider the current user. The user that executes the command must have admin rights, as well as the owner. This command commits an open transaction in this connection. In this example, let us create a schema named test_schema under SA user, using the following command. CREATE SCHEMA test_schema AUTHORIZATION sa; The above command produces the following output. (0) rows effected Sequence is concept which is used to generate a number by following a sequence for id or any random column values. Following is the generic syntax of the create sequence command. CREATE SEQUENCE [ IF NOT EXISTS ] newSequenceName [ START WITH long ] [ INCREMENT BY long ] [ MINVALUE long | NOMINVALUE | NO MINVALUE ] [ MAXVALUE long | NOMAXVALUE | NO MAXVALUE ] [ CYCLE long | NOCYCLE | NO CYCLE ] [ CACHE long | NOCACHE | NO CACHE ] This generic syntax is used to create a sequence. The datatype of a sequence is BIGINT. In this the sequence, values are never re-used, even when the transaction is roll backed. In this example, let us create a sequence named SEQ_ID, using the following query. CREATE SEQUENCE SEQ_ID; The above query produces the following output. (0) rows effected ALTER is a command used to change the table structure by adding different clauses to the alter command. Based on the scenario, we need to add respective clause to the alter command. In this chapter, we will discuss various scenarios of alter command. Alter Table Add is a command used to add a new column to a table along with the respective data type. This command commits the transaction in this connection. Following is the generic syntax of the Alter Table Add command. ALTER TABLE [ IF EXISTS ] tableName ADD [ COLUMN ] { [ IF NOT EXISTS ] columnDefinition [ { BEFORE | AFTER } columnName ] | ( { columnDefinition } [,...] ) } In this example, we will add a new column start_date to the table tutorials_tbl. The datatype for start_date is Date. Following is the query to add a new column. ALTER TABLE tutorials_tbl ADD start_date DATE; The above query produces the following output. (6) rows effected Alter table add constraint is a command used to add different constraints to the table such as primary key, foreign key, not null, etc. The required indexes are automatically created if they don’t exist yet. It is not possible to disable checking for unique constraint. This command commits an open transaction in this connection. Following is the generic syntax of the Alter table add constraint command. ALTER TABLE [ IF EXISTS ] tableName ADD constraint [ CHECK | NOCHECK ] In this example, let us add a primary key constraint (tutorials_tbl_pk) to the column id of the table tutorials_tbl, using the following query. ALTER TABLE tutorials_tbl ADD CONSTRAINT tutorials_tbl_pk PRIMARYKEY(id); The above query produces the following output. (6) row (s) effected This command is used to rename the constraint name of a particular relation table. This command commits an open transaction in this connection. Following is the generic syntax of the Alter Table Rename Constraint command. ALTER TABLE [ IF EXISTS ] tableName RENAME oldConstraintName TO newConstraintName While using this syntax, make sure that the old constraint name should exist with the respective column. In this example, we will change the primary key constraint name of the table tutorials_tbl from tutorials_tbl_pk to tutorials_tbl_pk_constraint. Following is the query to do so. ALTER TABLE tutorials_tbl RENAME CONSTRAINT tutorials_tbl_pk TO tutorials_tbl_pk_constraint; The above query produces the following output. (1) row (s) effected This command is used to change the structure and properties of the column of a particular table. Changing the properties means changing the datatype of a column, rename a column, change the identity value, or change the selectivity. Following is the generic syntax of the Alter Table Alter Column command. ALTER TABLE [ IF EXISTS ] tableName ALTER COLUMN columnName { { dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] } | { RENAME TO name } | { RESTART WITH long } | { SELECTIVITY int } | { SET DEFAULT expression } | { SET NULL } | { SET NOT NULL } } In the above syntax − RESTART − command changes the next value of an auto increment column. RESTART − command changes the next value of an auto increment column. SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column. SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column. SET DEFAULT − changes the default value of a column. SET DEFAULT − changes the default value of a column. SET NULL − sets the column to allow NULL. SET NULL − sets the column to allow NULL. SET NOT NULL − sets the column to allow NOT NULL. SET NOT NULL − sets the column to allow NOT NULL. In this example, we will rename the column of the table tutorials_tbl from Title to Tutorial_Title using the following query. ALTER TABLE tutorials_tbl ALTER COLUMN title RENAME TO tutorial_title; The above query produces the following output. (0) row(s) effected In a similar way, we can perform different scenarios with the ALTER command. DROP is a command taken from the generic SQL grammar. This command is used to delete a database component and its structure from the memory. There are different scenarios with the Drop command that we will discuss in this chapter. Drop Table is a command that deletes the respective table and its structure. Following is the generic syntax of the Drop Table command. DROP TABLE [ IF EXISTS ] tableName [,...] [ RESTRICT | CASCADE ] The command will fail if we are using RESTRICT and the table having dependent views exist. All dependent views are dropped, when we are using CASCADE keyword. In this example, we will drop a table named test using the following query. DROP TABLE test; The above query produces the following output. (6) row (s) effected Drop Schema is a command that drops a respective schema from the database server. It will not work from the current schema. DROP SCHEMA [ IF EXISTS ] schemaName In this example, we will drop a schema named test_schema using the following query. DROP SCHEMA TEST_SCHEMA; The above query produces the following output. (0) row(s) effected Drop Sequence is a command used to drop a sequence from the table structure. Following is the generic syntax of the Drop Sequence command. DROP SEQUENCE [ IF EXISTS ] sequenceName This command commits an open transaction in this connection. In this example, we will drop a sequence named sequence_id. Following is the command. DROP SEQUENCE sequence_id; The above command produces the following output. (0) row (s) effected Drop View is a command used to drop the existing view. All dependent views are dropped as well if the CASCADE clause is used. Following is the generic syntax of the Drop View command. DROP VIEW [ IF EXISTS ] viewName [ RESTRICT | CASCADE ] In this example, we will drop a view named sample_view using the following query. DROP VIEW sample_view; The above query produces the following output. (0) row (s) effected TRUNCATE is a command used to delete the data from the table. Unlike DELETE FROM without WHERE clause, this command cannot be rolled back. This command commits an open transaction in this connection. Following is the generic syntax of the truncate command. TRUNCATE TABLE tableName In this example, we will truncate a table named test using the following query. TRUNCATE TABLE test; The above query produces the following output. (6) row (s) effected COMMIT is a command from the SQL grammar used to commit the transaction. We can either commit the specific transaction or we can commit the currently executed transaction. There are two different syntaxes for COMMIT command. Following is the generic syntax for the commit command to commit the current transaction. COMMIT [ WORK ] Following is the generic syntax for the commit command to commit the specific transaction. COMMIT TRANSACTION transactionName In this example, let us commit the current transaction using the following command. COMMIT The above command produces the following output. Committed successfully In this example, we will commit the transaction named tx_test using the following command. COMMIT TRANSACTION tx_test; The above command produces the following output. Committed successfully Grant is a command coming from the SQL grammar used to grant the rights to a table, to a user, or to a role. Admin rights are required to execute this command. This command commits an open transaction in this connection. In this chapter, we will discuss the different scenarios of Grant command. Grant Right is a command to provide admin rights to a table, to a user, or to a role. Following is the generic syntax of the Grant command. GRANT { SELECT | INSERT | UPDATE | DELETE | ALL } [,...] ON { { SCHEMA schemaName } | { tableName [,...] } } TO { PUBLIC | userName | roleName } In this example, we will grant the test table as read-only using the following command. GRANT SELECT ON TEST TO READONLY The above command produces the following output. Grant successfully Grant Alter Any Schema is a command to grant schema altering rights to a respective user. Following is the generic syntax of the Grant Alter Any Schema command. GRANT ALTER ANY SCHEMA TO userName In this example, we will grant altering privileges of a schema to a user named test_user. Make sure that test_user exists. Following is the query to grant altering privileges. GRANT ALTER ANY SCHEMA TO test_user; The above query produces the following output. Granted successfully to test_user SAVEPOINT is a command used to temporarily save the transaction. It is better to maintain savepoints in your transaction as it is helpful to roll back the transaction to the respective Savepoint whenever necessary. Following is the generic syntax of the Savepoint command. SAVEPOINT savepointName In this example, we will create a Savepoint named Half_Done using the following command. SAVEPOINT Half_Done; The above command produces the following output. Savepoint created ROLLBACK is a command from the SQL grammar used to roll back the transaction to a Savepoint or to the previous transaction. By using this command, we can either roll back to the specific Savepoint or we can roll back to the previous executed transaction. There are two different syntaxes for ROLLABCK command. Following is the generic syntax for the rollback command. ROLLBACK [ TO SAVEPOINT savepointName ] Following is the generic syntax of the Rollback command to the specific transaction. ROLLBACK TRANSACTION transactionName In this example, we will roll back the current transaction to a Savepoint named sp1_test using the following command. ROLLBACK sp1_test; The above command produces the following output. Rollback successfully In the following example, we will roll back the complete transaction named tx_test using the given command. ROLLBACK TRANSACTION tx_test; The above command produces the following output. Rollback successfully H2 is a JAVA database. We can interact with this database by using JDBC. In this chapter, we will see how to create a JDBC connection with H2 database and the CRUD operations with the H2 database. Generally, there are five steps to create a JDBC connection. Step 1 − Registering the JDBC database driver. Class.forName ("org.h2.Driver"); Step 2 − Opening the connection. Connection conn = DriverManager.getConnection ("jdbc:h2:~/test", "sa",""); Step 3 − Creating a statement. Statement st = conn.createStatement(); Step 4 − Executing a statement and receiving Resultset. Stmt.executeUpdate("sql statement"); Step 5 − Closing a connection. conn.close(); Before moving on to create a full program, we need to add h2-1.4.192.jar file to CLASSPATH. We can get this jar from the folder C:\Program Files (x86)\H2\bin. In this example, we will write a program for create table. Consider a table named Registration having the following fields. Following is an example program named H2jdbcCreateDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcCreateDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 3: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " + " first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println("Created table in given database..."); // STEP 4: Clean-up environment stmt.close(); conn.close(); } catch(SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try{ if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se){ se.printStackTrace(); } //end finally try } //end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcCreateDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcCreateDemo.java \>java H2jdbcCreateDemo The above command produces the following output. Connecting to database... Creating table in given database... Created table in given database... Goodbye! After this execution, we can check the table created using the H2 SQL interface. In this example, we will write a program for inserting records. Let us insert the following records into the table Registration. Following is an example program named H2jdbcInsertDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcInsertDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("Connected database successfully..."); // STEP 3: Execute a query stmt = conn.createStatement(); String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)"; stmt.executeUpdate(sql); sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)"; stmt.executeUpdate(sql); System.out.println("Inserted records into the table..."); // STEP 4: Clean-up environment stmt.close(); conn.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcInsertDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcInsertDemo.java \>java H2jdbcInsertDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... Inserted records into the table... Goodbye! In this example, we will write a program for reading records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcRecordDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcReadDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Connected database successfully..."); stmt = conn.createStatement(); String sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); // STEP 4: Extract data from result set while(rs.next()) { // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } // STEP 5: Clean-up environment rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcReadDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcReadDemo.java \>java H2jdbcReadDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! In this example, we will write a program to update records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcUpdateDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcUpdateDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to a database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Connected database successfully..."); stmt = conn.createStatement(); String sql = "UPDATE Registration " + "SET age = 30 WHERE id in (100, 101)"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the updated records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcUpdateDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcUpdateDemo.java \>java H2jdbcUpdateDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 30, First: Zara, Last: Ali ID: 101, Age: 30, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! In this example, we will write a program to delete records. Let us try to read all records from the table Registration. Following is an example program named H2jdbcDeleteDemo. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class H2jdbcDeleteDemo { // JDBC driver name and database URL static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; // Database credentials static final String USER = "sa"; static final String PASS = ""; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // STEP 1: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // STEP 3: Execute a query System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "DELETE FROM Registration " + "WHERE id = 101"; stmt.executeUpdate(sql); // Now you can extract all the records // to see the remaining records sql = "SELECT id, first, last, age FROM Registration"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ // Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); // Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); } catch(SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } } Save the above program into H2jdbcDeleteDemo.java. Compile and execute the above program by executing the following commands in the command prompt. \>javac H2jdbcDeleteDemo.java \>java H2jdbcDeleteDemo The above command produces the following output. Connecting to a selected database... Connected database successfully... ID: 100, Age: 30, First: Zara, Last: Ali ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! 14 Lectures 1 hours Mahesh Kumar 100 Lectures 9.5 hours Hari Om Singh 108 Lectures 8 hours Pavan Lalwani 10 Lectures 1 hours Deepti Trivedi 20 Lectures 2 hours Deepti Trivedi 14 Lectures 1 hours Deepti Trivedi Print Add Notes Bookmark this page
[ { "code": null, "e": 2465, "s": 2107, "text": "H2 is an open-source lightweight Java database. It can be embedded in Java applications or run in the client-server mode. Mainly, H2 database can be configured to run as inmemory database, which means that data will not persist on the disk. Because of embedded database it is not used for production development, but mostly used for development and testing." }, { "code": null, "e": 2576, "s": 2465, "text": "This database can be used in embedded mode or in server mode. Following are the main features of H2 database −" }, { "code": null, "e": 2614, "s": 2576, "text": "Extremely fast, open source, JDBC API" }, { "code": null, "e": 2674, "s": 2614, "text": "Available in embedded and server modes; in-memory databases" }, { "code": null, "e": 2708, "s": 2674, "text": "Browser-based Console application" }, { "code": null, "e": 2753, "s": 2708, "text": "Small footprint − Around 1.5MB jar file size" }, { "code": null, "e": 2803, "s": 2753, "text": "The main features of H2 Database are as follows −" }, { "code": null, "e": 2844, "s": 2803, "text": "It is an extremely fast database engine." }, { "code": null, "e": 2885, "s": 2844, "text": "It is an extremely fast database engine." }, { "code": null, "e": 2924, "s": 2885, "text": "H2 is open source and written in Java." }, { "code": null, "e": 2963, "s": 2924, "text": "H2 is open source and written in Java." }, { "code": null, "e": 3041, "s": 2963, "text": "It supports standard SQL and JDBC API. It can use PostgreSQL ODBC driver too." }, { "code": null, "e": 3119, "s": 3041, "text": "It supports standard SQL and JDBC API. It can use PostgreSQL ODBC driver too." }, { "code": null, "e": 3152, "s": 3119, "text": "It has embedded and Server mode." }, { "code": null, "e": 3185, "s": 3152, "text": "It has embedded and Server mode." }, { "code": null, "e": 3239, "s": 3185, "text": "H2 supports clustering and multi-version concurrency." }, { "code": null, "e": 3293, "s": 3239, "text": "H2 supports clustering and multi-version concurrency." }, { "code": null, "e": 3326, "s": 3293, "text": "It has strong security features." }, { "code": null, "e": 3359, "s": 3326, "text": "It has strong security features." }, { "code": null, "e": 3415, "s": 3359, "text": "Following are some additional features of H2 Database −" }, { "code": null, "e": 3515, "s": 3415, "text": "H2 is a disk-based or in-memory databases and tables, read-only database support, temporary tables." }, { "code": null, "e": 3615, "s": 3515, "text": "H2 is a disk-based or in-memory databases and tables, read-only database support, temporary tables." }, { "code": null, "e": 3723, "s": 3615, "text": "H2 provides transaction support (read committed), 2-phase-commit multiple connections, table level locking." }, { "code": null, "e": 3831, "s": 3723, "text": "H2 provides transaction support (read committed), 2-phase-commit multiple connections, table level locking." }, { "code": null, "e": 3928, "s": 3831, "text": "H2 is a cost-based optimizer, using a genetic algorithm for complex queries, zeroadministration." }, { "code": null, "e": 4025, "s": 3928, "text": "H2 is a cost-based optimizer, using a genetic algorithm for complex queries, zeroadministration." }, { "code": null, "e": 4160, "s": 4025, "text": "H2 contains scrollable and updatable result set support, large result set, external result sorting, functions can return a result set." }, { "code": null, "e": 4295, "s": 4160, "text": "H2 contains scrollable and updatable result set support, large result set, external result sorting, functions can return a result set." }, { "code": null, "e": 4393, "s": 4295, "text": "H2 supports encrypted database (AES), SHA-256 password encryption, encryption functions, and SSL." }, { "code": null, "e": 4491, "s": 4393, "text": "H2 supports encrypted database (AES), SHA-256 password encryption, encryption functions, and SSL." }, { "code": null, "e": 4564, "s": 4491, "text": "In order to use H2 Database, you need to have the following components −" }, { "code": null, "e": 4578, "s": 4564, "text": "A web browser" }, { "code": null, "e": 4598, "s": 4578, "text": "A H2 console server" }, { "code": null, "e": 4697, "s": 4598, "text": "This is a client/server application, so both server and client (a browser) are required to run it." }, { "code": null, "e": 4974, "s": 4697, "text": "H2 is a database written in Java. We can easily embed this database to our application by using JDBC. We can run this on many different platforms or any version of Java Runtime Environment. However, before installing the database, there should be Java installed in the system." }, { "code": null, "e": 5063, "s": 4974, "text": "If JDK is installed in the system, try the following command to verify the Java version." }, { "code": null, "e": 5078, "s": 5063, "text": "java –version\n" }, { "code": null, "e": 5165, "s": 5078, "text": "If JDk is successfully installed in the system, then we will get the following output." }, { "code": null, "e": 5309, "s": 5165, "text": "java version \"1.8.0_91\" \nJava(TM) SE Runtime Environment (build 1.8.0_91-b14) \nJava HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)\n" }, { "code": null, "e": 5394, "s": 5309, "text": "If JDK is not installed in the system, then visit the following link to Install JDK." }, { "code": null, "e": 5522, "s": 5394, "text": "We can run this database on many different platforms. In this chapter, we will learn about H2 Database installation on Windows." }, { "code": null, "e": 5598, "s": 5522, "text": "Following are the steps to install H2 Database on Windows operating system." }, { "code": null, "e": 5860, "s": 5598, "text": "Download the latest version of H2 Database from the given link. In this link, you will get the latest version of H2 database in two types. One is Windows Installer type (that is .exe file) and second is Platform-Independent zip file for other operating systems." }, { "code": null, "e": 6038, "s": 5860, "text": "Click the Windows installer for downloading the Windows supportable H2 database after downloading the .exe file. In this case, we are using H2 Database with the version 1.4.192." }, { "code": null, "e": 6238, "s": 6038, "text": "After downloading we get the H2 Windows installer file (i.e. h2-setup-yyyy-mm-dd.exe) in the Downloads directory. To start the installation process of H2 Database, double click on the installer file." }, { "code": null, "e": 6407, "s": 6238, "text": "The following screen is the first step in the installation process. Provide a path where we want to install the H2 database server as shown in the following screenshot." }, { "code": null, "e": 6586, "s": 6407, "text": "As seen in the above screenshot, by default it will take C:\\ProgramFiles (x86)\\H2 as the destination folder. Click next to proceed to the next step. The following screen pops up." }, { "code": null, "e": 6724, "s": 6586, "text": "In the above screenshot, click the Install button to start the installation process. After installation, we get the following screenshot." }, { "code": null, "e": 6775, "s": 6724, "text": "Click Finish to complete the installation process." }, { "code": null, "e": 7065, "s": 6775, "text": "After installation, let us verify the database installation in the system. Click Windows → type H2 Console → Click H2 console icon. Connect to the URL http://localhost:8082. At the time of connecting, the H2 database will ask for database registration as shown in the following screenshot." }, { "code": null, "e": 7367, "s": 7065, "text": "Fill all the details in the above dialog box such as Saved Settings, Settings Name, Driver Class, JDBC URL, User Name, and Password. In the JDBC URL, specify the database is located and the database name. User Name and Password are the fields for user name and password of the database. Click Connect." }, { "code": null, "e": 7439, "s": 7367, "text": "The Database welcome page pops up as shown in the following screenshot." }, { "code": null, "e": 7614, "s": 7439, "text": "Select command is used to fetch record data from a table or multiple tables. If we design a select query, then it returns data in the form of result table called result sets." }, { "code": null, "e": 7667, "s": 7614, "text": "The basic syntax of SELECT statement is as follows −" }, { "code": null, "e": 8012, "s": 7667, "text": "SELECT [ TOP term ] [ DISTINCT | ALL ] selectExpression [,...] \nFROM tableExpression [,...] [ WHERE expression ] \n[ GROUP BY expression [,...] ] [ HAVING expression ] \n[ { UNION [ ALL ] | MINUS | EXCEPT | INTERSECT } select ] [ ORDER BY order [,...] ] \n[ [ LIMIT expression ] [ OFFSET expression ] [ SAMPLE_SIZE rowCountInt ] ] \n[ FOR UPDATE ]\n" }, { "code": null, "e": 8073, "s": 8012, "text": "To fetch all the available fields, use the following syntax." }, { "code": null, "e": 8100, "s": 8073, "text": "SELECT * FROM table_name;\n" }, { "code": null, "e": 8159, "s": 8100, "text": "Consider the CUSTOMER table having the following records −" }, { "code": null, "e": 8688, "s": 8159, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 8772, "s": 8688, "text": "To get the customer table along with the given data, execute the following queries." }, { "code": null, "e": 9322, "s": 8772, "text": "CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20), \nsalary number); \n\nINSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000); \nINSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500); \nINSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000); \nINSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500); \nINSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500); \nINSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500); \nINSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);" }, { "code": null, "e": 9454, "s": 9322, "text": "The following command is an example, which would fetch ID, Name and Salary fields of the customers available in the CUSTOMER table." }, { "code": null, "e": 9494, "s": 9454, "text": "SELECT ID, NAME, SALARY FROM CUSTOMERS;" }, { "code": null, "e": 9543, "s": 9494, "text": "The above command produces the following result." }, { "code": null, "e": 9874, "s": 9543, "text": "+----+----------+----------+ \n| ID | NAME | SALARY | \n+----+----------+----------+ \n| 1 | Ramesh | 2000.00 | \n| 2 | Khilan | 1500.00 | \n| 3 | kaushik | 2000.00 | \n| 4 | Chaitali | 6500.00 | \n| 5 | Hardik | 8500.00 | \n| 6 | Komal | 4500.00 | \n| 7 | Muffy | 10000.00 | \n+----+----------+----------+ \n" }, { "code": null, "e": 9942, "s": 9874, "text": "Use the following query to fetch all the fields of CUSTOMERS table." }, { "code": null, "e": 9972, "s": 9942, "text": "SQL> SELECT * FROM CUSTOMERS;" }, { "code": null, "e": 10020, "s": 9972, "text": "The above query produces the following result −" }, { "code": null, "e": 10549, "s": 10020, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 10634, "s": 10549, "text": "The SQL INSERT statement is used to add new rows of data to a table in the database." }, { "code": null, "e": 10690, "s": 10634, "text": "Following is the basic syntax of INSERT INTO statement." }, { "code": null, "e": 10895, "s": 10690, "text": "INSERT INTO tableName \n{ [ ( columnName [,...] ) ] \n{ VALUES \n{ ( { DEFAULT | expression } [,...] ) } [,...] | [ DIRECT ] [ SORTED ] select } } | \n{ SET { columnName = { DEFAULT | expression } } [,...] }\n" }, { "code": null, "e": 11235, "s": 10895, "text": "Using this INSERT statement, we can insert a new record or new rows into a table. When using DIRECT clause, the results are directly affected to the target table without any intermediate step. However, while adding values for all the columns of the table, make sure the order of the values is in the same order as the columns in the table." }, { "code": null, "e": 11329, "s": 11235, "text": "Let us take an example and try to insert the following given records into the Customer table." }, { "code": null, "e": 11423, "s": 11329, "text": "We can get all the given records into the customer table by executing the following commands." }, { "code": null, "e": 11870, "s": 11423, "text": "INSERT INTO CUSTOMER VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000); \nINSERT INTO CUSTOMER VALUES (2, 'Khilan', 25, 'Delhi', 1500); \nINSERT INTO CUSTOMER VALUES (3, 'kaushik', 23, 'Kota', 2000); \nINSERT INTO CUSTOMER VALUES (4, 'Chaitali', 25, 'Mumbai', 6500); \nINSERT INTO CUSTOMER VALUES (5, 'Hardik', 27, 'Bhopal', 8500); \nINSERT INTO CUSTOMER VALUES (6, 'Komal', 22, 'MP', 4500); \nINSERT INTO CUSTOMER VALUES (7, 'Muffy', 24, 'Indore', 10000); \n" }, { "code": null, "e": 12061, "s": 11870, "text": "The UPDATE query is used to update or modify the existing records in a table. We can use WHERE clause with UPDATE query to update the selected rows, otherwise all the rows would be affected." }, { "code": null, "e": 12112, "s": 12061, "text": "Following is the basic syntax of the UPDATE query." }, { "code": null, "e": 12324, "s": 12112, "text": "UPDATE tableName [ [ AS ] newTableAlias ] SET \n{ { columnName = { DEFAULT | expression } } [,...] } | \n{ ( columnName [,...] ) = ( select ) } \n[ WHERE expression ] [ ORDER BY order [,...] ] [ LIMIT expression ]\n" }, { "code": null, "e": 12414, "s": 12324, "text": "In this UPDATE syntax, we can combine more than one condition by using AND or OR clauses." }, { "code": null, "e": 12472, "s": 12414, "text": "Consider the CUSTOMER table having the following records." }, { "code": null, "e": 13001, "s": 12472, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 13097, "s": 13001, "text": "If you want to get the customer table along with the given data, execute the following queries." }, { "code": null, "e": 13650, "s": 13097, "text": "CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20), \n salary number); \nINSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000); \nINSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500); \nINSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000); \nINSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500); \nINSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500); \nINSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500); \nINSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);\n" }, { "code": null, "e": 13745, "s": 13650, "text": "The following command is an example, which would update ADDRESS for a customer whose ID is 6 −" }, { "code": null, "e": 13798, "s": 13745, "text": "UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;\n" }, { "code": null, "e": 13927, "s": 13798, "text": "Now, CUSTOMERS table would have the following records. We can check the customer table records by executing the following query." }, { "code": null, "e": 13953, "s": 13927, "text": "SELECT * FROM CUSTOMERS;\n" }, { "code": null, "e": 14000, "s": 13953, "text": "The above query produces the following result." }, { "code": null, "e": 14529, "s": 14000, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | Pune | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 14669, "s": 14529, "text": "To modify all ADDRESS and SALARY column values in CUSTOMERS table, we need not use the WHERE clause. The UPDATE query would be as follows −" }, { "code": null, "e": 14728, "s": 14669, "text": "UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00; \n" }, { "code": null, "e": 14857, "s": 14728, "text": "Now, CUSTOMERS table would have the following records. We can check the customer table records by executing the following query." }, { "code": null, "e": 14883, "s": 14857, "text": "SELECT * FROM CUSTOMERS;\n" }, { "code": null, "e": 14931, "s": 14883, "text": "The above query produces the following result −" }, { "code": null, "e": 15427, "s": 14931, "text": "+----+----------+-----+---------+---------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+---------+---------+ \n| 1 | Ramesh | 32 | Pune | 1000.00 | \n| 2 | Khilan | 25 | Pune | 1000.00 | \n| 3 | kaushik | 23 | Pune | 1000.00 | \n| 4 | Chaitali | 25 | Pune | 1000.00 | \n| 5 | Hardik | 27 | Pune | 1000.00 | \n| 6 | Komal | 22 | Pune | 1000.00 | \n| 7 | Muffy | 24 | Pune | 1000.00 | \n+----+----------+-----+---------+---------+ \n" }, { "code": null, "e": 15614, "s": 15427, "text": "The SQL DELETE query is used to delete the existing records from a table. We can use WHERE clause with DELETE query to delete selected records, otherwise all the records will be deleted." }, { "code": null, "e": 15675, "s": 15614, "text": "Following is the generic query syntax of the delete command." }, { "code": null, "e": 15747, "s": 15675, "text": "DELETE [ TOP term ] FROM tableName [ WHERE expression ] [ LIMIT term ]\n" }, { "code": null, "e": 15915, "s": 15747, "text": "The above syntax deletes the rows from a table. If TOP or LIMIT is specified, at most the specified number of rows are deleted (no limit if null or smaller than zero)." }, { "code": null, "e": 15973, "s": 15915, "text": "Consider the CUSTOMER table having the following records." }, { "code": null, "e": 16501, "s": 15973, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 16579, "s": 16501, "text": "The following command will delete the details of the customer, whose ID is 6." }, { "code": null, "e": 16616, "s": 16579, "text": "DELETE FROM CUSTOMERS WHERE ID = 6;\n" }, { "code": null, "e": 16715, "s": 16616, "text": "After execution of the above command, check the Customer table by executing the following command." }, { "code": null, "e": 16741, "s": 16715, "text": "SELECT * FROM CUSTOMERS; " }, { "code": null, "e": 16791, "s": 16741, "text": "The above command produces the following output −" }, { "code": null, "e": 17272, "s": 16791, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 17397, "s": 17272, "text": "If we want to DELETE all the records from CUSTOMERS table, we do not use WHERE clause. The DELETE query would be as follows." }, { "code": null, "e": 17421, "s": 17397, "text": "DELETE FROM CUSTOMER; \n" }, { "code": null, "e": 17508, "s": 17421, "text": "After executing the above command, no records will be available in the Customer table." }, { "code": null, "e": 17722, "s": 17508, "text": "BACKUP is the command used to take database backup into a separate .zip file. Objects are not locked, and when it takes backup the transaction log is also copied. Admin rights are required to execute this command." }, { "code": null, "e": 17777, "s": 17722, "text": "Following is the generic syntax of the Backup command." }, { "code": null, "e": 17804, "s": 17777, "text": "BACKUP TO fileNameString;\n" }, { "code": null, "e": 17928, "s": 17804, "text": "In this example, let us take a backup of the current database into backup.zip file. Use the following command for the same." }, { "code": null, "e": 17952, "s": 17928, "text": "BACKUP TO 'backup.zip';" }, { "code": null, "e": 18044, "s": 17952, "text": "On executing the above command, you will get the backup.zip file in your local file system." }, { "code": null, "e": 18330, "s": 18044, "text": "CALL is a SQL command which belongs to H2 database server. This command is used to calculate a simple expression. It returns the result of the given expression in a single column field. When it returns an array of results, then each element in the array is displayed as a column value." }, { "code": null, "e": 18383, "s": 18330, "text": "Following is the generic syntax of the CALL command." }, { "code": null, "e": 18401, "s": 18383, "text": "CALL expression;\n" }, { "code": null, "e": 18454, "s": 18401, "text": "We can use the arithmetic expression in this syntax." }, { "code": null, "e": 18544, "s": 18454, "text": "Let us take an example and execute an arithmetic expression (15 * 25) using call command." }, { "code": null, "e": 18558, "s": 18544, "text": "CALL 15*25; \n" }, { "code": null, "e": 18607, "s": 18558, "text": "The above command produces the following output." }, { "code": null, "e": 18797, "s": 18607, "text": "EXPLAIN command displays the execution plan for a statement. When we execute a statement using EXPLAIN ANALYZE command, the query plan will include the actual row scan count for each table." }, { "code": null, "e": 18853, "s": 18797, "text": "Following is the generic syntax of the EXPLAIN command." }, { "code": null, "e": 18935, "s": 18853, "text": "EXPLAIN { [ PLAN FOR ] | ANALYZE } { select | insert | update | delete | merge} \n" }, { "code": null, "e": 19004, "s": 18935, "text": "Along with this syntax we can use select, insert, delete, and merge." }, { "code": null, "e": 19076, "s": 19004, "text": "This example explains the query plan details of the customer with ID 1." }, { "code": null, "e": 19122, "s": 19076, "text": "EXPLAIN SELECT * FROM CUSTOMER WHERE ID = 1;\n" }, { "code": null, "e": 19172, "s": 19122, "text": "The above command produces the following output −" }, { "code": null, "e": 19358, "s": 19172, "text": "MERGE command is used to update the existing rows and insert new rows into a table. The primary key column plays an important role while using this command; it is used to find the row." }, { "code": null, "e": 19412, "s": 19358, "text": "Following is the generic syntax of the MERGE command." }, { "code": null, "e": 19560, "s": 19412, "text": "MERGE INTO tableName [ ( columnName [,...] ) ] \n[ KEY ( columnName [,...] ) ] \n{ VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | select } \n" }, { "code": null, "e": 19800, "s": 19560, "text": "In the above syntax, the KEY clause is used to specify the primary key column name. Along with VALUES clause, we can use primitive values to insert or we can retrieve and store another table values into this table using the select command." }, { "code": null, "e": 19928, "s": 19800, "text": "In this example, let us try to add a new record into Customers table. Following are the details of the new record in the table." }, { "code": null, "e": 20014, "s": 19928, "text": "Using the following query, let us insert the given record into the H2 database query." }, { "code": null, "e": 20089, "s": 20014, "text": "MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Lokesh', 32, 'Hyderabad', 2500);\n" }, { "code": null, "e": 20136, "s": 20089, "text": "The above query produces the following output." }, { "code": null, "e": 20154, "s": 20136, "text": "Update count: 1 \n" }, { "code": null, "e": 20236, "s": 20154, "text": "Let us verify the records of the Customer table by executing the following query." }, { "code": null, "e": 20260, "s": 20236, "text": "SELECT * FROM CUSTOMER;" }, { "code": null, "e": 20307, "s": 20260, "text": "The above query produces the following output." }, { "code": null, "e": 20423, "s": 20307, "text": "Now let us try to update the record using the Merge command. Following are the details of the record to be updated." }, { "code": null, "e": 20502, "s": 20423, "text": "Use the following query to insert the given record into the H2 database query." }, { "code": null, "e": 20575, "s": 20502, "text": "MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Loki', 32, 'Hyderabad', 3000);\n" }, { "code": null, "e": 20622, "s": 20575, "text": "The above query produces the following output." }, { "code": null, "e": 20640, "s": 20622, "text": "Update count: 1 \n" }, { "code": null, "e": 20722, "s": 20640, "text": "Let us verify the records of the Customer table by executing the following query." }, { "code": null, "e": 20748, "s": 20722, "text": "SELECT * FROM CUSTOMER; \n" }, { "code": null, "e": 20796, "s": 20748, "text": "The above query produces the following output −" }, { "code": null, "e": 20884, "s": 20796, "text": "SHOW is a command used to display the list of Schemas, Tables, or Columns of the table." }, { "code": null, "e": 20937, "s": 20884, "text": "Following is the generic syntax of the SHOW command." }, { "code": null, "e": 21031, "s": 20937, "text": "SHOW { SCHEMAS | TABLES [ FROM schemaName ] | \nCOLUMNS FROM tableName [ FROM schemaName ] } \n" }, { "code": null, "e": 21116, "s": 21031, "text": "The following command can be used to get the list of tables in the current database." }, { "code": null, "e": 21130, "s": 21116, "text": "SHOW TABLES; " }, { "code": null, "e": 21179, "s": 21130, "text": "The above command produces the following output." }, { "code": null, "e": 21294, "s": 21179, "text": "CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views, and Users in H2 Database server." }, { "code": null, "e": 21381, "s": 21294, "text": "Create Table is a command used to create a user-defined table in the current database." }, { "code": null, "e": 21443, "s": 21381, "text": "Following is the generic syntax for the Create Table command." }, { "code": null, "e": 21710, "s": 21443, "text": "CREATE [ CACHED | MEMORY ] [ TEMP | [ GLOBAL | LOCAL ] TEMPORARY ] \nTABLE [ IF NOT EXISTS ] name \n[ ( { columnDefinition | constraint } [,...] ) ] \n[ ENGINE tableEngineName [ WITH tableEngineParamName [,...] ] ] \n[ NOT PERSISTENT ] [ TRANSACTIONAL ] \n[ AS select ] \n" }, { "code": null, "e": 21942, "s": 21710, "text": "By using the generic syntax of the Create Table command, we can create different types of tables such as cached tables, memory tables, and temporary tables. Following is the list to describe different clauses from the given syntax." }, { "code": null, "e": 22075, "s": 21942, "text": "CACHED − The cached tables are the default type for regular tables. This means the number of rows is not limited by the main memory." }, { "code": null, "e": 22208, "s": 22075, "text": "CACHED − The cached tables are the default type for regular tables. This means the number of rows is not limited by the main memory." }, { "code": null, "e": 22379, "s": 22208, "text": "MEMORY − The memory tables are the default type for temporary tables. This means the memory tables should not get too large and the index data is kept in the main memory." }, { "code": null, "e": 22550, "s": 22379, "text": "MEMORY − The memory tables are the default type for temporary tables. This means the memory tables should not get too large and the index data is kept in the main memory." }, { "code": null, "e": 22949, "s": 22550, "text": "TEMPORARY − Temporary tables are deleted while closing or opening a database. Basically, temporary tables are of two types −\n\nGLOBAL type − Accessible by all connections.\nLOCAL type − Accessible by the current connection.\n\nThe default type for temporary tables is global type. Indexes of temporary tables are kept in the main memory, unless the temporary table is created using CREATE CACHED TABLE." }, { "code": null, "e": 23074, "s": 22949, "text": "TEMPORARY − Temporary tables are deleted while closing or opening a database. Basically, temporary tables are of two types −" }, { "code": null, "e": 23119, "s": 23074, "text": "GLOBAL type − Accessible by all connections." }, { "code": null, "e": 23164, "s": 23119, "text": "GLOBAL type − Accessible by all connections." }, { "code": null, "e": 23215, "s": 23164, "text": "LOCAL type − Accessible by the current connection." }, { "code": null, "e": 23266, "s": 23215, "text": "LOCAL type − Accessible by the current connection." }, { "code": null, "e": 23442, "s": 23266, "text": "The default type for temporary tables is global type. Indexes of temporary tables are kept in the main memory, unless the temporary table is created using CREATE CACHED TABLE." }, { "code": null, "e": 23530, "s": 23442, "text": "ENGINE − The ENGINE option is only required when custom table implementations are used." }, { "code": null, "e": 23618, "s": 23530, "text": "ENGINE − The ENGINE option is only required when custom table implementations are used." }, { "code": null, "e": 23745, "s": 23618, "text": "NOT PERSISTENT − It is a modifier to keep the complete table data in-memory and all rows are lost when the database is closed." }, { "code": null, "e": 23872, "s": 23745, "text": "NOT PERSISTENT − It is a modifier to keep the complete table data in-memory and all rows are lost when the database is closed." }, { "code": null, "e": 23986, "s": 23872, "text": "TRANSACTIONAL − It is a keyword that commits an open transaction and this command supports only temporary tables." }, { "code": null, "e": 24100, "s": 23986, "text": "TRANSACTIONAL − It is a keyword that commits an open transaction and this command supports only temporary tables." }, { "code": null, "e": 24191, "s": 24100, "text": "In this example, let us create a table named tutorials_tbl using the following given data." }, { "code": null, "e": 24285, "s": 24191, "text": "The following query is used to create a table tutorials_tbl along with the given column data." }, { "code": null, "e": 24430, "s": 24285, "text": "CREATE TABLE tutorials_tbl ( \n id INT NOT NULL, \n title VARCHAR(50) NOT NULL, \n author VARCHAR(20) NOT NULL, \n submission_date DATE \n);\n" }, { "code": null, "e": 24477, "s": 24430, "text": "The above query produces the following output." }, { "code": null, "e": 24497, "s": 24477, "text": "(0) rows effected \n" }, { "code": null, "e": 24635, "s": 24497, "text": "Create Schema is a command used to create a user-dependent schema under a particular authorization (under the currently registered user)." }, { "code": null, "e": 24697, "s": 24635, "text": "Following is the generic syntax of the Create Schema command." }, { "code": null, "e": 24768, "s": 24697, "text": "CREATE SCHEMA [ IF NOT EXISTS ] name [ AUTHORIZATION ownerUserName ] \n" }, { "code": null, "e": 25063, "s": 24768, "text": "In the above generic syntax, AUTHORIZATION is a keyword used to provide the respective user name. This command is optional which means if we are not providing the user name, then it will consider the current user. The user that executes the command must have admin rights, as well as the owner." }, { "code": null, "e": 25124, "s": 25063, "text": "This command commits an open transaction in this connection." }, { "code": null, "e": 25226, "s": 25124, "text": "In this example, let us create a schema named test_schema under SA user, using the following command." }, { "code": null, "e": 25271, "s": 25226, "text": "CREATE SCHEMA test_schema AUTHORIZATION sa; " }, { "code": null, "e": 25320, "s": 25271, "text": "The above command produces the following output." }, { "code": null, "e": 25340, "s": 25320, "text": "(0) rows effected \n" }, { "code": null, "e": 25455, "s": 25340, "text": "Sequence is concept which is used to generate a number by following a sequence for id or any random column values." }, { "code": null, "e": 25519, "s": 25455, "text": "Following is the generic syntax of the create sequence command." }, { "code": null, "e": 25780, "s": 25519, "text": "CREATE SEQUENCE [ IF NOT EXISTS ] newSequenceName [ START WITH long ] \n[ INCREMENT BY long ] \n[ MINVALUE long | NOMINVALUE | NO MINVALUE ] \n[ MAXVALUE long | NOMAXVALUE | NO MAXVALUE ] \n[ CYCLE long | NOCYCLE | NO CYCLE ] \n[ CACHE long | NOCACHE | NO CACHE ] \n" }, { "code": null, "e": 25958, "s": 25780, "text": "This generic syntax is used to create a sequence. The datatype of a sequence is BIGINT. In this the sequence, values are never re-used, even when the transaction is roll backed." }, { "code": null, "e": 26041, "s": 25958, "text": "In this example, let us create a sequence named SEQ_ID, using the following query." }, { "code": null, "e": 26066, "s": 26041, "text": "CREATE SEQUENCE SEQ_ID; " }, { "code": null, "e": 26113, "s": 26066, "text": "The above query produces the following output." }, { "code": null, "e": 26133, "s": 26113, "text": "(0) rows effected \n" }, { "code": null, "e": 26384, "s": 26133, "text": "ALTER is a command used to change the table structure by adding different clauses to the alter command. Based on the scenario, we need to add respective clause to the alter command. In this chapter, we will discuss various scenarios of alter command." }, { "code": null, "e": 26543, "s": 26384, "text": "Alter Table Add is a command used to add a new column to a table along with the respective data type. This command commits the transaction in this connection." }, { "code": null, "e": 26607, "s": 26543, "text": "Following is the generic syntax of the Alter Table Add command." }, { "code": null, "e": 26771, "s": 26607, "text": "ALTER TABLE [ IF EXISTS ] tableName ADD [ COLUMN ] \n{ [ IF NOT EXISTS ] columnDefinition [ { BEFORE | AFTER } columnName ] \n | ( { columnDefinition } [,...] ) }\n" }, { "code": null, "e": 26933, "s": 26771, "text": "In this example, we will add a new column start_date to the table tutorials_tbl. The datatype for start_date is Date. Following is the query to add a new column." }, { "code": null, "e": 26980, "s": 26933, "text": "ALTER TABLE tutorials_tbl ADD start_date DATE;" }, { "code": null, "e": 27027, "s": 26980, "text": "The above query produces the following output." }, { "code": null, "e": 27047, "s": 27027, "text": "(6) rows effected \n" }, { "code": null, "e": 27183, "s": 27047, "text": "Alter table add constraint is a command used to add different constraints to the table such as primary key, foreign key, not null, etc." }, { "code": null, "e": 27378, "s": 27183, "text": "The required indexes are automatically created if they don’t exist yet. It is not possible to disable checking for unique constraint. This command commits an open transaction in this connection." }, { "code": null, "e": 27453, "s": 27378, "text": "Following is the generic syntax of the Alter table add constraint command." }, { "code": null, "e": 27526, "s": 27453, "text": "ALTER TABLE [ IF EXISTS ] tableName ADD constraint [ CHECK | NOCHECK ] \n" }, { "code": null, "e": 27670, "s": 27526, "text": "In this example, let us add a primary key constraint (tutorials_tbl_pk) to the column id of the table tutorials_tbl, using the following query." }, { "code": null, "e": 27745, "s": 27670, "text": "ALTER TABLE tutorials_tbl ADD CONSTRAINT tutorials_tbl_pk PRIMARYKEY(id); " }, { "code": null, "e": 27792, "s": 27745, "text": "The above query produces the following output." }, { "code": null, "e": 27814, "s": 27792, "text": "(6) row (s) effected\n" }, { "code": null, "e": 27958, "s": 27814, "text": "This command is used to rename the constraint name of a particular relation table. This command commits an open transaction in this connection." }, { "code": null, "e": 28036, "s": 27958, "text": "Following is the generic syntax of the Alter Table Rename Constraint command." }, { "code": null, "e": 28119, "s": 28036, "text": "ALTER TABLE [ IF EXISTS ] tableName RENAME oldConstraintName TO newConstraintName\n" }, { "code": null, "e": 28224, "s": 28119, "text": "While using this syntax, make sure that the old constraint name should exist with the respective column." }, { "code": null, "e": 28402, "s": 28224, "text": "In this example, we will change the primary key constraint name of the table tutorials_tbl from tutorials_tbl_pk to tutorials_tbl_pk_constraint. Following is the query to do so." }, { "code": null, "e": 28496, "s": 28402, "text": "ALTER TABLE tutorials_tbl RENAME CONSTRAINT \ntutorials_tbl_pk TO tutorials_tbl_pk_constraint;" }, { "code": null, "e": 28543, "s": 28496, "text": "The above query produces the following output." }, { "code": null, "e": 28566, "s": 28543, "text": "(1) row (s) effected \n" }, { "code": null, "e": 28799, "s": 28566, "text": "This command is used to change the structure and properties of the column of a particular table. Changing the properties means changing the datatype of a column, rename a column, change the identity value, or change the selectivity." }, { "code": null, "e": 28872, "s": 28799, "text": "Following is the generic syntax of the Alter Table Alter Column command." }, { "code": null, "e": 29158, "s": 28872, "text": "ALTER TABLE [ IF EXISTS ] tableName ALTER COLUMN columnName \n{ { dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] } \n| { RENAME TO name } \n| { RESTART WITH long } \n| { SELECTIVITY int } \n| { SET DEFAULT expression } \n| { SET NULL } \n| { SET NOT NULL } } \n" }, { "code": null, "e": 29180, "s": 29158, "text": "In the above syntax −" }, { "code": null, "e": 29250, "s": 29180, "text": "RESTART − command changes the next value of an auto increment column." }, { "code": null, "e": 29320, "s": 29250, "text": "RESTART − command changes the next value of an auto increment column." }, { "code": null, "e": 29454, "s": 29320, "text": "SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column." }, { "code": null, "e": 29588, "s": 29454, "text": "SELECTIVITY − command sets the selectivity (1-100) for a column. Based on the selectivity value we can image the value of the column." }, { "code": null, "e": 29641, "s": 29588, "text": "SET DEFAULT − changes the default value of a column." }, { "code": null, "e": 29694, "s": 29641, "text": "SET DEFAULT − changes the default value of a column." }, { "code": null, "e": 29736, "s": 29694, "text": "SET NULL − sets the column to allow NULL." }, { "code": null, "e": 29778, "s": 29736, "text": "SET NULL − sets the column to allow NULL." }, { "code": null, "e": 29828, "s": 29778, "text": "SET NOT NULL − sets the column to allow NOT NULL." }, { "code": null, "e": 29878, "s": 29828, "text": "SET NOT NULL − sets the column to allow NOT NULL." }, { "code": null, "e": 30004, "s": 29878, "text": "In this example, we will rename the column of the table tutorials_tbl from Title to Tutorial_Title using the following query." }, { "code": null, "e": 30077, "s": 30004, "text": "ALTER TABLE tutorials_tbl ALTER COLUMN title RENAME TO tutorial_title; \n" }, { "code": null, "e": 30124, "s": 30077, "text": "The above query produces the following output." }, { "code": null, "e": 30146, "s": 30124, "text": "(0) row(s) effected \n" }, { "code": null, "e": 30223, "s": 30146, "text": "In a similar way, we can perform different scenarios with the ALTER command." }, { "code": null, "e": 30454, "s": 30223, "text": "DROP is a command taken from the generic SQL grammar. This command is used to delete a database component and its structure from the memory. There are different scenarios with the Drop command that we will discuss in this chapter." }, { "code": null, "e": 30531, "s": 30454, "text": "Drop Table is a command that deletes the respective table and its structure." }, { "code": null, "e": 30590, "s": 30531, "text": "Following is the generic syntax of the Drop Table command." }, { "code": null, "e": 30656, "s": 30590, "text": "DROP TABLE [ IF EXISTS ] tableName [,...] [ RESTRICT | CASCADE ]\n" }, { "code": null, "e": 30815, "s": 30656, "text": "The command will fail if we are using RESTRICT and the table having dependent views exist. All dependent views are dropped, when we are using CASCADE keyword." }, { "code": null, "e": 30891, "s": 30815, "text": "In this example, we will drop a table named test using the following query." }, { "code": null, "e": 30909, "s": 30891, "text": "DROP TABLE test;\n" }, { "code": null, "e": 30956, "s": 30909, "text": "The above query produces the following output." }, { "code": null, "e": 30979, "s": 30956, "text": "(6) row (s) effected \n" }, { "code": null, "e": 31103, "s": 30979, "text": "Drop Schema is a command that drops a respective schema from the database server. It will not work from the current schema." }, { "code": null, "e": 31142, "s": 31103, "text": "DROP SCHEMA [ IF EXISTS ] schemaName \n" }, { "code": null, "e": 31226, "s": 31142, "text": "In this example, we will drop a schema named test_schema using the following query." }, { "code": null, "e": 31253, "s": 31226, "text": "DROP SCHEMA TEST_SCHEMA; \n" }, { "code": null, "e": 31300, "s": 31253, "text": "The above query produces the following output." }, { "code": null, "e": 31321, "s": 31300, "text": "(0) row(s) effected\n" }, { "code": null, "e": 31398, "s": 31321, "text": "Drop Sequence is a command used to drop a sequence from the table structure." }, { "code": null, "e": 31460, "s": 31398, "text": "Following is the generic syntax of the Drop Sequence command." }, { "code": null, "e": 31502, "s": 31460, "text": "DROP SEQUENCE [ IF EXISTS ] sequenceName\n" }, { "code": null, "e": 31563, "s": 31502, "text": "This command commits an open transaction in this connection." }, { "code": null, "e": 31649, "s": 31563, "text": "In this example, we will drop a sequence named sequence_id. Following is the command." }, { "code": null, "e": 31677, "s": 31649, "text": "DROP SEQUENCE sequence_id;\n" }, { "code": null, "e": 31726, "s": 31677, "text": "The above command produces the following output." }, { "code": null, "e": 31749, "s": 31726, "text": "(0) row (s) effected \n" }, { "code": null, "e": 31875, "s": 31749, "text": "Drop View is a command used to drop the existing view. All dependent views are dropped as well if the CASCADE clause is used." }, { "code": null, "e": 31933, "s": 31875, "text": "Following is the generic syntax of the Drop View command." }, { "code": null, "e": 31990, "s": 31933, "text": "DROP VIEW [ IF EXISTS ] viewName [ RESTRICT | CASCADE ]\n" }, { "code": null, "e": 32072, "s": 31990, "text": "In this example, we will drop a view named sample_view using the following query." }, { "code": null, "e": 32096, "s": 32072, "text": "DROP VIEW sample_view;\n" }, { "code": null, "e": 32143, "s": 32096, "text": "The above query produces the following output." }, { "code": null, "e": 32166, "s": 32143, "text": "(0) row (s) effected \n" }, { "code": null, "e": 32367, "s": 32166, "text": "TRUNCATE is a command used to delete the data from the table. Unlike DELETE FROM without WHERE clause, this command cannot be rolled back. This command commits an open transaction in this connection." }, { "code": null, "e": 32424, "s": 32367, "text": "Following is the generic syntax of the truncate command." }, { "code": null, "e": 32451, "s": 32424, "text": "TRUNCATE TABLE tableName \n" }, { "code": null, "e": 32531, "s": 32451, "text": "In this example, we will truncate a table named test using the following query." }, { "code": null, "e": 32553, "s": 32531, "text": "TRUNCATE TABLE test;\n" }, { "code": null, "e": 32600, "s": 32553, "text": "The above query produces the following output." }, { "code": null, "e": 32623, "s": 32600, "text": "(6) row (s) effected \n" }, { "code": null, "e": 32795, "s": 32623, "text": "COMMIT is a command from the SQL grammar used to commit the transaction. We can either commit the specific transaction or we can commit the currently executed transaction." }, { "code": null, "e": 32848, "s": 32795, "text": "There are two different syntaxes for COMMIT command." }, { "code": null, "e": 32938, "s": 32848, "text": "Following is the generic syntax for the commit command to commit the current transaction." }, { "code": null, "e": 32956, "s": 32938, "text": "COMMIT [ WORK ] \n" }, { "code": null, "e": 33047, "s": 32956, "text": "Following is the generic syntax for the commit command to commit the specific transaction." }, { "code": null, "e": 33083, "s": 33047, "text": "COMMIT TRANSACTION transactionName\n" }, { "code": null, "e": 33167, "s": 33083, "text": "In this example, let us commit the current transaction using the following command." }, { "code": null, "e": 33175, "s": 33167, "text": "COMMIT\n" }, { "code": null, "e": 33224, "s": 33175, "text": "The above command produces the following output." }, { "code": null, "e": 33248, "s": 33224, "text": "Committed successfully\n" }, { "code": null, "e": 33339, "s": 33248, "text": "In this example, we will commit the transaction named tx_test using the following command." }, { "code": null, "e": 33368, "s": 33339, "text": "COMMIT TRANSACTION tx_test;\n" }, { "code": null, "e": 33417, "s": 33368, "text": "The above command produces the following output." }, { "code": null, "e": 33442, "s": 33417, "text": "Committed successfully \n" }, { "code": null, "e": 33663, "s": 33442, "text": "Grant is a command coming from the SQL grammar used to grant the rights to a table, to a user, or to a role. Admin rights are required to execute this command. This command commits an open transaction in this connection." }, { "code": null, "e": 33738, "s": 33663, "text": "In this chapter, we will discuss the different scenarios of Grant command." }, { "code": null, "e": 33824, "s": 33738, "text": "Grant Right is a command to provide admin rights to a table, to a user, or to a role." }, { "code": null, "e": 33878, "s": 33824, "text": "Following is the generic syntax of the Grant command." }, { "code": null, "e": 34026, "s": 33878, "text": "GRANT { SELECT | INSERT | UPDATE | DELETE | ALL } [,...] ON \n{ { SCHEMA schemaName } | { tableName [,...] } } \nTO { PUBLIC | userName | roleName }\n" }, { "code": null, "e": 34114, "s": 34026, "text": "In this example, we will grant the test table as read-only using the following command." }, { "code": null, "e": 34148, "s": 34114, "text": "GRANT SELECT ON TEST TO READONLY\n" }, { "code": null, "e": 34197, "s": 34148, "text": "The above command produces the following output." }, { "code": null, "e": 34217, "s": 34197, "text": "Grant successfully\n" }, { "code": null, "e": 34307, "s": 34217, "text": "Grant Alter Any Schema is a command to grant schema altering rights to a respective user." }, { "code": null, "e": 34378, "s": 34307, "text": "Following is the generic syntax of the Grant Alter Any Schema command." }, { "code": null, "e": 34415, "s": 34378, "text": "GRANT ALTER ANY SCHEMA TO userName \n" }, { "code": null, "e": 34591, "s": 34415, "text": "In this example, we will grant altering privileges of a schema to a user named test_user. Make sure that test_user exists. Following is the query to grant altering privileges." }, { "code": null, "e": 34629, "s": 34591, "text": "GRANT ALTER ANY SCHEMA TO test_user;\n" }, { "code": null, "e": 34676, "s": 34629, "text": "The above query produces the following output." }, { "code": null, "e": 34711, "s": 34676, "text": "Granted successfully to test_user\n" }, { "code": null, "e": 34926, "s": 34711, "text": "SAVEPOINT is a command used to temporarily save the transaction. It is better to maintain savepoints in your transaction as it is helpful to roll back the transaction to the respective Savepoint whenever necessary." }, { "code": null, "e": 34984, "s": 34926, "text": "Following is the generic syntax of the Savepoint command." }, { "code": null, "e": 35009, "s": 34984, "text": "SAVEPOINT savepointName\n" }, { "code": null, "e": 35099, "s": 35009, "text": "In this example, we will create a Savepoint named Half_Done using the following command." }, { "code": null, "e": 35121, "s": 35099, "text": "SAVEPOINT Half_Done; " }, { "code": null, "e": 35170, "s": 35121, "text": "The above command produces the following output." }, { "code": null, "e": 35189, "s": 35170, "text": "Savepoint created\n" }, { "code": null, "e": 35445, "s": 35189, "text": "ROLLBACK is a command from the SQL grammar used to roll back the transaction to a Savepoint or to the previous transaction. By using this command, we can either roll back to the specific Savepoint or we can roll back to the previous executed transaction." }, { "code": null, "e": 35500, "s": 35445, "text": "There are two different syntaxes for ROLLABCK command." }, { "code": null, "e": 35558, "s": 35500, "text": "Following is the generic syntax for the rollback command." }, { "code": null, "e": 35600, "s": 35558, "text": "ROLLBACK [ TO SAVEPOINT savepointName ] \n" }, { "code": null, "e": 35685, "s": 35600, "text": "Following is the generic syntax of the Rollback command to the specific transaction." }, { "code": null, "e": 35724, "s": 35685, "text": "ROLLBACK TRANSACTION transactionName \n" }, { "code": null, "e": 35842, "s": 35724, "text": "In this example, we will roll back the current transaction to a Savepoint named sp1_test using the following command." }, { "code": null, "e": 35863, "s": 35842, "text": "ROLLBACK sp1_test; \n" }, { "code": null, "e": 35912, "s": 35863, "text": "The above command produces the following output." }, { "code": null, "e": 35936, "s": 35912, "text": "Rollback successfully \n" }, { "code": null, "e": 36044, "s": 35936, "text": "In the following example, we will roll back the complete transaction named tx_test using the given command." }, { "code": null, "e": 36075, "s": 36044, "text": "ROLLBACK TRANSACTION tx_test;\n" }, { "code": null, "e": 36124, "s": 36075, "text": "The above command produces the following output." }, { "code": null, "e": 36148, "s": 36124, "text": "Rollback successfully \n" }, { "code": null, "e": 36345, "s": 36148, "text": "H2 is a JAVA database. We can interact with this database by using JDBC. In this chapter, we will see how to create a JDBC connection with H2 database and the CRUD operations with the H2 database." }, { "code": null, "e": 36406, "s": 36345, "text": "Generally, there are five steps to create a JDBC connection." }, { "code": null, "e": 36453, "s": 36406, "text": "Step 1 − Registering the JDBC database driver." }, { "code": null, "e": 36488, "s": 36453, "text": "Class.forName (\"org.h2.Driver\"); \n" }, { "code": null, "e": 36521, "s": 36488, "text": "Step 2 − Opening the connection." }, { "code": null, "e": 36598, "s": 36521, "text": "Connection conn = DriverManager.getConnection (\"jdbc:h2:~/test\", \"sa\",\"\"); \n" }, { "code": null, "e": 36629, "s": 36598, "text": "Step 3 − Creating a statement." }, { "code": null, "e": 36670, "s": 36629, "text": "Statement st = conn.createStatement(); \n" }, { "code": null, "e": 36726, "s": 36670, "text": "Step 4 − Executing a statement and receiving Resultset." }, { "code": null, "e": 36765, "s": 36726, "text": "Stmt.executeUpdate(\"sql statement\"); \n" }, { "code": null, "e": 36796, "s": 36765, "text": "Step 5 − Closing a connection." }, { "code": null, "e": 36812, "s": 36796, "text": "conn.close(); \n" }, { "code": null, "e": 36971, "s": 36812, "text": "Before moving on to create a full program, we need to add h2-1.4.192.jar file to CLASSPATH. We can get this jar from the folder C:\\Program Files (x86)\\H2\\bin." }, { "code": null, "e": 37095, "s": 36971, "text": "In this example, we will write a program for create table. Consider a table named Registration having the following fields." }, { "code": null, "e": 37151, "s": 37095, "text": "Following is an example program named H2jdbcCreateDemo." }, { "code": null, "e": 39171, "s": 37151, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcCreateDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n //STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n //STEP 3: Execute a query \n System.out.println(\"Creating table in given database...\"); \n stmt = conn.createStatement(); \n String sql = \"CREATE TABLE REGISTRATION \" + \n \"(id INTEGER not NULL, \" + \n \" first VARCHAR(255), \" + \n \" last VARCHAR(255), \" + \n \" age INTEGER, \" + \n \" PRIMARY KEY ( id ))\"; \n stmt.executeUpdate(sql);\n System.out.println(\"Created table in given database...\"); \n \n // STEP 4: Clean-up environment \n stmt.close(); \n conn.close(); \n } catch(SQLException se) { \n //Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n //Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n //finally block used to close resources \n try{ \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se){ \n se.printStackTrace(); \n } //end finally try \n } //end try \n System.out.println(\"Goodbye!\");\n } \n}" }, { "code": null, "e": 39319, "s": 39171, "text": "Save the above program into H2jdbcCreateDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 39376, "s": 39319, "text": "\\>javac H2jdbcCreateDemo.java \n\\>java H2jdbcCreateDemo \n" }, { "code": null, "e": 39425, "s": 39376, "text": "The above command produces the following output." }, { "code": null, "e": 39535, "s": 39425, "text": "Connecting to database... \nCreating table in given database... \nCreated table in given database... \nGoodbye!\n" }, { "code": null, "e": 39616, "s": 39535, "text": "After this execution, we can check the table created using the H2 SQL interface." }, { "code": null, "e": 39745, "s": 39616, "text": "In this example, we will write a program for inserting records. Let us insert the following records into the table Registration." }, { "code": null, "e": 39801, "s": 39745, "text": "Following is an example program named H2jdbcInsertDemo." }, { "code": null, "e": 42075, "s": 39801, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcInsertDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try{\n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to a selected database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n System.out.println(\"Connected database successfully...\"); \n \n // STEP 3: Execute a query \n stmt = conn.createStatement(); \n String sql = \"INSERT INTO Registration \" + \"VALUES (100, 'Zara', 'Ali', 18)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES (101, 'Mahnaz', 'Fatma', 25)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES (102, 'Zaid', 'Khan', 30)\"; \n \n stmt.executeUpdate(sql); \n sql = \"INSERT INTO Registration \" + \"VALUES(103, 'Sumit', 'Mittal', 28)\"; \n \n stmt.executeUpdate(sql); \n System.out.println(\"Inserted records into the table...\"); \n \n // STEP 4: Clean-up environment \n stmt.close(); \n conn.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try {\n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 42223, "s": 42075, "text": "Save the above program into H2jdbcInsertDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 42280, "s": 42223, "text": "\\>javac H2jdbcInsertDemo.java \n\\>java H2jdbcInsertDemo \n" }, { "code": null, "e": 42329, "s": 42280, "text": "The above command produces the following output." }, { "code": null, "e": 42450, "s": 42329, "text": "Connecting to a selected database... \nConnected database successfully... \nInserted records into the table... \nGoodbye! \n" }, { "code": null, "e": 42572, "s": 42450, "text": "In this example, we will write a program for reading records. Let us try to read all records from the table Registration." }, { "code": null, "e": 42628, "s": 42572, "text": "Following is an example program named H2jdbcRecordDemo." }, { "code": null, "e": 44980, "s": 42628, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcReadDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query \n System.out.println(\"Connected database successfully...\"); \n stmt = conn.createStatement(); \n String sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n // STEP 4: Extract data from result set \n while(rs.next()) { \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n // STEP 5: Clean-up environment \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 45126, "s": 44980, "text": "Save the above program into H2jdbcReadDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 45179, "s": 45126, "text": "\\>javac H2jdbcReadDemo.java \n\\>java H2jdbcReadDemo \n" }, { "code": null, "e": 45228, "s": 45179, "text": "The above command produces the following output." }, { "code": null, "e": 45489, "s": 45228, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 18, First: Zara, Last: Ali \nID: 101, Age: 25, First: Mahnaz, Last: Fatma \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye!\n" }, { "code": null, "e": 45609, "s": 45489, "text": "In this example, we will write a program to update records. Let us try to read all records from the table Registration." }, { "code": null, "e": 45665, "s": 45609, "text": "Following is an example program named H2jdbcUpdateDemo." }, { "code": null, "e": 48147, "s": 45665, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcUpdateDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to a database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query \n System.out.println(\"Connected database successfully...\"); \n stmt = conn.createStatement(); \n String sql = \"UPDATE Registration \" + \"SET age = 30 WHERE id in (100, 101)\"; \n stmt.executeUpdate(sql); \n \n // Now you can extract all the records \n // to see the updated records \n sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n while(rs.next()){ \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try \n } // end try \n System.out.println(\"Goodbye!\"); \n } \n} " }, { "code": null, "e": 48295, "s": 48147, "text": "Save the above program into H2jdbcUpdateDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 48352, "s": 48295, "text": "\\>javac H2jdbcUpdateDemo.java \n\\>java H2jdbcUpdateDemo \n" }, { "code": null, "e": 48401, "s": 48352, "text": "The above command produces the following output." }, { "code": null, "e": 48662, "s": 48401, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 30, First: Zara, Last: Ali \nID: 101, Age: 30, First: Mahnaz, Last: Fatma \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye!\n" }, { "code": null, "e": 48782, "s": 48662, "text": "In this example, we will write a program to delete records. Let us try to read all records from the table Registration." }, { "code": null, "e": 48838, "s": 48782, "text": "Following is an example program named H2jdbcDeleteDemo." }, { "code": null, "e": 51300, "s": 48838, "text": "import java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.ResultSet; \nimport java.sql.SQLException; \nimport java.sql.Statement; \n\npublic class H2jdbcDeleteDemo { \n // JDBC driver name and database URL \n static final String JDBC_DRIVER = \"org.h2.Driver\"; \n static final String DB_URL = \"jdbc:h2:~/test\"; \n \n // Database credentials \n static final String USER = \"sa\"; \n static final String PASS = \"\"; \n \n public static void main(String[] args) { \n Connection conn = null; \n Statement stmt = null; \n try { \n // STEP 1: Register JDBC driver \n Class.forName(JDBC_DRIVER); \n \n // STEP 2: Open a connection \n System.out.println(\"Connecting to database...\"); \n conn = DriverManager.getConnection(DB_URL,USER,PASS); \n \n // STEP 3: Execute a query\n System.out.println(\"Creating table in given database...\"); \n stmt = conn.createStatement(); \n String sql = \"DELETE FROM Registration \" + \"WHERE id = 101\"; \n stmt.executeUpdate(sql); \n \n // Now you can extract all the records \n // to see the remaining records \n sql = \"SELECT id, first, last, age FROM Registration\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n while(rs.next()){ \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n int age = rs.getInt(\"age\"); \n String first = rs.getString(\"first\"); \n String last = rs.getString(\"last\"); \n \n // Display values \n System.out.print(\"ID: \" + id); \n System.out.print(\", Age: \" + age); \n System.out.print(\", First: \" + first); \n System.out.println(\", Last: \" + last); \n } \n rs.close(); \n } catch(SQLException se) { \n // Handle errors for JDBC \n se.printStackTrace(); \n } catch(Exception e) { \n // Handle errors for Class.forName \n e.printStackTrace(); \n } finally { \n // finally block used to close resources \n try { \n if(stmt!=null) stmt.close(); \n } catch(SQLException se2) { \n } // nothing we can do \n try { \n if(conn!=null) conn.close(); \n } catch(SQLException se) { \n se.printStackTrace(); \n } // end finally try\n } // end try \n System.out.println(\"Goodbye!\"); \n } \n}" }, { "code": null, "e": 51448, "s": 51300, "text": "Save the above program into H2jdbcDeleteDemo.java. Compile and execute the above program by executing the following commands in the command prompt." }, { "code": null, "e": 51504, "s": 51448, "text": "\\>javac H2jdbcDeleteDemo.java \n\\>java H2jdbcDeleteDemo\n" }, { "code": null, "e": 51553, "s": 51504, "text": "The above command produces the following output." }, { "code": null, "e": 51769, "s": 51553, "text": "Connecting to a selected database... \nConnected database successfully... \nID: 100, Age: 30, First: Zara, Last: Ali \nID: 102, Age: 30, First: Zaid, Last: Khan \nID: 103, Age: 28, First: Sumit, Last: Mittal \nGoodbye! \n" }, { "code": null, "e": 51802, "s": 51769, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 51816, "s": 51802, "text": " Mahesh Kumar" }, { "code": null, "e": 51852, "s": 51816, "text": "\n 100 Lectures \n 9.5 hours \n" }, { "code": null, "e": 51867, "s": 51852, "text": " Hari Om Singh" }, { "code": null, "e": 51901, "s": 51867, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 51916, "s": 51901, "text": " Pavan Lalwani" }, { "code": null, "e": 51949, "s": 51916, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 51965, "s": 51949, "text": " Deepti Trivedi" }, { "code": null, "e": 51998, "s": 51965, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 52014, "s": 51998, "text": " Deepti Trivedi" }, { "code": null, "e": 52047, "s": 52014, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 52063, "s": 52047, "text": " Deepti Trivedi" }, { "code": null, "e": 52070, "s": 52063, "text": " Print" }, { "code": null, "e": 52081, "s": 52070, "text": " Add Notes" } ]
How to Solve Quadratic Equation using Python?
You can use the cmath module in order to solve Quadratic Equation using Python. This is because roots of quadratic equations might be complex in nature. If you have a quadratic equation of the form ax^2 + bx + c = 0, then, import cmath a = 12 b = 8 c = 1 # Discriminent d = (b**2) - (4*a*c) root1 = (-b - cmath.sqrt(d)) / (2 * a) root2 = (-b + cmath.sqrt(d)) / (2 * a) print(root1) print(root2) This will give the output (-0.5+0j) (-0.16666666666666666+0j)
[ { "code": null, "e": 1285, "s": 1062, "text": "You can use the cmath module in order to solve Quadratic Equation using Python. This is because roots of quadratic equations might be complex in nature. If you have a quadratic equation of the form ax^2 + bx + c = 0, then," }, { "code": null, "e": 1298, "s": 1285, "text": "import cmath" }, { "code": null, "e": 1457, "s": 1298, "text": "a = 12\nb = 8\nc = 1\n# Discriminent\nd = (b**2) - (4*a*c)\nroot1 = (-b - cmath.sqrt(d)) / (2 * a)\nroot2 = (-b + cmath.sqrt(d)) / (2 * a)\nprint(root1)\nprint(root2)" }, { "code": null, "e": 1483, "s": 1457, "text": "This will give the output" }, { "code": null, "e": 1519, "s": 1483, "text": "(-0.5+0j)\n(-0.16666666666666666+0j)" } ]
JqueryUI - Slider
A slider is used whenever a numeric value within a certain range is to be obtained. The advantage of a slider over text input is that it becomes impossible for the user to enter a bad value. Any value that they can pick with the slider is valid. jQueryUI provides us a slider control through slider widget. jQueryUI provides slider() method changes the appearance of HTML elements in the page, adding new CSS classes that give them the appropriate style. The slider () method can be used in two forms − $(selector, context).slider (options) Method $(selector, context).slider (options) Method $(selector, context).slider ("action", params) Method $(selector, context).slider ("action", params) Method The slider (options) method declares that an HTML element should be managed as a slider. The options parameter is an object that specifies the appearance and behavior of slider. $(selector, context).slider (options); You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows − $(selector, context).slider({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method − This option when set to true, creates an animated effect when users click directly on the axis. By default its value is false. Option - animate This option when set to true, creates an animated effect when users click directly on the axis. By default its value is false. This can be of type − Boolean − When set to true, the handle will animate with the default duration. Boolean − When set to true, the handle will animate with the default duration. String − The name of speed such as slow, normal, or fast String − Number − The duration of the animation, in milliseconds. Number − Syntax $( ".selector" ).slider( { animate: "fast" } ); This option when set to true, disables the slider. By default its value is false. Option - disabled This option when set to true, disables the slider. By default its value is false. Syntax $( ".selector" ).slider( { disabled: true } ); This option specifies the upper value of the range that the slider can attain—the value represented when the handle is moved to the far right (for horizontal sliders) or top (for vertical sliders). By default its value is 100. Option - max This option specifies the upper value of the range that the slider can attain—the value represented when the handle is moved to the far right (for horizontal sliders) or top (for vertical sliders). By default its value is 100. Syntax $( ".selector" ).slider( { max: 50 } ); This option specifies the lower value of the range that the slider can attain—the value represented when the handle is moved to the far left (for horizontal sliders) or bottom (for vertical sliders). By default its value is 0. Option - min This option specifies the lower value of the range that the slider can attain—the value represented when the handle is moved to the far left (for horizontal sliders) or bottom (for vertical sliders). By default its value is 0. Syntax $( ".selector" ).slider( { min: 10 } ); This option indicates the horizontal or vertical orientation of the slider. By default its value is horizontal. Option - orientation This option indicates the horizontal or vertical orientation of the slider. By default its value is horizontal. Syntax $( ".selector" ).slider( { "option", "orientation" } ); This option specifies whether the slider represents a range. By default its value is false. Option - range This option specifies whether the slider represents a range. By default its value is false. This can be of type − Boolean − If specified as true, and the slider has exactly two handles, an element that can be styled is created between the handles. Boolean − If specified as true, and the slider has exactly two handles, an element that can be styled is created between the handles. String − Can be min or max. If specified creates a range element from the handle to the beginning or end of the slider respectively. String − Syntax $( ".selector" ).slider( { range: true } ); This option specifies discrete intervals between the minimum and maximum values that the slider is allowed to represent. By default its value is 1. Option - step This option specifies discrete intervals between the minimum and maximum values that the slider is allowed to represent. By default its value is 1. Syntax $( ".selector" ).slider( { step: 5 } ); This option specifies the initial value of a single-handle slider. If there are multiple handles (see the values options), specifies the value for the first handle. By default its value is 1. Option - value >This option specifies the initial value of a single-handle slider. If there are multiple handles (see the values options), specifies the value for the first handle. By default its value is 1. Syntax $( ".selector" ).slider( { value: 10 } ); This option is of type Array and causes multiple handles to be created and specifies the initial values for those handles. This option should be an array of possible values, one for each handle. By default its value is null. Option - values This option is of type Array and causes multiple handles to be created and specifies the initial values for those handles. This option should be an array of possible values, one for each handle. By default its value is null. Syntax $( ".selector" ).slider( { values: [ 10, 25 ] } ); The following section will show you a few working examples of slider functionality. The following example demonstrates a simple example of slider functionality, passing no parameters to the slider() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Slider functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#slider-1" ).slider(); }); </script> </head> <body> <!-- HTML --> <div id = "slider-1"></div> </body> </html> Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − In the above example, it is a basic horizontal slider and has a single handle that can be moved with the mouse or by using the arrow keys. The following example demonstrates the usage of three options (a) value (b) animate and, (c) orientation in the slider function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Slider functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#slider-2" ).slider({ value: 60, animate:"slow", orientation: "horizontal" }); }); </script> </head> <body> <!-- HTML --> <div id = "slider-2"></div> </body> </html> Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − In the above example the value of slider i.e the initial value is set as 60, hence you see the handle at initial value of 60. Now just click directly on the axis and see the animation effect. The following example demonstrates the usage of three options (a) range, (b) min, (c) max, and (d) values in the slider function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Slider functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#slider-3" ).slider({ range:true, min: 0, max: 500, values: [ 35, 200 ], slide: function( event, ui ) { $( "#price" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#price" ).val( "$" + $( "#slider-3" ).slider( "values", 0 ) + " - $" + $( "#slider-3" ).slider( "values", 1 ) ); }); </script> </head> <body> <!-- HTML --> <p> <label for = "price">Price range:</label> <input type = "text" id = "price" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> <div id = "slider-3"></div> </body> </html> Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Price range: In the above example we have set the range option to true to capture a range of values with two drag handles. The space between the handles is filled with a different background color to indicate those values are selected. The slider ("action", params) method allows an action on the slider, such as moving the cursor to a new location. The action is specified as a string in the first argument (e.g., "value" to indicate a new value of the cursor). Check out the actions that can be passed, in the following table. $(selector, context).slider ("action", params);; The following table lists the different actions that can be used with this method − This action destroys the slider functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments. Action - destroy This action destroys the slider functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments. Syntax $( ".selector" ).slider("destroy"); This action disables the slider functionality. This method does not accept any arguments. Action - disable This action disables the slider functionality. This method does not accept any arguments. Syntax $( ".selector" ).slider("disable"); This action enables the slider functionality. This method does not accept any arguments. Action - enable This action enables the slider functionality. This method does not accept any arguments. Syntax $( ".selector" ).slider("enable"); This action retrieves the value of the specified param option. This option corresponds to one of those used with slider (options). Where optionName is the name of the option to get. Action - option( optionName ) This action retrieves the value of the specified param option. This option corresponds to one of those used with slider (options). Where optionName is the name of the option to get. Syntax var isDisabled = $( ".selector" ).slider( "option", "disabled" ); This action gets an object containing key/value pairs representing the current slider options hash. Action - option() This action gets an object containing key/value pairs representing the current slider options hash. Syntax var options = $( ".selector" ).slider( "option" ); This action sets the value of the slider option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Action - option( optionName, value ) This action sets the value of the slider option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Syntax $( ".selector" ).slider( "option", "disabled", true ); This action sets one or more options for the slider. The argument options is a map of option-value pairs to be set. Action - option( options ) This action sets one or more options for the slider. The argument options is a map of option-value pairs to be set. Syntax $( ".selector" ).slider( "option", { disabled: true } ); This action retrieves the current value of options.value (the slider). Use only if the slider is unique (if not, use slider ("values")). This signature does not accept any arguments. Action - value This action retrieves the current value of options.value (the indicator). Use only if the indicator is unique (if not, use slider ("values")). This signature does not accept any arguments. Syntax $( ".selector" ).slider("value"); This action sets the value of the slider. Action - value( value ) This action sets the value of the slider. Syntax $( ".selector" ).slider( "value", 55 ); This action retrieves the current value of options.values (the value of the sliders in an array). This signature does not accept any arguments. Action - values This action retrieves the current value of options.values (the value of the sliders in an array). This signature does not accept any arguments. Syntax var values = $( ".selector" ).slider( "values" ); This action gets the value for the specified handle. Where index is of type Integer and is a zero-based index of the handle. Action - values( index ) This action gets the value for the specified handle. Where index is of type Integer and is a zero-based index of the handle. Syntax var value = $( ".selector" ).slider( "values", 0 ); This action sets the value for the specified handle. Where index is the zero-based index of the handle and value is the value to set. Action - values( index, value ) This action sets the value for the specified handle. Where index is the zero-based index of the handle and value is the value to set. Syntax $( ".selector" ).slider( "values", 0, 55 ); This action sets the value for all the handles. Action - values( values ) This action sets the value for all the handles. Syntax $( ".selector" ).slider( "values", [ 55, 105 ] ); This action returns a jQuery object containing the slider. This method does not accept any arguments. Action - widget This action returns a jQuery object containing the slider. This method does not accept any arguments. Syntax var widget = $( ".selector" ).slider( "widget" ); Now let us see an example using the actions from the above table. The following example demonstrates the use of disable() and value() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Slider functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#slider-4" ).slider({ orientation:"vertical" }); $( "#slider-4" ).slider('disable'); $( "#slider-5" ).slider({ orientation:"vertical", value:50, slide: function( event, ui ) { $( "#minval" ).val( ui.value ); } }); $( "#minval" ).val( $( "#slider-5" ).slider( "value" ) ); }); </script> </head> <body> <!-- HTML --> <div id = "slider-4"></div> <p> <label for = "minval">Minumum value:</label> <input type = "text" id = "minval" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> <div id = "slider-5"></div> </body> </html> Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Minumum value: In the above example, the first slider is disabled and the second slider the value is set to 50. In addition to the slider (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below − This event is triggered handle’s value changes, either through user action or programmatically. Event - change(event, ui) This event is triggered handle’s value changes, either through user action or programmatically. Where event is of type Event, and ui is of type Object. Possible values of ui are − handle − A jQuery object representing the handle that was changed. handle − A jQuery object representing the handle that was changed. value − The current value of the slider. value − The current value of the slider. Syntax $( ".selector" ).slider({ change: function( event, ui ) {} }); This event is triggered when the slider is created. Event - create(event, ui) This event is triggered when the slider is created. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).slider({ create: function( event, ui ) {} }); This event is triggered for mouse move events whenever the handle is being dragged through the slider. Returning false cancels the slide. Event - slide(event, ui) This event is triggered for mouse move events whenever the handle is being dragged through the slider. Returning false cancels the slide. Where event is of type Event, and ui is of type Object. Possible values of ui are − handle − A jQuery object representing the handle being moved. handle − A jQuery object representing the handle being moved. value − The value that the handle will move to if the event is not canceled. value − The value that the handle will move to if the event is not canceled. values − An array of the current values of a multi-handled slider. values − An array of the current values of a multi-handled slider. Syntax $( ".selector" ).slider({ slide: function( event, ui ) {} }); This event is triggered when the user starts sliding. Event - start(event, ui) This event is triggered when the user starts sliding. Where event is of type Event, and ui is of type Object. Possible values of ui are − handle − A jQuery object representing the handle being moved. handle − A jQuery object representing the handle being moved. value − The current value of the slider. value − The current value of the slider. Syntax $( ".selector" ).slider({ start: function( event, ui ) {} }); This event is triggered when a slide stops. Event - stop(event, ui) This event is triggered when a slide stops. Where event is of type Event, and ui is of type Object. Possible values of ui are − handle − A jQuery object representing the handle that was moved. handle − A jQuery object representing the handle that was moved. value − The current value of the slider. value − The current value of the slider. Syntax $( ".selector" ).slider({ stop: function( event, ui ) {} }); The following example demonstrates the event method usage during slider functionality. This example demonstrates the use of events start, stop, change and slide. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Slider functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#slider-6" ).slider({ range:true, min: 0, max: 500, values: [ 35, 200 ], start: function( event, ui ) { $( "#startvalue" ) .val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); }, stop: function( event, ui ) { $( "#stopvalue" ) .val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); }, change: function( event, ui ) { $( "#changevalue" ) .val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); }, slide: function( event, ui ) { $( "#slidevalue" ) .val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); }); </script> </head> <body> <!-- HTML --> <div id = "slider-6"></div> <p> <label for = "startvalue">Start:</label> <input type = "text" id = "startvalue" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> <p> <label for = "stopvalue">Stop:</label> <input type = "text" id = "stopvalue" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> <p> <label for = "changevalue">Change:</label> <input type = "text" id = "changevalue" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> <p> <label for = "slidevalue">Slide:</label> <input type = "text" id = "slidevalue" style = "border:0; color:#b9cd6d; font-weight:bold;"> </p> </body> </html> Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Start: Stop: Change: Slide: Print Add Notes Bookmark this page
[ { "code": null, "e": 2510, "s": 2264, "text": "A slider is used whenever a numeric value within a certain range is to be obtained. The advantage of a slider over text input is that it becomes impossible for the user to enter a bad value. Any value that they can pick with the slider is valid." }, { "code": null, "e": 2719, "s": 2510, "text": "jQueryUI provides us a slider control through slider widget. jQueryUI provides slider() method changes the appearance of HTML elements in the page, adding new CSS classes that give them the appropriate style." }, { "code": null, "e": 2767, "s": 2719, "text": "The slider () method can be used in two forms −" }, { "code": null, "e": 2812, "s": 2767, "text": "$(selector, context).slider (options) Method" }, { "code": null, "e": 2857, "s": 2812, "text": "$(selector, context).slider (options) Method" }, { "code": null, "e": 2911, "s": 2857, "text": "$(selector, context).slider (\"action\", params) Method" }, { "code": null, "e": 2965, "s": 2911, "text": "$(selector, context).slider (\"action\", params) Method" }, { "code": null, "e": 3143, "s": 2965, "text": "The slider (options) method declares that an HTML element should be managed as a slider. The options parameter is an object that specifies the appearance and behavior of slider." }, { "code": null, "e": 3183, "s": 3143, "text": "$(selector, context).slider (options);\n" }, { "code": null, "e": 3359, "s": 3183, "text": "You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −" }, { "code": null, "e": 3430, "s": 3359, "text": "$(selector, context).slider({option1: value1, option2: value2..... });" }, { "code": null, "e": 3514, "s": 3430, "text": "The following table lists the different options that can be used with this method −" }, { "code": null, "e": 3641, "s": 3514, "text": "This option when set to true, creates an animated effect when users click directly on the axis. By default its value is false." }, { "code": null, "e": 3658, "s": 3641, "text": "Option - animate" }, { "code": null, "e": 3785, "s": 3658, "text": "This option when set to true, creates an animated effect when users click directly on the axis. By default its value is false." }, { "code": null, "e": 3807, "s": 3785, "text": "This can be of type −" }, { "code": null, "e": 3886, "s": 3807, "text": "Boolean − When set to true, the handle will animate with the default duration." }, { "code": null, "e": 3965, "s": 3886, "text": "Boolean − When set to true, the handle will animate with the default duration." }, { "code": null, "e": 4022, "s": 3965, "text": "String − The name of speed such as slow, normal, or fast" }, { "code": null, "e": 4031, "s": 4022, "text": "String −" }, { "code": null, "e": 4088, "s": 4031, "text": "Number − The duration of the animation, in milliseconds." }, { "code": null, "e": 4097, "s": 4088, "text": "Number −" }, { "code": null, "e": 4104, "s": 4097, "text": "Syntax" }, { "code": null, "e": 4156, "s": 4104, "text": "$( \".selector\" ).slider(\n { animate: \"fast\" }\n);\n" }, { "code": null, "e": 4238, "s": 4156, "text": "This option when set to true, disables the slider. By default its value is false." }, { "code": null, "e": 4256, "s": 4238, "text": "Option - disabled" }, { "code": null, "e": 4338, "s": 4256, "text": "This option when set to true, disables the slider. By default its value is false." }, { "code": null, "e": 4345, "s": 4338, "text": "Syntax" }, { "code": null, "e": 4396, "s": 4345, "text": "$( \".selector\" ).slider(\n { disabled: true }\n);\n" }, { "code": null, "e": 4623, "s": 4396, "text": "This option specifies the upper value of the range that the slider can attain—the value represented when the handle is moved to the far right (for horizontal sliders) or top (for vertical sliders). By default its value is 100." }, { "code": null, "e": 4636, "s": 4623, "text": "Option - max" }, { "code": null, "e": 4863, "s": 4636, "text": "This option specifies the upper value of the range that the slider can attain—the value represented when the handle is moved to the far right (for horizontal sliders) or top (for vertical sliders). By default its value is 100." }, { "code": null, "e": 4870, "s": 4863, "text": "Syntax" }, { "code": null, "e": 4914, "s": 4870, "text": "$( \".selector\" ).slider(\n { max: 50 }\n);\n" }, { "code": null, "e": 5141, "s": 4914, "text": "This option specifies the lower value of the range that the slider can attain—the value represented when the handle is moved to the far left (for horizontal sliders) or bottom (for vertical sliders). By default its value is 0." }, { "code": null, "e": 5154, "s": 5141, "text": "Option - min" }, { "code": null, "e": 5381, "s": 5154, "text": "This option specifies the lower value of the range that the slider can attain—the value represented when the handle is moved to the far left (for horizontal sliders) or bottom (for vertical sliders). By default its value is 0." }, { "code": null, "e": 5388, "s": 5381, "text": "Syntax" }, { "code": null, "e": 5432, "s": 5388, "text": "$( \".selector\" ).slider(\n { min: 10 }\n);\n" }, { "code": null, "e": 5544, "s": 5432, "text": "This option indicates the horizontal or vertical orientation of the slider. By default its value is horizontal." }, { "code": null, "e": 5565, "s": 5544, "text": "Option - orientation" }, { "code": null, "e": 5677, "s": 5565, "text": "This option indicates the horizontal or vertical orientation of the slider. By default its value is horizontal." }, { "code": null, "e": 5684, "s": 5677, "text": "Syntax" }, { "code": null, "e": 5744, "s": 5684, "text": "$( \".selector\" ).slider(\n { \"option\", \"orientation\" }\n);\n" }, { "code": null, "e": 5836, "s": 5744, "text": "This option specifies whether the slider represents a range. By default its value is false." }, { "code": null, "e": 5851, "s": 5836, "text": "Option - range" }, { "code": null, "e": 5943, "s": 5851, "text": "This option specifies whether the slider represents a range. By default its value is false." }, { "code": null, "e": 5965, "s": 5943, "text": "This can be of type −" }, { "code": null, "e": 6101, "s": 5965, "text": "Boolean − If specified as true, and the slider has exactly two handles, an element that can be styled is created between the handles. \n" }, { "code": null, "e": 6237, "s": 6101, "text": "Boolean − If specified as true, and the slider has exactly two handles, an element that can be styled is created between the handles. \n" }, { "code": null, "e": 6371, "s": 6237, "text": "String − Can be min or max. If specified creates a range element from the handle to the beginning or end of the slider respectively. " }, { "code": null, "e": 6380, "s": 6371, "text": "String −" }, { "code": null, "e": 6387, "s": 6380, "text": "Syntax" }, { "code": null, "e": 6435, "s": 6387, "text": "$( \".selector\" ).slider(\n { range: true }\n);\n" }, { "code": null, "e": 6583, "s": 6435, "text": "This option specifies discrete intervals between the minimum and maximum values that the slider is allowed to represent. By default its value is 1." }, { "code": null, "e": 6597, "s": 6583, "text": "Option - step" }, { "code": null, "e": 6745, "s": 6597, "text": "This option specifies discrete intervals between the minimum and maximum values that the slider is allowed to represent. By default its value is 1." }, { "code": null, "e": 6752, "s": 6745, "text": "Syntax" }, { "code": null, "e": 6796, "s": 6752, "text": "$( \".selector\" ).slider(\n { step: 5 }\n);\n" }, { "code": null, "e": 6988, "s": 6796, "text": "This option specifies the initial value of a single-handle slider. If there are multiple handles (see the values options), specifies the value for the first handle. By default its value is 1." }, { "code": null, "e": 7003, "s": 6988, "text": "Option - value" }, { "code": null, "e": 7196, "s": 7003, "text": ">This option specifies the initial value of a single-handle slider. If there are multiple handles (see the values options), specifies the value for the first handle. By default its value is 1." }, { "code": null, "e": 7203, "s": 7196, "text": "Syntax" }, { "code": null, "e": 7249, "s": 7203, "text": "$( \".selector\" ).slider(\n { value: 10 }\n);\n" }, { "code": null, "e": 7474, "s": 7249, "text": "This option is of type Array and causes multiple handles to be created and specifies the initial values for those handles. This option should be an array of possible values, one for each handle. By default its value is null." }, { "code": null, "e": 7490, "s": 7474, "text": "Option - values" }, { "code": null, "e": 7715, "s": 7490, "text": "This option is of type Array and causes multiple handles to be created and specifies the initial values for those handles. This option should be an array of possible values, one for each handle. By default its value is null." }, { "code": null, "e": 7722, "s": 7715, "text": "Syntax" }, { "code": null, "e": 7777, "s": 7722, "text": "$( \".selector\" ).slider(\n { values: [ 10, 25 ] }\n);\n" }, { "code": null, "e": 7861, "s": 7777, "text": "The following section will show you a few working examples of slider functionality." }, { "code": null, "e": 7984, "s": 7861, "text": "The following example demonstrates a simple example of slider functionality, passing no parameters to the slider() method." }, { "code": null, "e": 8615, "s": 7984, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Slider functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n\n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#slider-1\" ).slider();\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"slider-1\"></div>\n </body>\n</html>" }, { "code": null, "e": 8813, "s": 8615, "text": "Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 8952, "s": 8813, "text": "In the above example, it is a basic horizontal slider and has a single handle that can be moved with the mouse or by using the arrow keys." }, { "code": null, "e": 9093, "s": 8952, "text": "The following example demonstrates the usage of three options (a) value (b) animate and, (c) orientation in the slider function of JqueryUI." }, { "code": null, "e": 9843, "s": 9093, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Slider functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#slider-2\" ).slider({\n value: 60,\n animate:\"slow\",\n orientation: \"horizontal\"\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"slider-2\"></div>\n </body>\n</html>" }, { "code": null, "e": 10041, "s": 9843, "text": "Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 10233, "s": 10041, "text": "In the above example the value of slider i.e the initial value is set as 60, hence you see the handle at initial value of 60. Now just click directly on the axis and see the animation effect." }, { "code": null, "e": 10375, "s": 10233, "text": "The following example demonstrates the usage of three options (a) range, (b) min, (c) max, and (d) values in the slider function of JqueryUI." }, { "code": null, "e": 11614, "s": 10375, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Slider functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#slider-3\" ).slider({\n range:true,\n min: 0,\n max: 500,\n values: [ 35, 200 ],\n slide: function( event, ui ) {\n $( \"#price\" ).val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n }\n });\n $( \"#price\" ).val( \"$\" + $( \"#slider-3\" ).slider( \"values\", 0 ) +\n \" - $\" + $( \"#slider-3\" ).slider( \"values\", 1 ) );\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <p>\n <label for = \"price\">Price range:</label>\n <input type = \"text\" id = \"price\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n <div id = \"slider-3\"></div>\n </body>\n</html>" }, { "code": null, "e": 11812, "s": 11614, "text": "Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 11828, "s": 11812, "text": "\nPrice range:\n\n" }, { "code": null, "e": 12051, "s": 11828, "text": "In the above example we have set the range option to true to capture a range of values with two drag handles. The space between the handles is filled with a different background color to indicate those values are selected." }, { "code": null, "e": 12344, "s": 12051, "text": "The slider (\"action\", params) method allows an action on the slider, such as moving the cursor to a new location. The action is specified as a string in the first argument (e.g., \"value\" to indicate a new value of the cursor). Check out the actions that can be passed, in the following table." }, { "code": null, "e": 12394, "s": 12344, "text": "$(selector, context).slider (\"action\", params);;\n" }, { "code": null, "e": 12478, "s": 12394, "text": "The following table lists the different actions that can be used with this method −" }, { "code": null, "e": 12638, "s": 12478, "text": "This action destroys the slider functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments." }, { "code": null, "e": 12655, "s": 12638, "text": "Action - destroy" }, { "code": null, "e": 12815, "s": 12655, "text": "This action destroys the slider functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments." }, { "code": null, "e": 12822, "s": 12815, "text": "Syntax" }, { "code": null, "e": 12859, "s": 12822, "text": "$( \".selector\" ).slider(\"destroy\");\n" }, { "code": null, "e": 12949, "s": 12859, "text": "This action disables the slider functionality. This method does not accept any arguments." }, { "code": null, "e": 12966, "s": 12949, "text": "Action - disable" }, { "code": null, "e": 13056, "s": 12966, "text": "This action disables the slider functionality. This method does not accept any arguments." }, { "code": null, "e": 13063, "s": 13056, "text": "Syntax" }, { "code": null, "e": 13100, "s": 13063, "text": "$( \".selector\" ).slider(\"disable\");\n" }, { "code": null, "e": 13189, "s": 13100, "text": "This action enables the slider functionality. This method does not accept any arguments." }, { "code": null, "e": 13205, "s": 13189, "text": "Action - enable" }, { "code": null, "e": 13294, "s": 13205, "text": "This action enables the slider functionality. This method does not accept any arguments." }, { "code": null, "e": 13301, "s": 13294, "text": "Syntax" }, { "code": null, "e": 13337, "s": 13301, "text": "$( \".selector\" ).slider(\"enable\");\n" }, { "code": null, "e": 13519, "s": 13337, "text": "This action retrieves the value of the specified param option. This option corresponds to one of those used with slider (options). Where optionName is the name of the option to get." }, { "code": null, "e": 13549, "s": 13519, "text": "Action - option( optionName )" }, { "code": null, "e": 13731, "s": 13549, "text": "This action retrieves the value of the specified param option. This option corresponds to one of those used with slider (options). Where optionName is the name of the option to get." }, { "code": null, "e": 13738, "s": 13731, "text": "Syntax" }, { "code": null, "e": 13805, "s": 13738, "text": "var isDisabled = $( \".selector\" ).slider( \"option\", \"disabled\" );\n" }, { "code": null, "e": 13905, "s": 13805, "text": "This action gets an object containing key/value pairs representing the current slider options hash." }, { "code": null, "e": 13923, "s": 13905, "text": "Action - option()" }, { "code": null, "e": 14023, "s": 13923, "text": "This action gets an object containing key/value pairs representing the current slider options hash." }, { "code": null, "e": 14030, "s": 14023, "text": "Syntax" }, { "code": null, "e": 14082, "s": 14030, "text": "var options = $( \".selector\" ).slider( \"option\" );\n" }, { "code": null, "e": 14277, "s": 14082, "text": "This action sets the value of the slider option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 14314, "s": 14277, "text": "Action - option( optionName, value )" }, { "code": null, "e": 14509, "s": 14314, "text": "This action sets the value of the slider option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 14516, "s": 14509, "text": "Syntax" }, { "code": null, "e": 14572, "s": 14516, "text": "$( \".selector\" ).slider( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 14688, "s": 14572, "text": "This action sets one or more options for the slider. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 14715, "s": 14688, "text": "Action - option( options )" }, { "code": null, "e": 14831, "s": 14715, "text": "This action sets one or more options for the slider. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 14838, "s": 14831, "text": "Syntax" }, { "code": null, "e": 14896, "s": 14838, "text": "$( \".selector\" ).slider( \"option\", { disabled: true } );\n" }, { "code": null, "e": 15079, "s": 14896, "text": "This action retrieves the current value of options.value (the slider). Use only if the slider is unique (if not, use slider (\"values\")). This signature does not accept any arguments." }, { "code": null, "e": 15094, "s": 15079, "text": "Action - value" }, { "code": null, "e": 15283, "s": 15094, "text": "This action retrieves the current value of options.value (the indicator). Use only if the indicator is unique (if not, use slider (\"values\")). This signature does not accept any arguments." }, { "code": null, "e": 15290, "s": 15283, "text": "Syntax" }, { "code": null, "e": 15325, "s": 15290, "text": "$( \".selector\" ).slider(\"value\");\n" }, { "code": null, "e": 15367, "s": 15325, "text": "This action sets the value of the slider." }, { "code": null, "e": 15391, "s": 15367, "text": "Action - value( value )" }, { "code": null, "e": 15433, "s": 15391, "text": "This action sets the value of the slider." }, { "code": null, "e": 15440, "s": 15433, "text": "Syntax" }, { "code": null, "e": 15481, "s": 15440, "text": "$( \".selector\" ).slider( \"value\", 55 );\n" }, { "code": null, "e": 15625, "s": 15481, "text": "This action retrieves the current value of options.values (the value of the sliders in an array). This signature does not accept any arguments." }, { "code": null, "e": 15641, "s": 15625, "text": "Action - values" }, { "code": null, "e": 15785, "s": 15641, "text": "This action retrieves the current value of options.values (the value of the sliders in an array). This signature does not accept any arguments." }, { "code": null, "e": 15792, "s": 15785, "text": "Syntax" }, { "code": null, "e": 15843, "s": 15792, "text": "var values = $( \".selector\" ).slider( \"values\" );\n" }, { "code": null, "e": 15968, "s": 15843, "text": "This action gets the value for the specified handle. Where index is of type Integer and is a zero-based index of the handle." }, { "code": null, "e": 15993, "s": 15968, "text": "Action - values( index )" }, { "code": null, "e": 16118, "s": 15993, "text": "This action gets the value for the specified handle. Where index is of type Integer and is a zero-based index of the handle." }, { "code": null, "e": 16125, "s": 16118, "text": "Syntax" }, { "code": null, "e": 16178, "s": 16125, "text": "var value = $( \".selector\" ).slider( \"values\", 0 );\n" }, { "code": null, "e": 16312, "s": 16178, "text": "This action sets the value for the specified handle. Where index is the zero-based index of the handle and value is the value to set." }, { "code": null, "e": 16344, "s": 16312, "text": "Action - values( index, value )" }, { "code": null, "e": 16478, "s": 16344, "text": "This action sets the value for the specified handle. Where index is the zero-based index of the handle and value is the value to set." }, { "code": null, "e": 16485, "s": 16478, "text": "Syntax" }, { "code": null, "e": 16530, "s": 16485, "text": "$( \".selector\" ).slider( \"values\", 0, 55 );\n" }, { "code": null, "e": 16578, "s": 16530, "text": "This action sets the value for all the handles." }, { "code": null, "e": 16604, "s": 16578, "text": "Action - values( values )" }, { "code": null, "e": 16652, "s": 16604, "text": "This action sets the value for all the handles." }, { "code": null, "e": 16659, "s": 16652, "text": "Syntax" }, { "code": null, "e": 16710, "s": 16659, "text": "$( \".selector\" ).slider( \"values\", [ 55, 105 ] );\n" }, { "code": null, "e": 16812, "s": 16710, "text": "This action returns a jQuery object containing the slider. This method does not accept any arguments." }, { "code": null, "e": 16828, "s": 16812, "text": "Action - widget" }, { "code": null, "e": 16930, "s": 16828, "text": "This action returns a jQuery object containing the slider. This method does not accept any arguments." }, { "code": null, "e": 16937, "s": 16930, "text": "Syntax" }, { "code": null, "e": 16988, "s": 16937, "text": "var widget = $( \".selector\" ).slider( \"widget\" );\n" }, { "code": null, "e": 17130, "s": 16988, "text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of disable() and value() method." }, { "code": null, "e": 18391, "s": 17130, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Slider functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#slider-4\" ).slider({\n orientation:\"vertical\"\t\n });\n $( \"#slider-4\" ).slider('disable');\n $( \"#slider-5\" ).slider({\n orientation:\"vertical\",\n value:50,\n slide: function( event, ui ) {\n $( \"#minval\" ).val( ui.value );\n }\t\n });\n $( \"#minval\" ).val( $( \"#slider-5\" ).slider( \"value\" ) );\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"slider-4\"></div>\n <p>\n <label for = \"minval\">Minumum value:</label>\n <input type = \"text\" id = \"minval\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n <div id = \"slider-5\"></div>\n </body>\n</html>" }, { "code": null, "e": 18554, "s": 18391, "text": "Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 18572, "s": 18554, "text": "\nMinumum value:\n\n" }, { "code": null, "e": 18669, "s": 18572, "text": "In the above example, the first slider is disabled and the second slider the value is set to 50." }, { "code": null, "e": 18867, "s": 18669, "text": "In addition to the slider (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −" }, { "code": null, "e": 18963, "s": 18867, "text": "This event is triggered handle’s value changes, either through user action or programmatically." }, { "code": null, "e": 18989, "s": 18963, "text": "Event - change(event, ui)" }, { "code": null, "e": 19169, "s": 18989, "text": "This event is triggered handle’s value changes, either through user action or programmatically. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 19236, "s": 19169, "text": "handle − A jQuery object representing the handle that was changed." }, { "code": null, "e": 19303, "s": 19236, "text": "handle − A jQuery object representing the handle that was changed." }, { "code": null, "e": 19344, "s": 19303, "text": "value − The current value of the slider." }, { "code": null, "e": 19385, "s": 19344, "text": "value − The current value of the slider." }, { "code": null, "e": 19392, "s": 19385, "text": "Syntax" }, { "code": null, "e": 19459, "s": 19392, "text": "$( \".selector\" ).slider({\n change: function( event, ui ) {}\n});\n" }, { "code": null, "e": 19511, "s": 19459, "text": "This event is triggered when the slider is created." }, { "code": null, "e": 19537, "s": 19511, "text": "Event - create(event, ui)" }, { "code": null, "e": 19645, "s": 19537, "text": "This event is triggered when the slider is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 19652, "s": 19645, "text": "Syntax" }, { "code": null, "e": 19719, "s": 19652, "text": "$( \".selector\" ).slider({\n create: function( event, ui ) {}\n});\n" }, { "code": null, "e": 19857, "s": 19719, "text": "This event is triggered for mouse move events whenever the handle is being dragged through the slider. Returning false cancels the slide." }, { "code": null, "e": 19882, "s": 19857, "text": "Event - slide(event, ui)" }, { "code": null, "e": 20104, "s": 19882, "text": "This event is triggered for mouse move events whenever the handle is being dragged through the slider. Returning false cancels the slide. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 20166, "s": 20104, "text": "handle − A jQuery object representing the handle being moved." }, { "code": null, "e": 20228, "s": 20166, "text": "handle − A jQuery object representing the handle being moved." }, { "code": null, "e": 20305, "s": 20228, "text": "value − The value that the handle will move to if the event is not canceled." }, { "code": null, "e": 20382, "s": 20305, "text": "value − The value that the handle will move to if the event is not canceled." }, { "code": null, "e": 20449, "s": 20382, "text": "values − An array of the current values of a multi-handled slider." }, { "code": null, "e": 20516, "s": 20449, "text": "values − An array of the current values of a multi-handled slider." }, { "code": null, "e": 20523, "s": 20516, "text": "Syntax" }, { "code": null, "e": 20589, "s": 20523, "text": "$( \".selector\" ).slider({\n slide: function( event, ui ) {}\n});\n" }, { "code": null, "e": 20643, "s": 20589, "text": "This event is triggered when the user starts sliding." }, { "code": null, "e": 20668, "s": 20643, "text": "Event - start(event, ui)" }, { "code": null, "e": 20806, "s": 20668, "text": "This event is triggered when the user starts sliding. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 20868, "s": 20806, "text": "handle − A jQuery object representing the handle being moved." }, { "code": null, "e": 20930, "s": 20868, "text": "handle − A jQuery object representing the handle being moved." }, { "code": null, "e": 20971, "s": 20930, "text": "value − The current value of the slider." }, { "code": null, "e": 21012, "s": 20971, "text": "value − The current value of the slider." }, { "code": null, "e": 21019, "s": 21012, "text": "Syntax" }, { "code": null, "e": 21085, "s": 21019, "text": "$( \".selector\" ).slider({\n start: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21129, "s": 21085, "text": "This event is triggered when a slide stops." }, { "code": null, "e": 21153, "s": 21129, "text": "Event - stop(event, ui)" }, { "code": null, "e": 21281, "s": 21153, "text": "This event is triggered when a slide stops. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 21346, "s": 21281, "text": "handle − A jQuery object representing the handle that was moved." }, { "code": null, "e": 21411, "s": 21346, "text": "handle − A jQuery object representing the handle that was moved." }, { "code": null, "e": 21452, "s": 21411, "text": "value − The current value of the slider." }, { "code": null, "e": 21493, "s": 21452, "text": "value − The current value of the slider." }, { "code": null, "e": 21500, "s": 21493, "text": "Syntax" }, { "code": null, "e": 21565, "s": 21500, "text": "$( \".selector\" ).slider({\n stop: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21727, "s": 21565, "text": "The following example demonstrates the event method usage during slider functionality. This example demonstrates the use of events start, stop, change and slide." }, { "code": null, "e": 23944, "s": 21727, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Slider functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#slider-6\" ).slider({\n range:true,\n min: 0,\n max: 500,\n values: [ 35, 200 ],\n start: function( event, ui ) {\n $( \"#startvalue\" )\n .val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n },\n stop: function( event, ui ) {\n $( \"#stopvalue\" )\n .val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n },\n change: function( event, ui ) {\n $( \"#changevalue\" )\n .val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n },\n slide: function( event, ui ) {\n $( \"#slidevalue\" )\n .val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n }\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div id = \"slider-6\"></div>\n <p>\n <label for = \"startvalue\">Start:</label>\n <input type = \"text\" id = \"startvalue\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n <p>\n <label for = \"stopvalue\">Stop:</label>\n <input type = \"text\" id = \"stopvalue\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n <p>\n <label for = \"changevalue\">Change:</label>\n <input type = \"text\" id = \"changevalue\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n <p>\n <label for = \"slidevalue\">Slide:</label>\n <input type = \"text\" id = \"slidevalue\" \n style = \"border:0; color:#b9cd6d; font-weight:bold;\">\n </p>\n </body>\n</html>" }, { "code": null, "e": 24107, "s": 23944, "text": "Let us save the above code in an HTML file sliderexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 24117, "s": 24107, "text": "\nStart:\n\n" }, { "code": null, "e": 24126, "s": 24117, "text": "\nStop:\n\n" }, { "code": null, "e": 24137, "s": 24126, "text": "\nChange:\n\n" }, { "code": null, "e": 24147, "s": 24137, "text": "\nSlide:\n\n" }, { "code": null, "e": 24154, "s": 24147, "text": " Print" }, { "code": null, "e": 24165, "s": 24154, "text": " Add Notes" } ]
Beautiful Soup - Trouble Shooting
There are two main kinds of errors that need to be handled in BeautifulSoup. These two errors are not from your script but from the structure of the snippet because the BeautifulSoup API throws an error. The two main errors are as follows − It is caused when the dot notation doesn’t find a sibling tag to the current HTML tag. For example, you may have encountered this error, because of missing “anchor tag”, cost-key will throw an error as it traverses and requires an anchor tag. This error occurs if the required HTML tag attribute is missing. For example, if we don’t have data-pid attribute in a snippet, the pid key will throw key-error. To avoid the above two listed errors when parsing a result, that result will be bypassed to make sure that a malformed snippet isn’t inserted into the databases − except(AttributeError, KeyError) as er: pass Whenever we find any difficulty in understanding what BeautifulSoup does to our document or HTML, simply pass it to the diagnose() function. On passing document file to the diagnose() function, we can show how list of different parser handles the document. Below is one example to demonstrate the use of diagnose() function − from bs4.diagnose import diagnose with open("20 Books.html",encoding="utf8") as fp: data = fp.read() diagnose(data) There are two main types of parsing errors. You might get an exception like HTMLParseError, when you feed your document to BeautifulSoup. You may also get an unexpected result, where the BeautifulSoup parse tree looks a lot different from the expected result from the parse document. None of the parsing error is caused due to BeautifulSoup. It is because of external parser we use (html5lib, lxml) since BeautifulSoup doesn’t contain any parser code. One way to resolve above parsing error is to use another parser. from HTMLParser import HTMLParser try: from HTMLParser import HTMLParseError except ImportError, e: # From python 3.5, HTMLParseError is removed. Since it can never be # thrown in 3.5, we can just define our own class as a placeholder. class HTMLParseError(Exception): pass Python built-in HTML parser causes two most common parse errors, HTMLParser.HTMLParserError: malformed start tag and HTMLParser.HTMLParserError: bad end tag and to resolve this, is to use another parser mainly: lxml or html5lib. Another common type of unexpected behavior is that you can’t find a tag that you know is in the document. However, when you run the find_all() returns [] or find() returns None. This may be due to python built-in HTML parser sometimes skips tags it doesn’t understand. By default, BeautifulSoup package parses the documents as HTML, however, it is very easy-to-use and handle ill-formed XML in a very elegant manner using beautifulsoup4. To parse the document as XML, you need to have lxml parser and you just need to pass the “xml” as the second argument to the Beautifulsoup constructor − soup = BeautifulSoup(markup, "lxml-xml") or soup = BeautifulSoup(markup, "xml") One common XML parsing error is − AttributeError: 'NoneType' object has no attribute 'attrib' This might happen in case, some element is missing or not defined while using find() or findall() function. Given below are some of the other parsing errors we are going to discuss in this section − Apart from the above mentioned parsing errors, you may encounter other parsing issues such as environmental issues where your script might work in one operating system but not in another operating system or may work in one virtual environment but not in another virtual environment or may not work outside the virtual environment. All these issues may be because the two environments have different parser libraries available. It is recommended to know or check your default parser in your current working environment. You can check the current default parser available for the current working environment or else pass explicitly the required parser library as second arguments to the BeautifulSoup constructor. As the HTML tags and attributes are case-insensitive, all three HTML parsers convert tag and attribute names to lowercase. However, if you want to preserve mixed-case or uppercase tags and attributes, then it is better to parse the document as XML. Let us look into below code segment − soup = BeautifulSoup(response, "html.parser") print (soup) UnicodeEncodeError: 'charmap' codec can't encode character '\u011f' Above problem may be because of two main situations. You might be trying to print out a unicode character that your console doesn’t know how to display. Second, you are trying to write to a file and you pass in a Unicode character that’s not supported by your default encoding. One way to resolve above problem is to encode the response text/character before making the soup to get the desired result, as follows − responseTxt = response.text.encode('UTF-8') It is caused by accessing tag[‘attr’] when the tag in question doesn’t define the attr attribute. Most common errors are: “KeyError: ‘href’” and “KeyError: ‘class’”. Use tag.get(‘attr’) if you are not sure attr is defined. for item in soup.fetch('a'): try: if (item['href'].startswith('/') or "tutorialspoint" in item['href']): (...) except KeyError: pass # or some other fallback action You may encounter AttributeError as follows − AttributeError: 'list' object has no attribute 'find_all' The above error mainly occurs because you expected find_all() return a single tag or string. However, soup.find_all returns a python list of elements. All you need to do is to iterate through the list and catch data from those elements. 38 Lectures 3.5 hours Chandramouli Jayendran 22 Lectures 1 hours TELCOMA Global 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 6 Lectures 1 hours AlexanderSchlee 22 Lectures 4 hours AlexanderSchlee Print Add Notes Bookmark this page
[ { "code": null, "e": 2189, "s": 1985, "text": "There are two main kinds of errors that need to be handled in BeautifulSoup. These two errors are not from your script but from the structure of the snippet because the BeautifulSoup API throws an error." }, { "code": null, "e": 2226, "s": 2189, "text": "The two main errors are as follows −" }, { "code": null, "e": 2469, "s": 2226, "text": "It is caused when the dot notation doesn’t find a sibling tag to the current HTML tag. For example, you may have encountered this error, because of missing “anchor tag”, cost-key will throw an error as it traverses and requires an anchor tag." }, { "code": null, "e": 2631, "s": 2469, "text": "This error occurs if the required HTML tag attribute is missing. For example, if we don’t have data-pid attribute in a snippet, the pid key will throw key-error." }, { "code": null, "e": 2794, "s": 2631, "text": "To avoid the above two listed errors when parsing a result, that result will be bypassed to make sure that a malformed snippet isn’t inserted into the databases −" }, { "code": null, "e": 2840, "s": 2794, "text": "except(AttributeError, KeyError) as er:\npass\n" }, { "code": null, "e": 3097, "s": 2840, "text": "Whenever we find any difficulty in understanding what BeautifulSoup does to our document or HTML, simply pass it to the diagnose() function. On passing document file to the diagnose() function, we can show how list of different parser handles the document." }, { "code": null, "e": 3166, "s": 3097, "text": "Below is one example to demonstrate the use of diagnose() function −" }, { "code": null, "e": 3290, "s": 3166, "text": "from bs4.diagnose import diagnose\n\nwith open(\"20 Books.html\",encoding=\"utf8\") as fp:\n data = fp.read()\n \ndiagnose(data)" }, { "code": null, "e": 3574, "s": 3290, "text": "There are two main types of parsing errors. You might get an exception like HTMLParseError, when you feed your document to BeautifulSoup. You may also get an unexpected result, where the BeautifulSoup parse tree looks a lot different from the expected result from the parse document." }, { "code": null, "e": 3807, "s": 3574, "text": "None of the parsing error is caused due to BeautifulSoup. It is because of external parser we use (html5lib, lxml) since BeautifulSoup doesn’t contain any parser code. One way to resolve above parsing error is to use another parser." }, { "code": null, "e": 4100, "s": 3807, "text": "from HTMLParser import HTMLParser\n\ntry:\n from HTMLParser import HTMLParseError\nexcept ImportError, e:\n # From python 3.5, HTMLParseError is removed. Since it can never be\n # thrown in 3.5, we can just define our own class as a placeholder.\n class HTMLParseError(Exception):\n pass" }, { "code": null, "e": 4329, "s": 4100, "text": "Python built-in HTML parser causes two most common parse errors, HTMLParser.HTMLParserError: malformed start tag and HTMLParser.HTMLParserError: bad end tag and to resolve this, is to use another parser mainly: lxml or html5lib." }, { "code": null, "e": 4507, "s": 4329, "text": "Another common type of unexpected behavior is that you can’t find a tag that you know is in the document. However, when you run the find_all() returns [] or find() returns None." }, { "code": null, "e": 4598, "s": 4507, "text": "This may be due to python built-in HTML parser sometimes skips tags it doesn’t understand." }, { "code": null, "e": 4767, "s": 4598, "text": "By default, BeautifulSoup package parses the documents as HTML, however, it is very easy-to-use and handle ill-formed XML in a very elegant manner using beautifulsoup4." }, { "code": null, "e": 4920, "s": 4767, "text": "To parse the document as XML, you need to have lxml parser and you just need to pass the “xml” as the second argument to the Beautifulsoup constructor −" }, { "code": null, "e": 4962, "s": 4920, "text": "soup = BeautifulSoup(markup, \"lxml-xml\")\n" }, { "code": null, "e": 4965, "s": 4962, "text": "or" }, { "code": null, "e": 5002, "s": 4965, "text": "soup = BeautifulSoup(markup, \"xml\")\n" }, { "code": null, "e": 5036, "s": 5002, "text": "One common XML parsing error is −" }, { "code": null, "e": 5097, "s": 5036, "text": "AttributeError: 'NoneType' object has no attribute 'attrib'\n" }, { "code": null, "e": 5205, "s": 5097, "text": "This might happen in case, some element is missing or not defined while using find() or findall() function." }, { "code": null, "e": 5296, "s": 5205, "text": "Given below are some of the other parsing errors we are going to discuss in this section −" }, { "code": null, "e": 5723, "s": 5296, "text": "Apart from the above mentioned parsing errors, you may encounter other parsing issues such as environmental issues where your script might work in one operating system but not in another operating system or may work in one virtual environment but not in another virtual environment or may not work outside the virtual environment. All these issues may be because the two environments have different parser libraries available." }, { "code": null, "e": 6008, "s": 5723, "text": "It is recommended to know or check your default parser in your current working environment. You can check the current default parser available for the current working environment or else pass explicitly the required parser library as second arguments to the BeautifulSoup constructor." }, { "code": null, "e": 6257, "s": 6008, "text": "As the HTML tags and attributes are case-insensitive, all three HTML parsers convert tag and attribute names to lowercase. However, if you want to preserve mixed-case or uppercase tags and attributes, then it is better to parse the document as XML." }, { "code": null, "e": 6295, "s": 6257, "text": "Let us look into below code segment −" }, { "code": null, "e": 6358, "s": 6295, "text": "soup = BeautifulSoup(response, \"html.parser\")\n print (soup)\n" }, { "code": null, "e": 6427, "s": 6358, "text": "UnicodeEncodeError: 'charmap' codec can't encode character '\\u011f'\n" }, { "code": null, "e": 6705, "s": 6427, "text": "Above problem may be because of two main situations. You might be trying to print out a unicode character that your console doesn’t know how to display. Second, you are trying to write to a file and you pass in a Unicode character that’s not supported by your default encoding." }, { "code": null, "e": 6842, "s": 6705, "text": "One way to resolve above problem is to encode the response text/character before making the soup to get the desired result, as follows −" }, { "code": null, "e": 6887, "s": 6842, "text": "responseTxt = response.text.encode('UTF-8')\n" }, { "code": null, "e": 7110, "s": 6887, "text": "It is caused by accessing tag[‘attr’] when the tag in question doesn’t define the attr attribute. Most common errors are: “KeyError: ‘href’” and “KeyError: ‘class’”. Use tag.get(‘attr’) if you are not sure attr is defined." }, { "code": null, "e": 7299, "s": 7110, "text": "for item in soup.fetch('a'):\n try:\n if (item['href'].startswith('/') or \"tutorialspoint\" in item['href']):\n (...)\n except KeyError:\n pass # or some other fallback action" }, { "code": null, "e": 7345, "s": 7299, "text": "You may encounter AttributeError as follows −" }, { "code": null, "e": 7404, "s": 7345, "text": "AttributeError: 'list' object has no attribute 'find_all'\n" }, { "code": null, "e": 7555, "s": 7404, "text": "The above error mainly occurs because you expected find_all() return a single tag or string. However, soup.find_all returns a python list of elements." }, { "code": null, "e": 7641, "s": 7555, "text": "All you need to do is to iterate through the list and catch data from those elements." }, { "code": null, "e": 7676, "s": 7641, "text": "\n 38 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7700, "s": 7676, "text": " Chandramouli Jayendran" }, { "code": null, "e": 7733, "s": 7700, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 7749, "s": 7733, "text": " TELCOMA Global" }, { "code": null, "e": 7781, "s": 7749, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 7798, "s": 7781, "text": " AlexanderSchlee" }, { "code": null, "e": 7830, "s": 7798, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 7847, "s": 7830, "text": " AlexanderSchlee" }, { "code": null, "e": 7879, "s": 7847, "text": "\n 6 Lectures \n 1 hours \n" }, { "code": null, "e": 7896, "s": 7879, "text": " AlexanderSchlee" }, { "code": null, "e": 7929, "s": 7896, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 7946, "s": 7929, "text": " AlexanderSchlee" }, { "code": null, "e": 7953, "s": 7946, "text": " Print" }, { "code": null, "e": 7964, "s": 7953, "text": " Add Notes" } ]
Calendar Functions in Python -(monthrange(), prcal(), weekday()?)
We are going to explore different methods of calendar module in this tutorial. Let's see one by one. The method calendar.monthrange(year, month) returns starting weekday number and number of days of the given month. It returns two values in a tuple. Let's see one example. Live Demo # importing the calendar module import calendar # initializing year and month year = 2019 month = 1 # getting the tuple of weekday and no. of days weekday, no_of_days = calendar.monthrange(year, month) print(f'Weekday number: {weekday}') print(f'No. of days: {no_of_days}') If you run the above code, you will get the following results. Weekday number: 1 No. of days: 31 The method calendar.prcal(year) prints the calendar of the year without print function. Live Demo # importing the calendar module import calendar # initializing year year = 2019 # printing the calendar using prcal() method calendar.prcal(year) If you run the above program, you will get the following results. The method calendar.weekday(year, month, day) takes three arguments and returns the weekday number. Live Demo # importing the calendar module import calendar # initializing year, month and day year = 2020 month = 1 day = 28 # getting weekday print(calendar.weekday(year, month, day)) If you run the above code, you will get the following results. 1 If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1163, "s": 1062, "text": "We are going to explore different methods of calendar module in this tutorial. Let's see one by one." }, { "code": null, "e": 1335, "s": 1163, "text": "The method calendar.monthrange(year, month) returns starting weekday number and number of days of the given month. It returns two values in a tuple. Let's see one example." }, { "code": null, "e": 1346, "s": 1335, "text": " Live Demo" }, { "code": null, "e": 1620, "s": 1346, "text": "# importing the calendar module\nimport calendar\n# initializing year and month\nyear = 2019\nmonth = 1\n# getting the tuple of weekday and no. of days\nweekday, no_of_days = calendar.monthrange(year, month)\nprint(f'Weekday number: {weekday}')\nprint(f'No. of days: {no_of_days}')" }, { "code": null, "e": 1683, "s": 1620, "text": "If you run the above code, you will get the following results." }, { "code": null, "e": 1717, "s": 1683, "text": "Weekday number: 1\nNo. of days: 31" }, { "code": null, "e": 1805, "s": 1717, "text": "The method calendar.prcal(year) prints the calendar of the year without print function." }, { "code": null, "e": 1816, "s": 1805, "text": " Live Demo" }, { "code": null, "e": 1962, "s": 1816, "text": "# importing the calendar module\nimport calendar\n# initializing year\nyear = 2019\n# printing the calendar using prcal() method\ncalendar.prcal(year)" }, { "code": null, "e": 2028, "s": 1962, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 2128, "s": 2028, "text": "The method calendar.weekday(year, month, day) takes three arguments and returns the weekday number." }, { "code": null, "e": 2139, "s": 2128, "text": " Live Demo" }, { "code": null, "e": 2313, "s": 2139, "text": "# importing the calendar module\nimport calendar\n# initializing year, month and day\nyear = 2020\nmonth = 1\nday = 28\n# getting weekday\nprint(calendar.weekday(year, month, day))" }, { "code": null, "e": 2376, "s": 2313, "text": "If you run the above code, you will get the following results." }, { "code": null, "e": 2378, "s": 2376, "text": "1" }, { "code": null, "e": 2455, "s": 2378, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
GATE | GATE-CS-2016 (Set 2) | Question 14 - GeeksforGeeks
06 Oct, 2021 Consider the systems, each consisting of m linear equations in n variables. I. If m < n, then all such systems have a solution II. If m > n, then none of these systems has a solution III. If m = n, then there exists a system which has a solution Which one of the following is CORRECT?(A) I, II and III are true(B) Only II and III are true(C) Only III is true(D) None of them is trueAnswer: (C)Explanation: For ‘n’ variables, we need atleast ‘n’ linear equations in terms of the given variable to find value of each variable. If no. of equations > no. of variables then also we can find the value of each variable.Here, m : No. of linear equations n : No. of variables For solution, m > or = n. This solution is contributed by Mohit Gupta. YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersSystem of Linear Equation using rank of matrix with Sakshi Singhal | GeeksforGeeks GATEWatch 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:0026:52 / 29:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hmtz4zIohNQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2016 (Set 2) GATE-GATE-CS-2016 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE CS 2019 | Question 27 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | Gate IT 2007 | Question 30 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2021 | Set 1 | Question 47
[ { "code": null, "e": 24508, "s": 24480, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24584, "s": 24508, "text": "Consider the systems, each consisting of m linear equations in n variables." }, { "code": null, "e": 24754, "s": 24584, "text": "I. If m < n, then all such systems have a solution\nII. If m > n, then none of these systems has a solution\nIII. If m = n, then there exists a system which has a solution" }, { "code": null, "e": 24916, "s": 24754, "text": "Which one of the following is CORRECT?(A) I, II and III are true(B) Only II and III are true(C) Only III is true(D) None of them is trueAnswer: (C)Explanation: " }, { "code": null, "e": 25205, "s": 24916, "text": "For ‘n’ variables, we need atleast ‘n’ linear equations in terms of the given variable to find value of each variable. If no. of equations > no. of variables then also we can find the value of each variable.Here, m : No. of linear equations n : No. of variables For solution, m > or = n." }, { "code": null, "e": 25250, "s": 25205, "text": "This solution is contributed by Mohit Gupta." }, { "code": null, "e": 26166, "s": 25250, "text": "YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersSystem of Linear Equation using rank of matrix with Sakshi Singhal | GeeksforGeeks GATEWatch 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:0026:52 / 29:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hmtz4zIohNQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26187, "s": 26166, "text": "GATE-CS-2016 (Set 2)" }, { "code": null, "e": 26213, "s": 26187, "text": "GATE-GATE-CS-2016 (Set 2)" }, { "code": null, "e": 26218, "s": 26213, "text": "GATE" }, { "code": null, "e": 26316, "s": 26218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26350, "s": 26316, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26384, "s": 26350, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26418, "s": 26384, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26460, "s": 26418, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26493, "s": 26460, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26527, "s": 26493, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 26569, "s": 26527, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 26603, "s": 26569, "text": "GATE | Gate IT 2007 | Question 30" }, { "code": null, "e": 26637, "s": 26603, "text": "GATE | GATE CS 2010 | Question 24" } ]
Google Sheets to Jupyter | Towards Data Science
Jupyter Notebook is a powerful tool for data scientists. You could perform many complex algorithms with few lines and perform an analysis on a huge amount of data. Jupyter notebook itself capable to be connected with a database system where the data sleep. Although, if we talk about the database, as a data scientist the first thing that comes in mind often is the SQL. Of course, SQL currently still the main thing if we talk about database but many people who are not coming from programming background would not that familiar with SQL. Especially professional with experience who want to move into programming data science field, often they use google sheet just to put their data. For that reason, I want to show you how to connect our Jupyter Notebook to our Google Sheets. Connecting Jupyter Notebook to the Google Sheets is not a big hassle; the preparation thou could be a little. Luckily we only have to do it once. The first thing we need to do is getting an appropriate credential from the Google Developer Console. The credential is asking a request to let us access the google sheets. In the console, click create project. There you would find the screen shown up similar to the picture below. It does not matter what project name you give, what important is that you create a new project. To connect into the Google Sheets, we only need this one project so at the very least choose a name you could remember. Get back into our console and see if the project had been created or not. Select the newly created project and click on the hamburger menu on the top left (The one besides Google APIs symbol). On there select the APIs & Services then select the Dashboard. On the dashboard, select the ENABLE APIS AND SERVICES button. From there we would be taken to the APIs Library. It should look like the picture below. On the search bar, type ‘Google Sheets’ to find the Google Sheets API. From there click the Google Sheets API and enable the API. In this step, we also Enable the Google Drive API, so search as well ‘Google Drive API’. Now we would be taken to the Google Sheets API Dashboard. To use this API, first, we need to create the credential. Here we would be prompt by another screen to create our credentials. Choose the Google Sheets API for Which API are you using question, Other UI for Where will you be calling the API from question and User data for What data will you be accessing question. Now click the What credentials do I need? button. The steps are shown in the picture below. If it is your first time creating credentials, you would be prompt to create an OAuth consent screen. Click the Set up Consent Screen to create one. There, just put any name you like in the application name and click save. Back to the dashboard, now click the Create credentials button and select the OAuth client ID. Here, just select the Other type and type any name you like. Then click Create. You would return to the dashboard. Now download your newly created OAuth Client ID and put it in the folder where you would use your Jupyter Notebook. This step above is not necessarily needed for connecting, but we did it just in case if we need it later. We need one more thing. Now back to the create credentials and click the Service account button. Type any name you like then click the Create button. In the next screen, choose the role as the Service Account User. Then click create key button. Choose JSON Key Type and click create. Save the file in the same folder with your intended notebook. Now we get all the credentials we need. It is a long step but we only need to do it once. Before we start, we need to install 3 different Python modules. pip install gspread oauth2client df2gspread Now we come to the part where we could connect the sheets to the Jupyter Notebook. I would show it in the steps below. Import all the important modules Import all the important modules #Importing the moduleimport gspreadfrom df2gspread import df2gspread as d2gfrom oauth2client.service_account import ServiceAccountCredentials 2. Create a new worksheet in your Google Sheet. Then click the share button on the top right and input the email from the Service Account in your google API dashboard. This to make sure that the Worksheet is connected to our Jupyter Notebook. 3. Initialize all the important variables #The scope is always look like this so we did not need to change anythingscope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']#Name of our Service Account Keygoogle_key_file = 'service_key.json'credentials = ServiceAccountCredentials.from_json_keyfile_name(google_key_file, scope)gc = gspread.authorize(credentials) Here now we have all the important connections we need. First, let’s try to upload our data from Jupyter Notebook to the Google Sheet. import seaborn as sns#I would use tips dataset as an exampletips = sns.load_dataset('tips') Here is our data. Now there are few things to note when we want to upload our data to the google sheet. We need our Worksheet ID and our sheet name. How to get it is shown in the picture below. Let’s Upload the data now to this empty Google Sheet. #This is the Worksheet IDspreadsheet_key = '1ZJzLxLyfExKC-vziq21JFNzVcCISJVQxa0Dx-55Qc8k'#This is the sheet namewks_name = 'test_data'#We upload the tips data to our Google Sheet. Setting the row_names to False if you did not want the index to be includedd2g.upload(tips, spreadsheet_key, wks_name, credentials=credentials, row_names=False) And done, now we have our data in the google sheet. It is as easy as uploading the data to google sheet if we want to pull the data. I would show it in the code below. #Opening the worksheet by using Worksheet IDworkbook = gc.open_by_key(spreadsheet_key)#Selecting which sheet to pulling the datasheet = workbook.worksheet('test_data')#Pulling the data and transform it to the data framevalues = sheet.get_all_values()pull_tips = pd.DataFrame(values[1:], columns = values[0])pull_tips And that is it. We already connected with our Google Sheet from our Jupyter Notebook. I have shown you to set up the required steps for us to connect our Jupyter Notebook with the Google Sheets. I also have shown how to upload and pull our data from and to Google Sheets. I hope it helps! If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 542, "s": 171, "text": "Jupyter Notebook is a powerful tool for data scientists. You could perform many complex algorithms with few lines and perform an analysis on a huge amount of data. Jupyter notebook itself capable to be connected with a database system where the data sleep. Although, if we talk about the database, as a data scientist the first thing that comes in mind often is the SQL." }, { "code": null, "e": 857, "s": 542, "text": "Of course, SQL currently still the main thing if we talk about database but many people who are not coming from programming background would not that familiar with SQL. Especially professional with experience who want to move into programming data science field, often they use google sheet just to put their data." }, { "code": null, "e": 951, "s": 857, "text": "For that reason, I want to show you how to connect our Jupyter Notebook to our Google Sheets." }, { "code": null, "e": 1097, "s": 951, "text": "Connecting Jupyter Notebook to the Google Sheets is not a big hassle; the preparation thou could be a little. Luckily we only have to do it once." }, { "code": null, "e": 1270, "s": 1097, "text": "The first thing we need to do is getting an appropriate credential from the Google Developer Console. The credential is asking a request to let us access the google sheets." }, { "code": null, "e": 1379, "s": 1270, "text": "In the console, click create project. There you would find the screen shown up similar to the picture below." }, { "code": null, "e": 1595, "s": 1379, "text": "It does not matter what project name you give, what important is that you create a new project. To connect into the Google Sheets, we only need this one project so at the very least choose a name you could remember." }, { "code": null, "e": 1851, "s": 1595, "text": "Get back into our console and see if the project had been created or not. Select the newly created project and click on the hamburger menu on the top left (The one besides Google APIs symbol). On there select the APIs & Services then select the Dashboard." }, { "code": null, "e": 1913, "s": 1851, "text": "On the dashboard, select the ENABLE APIS AND SERVICES button." }, { "code": null, "e": 2002, "s": 1913, "text": "From there we would be taken to the APIs Library. It should look like the picture below." }, { "code": null, "e": 2073, "s": 2002, "text": "On the search bar, type ‘Google Sheets’ to find the Google Sheets API." }, { "code": null, "e": 2132, "s": 2073, "text": "From there click the Google Sheets API and enable the API." }, { "code": null, "e": 2221, "s": 2132, "text": "In this step, we also Enable the Google Drive API, so search as well ‘Google Drive API’." }, { "code": null, "e": 2337, "s": 2221, "text": "Now we would be taken to the Google Sheets API Dashboard. To use this API, first, we need to create the credential." }, { "code": null, "e": 2686, "s": 2337, "text": "Here we would be prompt by another screen to create our credentials. Choose the Google Sheets API for Which API are you using question, Other UI for Where will you be calling the API from question and User data for What data will you be accessing question. Now click the What credentials do I need? button. The steps are shown in the picture below." }, { "code": null, "e": 2835, "s": 2686, "text": "If it is your first time creating credentials, you would be prompt to create an OAuth consent screen. Click the Set up Consent Screen to create one." }, { "code": null, "e": 2909, "s": 2835, "text": "There, just put any name you like in the application name and click save." }, { "code": null, "e": 3004, "s": 2909, "text": "Back to the dashboard, now click the Create credentials button and select the OAuth client ID." }, { "code": null, "e": 3084, "s": 3004, "text": "Here, just select the Other type and type any name you like. Then click Create." }, { "code": null, "e": 3235, "s": 3084, "text": "You would return to the dashboard. Now download your newly created OAuth Client ID and put it in the folder where you would use your Jupyter Notebook." }, { "code": null, "e": 3341, "s": 3235, "text": "This step above is not necessarily needed for connecting, but we did it just in case if we need it later." }, { "code": null, "e": 3438, "s": 3341, "text": "We need one more thing. Now back to the create credentials and click the Service account button." }, { "code": null, "e": 3556, "s": 3438, "text": "Type any name you like then click the Create button. In the next screen, choose the role as the Service Account User." }, { "code": null, "e": 3586, "s": 3556, "text": "Then click create key button." }, { "code": null, "e": 3687, "s": 3586, "text": "Choose JSON Key Type and click create. Save the file in the same folder with your intended notebook." }, { "code": null, "e": 3777, "s": 3687, "text": "Now we get all the credentials we need. It is a long step but we only need to do it once." }, { "code": null, "e": 3841, "s": 3777, "text": "Before we start, we need to install 3 different Python modules." }, { "code": null, "e": 3885, "s": 3841, "text": "pip install gspread oauth2client df2gspread" }, { "code": null, "e": 4004, "s": 3885, "text": "Now we come to the part where we could connect the sheets to the Jupyter Notebook. I would show it in the steps below." }, { "code": null, "e": 4037, "s": 4004, "text": "Import all the important modules" }, { "code": null, "e": 4070, "s": 4037, "text": "Import all the important modules" }, { "code": null, "e": 4212, "s": 4070, "text": "#Importing the moduleimport gspreadfrom df2gspread import df2gspread as d2gfrom oauth2client.service_account import ServiceAccountCredentials" }, { "code": null, "e": 4455, "s": 4212, "text": "2. Create a new worksheet in your Google Sheet. Then click the share button on the top right and input the email from the Service Account in your google API dashboard. This to make sure that the Worksheet is connected to our Jupyter Notebook." }, { "code": null, "e": 4497, "s": 4455, "text": "3. Initialize all the important variables" }, { "code": null, "e": 4861, "s": 4497, "text": "#The scope is always look like this so we did not need to change anythingscope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']#Name of our Service Account Keygoogle_key_file = 'service_key.json'credentials = ServiceAccountCredentials.from_json_keyfile_name(google_key_file, scope)gc = gspread.authorize(credentials)" }, { "code": null, "e": 4917, "s": 4861, "text": "Here now we have all the important connections we need." }, { "code": null, "e": 4996, "s": 4917, "text": "First, let’s try to upload our data from Jupyter Notebook to the Google Sheet." }, { "code": null, "e": 5088, "s": 4996, "text": "import seaborn as sns#I would use tips dataset as an exampletips = sns.load_dataset('tips')" }, { "code": null, "e": 5106, "s": 5088, "text": "Here is our data." }, { "code": null, "e": 5282, "s": 5106, "text": "Now there are few things to note when we want to upload our data to the google sheet. We need our Worksheet ID and our sheet name. How to get it is shown in the picture below." }, { "code": null, "e": 5336, "s": 5282, "text": "Let’s Upload the data now to this empty Google Sheet." }, { "code": null, "e": 5677, "s": 5336, "text": "#This is the Worksheet IDspreadsheet_key = '1ZJzLxLyfExKC-vziq21JFNzVcCISJVQxa0Dx-55Qc8k'#This is the sheet namewks_name = 'test_data'#We upload the tips data to our Google Sheet. Setting the row_names to False if you did not want the index to be includedd2g.upload(tips, spreadsheet_key, wks_name, credentials=credentials, row_names=False)" }, { "code": null, "e": 5729, "s": 5677, "text": "And done, now we have our data in the google sheet." }, { "code": null, "e": 5845, "s": 5729, "text": "It is as easy as uploading the data to google sheet if we want to pull the data. I would show it in the code below." }, { "code": null, "e": 6162, "s": 5845, "text": "#Opening the worksheet by using Worksheet IDworkbook = gc.open_by_key(spreadsheet_key)#Selecting which sheet to pulling the datasheet = workbook.worksheet('test_data')#Pulling the data and transform it to the data framevalues = sheet.get_all_values()pull_tips = pd.DataFrame(values[1:], columns = values[0])pull_tips" }, { "code": null, "e": 6248, "s": 6162, "text": "And that is it. We already connected with our Google Sheet from our Jupyter Notebook." }, { "code": null, "e": 6434, "s": 6248, "text": "I have shown you to set up the required steps for us to connect our Jupyter Notebook with the Google Sheets. I also have shown how to upload and pull our data from and to Google Sheets." }, { "code": null, "e": 6451, "s": 6434, "text": "I hope it helps!" } ]
Interface in Dart - GeeksforGeeks
20 Jul, 2020 The interface in the dart provides the user with the blueprint of the class, that any class should follow if it interfaces that class i.e. if a class inherits another it should redefine each function present inside an interfaced class in its way. They are nothing but a set of methods defined for an object. Dart doesn’t have any direct way to create inherited class, we have to make use of implements keyword to do so. Syntax: class Interface_class_name{ ... } class Class_name implements Interface_class_name { ... } Example 1: Dart void main(){ // Creating Object // of the class Gfg Gfg geek1= new Gfg(); // Calling method // (After Implementation ) geek1.printdata(); } // Class Geek (Interface)class Geek { void printdata() { print("Hello Geek !!"); } } // Class Gfg implementing Geekclass Gfg implements Geek { void printdata() { print("Welcome to GeeksForGeeks"); } } Output: Welcome to GeeksForGeeks Note: Class should use the implements keyword, instead of extending to be able to use an interface method. In dart, multiple inheritances are achieved by the use of implements. Although practically dart doesn’t support multiple inheritances, it supports multiple interfaces. Syntax: class interface_class1 { ... } class interface_class2 { ... } . . . . class interface_classN { ... } class class_name implements interface_class1, interface_class2, ...., interface_classN { ... } Example: Dart // Dart Program to show Multiple Inheritance void main(){ // Creating Object of // the class Gfg Gfg geek1= new Gfg(); // Calling method (After Implementation ) geek1.printdata1(); geek1.printdata2(); geek1.printdata3(); } // Class Geek1 (Interface1)class Geek1 { void printdata1() { print("Hello Geek1 !!"); } } // Class Geek2 (Interface2)class Geek2 { void printdata2() { print("Hello Geek2 !!"); } } // Class Geek3 (Interface3)class Geek3 { void printdata3() { print("Hello Geek3 !!"); } } // Class Gfg implementing Geek1, Geek2, Geek3.class Gfg implements Geek1, Geek2, Geek3 { void printdata1() { print("Howdy Geek1,\nWelcome to GeeksForGeeks"); } void printdata2() { print("Howdy Geek2,\nWelcome to GeeksForGeeks"); } void printdata3() { print("Howdy Geek3,\nWelcome to GeeksForGeeks"); } } Output: Howdy Geek1, Welcome to GeeksForGeeks Howdy Geek2, Welcome to GeeksForGeeks Howdy Geek3, Welcome to GeeksForGeeks Importance of Interface: Used to achieve abstraction in Dart.It is a way to achieve multiple inheritances in Dart. Used to achieve abstraction in Dart. It is a way to achieve multiple inheritances in Dart. Important Points: If a class has been implemented then all of its method and instance variable must be overridden during the interface.In dart, there are no direct means to declare an interface, so a declaration of a class is itself considered as a declaration on the interface.A class can extend only one class but can implement as many as you want. If a class has been implemented then all of its method and instance variable must be overridden during the interface. In dart, there are no direct means to declare an interface, so a declaration of a class is itself considered as a declaration on the interface. A class can extend only one class but can implement as many as you want. Dart-Interface Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - BorderRadius Widget Android Studio Setup for Flutter Development Flutter - Flexible Widget Flutter - Stack Widget What is widgets in Flutter? Flutter - Dialogs Flutter - Positioned Widget Format Dates in Flutter
[ { "code": null, "e": 23930, "s": 23902, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24350, "s": 23930, "text": "The interface in the dart provides the user with the blueprint of the class, that any class should follow if it interfaces that class i.e. if a class inherits another it should redefine each function present inside an interfaced class in its way. They are nothing but a set of methods defined for an object. Dart doesn’t have any direct way to create inherited class, we have to make use of implements keyword to do so." }, { "code": null, "e": 24359, "s": 24350, "text": "Syntax: " }, { "code": null, "e": 24458, "s": 24359, "text": "class Interface_class_name{\n ...\n}\n\nclass Class_name implements Interface_class_name {\n ...\n}\n" }, { "code": null, "e": 24470, "s": 24458, "text": "Example 1: " }, { "code": null, "e": 24475, "s": 24470, "text": "Dart" }, { "code": "void main(){ // Creating Object // of the class Gfg Gfg geek1= new Gfg(); // Calling method // (After Implementation ) geek1.printdata(); } // Class Geek (Interface)class Geek { void printdata() { print(\"Hello Geek !!\"); } } // Class Gfg implementing Geekclass Gfg implements Geek { void printdata() { print(\"Welcome to GeeksForGeeks\"); } }", "e": 24865, "s": 24475, "text": null }, { "code": null, "e": 24876, "s": 24867, "text": "Output: " }, { "code": null, "e": 24902, "s": 24876, "text": "Welcome to GeeksForGeeks\n" }, { "code": null, "e": 25009, "s": 24902, "text": "Note: Class should use the implements keyword, instead of extending to be able to use an interface method." }, { "code": null, "e": 25177, "s": 25009, "text": "In dart, multiple inheritances are achieved by the use of implements. Although practically dart doesn’t support multiple inheritances, it supports multiple interfaces." }, { "code": null, "e": 25185, "s": 25177, "text": "Syntax:" }, { "code": null, "e": 25399, "s": 25185, "text": "class interface_class1 {\n ...\n}\nclass interface_class2 {\n ...\n}\n.\n.\n.\n.\nclass interface_classN {\n ...\n}\n\nclass class_name implements interface_class1, interface_class2, ...., interface_classN {\n ...\n}\n" }, { "code": null, "e": 25409, "s": 25399, "text": "Example: " }, { "code": null, "e": 25414, "s": 25409, "text": "Dart" }, { "code": "// Dart Program to show Multiple Inheritance void main(){ // Creating Object of // the class Gfg Gfg geek1= new Gfg(); // Calling method (After Implementation ) geek1.printdata1(); geek1.printdata2(); geek1.printdata3(); } // Class Geek1 (Interface1)class Geek1 { void printdata1() { print(\"Hello Geek1 !!\"); } } // Class Geek2 (Interface2)class Geek2 { void printdata2() { print(\"Hello Geek2 !!\"); } } // Class Geek3 (Interface3)class Geek3 { void printdata3() { print(\"Hello Geek3 !!\"); } } // Class Gfg implementing Geek1, Geek2, Geek3.class Gfg implements Geek1, Geek2, Geek3 { void printdata1() { print(\"Howdy Geek1,\\nWelcome to GeeksForGeeks\"); } void printdata2() { print(\"Howdy Geek2,\\nWelcome to GeeksForGeeks\"); } void printdata3() { print(\"Howdy Geek3,\\nWelcome to GeeksForGeeks\"); } } ", "e": 26327, "s": 25414, "text": null }, { "code": null, "e": 26338, "s": 26329, "text": "Output: " }, { "code": null, "e": 26454, "s": 26338, "text": "Howdy Geek1,\nWelcome to GeeksForGeeks\nHowdy Geek2,\nWelcome to GeeksForGeeks\nHowdy Geek3,\nWelcome to GeeksForGeeks\n\n" }, { "code": null, "e": 26481, "s": 26454, "text": "Importance of Interface: " }, { "code": null, "e": 26571, "s": 26481, "text": "Used to achieve abstraction in Dart.It is a way to achieve multiple inheritances in Dart." }, { "code": null, "e": 26608, "s": 26571, "text": "Used to achieve abstraction in Dart." }, { "code": null, "e": 26662, "s": 26608, "text": "It is a way to achieve multiple inheritances in Dart." }, { "code": null, "e": 26682, "s": 26662, "text": "Important Points: " }, { "code": null, "e": 27015, "s": 26682, "text": "If a class has been implemented then all of its method and instance variable must be overridden during the interface.In dart, there are no direct means to declare an interface, so a declaration of a class is itself considered as a declaration on the interface.A class can extend only one class but can implement as many as you want." }, { "code": null, "e": 27133, "s": 27015, "text": "If a class has been implemented then all of its method and instance variable must be overridden during the interface." }, { "code": null, "e": 27277, "s": 27133, "text": "In dart, there are no direct means to declare an interface, so a declaration of a class is itself considered as a declaration on the interface." }, { "code": null, "e": 27350, "s": 27277, "text": "A class can extend only one class but can implement as many as you want." }, { "code": null, "e": 27365, "s": 27350, "text": "Dart-Interface" }, { "code": null, "e": 27370, "s": 27365, "text": "Dart" }, { "code": null, "e": 27468, "s": 27370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27477, "s": 27468, "text": "Comments" }, { "code": null, "e": 27490, "s": 27477, "text": "Old Comments" }, { "code": null, "e": 27529, "s": 27490, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27555, "s": 27529, "text": "ListView Class in Flutter" }, { "code": null, "e": 27585, "s": 27555, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 27630, "s": 27585, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 27656, "s": 27630, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27679, "s": 27656, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27707, "s": 27679, "text": "What is widgets in Flutter?" }, { "code": null, "e": 27725, "s": 27707, "text": "Flutter - Dialogs" }, { "code": null, "e": 27753, "s": 27725, "text": "Flutter - Positioned Widget" } ]
String transformation using XOR and OR - GeeksforGeeks
29 Apr, 2021 Given two binary strings. The task is to check if string s1 can be converted to string s2 by performing the given operations any number of times. Choose any two adjacent characters in a string s1 and replace one of them by a^b and the other by a b (a OR b). Examples: Input: S1 = “11”, S2 = “10” Output: YES Select two adjacent characters and replace s2[0] by s1[0]s1[1] and change s2[1] by s1[0]^s1[1] Input: S1 = “000”, S2 = “101” Output: NO Approach: Given below is a table that explains all the possibilities of XOR and OR operations. If both the string consists of 0’s only and their length is same, conversion is possible, as two adjacent zero will result in zeros only, irrespective of the operation done on it. If both the string have 1’s, follow the steps below to check if String1 can be converted to String2. Check if lengths are equal or not Check if both the strings have a minimum of one 1, as all the conversions are possible if both the strings have at least 1 which can be seen in the table If both of the above conditions are true, it is possible to convert String1 can be converted to String2. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to check if string1 can be// converted to string2 using XOR and OR operations#include <bits/stdc++.h>using namespace std; // function to check if conversion is possible or notbool solve(string s1, string s2){ bool flag1 = 0, flag2 = 0; // if lengths are different if (s1.length() != s2.length()) return false; int l = s1.length(); // iterate to check if both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = 1; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = 1; if (flag1 && flag2) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do not have a '1'. return false;} // Driver codeint main(){ string s1 = "100101"; string s2 = "100000"; if (solve(s1, s2)) cout << "Yes"; else cout << "No"; return 0;} // Java program to check if// string1 can be converted// to string2 using XOR and// OR operationsimport java.io.*;import java.util.*; class GFG{ // function to check if// conversion is possible// or notstatic boolean solve(String s1, String s2){ boolean flag1 = false, flag2 = false; // if lengths are different if (s1.length() != s2.length()) return false; int l = s1.length(); // iterate to check if // both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1.charAt(i) == '1') flag1 = true; // to check if there is even // one 1 in string s2 if (s2.charAt(i) == '1') flag2 = true; if (flag1 == true && flag2 == true) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do // not have a '1'. return false;} // Driver codepublic static void main(String args[]){ String s1 = "100101"; String s2 = "100000"; if (solve(s1, s2) == true) System.out.print("Yes"); else System.out.print("No");}} # Python3 program to check# if string1 can be converted# to string2 using XOR and# OR operations # function to check if# conversion is possible or notdef solve(s1, s2): flag1 = 0 flag2 = 0 # if lengths are different if (len(s1) != len(s2)): return False l = len(s1) # iterate to check if# both strings have 1 for i in range (0, l): # to check if there is # even one 1 in string s1 if (s1[i] == '1'): flag1 = 1; # to check if there is even # one 1 in string s2 if (s2[i] == '1'): flag2 = 1 # if both string # do not have a '1'. if (flag1 & flag2): return True if(!flag1 & !flag2): return True return False # Driver codes1 = "100101"s2 = "100000" if solve(s1, s2): print( "Yes")else: print("No") # This code is contributed# by Shivi_Aggarwal // C# program to check if// string1 can be converted// to string2 using XOR and// OR operationsusing System; class GFG{ // function to check if// conversion is possible// or notstatic bool solve(String s1, String s2){ bool flag1 = false, flag2 = false; // if lengths are different if (s1.Length != s2.Length) return false; int l = s1.Length; // iterate to check if // both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = true; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = true; if (flag1 == true && flag2 == true) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do // not have a '1'. return false;} // Driver codepublic static void Main(){ String s1 = "100101"; String s2 = "100000"; if (solve(s1, s2) == true) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to check if string1// can be converted to string2// using XOR and OR operations // function to check if conversion// is possible or notfunction solve($s1, $s2){ // if lengths are different if (strlen($s1) != strlen($s2)) return false; $l = strlen($s1); // iterate to check if // both strings have 1 for ($i = 0; $i < 1; $i++) { // to check if there is // even one 1 in string s1 if ($s1[$i] == '1') $flag1 = 1; // to check if there is even // one 1 in string s2 if ($s2[$i] == '1') $flag2 = 1; if (!$flag1 && !$flag2) return true; } // if both string do // not have a '1'. return false;} // Driver code$s1 = "100101";$s2 = "100000"; if (solve($s1, $s2)) echo("Yes"); else echo("No"); // This code is contributed// by Shivi_Aggarwal?> <script>// Javascript program to check if string1 can be// converted to string2 using XOR and OR operations // function to check if conversion is possible or notfunction solve(s1, s2){ let flag1 = 0, flag2 = 0; // if lengths are different if (s1.length != s2.length) return false; let l = s1.length; // iterate to check if both strings have 1 for (let i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = 1; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = 1; if (flag1 && flag2) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do not have a '1'. return false;} // Driver code let s1 = "100101"; let s2 = "100000"; if (solve(s1, s2)) document.write("Yes"); else document.write("No"); </script> Yes Time Complexity: O(n) where n is the length of input strings. Shivi_Aggarwal Akanksha_Rai UtkarshLal subham348 Bitwise-XOR Constructive Algorithms Bit Magic Competitive Programming Strings Strings Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Program to find whether a given number is power of 2 Add two numbers without using arithmetic operators 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 Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26115, "s": 26087, "text": "\n29 Apr, 2021" }, { "code": null, "e": 26263, "s": 26115, "text": "Given two binary strings. The task is to check if string s1 can be converted to string s2 by performing the given operations any number of times. " }, { "code": null, "e": 26375, "s": 26263, "text": "Choose any two adjacent characters in a string s1 and replace one of them by a^b and the other by a b (a OR b)." }, { "code": null, "e": 26385, "s": 26375, "text": "Examples:" }, { "code": null, "e": 26561, "s": 26385, "text": "Input: S1 = “11”, S2 = “10” Output: YES Select two adjacent characters and replace s2[0] by s1[0]s1[1] and change s2[1] by s1[0]^s1[1] Input: S1 = “000”, S2 = “101” Output: NO" }, { "code": null, "e": 26658, "s": 26561, "text": "Approach: Given below is a table that explains all the possibilities of XOR and OR operations. " }, { "code": null, "e": 26941, "s": 26658, "text": "If both the string consists of 0’s only and their length is same, conversion is possible, as two adjacent zero will result in zeros only, irrespective of the operation done on it. If both the string have 1’s, follow the steps below to check if String1 can be converted to String2. " }, { "code": null, "e": 26975, "s": 26941, "text": "Check if lengths are equal or not" }, { "code": null, "e": 27129, "s": 26975, "text": "Check if both the strings have a minimum of one 1, as all the conversions are possible if both the strings have at least 1 which can be seen in the table" }, { "code": null, "e": 27283, "s": 27129, "text": "If both of the above conditions are true, it is possible to convert String1 can be converted to String2. Below is the implementation of above approach: " }, { "code": null, "e": 27287, "s": 27283, "text": "C++" }, { "code": null, "e": 27292, "s": 27287, "text": "Java" }, { "code": null, "e": 27300, "s": 27292, "text": "Python3" }, { "code": null, "e": 27303, "s": 27300, "text": "C#" }, { "code": null, "e": 27307, "s": 27303, "text": "PHP" }, { "code": null, "e": 27318, "s": 27307, "text": "Javascript" }, { "code": "// C++ program to check if string1 can be// converted to string2 using XOR and OR operations#include <bits/stdc++.h>using namespace std; // function to check if conversion is possible or notbool solve(string s1, string s2){ bool flag1 = 0, flag2 = 0; // if lengths are different if (s1.length() != s2.length()) return false; int l = s1.length(); // iterate to check if both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = 1; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = 1; if (flag1 && flag2) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do not have a '1'. return false;} // Driver codeint main(){ string s1 = \"100101\"; string s2 = \"100000\"; if (solve(s1, s2)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 28357, "s": 27318, "text": null }, { "code": "// Java program to check if// string1 can be converted// to string2 using XOR and// OR operationsimport java.io.*;import java.util.*; class GFG{ // function to check if// conversion is possible// or notstatic boolean solve(String s1, String s2){ boolean flag1 = false, flag2 = false; // if lengths are different if (s1.length() != s2.length()) return false; int l = s1.length(); // iterate to check if // both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1.charAt(i) == '1') flag1 = true; // to check if there is even // one 1 in string s2 if (s2.charAt(i) == '1') flag2 = true; if (flag1 == true && flag2 == true) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do // not have a '1'. return false;} // Driver codepublic static void main(String args[]){ String s1 = \"100101\"; String s2 = \"100000\"; if (solve(s1, s2) == true) System.out.print(\"Yes\"); else System.out.print(\"No\");}}", "e": 29570, "s": 28357, "text": null }, { "code": "# Python3 program to check# if string1 can be converted# to string2 using XOR and# OR operations # function to check if# conversion is possible or notdef solve(s1, s2): flag1 = 0 flag2 = 0 # if lengths are different if (len(s1) != len(s2)): return False l = len(s1) # iterate to check if# both strings have 1 for i in range (0, l): # to check if there is # even one 1 in string s1 if (s1[i] == '1'): flag1 = 1; # to check if there is even # one 1 in string s2 if (s2[i] == '1'): flag2 = 1 # if both string # do not have a '1'. if (flag1 & flag2): return True if(!flag1 & !flag2): return True return False # Driver codes1 = \"100101\"s2 = \"100000\" if solve(s1, s2): print( \"Yes\")else: print(\"No\") # This code is contributed# by Shivi_Aggarwal", "e": 30440, "s": 29570, "text": null }, { "code": "// C# program to check if// string1 can be converted// to string2 using XOR and// OR operationsusing System; class GFG{ // function to check if// conversion is possible// or notstatic bool solve(String s1, String s2){ bool flag1 = false, flag2 = false; // if lengths are different if (s1.Length != s2.Length) return false; int l = s1.Length; // iterate to check if // both strings have 1 for (int i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = true; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = true; if (flag1 == true && flag2 == true) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do // not have a '1'. return false;} // Driver codepublic static void Main(){ String s1 = \"100101\"; String s2 = \"100000\"; if (solve(s1, s2) == true) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 31635, "s": 30440, "text": null }, { "code": "<?php// PHP program to check if string1// can be converted to string2// using XOR and OR operations // function to check if conversion// is possible or notfunction solve($s1, $s2){ // if lengths are different if (strlen($s1) != strlen($s2)) return false; $l = strlen($s1); // iterate to check if // both strings have 1 for ($i = 0; $i < 1; $i++) { // to check if there is // even one 1 in string s1 if ($s1[$i] == '1') $flag1 = 1; // to check if there is even // one 1 in string s2 if ($s2[$i] == '1') $flag2 = 1; if (!$flag1 && !$flag2) return true; } // if both string do // not have a '1'. return false;} // Driver code$s1 = \"100101\";$s2 = \"100000\"; if (solve($s1, $s2)) echo(\"Yes\"); else echo(\"No\"); // This code is contributed// by Shivi_Aggarwal?>", "e": 32543, "s": 31635, "text": null }, { "code": "<script>// Javascript program to check if string1 can be// converted to string2 using XOR and OR operations // function to check if conversion is possible or notfunction solve(s1, s2){ let flag1 = 0, flag2 = 0; // if lengths are different if (s1.length != s2.length) return false; let l = s1.length; // iterate to check if both strings have 1 for (let i = 0; i < l; i++) { // to check if there is // even one 1 in string s1 if (s1[i] == '1') flag1 = 1; // to check if there is even // one 1 in string s2 if (s2[i] == '1') flag2 = 1; if (flag1 && flag2) return true; } //if both strings have only '0' if(!flag1&&!flag2) return true; // if both string do not have a '1'. return false;} // Driver code let s1 = \"100101\"; let s2 = \"100000\"; if (solve(s1, s2)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 33531, "s": 32543, "text": null }, { "code": null, "e": 33535, "s": 33531, "text": "Yes" }, { "code": null, "e": 33600, "s": 33537, "text": "Time Complexity: O(n) where n is the length of input strings. " }, { "code": null, "e": 33615, "s": 33600, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33628, "s": 33615, "text": "Akanksha_Rai" }, { "code": null, "e": 33639, "s": 33628, "text": "UtkarshLal" }, { "code": null, "e": 33649, "s": 33639, "text": "subham348" }, { "code": null, "e": 33661, "s": 33649, "text": "Bitwise-XOR" }, { "code": null, "e": 33685, "s": 33661, "text": "Constructive Algorithms" }, { "code": null, "e": 33695, "s": 33685, "text": "Bit Magic" }, { "code": null, "e": 33719, "s": 33695, "text": "Competitive Programming" }, { "code": null, "e": 33727, "s": 33719, "text": "Strings" }, { "code": null, "e": 33735, "s": 33727, "text": "Strings" }, { "code": null, "e": 33745, "s": 33735, "text": "Bit Magic" }, { "code": null, "e": 33843, "s": 33745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33873, "s": 33843, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 33919, "s": 33873, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 33959, "s": 33919, "text": "Binary representation of a given number" }, { "code": null, "e": 34012, "s": 33959, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 34063, "s": 34012, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 34106, "s": 34063, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 34149, "s": 34106, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 34190, "s": 34149, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34268, "s": 34190, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Java log1p() with example - GeeksforGeeks
31 Mar, 2018 The java.lang.Math.log1p() is one of the Java Math Library method which is used to return the natural logarithm of the sum of the arguments and 1.For the small values, the result of log1p(a) is much closer to the true result of ln(1 + a) than the floating-point evaluation of log(1.0 + a).There are various cases : If the argument is positive double value, Math.log1p() method will return the logarithm of the given value. If the argument is NaN or less than -1, Math.log1p() method will return NaN. If the argument is positive infinity, Math.log1p() method will return the result as Positive Infinity If the argument is negative one, Math.log1p() method will return Negative Infinity f the argument is positive or negative zero, Math.log1p() method will return Zero Syntax : public static double log1p(double a) Parameter : a : User input Return : This method returns the value ln(x + 1), the natural log of x + 1. Example :To show working of java.lang.Math.log1p() method. // Java program to demonstrate working// of java.lang.Math.log1p() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 23.45; double b = -145.25; double c = 1.0 / 0; double d = -1; double e = 0; // positive double value as argument, // output double value System.out.println(Math.log1p(a)); // negative integer as argument, // output NAN System.out.println(Math.log1p(b)); // positive infinity as argument, // output Positive Infinity System.out.println(Math.log1p(c)); // negative one as argument, // output Negative Infinity System.out.println(Math.log1p(d)); // positive zero as argument, // output Zero System.out.println(Math.log1p(e)); }} 3.196630215920881 NaN Infinity -Infinity 0.0 java-math 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 PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n31 Mar, 2018" }, { "code": null, "e": 25662, "s": 25347, "text": "The java.lang.Math.log1p() is one of the Java Math Library method which is used to return the natural logarithm of the sum of the arguments and 1.For the small values, the result of log1p(a) is much closer to the true result of ln(1 + a) than the floating-point evaluation of log(1.0 + a).There are various cases :" }, { "code": null, "e": 25770, "s": 25662, "text": "If the argument is positive double value, Math.log1p() method will return the logarithm of the given value." }, { "code": null, "e": 25847, "s": 25770, "text": "If the argument is NaN or less than -1, Math.log1p() method will return NaN." }, { "code": null, "e": 25949, "s": 25847, "text": "If the argument is positive infinity, Math.log1p() method will return the result as Positive Infinity" }, { "code": null, "e": 26032, "s": 25949, "text": "If the argument is negative one, Math.log1p() method will return Negative Infinity" }, { "code": null, "e": 26114, "s": 26032, "text": "f the argument is positive or negative zero, Math.log1p() method will return Zero" }, { "code": null, "e": 26123, "s": 26114, "text": "Syntax :" }, { "code": null, "e": 26160, "s": 26123, "text": "public static double log1p(double a)" }, { "code": null, "e": 26172, "s": 26160, "text": "Parameter :" }, { "code": null, "e": 26187, "s": 26172, "text": "a : User input" }, { "code": null, "e": 26196, "s": 26187, "text": "Return :" }, { "code": null, "e": 26263, "s": 26196, "text": "This method returns the value ln(x + 1), the natural log of x + 1." }, { "code": null, "e": 26322, "s": 26263, "text": "Example :To show working of java.lang.Math.log1p() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.log1p() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 23.45; double b = -145.25; double c = 1.0 / 0; double d = -1; double e = 0; // positive double value as argument, // output double value System.out.println(Math.log1p(a)); // negative integer as argument, // output NAN System.out.println(Math.log1p(b)); // positive infinity as argument, // output Positive Infinity System.out.println(Math.log1p(c)); // negative one as argument, // output Negative Infinity System.out.println(Math.log1p(d)); // positive zero as argument, // output Zero System.out.println(Math.log1p(e)); }}", "e": 27191, "s": 26322, "text": null }, { "code": null, "e": 27237, "s": 27191, "text": "3.196630215920881\nNaN\nInfinity\n-Infinity\n0.0\n" }, { "code": null, "e": 27247, "s": 27237, "text": "java-math" }, { "code": null, "e": 27252, "s": 27247, "text": "Java" }, { "code": null, "e": 27257, "s": 27252, "text": "Java" }, { "code": null, "e": 27355, "s": 27257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27370, "s": 27355, "text": "Stream In Java" }, { "code": null, "e": 27391, "s": 27370, "text": "Constructors in Java" }, { "code": null, "e": 27410, "s": 27391, "text": "Exceptions in Java" }, { "code": null, "e": 27440, "s": 27410, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27486, "s": 27440, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27503, "s": 27486, "text": "Generics in Java" }, { "code": null, "e": 27524, "s": 27503, "text": "Introduction to Java" }, { "code": null, "e": 27567, "s": 27524, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27589, "s": 27567, "text": "PriorityQueue in Java" } ]
What is the append method in Java?
The append(char c) method of the java.lang.StringBuffer appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1. Live Demo import java.lang.*; public class StringBufferDemo { public static void main(String[] args) { StringBuffer buff = new StringBuffer("tuts "); System.out.println("buffer = " + buff); // appends the char argument as string to the string buffer. buff.append('A'); // print the string buffer after appending System.out.println("After append = " + buff); buff = new StringBuffer("abcd "); System.out.println("buffer = " + buff); // appends the char argument as string to the string buffer. buff.append('!'); // print the string buffer after appending System.out.println("After append = " + buff); } } buffer = tuts After append = tuts A buffer = abcd After append = abcd !
[ { "code": null, "e": 1294, "s": 1062, "text": "The append(char c) method of the java.lang.StringBuffer appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1." }, { "code": null, "e": 1305, "s": 1294, "text": " Live Demo" }, { "code": null, "e": 2001, "s": 1305, "text": "import java.lang.*;\npublic class StringBufferDemo {\n public static void main(String[] args) {\n StringBuffer buff = new StringBuffer(\"tuts \");\n System.out.println(\"buffer = \" + buff);\n \n // appends the char argument as string to the string buffer.\n buff.append('A');\n \n // print the string buffer after appending\n System.out.println(\"After append = \" + buff);\n buff = new StringBuffer(\"abcd \");\n System.out.println(\"buffer = \" + buff);\n \n // appends the char argument as string to the string buffer.\n buff.append('!');\n \n // print the string buffer after appending\n System.out.println(\"After append = \" + buff);\n }\n}" }, { "code": null, "e": 2073, "s": 2001, "text": "buffer = tuts\nAfter append = tuts A\nbuffer = abcd\nAfter append = abcd !" } ]
Calendar compareTo() Method in Java with Examples - GeeksforGeeks
13 Feb, 2019 The add(Calendar Calendar2) method of Calendar class is used to compare the time values or the millisecond offsets of this Calendar object with the passed Calendar object. Syntax: public int compareTo(Calendar Calendar2) Parameters: The method takes one parameter Calendar2 of Calendar object type and refers to the object to be compared to this Calendar object. Return Value: The method returns an integer value and can return any one of the following: The method returns 0 if the passed argument is equal to this Calendar object.The method returns 1 if the time of this Calendar object is more than the passed object.The method returns -1 if the time of this Calendar object is less than the passed object. The method returns 0 if the passed argument is equal to this Calendar object. The method returns 1 if the time of this Calendar object is more than the passed object. The method returns -1 if the time of this Calendar object is less than the passed object. Below programs illustrate the working of compareTo() Method of Calendar class:Example 1: // Java Code to illustrate compareTo() Method import java.util.*; public class CalendarClassDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr1 = Calendar.getInstance(); // Creating another calendar object Calendar calndr2 = new GregorianCalendar(2018, 12, 2); // Comparing the time int val = calndr1.compareTo(calndr2); // Displaying the result of comparison System.out.println("First" + " comparison result is: " + val); // Comparing the time val = calndr2.compareTo(calndr1); // Displaying the result of comparison System.out.println("Second" + " comparison result is: " + val); }} First comparison result is: 1 Second comparison result is: -1 Example 2: // Java Code to illustrate compareTo() Method import java.util.*; public class CalendarClassDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr1 = Calendar.getInstance(); // Creating another calendar object Calendar calndr2 = Calendar.getInstance(); // Comparing the time int val = calndr1.compareTo(calndr2); // Displaying the result of comparison System.out.println("The" + " comparison result is: " + val); }} The comparison result is: -1 Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#compareTo(java.util.Calendar) Java - util package Java-Calendar Java-Functions 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": 25749, "s": 25721, "text": "\n13 Feb, 2019" }, { "code": null, "e": 25921, "s": 25749, "text": "The add(Calendar Calendar2) method of Calendar class is used to compare the time values or the millisecond offsets of this Calendar object with the passed Calendar object." }, { "code": null, "e": 25929, "s": 25921, "text": "Syntax:" }, { "code": null, "e": 25970, "s": 25929, "text": "public int compareTo(Calendar Calendar2)" }, { "code": null, "e": 26112, "s": 25970, "text": "Parameters: The method takes one parameter Calendar2 of Calendar object type and refers to the object to be compared to this Calendar object." }, { "code": null, "e": 26203, "s": 26112, "text": "Return Value: The method returns an integer value and can return any one of the following:" }, { "code": null, "e": 26458, "s": 26203, "text": "The method returns 0 if the passed argument is equal to this Calendar object.The method returns 1 if the time of this Calendar object is more than the passed object.The method returns -1 if the time of this Calendar object is less than the passed object." }, { "code": null, "e": 26536, "s": 26458, "text": "The method returns 0 if the passed argument is equal to this Calendar object." }, { "code": null, "e": 26625, "s": 26536, "text": "The method returns 1 if the time of this Calendar object is more than the passed object." }, { "code": null, "e": 26715, "s": 26625, "text": "The method returns -1 if the time of this Calendar object is less than the passed object." }, { "code": null, "e": 26804, "s": 26715, "text": "Below programs illustrate the working of compareTo() Method of Calendar class:Example 1:" }, { "code": "// Java Code to illustrate compareTo() Method import java.util.*; public class CalendarClassDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr1 = Calendar.getInstance(); // Creating another calendar object Calendar calndr2 = new GregorianCalendar(2018, 12, 2); // Comparing the time int val = calndr1.compareTo(calndr2); // Displaying the result of comparison System.out.println(\"First\" + \" comparison result is: \" + val); // Comparing the time val = calndr2.compareTo(calndr1); // Displaying the result of comparison System.out.println(\"Second\" + \" comparison result is: \" + val); }}", "e": 27663, "s": 26804, "text": null }, { "code": null, "e": 27726, "s": 27663, "text": "First comparison result is: 1\nSecond comparison result is: -1\n" }, { "code": null, "e": 27737, "s": 27726, "text": "Example 2:" }, { "code": "// Java Code to illustrate compareTo() Method import java.util.*; public class CalendarClassDemo { public static void main(String args[]) { // Creating a calendar object Calendar calndr1 = Calendar.getInstance(); // Creating another calendar object Calendar calndr2 = Calendar.getInstance(); // Comparing the time int val = calndr1.compareTo(calndr2); // Displaying the result of comparison System.out.println(\"The\" + \" comparison result is: \" + val); }}", "e": 28317, "s": 27737, "text": null }, { "code": null, "e": 28347, "s": 28317, "text": "The comparison result is: -1\n" }, { "code": null, "e": 28454, "s": 28347, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#compareTo(java.util.Calendar)" }, { "code": null, "e": 28474, "s": 28454, "text": "Java - util package" }, { "code": null, "e": 28488, "s": 28474, "text": "Java-Calendar" }, { "code": null, "e": 28503, "s": 28488, "text": "Java-Functions" }, { "code": null, "e": 28508, "s": 28503, "text": "Java" }, { "code": null, "e": 28513, "s": 28508, "text": "Java" }, { "code": null, "e": 28611, "s": 28513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28662, "s": 28611, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28692, "s": 28662, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28707, "s": 28692, "text": "Stream In Java" }, { "code": null, "e": 28726, "s": 28707, "text": "Interfaces in Java" }, { "code": null, "e": 28757, "s": 28726, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28775, "s": 28757, "text": "ArrayList in Java" }, { "code": null, "e": 28807, "s": 28775, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28827, "s": 28807, "text": "Stack Class in Java" }, { "code": null, "e": 28851, "s": 28827, "text": "Singleton Class in Java" } ]
Program to remove consonants from a String - GeeksforGeeks
09 Jun, 2021 Given a string , the task is to remove all the consonants from the string and then print the string. Examples: Input: str= “Welcome to geeksforgeeks” Output: eoe o eeoee Input: str= “What is your name?” Output: a i ou ae? Approach: Traverse all the characters of the string, if the character is a consonant then remove it from the final answer. Below is the implementation of the above approach: Java Python3 C# Javascript // Java program to remove consonants from a Stringimport java.util.Arrays;import java.util.List; class Test { // function that returns true // if the character is an alphabet static boolean isAlphabet(char ch) { if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; return false; } // function to return the string after // removing all the consonants from it static String remConsonants(String str) { Character vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; List<Character> al = Arrays.asList(vowels); StringBuffer sb = new StringBuffer(str); for (int i = 0; i < sb.length(); i++) { if (isAlphabet(sb.charAt(i)) && !al.contains(sb.charAt(i))) { sb.replace(i, i + 1, ""); i--; } } return sb.toString(); } // Driver method to test the above function public static void main(String[] args) { String str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; System.out.println(remConsonants(str)); }} # Python3 program to remove consonants from a String # function that returns true# if the character is an alphabetdef isAlphabet(ch): if (ch >= 'a' and ch <= 'z'): return True; if (ch >= 'A' and ch <= 'Z'): return True; return False; # Function to return the string after# removing all the consonants from itdef remConsonants(str): vowels = [ 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ] sb = ""; for i in range(len(str)): present = False; for j in range(len(vowels)): if (str[i] == vowels[j]): present = True; break; if (not isAlphabet(str[i]) or present ): sb += str[i]; return sb; # Driver codeif __name__=='__main__': str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; print(remConsonants(str)); # This code is contributed by pratham76 // C# program to remove consonants from a Stringusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG{ // Function that returns true// if the character is an alphabetstatic bool isAlphabet(char ch){ if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; return false;} // Function to return the string after// removing all the consonants from itstatic string remConsonants(string str){ char []vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; string sb = ""; for(int i = 0; i < str.Length; i++) { bool present = false; for(int j = 0; j < vowels.Length; j++) { if (str[i] == vowels[j]) { present = true; break; } } if (!isAlphabet(str[i]) || present ) { sb += str[i]; } } return sb;} // Driver codepublic static void Main(string[] args){ string str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; Console.Write(remConsonants(str));}} // This code is contributed by rutvik_56 <script> // JavaScript program to remove // consonants from a String // Function that returns true // if the character is an alphabet function isAlphabet(ch) { if (ch >= "a" && ch <= "z") return true; if (ch >= "A" && ch <= "Z") return true; return false; } // Function to return the string after // removing all the consonants from it function remConsonants(str) { var vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]; var sb = ""; for (var i = 0; i < str.length; i++) { var present = false; for (var j = 0; j < vowels.length; j++) { if (str[i] === vowels[j]) { present = true; break; } } if (!isAlphabet(str[i]) || present) { sb += str[i]; } } return sb; } // Driver code var str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; document.write(remConsonants(str)); </script> eeeoee - A oue iee oa o ee Below is another program using Regular Expressions in Java Java C# // Java program to remove consonants from a String class Test{ static String remVowel(String str) { return str.replaceAll("[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]", ""); } // Driver method to test the above function public static void main(String[] args) { String str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; System.out.println(remVowel(str)); }} // C# program to remove consonants from a Stringusing System;using System.Text.RegularExpressions; class GFG{ static String remVowel(String str) { return Regex.Replace(str, "[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]", ""); } // Driver code public static void Main() { String str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; Console.WriteLine(remVowel(str)); }} // This code is contributed by Rajput-Ji eeeoee - A oue iee oa o ee Time complexity : O(n) where n is the length of string VishalBachchas Rajput-Ji rutvik_56 pratham76 rdtank java-regular-expression Technical Scripter 2018 vowel-consonant Java Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String How to Write Data into Excel Sheet using Java? Java Servlet and JDBC Example | Insert data in MySQL Removing last element from ArrayList in Java How to Replace a Element in Java ArrayList? Java Program to Find Sum of Array Elements Tic-Tac-Toe Game in Java
[ { "code": null, "e": 26242, "s": 26214, "text": "\n09 Jun, 2021" }, { "code": null, "e": 26343, "s": 26242, "text": "Given a string , the task is to remove all the consonants from the string and then print the string." }, { "code": null, "e": 26355, "s": 26343, "text": "Examples: " }, { "code": null, "e": 26414, "s": 26355, "text": "Input: str= “Welcome to geeksforgeeks” Output: eoe o eeoee" }, { "code": null, "e": 26467, "s": 26414, "text": "Input: str= “What is your name?” Output: a i ou ae? " }, { "code": null, "e": 26590, "s": 26467, "text": "Approach: Traverse all the characters of the string, if the character is a consonant then remove it from the final answer." }, { "code": null, "e": 26641, "s": 26590, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26646, "s": 26641, "text": "Java" }, { "code": null, "e": 26654, "s": 26646, "text": "Python3" }, { "code": null, "e": 26657, "s": 26654, "text": "C#" }, { "code": null, "e": 26668, "s": 26657, "text": "Javascript" }, { "code": "// Java program to remove consonants from a Stringimport java.util.Arrays;import java.util.List; class Test { // function that returns true // if the character is an alphabet static boolean isAlphabet(char ch) { if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; return false; } // function to return the string after // removing all the consonants from it static String remConsonants(String str) { Character vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; List<Character> al = Arrays.asList(vowels); StringBuffer sb = new StringBuffer(str); for (int i = 0; i < sb.length(); i++) { if (isAlphabet(sb.charAt(i)) && !al.contains(sb.charAt(i))) { sb.replace(i, i + 1, \"\"); i--; } } return sb.toString(); } // Driver method to test the above function public static void main(String[] args) { String str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; System.out.println(remConsonants(str)); }}", "e": 27855, "s": 26668, "text": null }, { "code": "# Python3 program to remove consonants from a String # function that returns true# if the character is an alphabetdef isAlphabet(ch): if (ch >= 'a' and ch <= 'z'): return True; if (ch >= 'A' and ch <= 'Z'): return True; return False; # Function to return the string after# removing all the consonants from itdef remConsonants(str): vowels = [ 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ] sb = \"\"; for i in range(len(str)): present = False; for j in range(len(vowels)): if (str[i] == vowels[j]): present = True; break; if (not isAlphabet(str[i]) or present ): sb += str[i]; return sb; # Driver codeif __name__=='__main__': str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; print(remConsonants(str)); # This code is contributed by pratham76", "e": 28778, "s": 27855, "text": null }, { "code": "// C# program to remove consonants from a Stringusing System;using System.Collections;using System.Collections.Generic;using System.Linq; class GFG{ // Function that returns true// if the character is an alphabetstatic bool isAlphabet(char ch){ if (ch >= 'a' && ch <= 'z') return true; if (ch >= 'A' && ch <= 'Z') return true; return false;} // Function to return the string after// removing all the consonants from itstatic string remConsonants(string str){ char []vowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; string sb = \"\"; for(int i = 0; i < str.Length; i++) { bool present = false; for(int j = 0; j < vowels.Length; j++) { if (str[i] == vowels[j]) { present = true; break; } } if (!isAlphabet(str[i]) || present ) { sb += str[i]; } } return sb;} // Driver codepublic static void Main(string[] args){ string str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; Console.Write(remConsonants(str));}} // This code is contributed by rutvik_56", "e": 29965, "s": 28778, "text": null }, { "code": "<script> // JavaScript program to remove // consonants from a String // Function that returns true // if the character is an alphabet function isAlphabet(ch) { if (ch >= \"a\" && ch <= \"z\") return true; if (ch >= \"A\" && ch <= \"Z\") return true; return false; } // Function to return the string after // removing all the consonants from it function remConsonants(str) { var vowels = [\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", \"I\", \"O\", \"U\"]; var sb = \"\"; for (var i = 0; i < str.length; i++) { var present = false; for (var j = 0; j < vowels.length; j++) { if (str[i] === vowels[j]) { present = true; break; } } if (!isAlphabet(str[i]) || present) { sb += str[i]; } } return sb; } // Driver code var str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; document.write(remConsonants(str)); </script>", "e": 31024, "s": 29965, "text": null }, { "code": null, "e": 31051, "s": 31024, "text": "eeeoee - A oue iee oa o ee" }, { "code": null, "e": 31113, "s": 31053, "text": "Below is another program using Regular Expressions in Java " }, { "code": null, "e": 31118, "s": 31113, "text": "Java" }, { "code": null, "e": 31121, "s": 31118, "text": "C#" }, { "code": "// Java program to remove consonants from a String class Test{ static String remVowel(String str) { return str.replaceAll(\"[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]\", \"\"); } // Driver method to test the above function public static void main(String[] args) { String str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; System.out.println(remVowel(str)); }}", "e": 31546, "s": 31121, "text": null }, { "code": "// C# program to remove consonants from a Stringusing System;using System.Text.RegularExpressions; class GFG{ static String remVowel(String str) { return Regex.Replace(str, \"[BCDFGHJKLMNPQRSTVXZbcdfghjklmnpqrstvxz]\", \"\"); } // Driver code public static void Main() { String str = \"GeeeksforGeeks - A Computer Science Portal for Geeks\"; Console.WriteLine(remVowel(str)); }} // This code is contributed by Rajput-Ji", "e": 32016, "s": 31546, "text": null }, { "code": null, "e": 32043, "s": 32016, "text": "eeeoee - A oue iee oa o ee" }, { "code": null, "e": 32101, "s": 32045, "text": "Time complexity : O(n) where n is the length of string " }, { "code": null, "e": 32116, "s": 32101, "text": "VishalBachchas" }, { "code": null, "e": 32126, "s": 32116, "text": "Rajput-Ji" }, { "code": null, "e": 32136, "s": 32126, "text": "rutvik_56" }, { "code": null, "e": 32146, "s": 32136, "text": "pratham76" }, { "code": null, "e": 32153, "s": 32146, "text": "rdtank" }, { "code": null, "e": 32177, "s": 32153, "text": "java-regular-expression" }, { "code": null, "e": 32201, "s": 32177, "text": "Technical Scripter 2018" }, { "code": null, "e": 32217, "s": 32201, "text": "vowel-consonant" }, { "code": null, "e": 32231, "s": 32217, "text": "Java Programs" }, { "code": null, "e": 32250, "s": 32231, "text": "Technical Scripter" }, { "code": null, "e": 32348, "s": 32250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32396, "s": 32348, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 32447, "s": 32396, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 32481, "s": 32447, "text": "Java Program to Write into a File" }, { "code": null, "e": 32519, "s": 32481, "text": "Java Program to Read a File to String" }, { "code": null, "e": 32566, "s": 32519, "text": "How to Write Data into Excel Sheet using Java?" }, { "code": null, "e": 32619, "s": 32566, "text": "Java Servlet and JDBC Example | Insert data in MySQL" }, { "code": null, "e": 32664, "s": 32619, "text": "Removing last element from ArrayList in Java" }, { "code": null, "e": 32708, "s": 32664, "text": "How to Replace a Element in Java ArrayList?" }, { "code": null, "e": 32751, "s": 32708, "text": "Java Program to Find Sum of Array Elements" } ]
Check if there is a root to leaf path with given sequence - GeeksforGeeks
30 Apr, 2020 Given a binary tree and an array, the task is to find if the given array sequence is present as a root to leaf path in given tree.Examples : Input : arr[] = {5, 2, 4, 8} for above tree Output: "Path Exist" Input : arr[] = {5, 3, 4, 9} for above tree Output: "Path does not Exist" A simple solution for this problem is to find all root to leaf paths in given tree and for each root to leaf path check that path and given sequence in array both are identical or not. An efficient solution for this problem is to traverse the tree once and while traversing the tree we have to check that if path from root to current node is identical to the given sequence of root to leaf path. Here is the algorithm : Start traversing tree in preorder fashion. Whenever we moves down in tree then we also move by one index in given sequence of root to leaf path . If current node is equal to the arr[index] this means that till this level of tree path is identical. Now remaining path will either be in left subtree or in right subtree. If any node gets mismatched with arr[index] this means that current path is not identical to the given sequence of root to leaf path, so we return back and move in right subtree. Now when we are at leaf node and it is equal to arr[index] and there is no further element in given sequence of root to leaf path, this means that path exist in given tree.C++JavaPython3C#C++// C++ program to see if there is a root to leaf path// with given sequence.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* utility that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Util functionbool existPathUtil(struct Node *root, int arr[], int n, int index){ // If root is NULL or reached end of the array if(root == NULL or index==n) return false; // If current node is leaf if (root->left == NULL && root->right == NULL) { if((root->data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root->data == arr[index]) && (existPathUtil(root->left, arr, n, index+1) || existPathUtil(root->right, arr, n, index+1) ));} // Function to check given sequence of root to leaf path exist// in tree or not.// index represents current element in sequence of rooth to// leaf pathbool existPath(struct Node *root, int arr[], int n, int index){ if(!root) return (n==0); return existPathUtil(root, arr, n, 0);} // Driver function to run the caseint main(){ // arr[] --> sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); struct Node *root = newnode(5); root->left = newnode(3); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->left->left->left = newnode(1); root->right->left = newnode(6); root->right->left->right = newnode(7); existPath(root, arr, n, 0)? cout << "Path Exists" : cout << "Path does not Exist"; return 0;}Java// Java program to see if there is a root to leaf path// with given sequence.import java.io.*; class Node{ int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; }} class GFG { // Util function static boolean existPathUtil(Node root, int arr[], int n, int index) { // If root is NULL or // reached end of the array if(root == null || index==n) return false; // If current node is leaf if (root.left == null && root.right == null) { if((root.data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root.data == arr[index]) && (existPathUtil(root.left, arr, n, index+1) || existPathUtil(root.right, arr, n, index+1) )); } // Function to check given sequence of root // to leaf path exist in tree or not. // index : current element in sequence of root to // leaf path static boolean existPath(Node root, int arr[], int n, int index) { if(root == null) return (n==0); return existPathUtil(root, arr, n, 0); } public static void main (String[] args) { // arr[] : sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = arr.length; Node root = new Node(5); root.left = new Node(3); root.right = new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, n, 0)) System.out.println("Path Exists"); else System.out.println("Path does not Exist"); }}Python3# Python program to see if# there is a root to leaf path# with given sequence # Class of Nodeclass Node: # Constructor to create a # node in Binary Tree def __init__(self, val): self.val = val self.left = None self.right = None # Util function def existPathUtil(root, arr, n, index): # If root is NULL or reached # end of the array if not root or index == n: return False # If current node is leaf if not root.left and not root.right: if root.val == arr[index] and index == n-1: return True return False # If current node is equal to arr[index] this means # that till this level path has been matched and # remaining path can be either in left subtree or # right subtree. return ((index < n) and (root.val == arr[index]) and \ (existPathUtil(root.left, arr, n, index+1) or \ existPathUtil(root.right, arr, n, index+1))) # Function to check given sequence of root to leaf path exist# in tree or not.# index represents current element in sequence of rooth to# leaf path def existPath(root, arr, n, index): if not root: return (n == 0) return existPathUtil(root, arr, n, 0) # Driver Codeif __name__ == "__main__": arr = [5, 8, 6, 7] n = len(arr) root = Node(5) root.left = Node(3) root.right = Node(8) root.left.left = Node(2) root.left.right = Node(4) root.left.left.left = Node(1) root.right.left = Node(6) root.right.left.right = Node(7) if existPath(root, arr, n, 0): print("Path Exists") else: print("Path does not Exist")C#// C# program to see if there// is a root to leaf path // with given sequence. using System; public class CheckForPath { // function to check given sequence // of root to leaf path exist // in tree or not. // index represents current element // in sequence of rooth to // leaf path public static bool existPath(Node root, int []arr, int index) { // If root is NULL, then there // must not be any element // in array. if(root == null) { return arr.Length == 0; } // If this node is a leaf and matches with last entry // of array. if((root.left == null && root.right == null) && (root.data == arr[index] && root.data == arr[arr.Length - 1])) { return true; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return (index < arr.Length && (root.data == arr[index] && (existPath(root.left,arr,index + 1) || existPath(root.right, arr, index + 1)))); } // Driver code public static void Main() { // arr[] is sequence of root to leaf path int []arr = {5, 8, 6, 7}; Node root=new Node(5); root.left=new Node(3); root.right=new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, 0)) { Console.Write("Path Exists"); } else { Console.Write("Path does not Exist"); } } } /* A binary tree node has data, pointer to left child and apointer to right child */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // This code is contributed Rajput-Ji Output:Path Exists Time complexity : O(n)This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave C++ Java Python3 C# // C++ program to see if there is a root to leaf path// with given sequence.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* utility that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Util functionbool existPathUtil(struct Node *root, int arr[], int n, int index){ // If root is NULL or reached end of the array if(root == NULL or index==n) return false; // If current node is leaf if (root->left == NULL && root->right == NULL) { if((root->data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root->data == arr[index]) && (existPathUtil(root->left, arr, n, index+1) || existPathUtil(root->right, arr, n, index+1) ));} // Function to check given sequence of root to leaf path exist// in tree or not.// index represents current element in sequence of rooth to// leaf pathbool existPath(struct Node *root, int arr[], int n, int index){ if(!root) return (n==0); return existPathUtil(root, arr, n, 0);} // Driver function to run the caseint main(){ // arr[] --> sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); struct Node *root = newnode(5); root->left = newnode(3); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->left->left->left = newnode(1); root->right->left = newnode(6); root->right->left->right = newnode(7); existPath(root, arr, n, 0)? cout << "Path Exists" : cout << "Path does not Exist"; return 0;} // Java program to see if there is a root to leaf path// with given sequence.import java.io.*; class Node{ int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; }} class GFG { // Util function static boolean existPathUtil(Node root, int arr[], int n, int index) { // If root is NULL or // reached end of the array if(root == null || index==n) return false; // If current node is leaf if (root.left == null && root.right == null) { if((root.data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root.data == arr[index]) && (existPathUtil(root.left, arr, n, index+1) || existPathUtil(root.right, arr, n, index+1) )); } // Function to check given sequence of root // to leaf path exist in tree or not. // index : current element in sequence of root to // leaf path static boolean existPath(Node root, int arr[], int n, int index) { if(root == null) return (n==0); return existPathUtil(root, arr, n, 0); } public static void main (String[] args) { // arr[] : sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = arr.length; Node root = new Node(5); root.left = new Node(3); root.right = new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, n, 0)) System.out.println("Path Exists"); else System.out.println("Path does not Exist"); }} # Python program to see if# there is a root to leaf path# with given sequence # Class of Nodeclass Node: # Constructor to create a # node in Binary Tree def __init__(self, val): self.val = val self.left = None self.right = None # Util function def existPathUtil(root, arr, n, index): # If root is NULL or reached # end of the array if not root or index == n: return False # If current node is leaf if not root.left and not root.right: if root.val == arr[index] and index == n-1: return True return False # If current node is equal to arr[index] this means # that till this level path has been matched and # remaining path can be either in left subtree or # right subtree. return ((index < n) and (root.val == arr[index]) and \ (existPathUtil(root.left, arr, n, index+1) or \ existPathUtil(root.right, arr, n, index+1))) # Function to check given sequence of root to leaf path exist# in tree or not.# index represents current element in sequence of rooth to# leaf path def existPath(root, arr, n, index): if not root: return (n == 0) return existPathUtil(root, arr, n, 0) # Driver Codeif __name__ == "__main__": arr = [5, 8, 6, 7] n = len(arr) root = Node(5) root.left = Node(3) root.right = Node(8) root.left.left = Node(2) root.left.right = Node(4) root.left.left.left = Node(1) root.right.left = Node(6) root.right.left.right = Node(7) if existPath(root, arr, n, 0): print("Path Exists") else: print("Path does not Exist") // C# program to see if there// is a root to leaf path // with given sequence. using System; public class CheckForPath { // function to check given sequence // of root to leaf path exist // in tree or not. // index represents current element // in sequence of rooth to // leaf path public static bool existPath(Node root, int []arr, int index) { // If root is NULL, then there // must not be any element // in array. if(root == null) { return arr.Length == 0; } // If this node is a leaf and matches with last entry // of array. if((root.left == null && root.right == null) && (root.data == arr[index] && root.data == arr[arr.Length - 1])) { return true; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return (index < arr.Length && (root.data == arr[index] && (existPath(root.left,arr,index + 1) || existPath(root.right, arr, index + 1)))); } // Driver code public static void Main() { // arr[] is sequence of root to leaf path int []arr = {5, 8, 6, 7}; Node root=new Node(5); root.left=new Node(3); root.right=new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, 0)) { Console.Write("Path Exists"); } else { Console.Write("Path does not Exist"); } } } /* A binary tree node has data, pointer to left child and apointer to right child */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // This code is contributed Rajput-Ji Path Exists Time complexity : O(n) This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari PranchalKatiyar Rajput-Ji somaniketan74 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 37091, "s": 37063, "text": "\n30 Apr, 2020" }, { "code": null, "e": 37232, "s": 37091, "text": "Given a binary tree and an array, the task is to find if the given array sequence is present as a root to leaf path in given tree.Examples :" }, { "code": null, "e": 37374, "s": 37232, "text": "Input : arr[] = {5, 2, 4, 8} for above tree\nOutput: \"Path Exist\"\n\nInput : arr[] = {5, 3, 4, 9} for above tree\nOutput: \"Path does not Exist\"\n" }, { "code": null, "e": 37559, "s": 37374, "text": "A simple solution for this problem is to find all root to leaf paths in given tree and for each root to leaf path check that path and given sequence in array both are identical or not." }, { "code": null, "e": 37794, "s": 37559, "text": "An efficient solution for this problem is to traverse the tree once and while traversing the tree we have to check that if path from root to current node is identical to the given sequence of root to leaf path. Here is the algorithm :" }, { "code": null, "e": 37837, "s": 37794, "text": "Start traversing tree in preorder fashion." }, { "code": null, "e": 37940, "s": 37837, "text": "Whenever we moves down in tree then we also move by one index in given sequence of root to leaf path ." }, { "code": null, "e": 38042, "s": 37940, "text": "If current node is equal to the arr[index] this means that till this level of tree path is identical." }, { "code": null, "e": 38113, "s": 38042, "text": "Now remaining path will either be in left subtree or in right subtree." }, { "code": null, "e": 38292, "s": 38113, "text": "If any node gets mismatched with arr[index] this means that current path is not identical to the given sequence of root to leaf path, so we return back and move in right subtree." }, { "code": null, "e": 47179, "s": 38292, "text": "Now when we are at leaf node and it is equal to arr[index] and there is no further element in given sequence of root to leaf path, this means that path exist in given tree.C++JavaPython3C#C++// C++ program to see if there is a root to leaf path// with given sequence.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* utility that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Util functionbool existPathUtil(struct Node *root, int arr[], int n, int index){ // If root is NULL or reached end of the array if(root == NULL or index==n) return false; // If current node is leaf if (root->left == NULL && root->right == NULL) { if((root->data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root->data == arr[index]) && (existPathUtil(root->left, arr, n, index+1) || existPathUtil(root->right, arr, n, index+1) ));} // Function to check given sequence of root to leaf path exist// in tree or not.// index represents current element in sequence of rooth to// leaf pathbool existPath(struct Node *root, int arr[], int n, int index){ if(!root) return (n==0); return existPathUtil(root, arr, n, 0);} // Driver function to run the caseint main(){ // arr[] --> sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); struct Node *root = newnode(5); root->left = newnode(3); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->left->left->left = newnode(1); root->right->left = newnode(6); root->right->left->right = newnode(7); existPath(root, arr, n, 0)? cout << \"Path Exists\" : cout << \"Path does not Exist\"; return 0;}Java// Java program to see if there is a root to leaf path// with given sequence.import java.io.*; class Node{ int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; }} class GFG { // Util function static boolean existPathUtil(Node root, int arr[], int n, int index) { // If root is NULL or // reached end of the array if(root == null || index==n) return false; // If current node is leaf if (root.left == null && root.right == null) { if((root.data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root.data == arr[index]) && (existPathUtil(root.left, arr, n, index+1) || existPathUtil(root.right, arr, n, index+1) )); } // Function to check given sequence of root // to leaf path exist in tree or not. // index : current element in sequence of root to // leaf path static boolean existPath(Node root, int arr[], int n, int index) { if(root == null) return (n==0); return existPathUtil(root, arr, n, 0); } public static void main (String[] args) { // arr[] : sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = arr.length; Node root = new Node(5); root.left = new Node(3); root.right = new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, n, 0)) System.out.println(\"Path Exists\"); else System.out.println(\"Path does not Exist\"); }}Python3# Python program to see if# there is a root to leaf path# with given sequence # Class of Nodeclass Node: # Constructor to create a # node in Binary Tree def __init__(self, val): self.val = val self.left = None self.right = None # Util function def existPathUtil(root, arr, n, index): # If root is NULL or reached # end of the array if not root or index == n: return False # If current node is leaf if not root.left and not root.right: if root.val == arr[index] and index == n-1: return True return False # If current node is equal to arr[index] this means # that till this level path has been matched and # remaining path can be either in left subtree or # right subtree. return ((index < n) and (root.val == arr[index]) and \\ (existPathUtil(root.left, arr, n, index+1) or \\ existPathUtil(root.right, arr, n, index+1))) # Function to check given sequence of root to leaf path exist# in tree or not.# index represents current element in sequence of rooth to# leaf path def existPath(root, arr, n, index): if not root: return (n == 0) return existPathUtil(root, arr, n, 0) # Driver Codeif __name__ == \"__main__\": arr = [5, 8, 6, 7] n = len(arr) root = Node(5) root.left = Node(3) root.right = Node(8) root.left.left = Node(2) root.left.right = Node(4) root.left.left.left = Node(1) root.right.left = Node(6) root.right.left.right = Node(7) if existPath(root, arr, n, 0): print(\"Path Exists\") else: print(\"Path does not Exist\")C#// C# program to see if there// is a root to leaf path // with given sequence. using System; public class CheckForPath { // function to check given sequence // of root to leaf path exist // in tree or not. // index represents current element // in sequence of rooth to // leaf path public static bool existPath(Node root, int []arr, int index) { // If root is NULL, then there // must not be any element // in array. if(root == null) { return arr.Length == 0; } // If this node is a leaf and matches with last entry // of array. if((root.left == null && root.right == null) && (root.data == arr[index] && root.data == arr[arr.Length - 1])) { return true; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return (index < arr.Length && (root.data == arr[index] && (existPath(root.left,arr,index + 1) || existPath(root.right, arr, index + 1)))); } // Driver code public static void Main() { // arr[] is sequence of root to leaf path int []arr = {5, 8, 6, 7}; Node root=new Node(5); root.left=new Node(3); root.right=new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, 0)) { Console.Write(\"Path Exists\"); } else { Console.Write(\"Path does not Exist\"); } } } /* A binary tree node has data, pointer to left child and apointer to right child */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // This code is contributed Rajput-Ji Output:Path Exists\nTime complexity : O(n)This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 47183, "s": 47179, "text": "C++" }, { "code": null, "e": 47188, "s": 47183, "text": "Java" }, { "code": null, "e": 47196, "s": 47188, "text": "Python3" }, { "code": null, "e": 47199, "s": 47196, "text": "C#" }, { "code": "// C++ program to see if there is a root to leaf path// with given sequence.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */struct Node{ int data; struct Node* left, *right;}; /* utility that allocates a new node with thegiven data and NULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Util functionbool existPathUtil(struct Node *root, int arr[], int n, int index){ // If root is NULL or reached end of the array if(root == NULL or index==n) return false; // If current node is leaf if (root->left == NULL && root->right == NULL) { if((root->data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root->data == arr[index]) && (existPathUtil(root->left, arr, n, index+1) || existPathUtil(root->right, arr, n, index+1) ));} // Function to check given sequence of root to leaf path exist// in tree or not.// index represents current element in sequence of rooth to// leaf pathbool existPath(struct Node *root, int arr[], int n, int index){ if(!root) return (n==0); return existPathUtil(root, arr, n, 0);} // Driver function to run the caseint main(){ // arr[] --> sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); struct Node *root = newnode(5); root->left = newnode(3); root->right = newnode(8); root->left->left = newnode(2); root->left->right = newnode(4); root->left->left->left = newnode(1); root->right->left = newnode(6); root->right->left->right = newnode(7); existPath(root, arr, n, 0)? cout << \"Path Exists\" : cout << \"Path does not Exist\"; return 0;}", "e": 49341, "s": 47199, "text": null }, { "code": "// Java program to see if there is a root to leaf path// with given sequence.import java.io.*; class Node{ int data; Node left; Node right; Node(int data) { this.data = data; this.left = null; this.right = null; }} class GFG { // Util function static boolean existPathUtil(Node root, int arr[], int n, int index) { // If root is NULL or // reached end of the array if(root == null || index==n) return false; // If current node is leaf if (root.left == null && root.right == null) { if((root.data == arr[index]) && (index == n-1)) return true; return false; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return ((index < n) && (root.data == arr[index]) && (existPathUtil(root.left, arr, n, index+1) || existPathUtil(root.right, arr, n, index+1) )); } // Function to check given sequence of root // to leaf path exist in tree or not. // index : current element in sequence of root to // leaf path static boolean existPath(Node root, int arr[], int n, int index) { if(root == null) return (n==0); return existPathUtil(root, arr, n, 0); } public static void main (String[] args) { // arr[] : sequence of root to leaf path int arr[] = {5, 8, 6, 7}; int n = arr.length; Node root = new Node(5); root.left = new Node(3); root.right = new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, n, 0)) System.out.println(\"Path Exists\"); else System.out.println(\"Path does not Exist\"); }}", "e": 51525, "s": 49341, "text": null }, { "code": "# Python program to see if# there is a root to leaf path# with given sequence # Class of Nodeclass Node: # Constructor to create a # node in Binary Tree def __init__(self, val): self.val = val self.left = None self.right = None # Util function def existPathUtil(root, arr, n, index): # If root is NULL or reached # end of the array if not root or index == n: return False # If current node is leaf if not root.left and not root.right: if root.val == arr[index] and index == n-1: return True return False # If current node is equal to arr[index] this means # that till this level path has been matched and # remaining path can be either in left subtree or # right subtree. return ((index < n) and (root.val == arr[index]) and \\ (existPathUtil(root.left, arr, n, index+1) or \\ existPathUtil(root.right, arr, n, index+1))) # Function to check given sequence of root to leaf path exist# in tree or not.# index represents current element in sequence of rooth to# leaf path def existPath(root, arr, n, index): if not root: return (n == 0) return existPathUtil(root, arr, n, 0) # Driver Codeif __name__ == \"__main__\": arr = [5, 8, 6, 7] n = len(arr) root = Node(5) root.left = Node(3) root.right = Node(8) root.left.left = Node(2) root.left.right = Node(4) root.left.left.left = Node(1) root.right.left = Node(6) root.right.left.right = Node(7) if existPath(root, arr, n, 0): print(\"Path Exists\") else: print(\"Path does not Exist\")", "e": 53184, "s": 51525, "text": null }, { "code": "// C# program to see if there// is a root to leaf path // with given sequence. using System; public class CheckForPath { // function to check given sequence // of root to leaf path exist // in tree or not. // index represents current element // in sequence of rooth to // leaf path public static bool existPath(Node root, int []arr, int index) { // If root is NULL, then there // must not be any element // in array. if(root == null) { return arr.Length == 0; } // If this node is a leaf and matches with last entry // of array. if((root.left == null && root.right == null) && (root.data == arr[index] && root.data == arr[arr.Length - 1])) { return true; } // If current node is equal to arr[index] this means // that till this level path has been matched and // remaining path can be either in left subtree or // right subtree. return (index < arr.Length && (root.data == arr[index] && (existPath(root.left,arr,index + 1) || existPath(root.right, arr, index + 1)))); } // Driver code public static void Main() { // arr[] is sequence of root to leaf path int []arr = {5, 8, 6, 7}; Node root=new Node(5); root.left=new Node(3); root.right=new Node(8); root.left.left = new Node(2); root.left.right = new Node(4); root.left.left.left = new Node(1); root.right.left = new Node(6); root.right.left.right = new Node(7); if(existPath(root, arr, 0)) { Console.Write(\"Path Exists\"); } else { Console.Write(\"Path does not Exist\"); } } } /* A binary tree node has data, pointer to left child and apointer to right child */public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // This code is contributed Rajput-Ji ", "e": 55373, "s": 53184, "text": null }, { "code": null, "e": 55386, "s": 55373, "text": "Path Exists\n" }, { "code": null, "e": 55409, "s": 55386, "text": "Time complexity : O(n)" }, { "code": null, "e": 55722, "s": 55409, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 55847, "s": 55722, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 55862, "s": 55847, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 55878, "s": 55862, "text": "PranchalKatiyar" }, { "code": null, "e": 55888, "s": 55878, "text": "Rajput-Ji" }, { "code": null, "e": 55902, "s": 55888, "text": "somaniketan74" }, { "code": null, "e": 55907, "s": 55902, "text": "Tree" }, { "code": null, "e": 55912, "s": 55907, "text": "Tree" }, { "code": null, "e": 56010, "s": 55912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 56060, "s": 56010, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 56095, "s": 56060, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 56124, "s": 56095, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 56158, "s": 56124, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 56201, "s": 56158, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 56242, "s": 56201, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 56304, "s": 56242, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 56337, "s": 56304, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 56351, "s": 56337, "text": "Decision Tree" } ]
C program to find the length of a string - GeeksforGeeks
24 Dec, 2021 Given a string str. The task is to find the length of the string. Examples: Input: str = "Geeks" Output: Length of Str is : 5 Input: str = "GeeksforGeeks" Output: Length of Str is : 13 In the below program, to find the length of the string str, first the string is taken as input from the user using scanf in , and then the length of Str is calculated using and using method .Below is the C program to find the length of the string.Example 1: Using loop to calculate the length of string. C // C program to find the length of string#include <stdio.h>#include <string.h> int main(){ char Str[1000]; int i; printf("Enter the String: "); scanf("%s", Str); for (i = 0; Str[i] != '\0'; ++i); printf("Length of Str is %d", i); return 0;} Enter the String: Geeks Length of Str is 5 Example 2: Using strlen() to find the length of the string. C // C program to find the length of// string using strlen function#include <stdio.h>#include <string.h> int main(){ char Str[1000]; int i; printf("Enter the String: "); scanf("%s", Str); printf("Length of Str is %ld", strlen(Str)); return 0;} Enter the String: Geeks Length of Str is 5 lokeshramdondapati C-String-Question school-programming C Language C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ rand() and srand() in C/C++ fork() in C std::string class in C++ Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25786, "s": 25758, "text": "\n24 Dec, 2021" }, { "code": null, "e": 25853, "s": 25786, "text": "Given a string str. The task is to find the length of the string. " }, { "code": null, "e": 25865, "s": 25853, "text": "Examples: " }, { "code": null, "e": 25975, "s": 25865, "text": "Input: str = \"Geeks\"\nOutput: Length of Str is : 5\n\nInput: str = \"GeeksforGeeks\"\nOutput: Length of Str is : 13" }, { "code": null, "e": 26282, "s": 25977, "text": "In the below program, to find the length of the string str, first the string is taken as input from the user using scanf in , and then the length of Str is calculated using and using method .Below is the C program to find the length of the string.Example 1: Using loop to calculate the length of string. " }, { "code": null, "e": 26284, "s": 26282, "text": "C" }, { "code": "// C program to find the length of string#include <stdio.h>#include <string.h> int main(){ char Str[1000]; int i; printf(\"Enter the String: \"); scanf(\"%s\", Str); for (i = 0; Str[i] != '\\0'; ++i); printf(\"Length of Str is %d\", i); return 0;}", "e": 26550, "s": 26284, "text": null }, { "code": null, "e": 26593, "s": 26550, "text": "Enter the String: Geeks\nLength of Str is 5" }, { "code": null, "e": 26656, "s": 26595, "text": "Example 2: Using strlen() to find the length of the string. " }, { "code": null, "e": 26658, "s": 26656, "text": "C" }, { "code": "// C program to find the length of// string using strlen function#include <stdio.h>#include <string.h> int main(){ char Str[1000]; int i; printf(\"Enter the String: \"); scanf(\"%s\", Str); printf(\"Length of Str is %ld\", strlen(Str)); return 0;}", "e": 26921, "s": 26658, "text": null }, { "code": null, "e": 26964, "s": 26921, "text": "Enter the String: Geeks\nLength of Str is 5" }, { "code": null, "e": 26985, "s": 26966, "text": "lokeshramdondapati" }, { "code": null, "e": 27003, "s": 26985, "text": "C-String-Question" }, { "code": null, "e": 27022, "s": 27003, "text": "school-programming" }, { "code": null, "e": 27033, "s": 27022, "text": "C Language" }, { "code": null, "e": 27044, "s": 27033, "text": "C Programs" }, { "code": null, "e": 27063, "s": 27044, "text": "School Programming" }, { "code": null, "e": 27161, "s": 27063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27183, "s": 27161, "text": "Function Pointer in C" }, { "code": null, "e": 27200, "s": 27183, "text": "Substring in C++" }, { "code": null, "e": 27228, "s": 27200, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27240, "s": 27228, "text": "fork() in C" }, { "code": null, "e": 27265, "s": 27240, "text": "std::string class in C++" }, { "code": null, "e": 27278, "s": 27265, "text": "Strings in C" }, { "code": null, "e": 27319, "s": 27278, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27360, "s": 27319, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27395, "s": 27360, "text": "Header files in C/C++ and its uses" } ]
How to Implement MultiSelect DropDown in Android? - GeeksforGeeks
30 Jan, 2022 In this article, we are going to see how we can make a MultiSelect DropDown in android studio and will select multiple items from a dropdown list. Advantages of MultiSelect DropDown. It is a good replacement for list boxes as it uses less space does the same work as a list box and gives a good look to UI. Dropdown lists are familiar selection mechanisms for most users since they are widely used both on the web and in android apps. User can select more than one item which he/she likes. In this article, we will be using a TextView, and we will set an onClickListener on that TextView so that whenever the user clicks on it dropdown list occurs. In the dropdown list, we will provide a feature to select multiple items, clear selected items, and a Button for canceling the selection process. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article. Step 1: Creating a new project Open a new project. We will be working on Empty Activity with language as Java. Leave all other options unchanged. You can change the name of the project at your convenience. There will be two default files named activity_main.xml and MainActivity.java. If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? Step 2: Working on activity_main.xml file Here we will design the user interface of our application. We will be using the following components for their respective works: TextView: To allow users to click on it so that a dropdown list can appear and display the selected items in it. Drop-down arrow: to indicate to the user that some action will be completed after clicking it. Use the following code in the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><!-- Relative layout as parent layout--><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <!-- text view to display selected items--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@android:drawable/editbox_background" android:drawableRight="@android:drawable/arrow_down_float" android:drawablePadding="16dp" android:hint="Select Language" android:padding="12dp" /> </RelativeLayout> After executing the above code design of the activity_main.xml file looks like this. Step 3: Working with MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.TextView; import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.Collections; public class MainActivity extends AppCompatActivity { // initialize variables TextView textView; boolean[] selectedLanguage; ArrayList<Integer> langList = new ArrayList<>(); String[] langArray = {"Java", "C++", "Kotlin", "C", "Python", "Javascript"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable textView = findViewById(R.id.textView); // initialize selected language array selectedLanguage = new boolean[langArray.length]; textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Initialize alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // set title builder.setTitle("Select Language"); // set dialog non cancelable builder.setCancelable(false); builder.setMultiChoiceItems(langArray, selectedLanguage, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { // check condition if (b) { // when checkbox selected // Add position in lang list langList.add(i); // Sort array list Collections.sort(langList); } else { // when checkbox unselected // Remove position from langList langList.remove(Integer.valueOf(i)); } } }); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Initialize string builder StringBuilder stringBuilder = new StringBuilder(); // use for loop for (int j = 0; j < langList.size(); j++) { // concat array value stringBuilder.append(langArray[langList.get(j)]); // check condition if (j != langList.size() - 1) { // When j value not equal // to lang list size - 1 // add comma stringBuilder.append(", "); } } // set text on textView textView.setText(stringBuilder.toString()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // dismiss dialog dialogInterface.dismiss(); } }); builder.setNeutralButton("Clear All", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // use for loop for (int j = 0; j < selectedLanguage.length; j++) { // remove all selection selectedLanguage[j] = false; // clear language list langList.clear(); // clear text view value textView.setText(""); } } }); // show dialog builder.show(); } }); }} Output: yashvirmalu Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n30 Jan, 2022" }, { "code": null, "e": 26564, "s": 26381, "text": "In this article, we are going to see how we can make a MultiSelect DropDown in android studio and will select multiple items from a dropdown list. Advantages of MultiSelect DropDown." }, { "code": null, "e": 26688, "s": 26564, "text": "It is a good replacement for list boxes as it uses less space does the same work as a list box and gives a good look to UI." }, { "code": null, "e": 26816, "s": 26688, "text": "Dropdown lists are familiar selection mechanisms for most users since they are widely used both on the web and in android apps." }, { "code": null, "e": 26871, "s": 26816, "text": "User can select more than one item which he/she likes." }, { "code": null, "e": 27342, "s": 26871, "text": "In this article, we will be using a TextView, and we will set an onClickListener on that TextView so that whenever the user clicks on it dropdown list occurs. In the dropdown list, we will provide a feature to select multiple items, clear selected items, and a Button for canceling the selection process. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 27373, "s": 27342, "text": "Step 1: Creating a new project" }, { "code": null, "e": 27393, "s": 27373, "text": "Open a new project." }, { "code": null, "e": 27488, "s": 27393, "text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged." }, { "code": null, "e": 27548, "s": 27488, "text": "You can change the name of the project at your convenience." }, { "code": null, "e": 27627, "s": 27548, "text": "There will be two default files named activity_main.xml and MainActivity.java." }, { "code": null, "e": 27767, "s": 27627, "text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? " }, { "code": null, "e": 27809, "s": 27767, "text": "Step 2: Working on activity_main.xml file" }, { "code": null, "e": 27938, "s": 27809, "text": "Here we will design the user interface of our application. We will be using the following components for their respective works:" }, { "code": null, "e": 28051, "s": 27938, "text": "TextView: To allow users to click on it so that a dropdown list can appear and display the selected items in it." }, { "code": null, "e": 28146, "s": 28051, "text": "Drop-down arrow: to indicate to the user that some action will be completed after clicking it." }, { "code": null, "e": 28200, "s": 28146, "text": "Use the following code in the activity_main.xml file." }, { "code": null, "e": 28204, "s": 28200, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- Relative layout as parent layout--><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <!-- text view to display selected items--> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:background=\"@android:drawable/editbox_background\" android:drawableRight=\"@android:drawable/arrow_down_float\" android:drawablePadding=\"16dp\" android:hint=\"Select Language\" android:padding=\"12dp\" /> </RelativeLayout>", "e": 29037, "s": 28204, "text": null }, { "code": null, "e": 29122, "s": 29037, "text": "After executing the above code design of the activity_main.xml file looks like this." }, { "code": null, "e": 29166, "s": 29122, "text": "Step 3: Working with MainActivity.java file" }, { "code": null, "e": 29356, "s": 29166, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 29361, "s": 29356, "text": "Java" }, { "code": "import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.TextView; import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.Collections; public class MainActivity extends AppCompatActivity { // initialize variables TextView textView; boolean[] selectedLanguage; ArrayList<Integer> langList = new ArrayList<>(); String[] langArray = {\"Java\", \"C++\", \"Kotlin\", \"C\", \"Python\", \"Javascript\"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable textView = findViewById(R.id.textView); // initialize selected language array selectedLanguage = new boolean[langArray.length]; textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Initialize alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // set title builder.setTitle(\"Select Language\"); // set dialog non cancelable builder.setCancelable(false); builder.setMultiChoiceItems(langArray, selectedLanguage, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { // check condition if (b) { // when checkbox selected // Add position in lang list langList.add(i); // Sort array list Collections.sort(langList); } else { // when checkbox unselected // Remove position from langList langList.remove(Integer.valueOf(i)); } } }); builder.setPositiveButton(\"OK\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Initialize string builder StringBuilder stringBuilder = new StringBuilder(); // use for loop for (int j = 0; j < langList.size(); j++) { // concat array value stringBuilder.append(langArray[langList.get(j)]); // check condition if (j != langList.size() - 1) { // When j value not equal // to lang list size - 1 // add comma stringBuilder.append(\", \"); } } // set text on textView textView.setText(stringBuilder.toString()); } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // dismiss dialog dialogInterface.dismiss(); } }); builder.setNeutralButton(\"Clear All\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // use for loop for (int j = 0; j < selectedLanguage.length; j++) { // remove all selection selectedLanguage[j] = false; // clear language list langList.clear(); // clear text view value textView.setText(\"\"); } } }); // show dialog builder.show(); } }); }}", "e": 33748, "s": 29361, "text": null }, { "code": null, "e": 33756, "s": 33748, "text": "Output:" }, { "code": null, "e": 33768, "s": 33756, "text": "yashvirmalu" }, { "code": null, "e": 33776, "s": 33768, "text": "Android" }, { "code": null, "e": 33781, "s": 33776, "text": "Java" }, { "code": null, "e": 33786, "s": 33781, "text": "Java" }, { "code": null, "e": 33794, "s": 33786, "text": "Android" }, { "code": null, "e": 33892, "s": 33794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33930, "s": 33892, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 33969, "s": 33930, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34019, "s": 33969, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34070, "s": 34019, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 34112, "s": 34070, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34127, "s": 34112, "text": "Arrays in Java" }, { "code": null, "e": 34171, "s": 34127, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34193, "s": 34171, "text": "For-each loop in Java" }, { "code": null, "e": 34244, "s": 34193, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
DMin and DMax Functions MS Access - GeeksforGeeks
15 Sep, 2020 1.DMin() Function : DMin() Function in MS Access is used to determine the minimum values in a specified set of records (a domain). The DMin functions return the minimum values that satisfy the criteria. If expression identifies numeric data, the DMin functions return numeric values. If expression identifies string data, they return the string that is first alphabetically. The difference between DMin and Min is that in DMin function, values are evaluated before the data is grouped and in the case of Min function, the data is grouped before values in the field expression are evaluated. Syntax : DMin ( expr , domain , criteria) Parameters : This method accepts three-parameter as mentioned above and described below : expr – It identifies the field for which we want to find the minimum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. domain – It identifies the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter. criteria – It identifies a string expression used to restrict the range of data on which the DMin function is performed. It is optional. It is the WHERE clause to apply to the domain. Returns : It returns minimum values in a specified set of records. Table -ProcuctDetails. Example-1 :Finding the minimum product price Select DMin("Product_Price", "ProcuctDetails") as Min_Price; Output : Example-2 :Finding the minimum product price for a given condition where the product id is 104. Select DMin("Product_Price", "ProcuctDetails","Product_Id = 104") as Min_Price; Output : 2.DMax() Function – DMax() Function in MS Access is used to determine the maximum values in a specified set of records (a domain). The DMax functions return the maximum values that satisfy the criteria. If expr identifies numeric data, the DMax functions return numeric values. If expr identifies string data, they return the string that is last alphabetically. The difference between DMax and Max is that in DMax function, values are evaluated before the data is grouped and in the case of Max function, the data is grouped before values in the field expression are evaluated. Syntax – DMax( expr , domain , criteria) Parameters : This method accepts three-parameter as mentioned above and described below : expr – It identifies the field for which we want to find the maximum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. domain – It identifies the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter. criteria – It identifies a string expression used to restrict the range of data on which the DMax function is performed. It is optional. It is the WHERE clause to apply to the domain. Returns : It returns maximum values in a specified set of records. Table -ProcuctDetails. Example-1 :Finding the maximum product price. Select DMax("Product_Price", "ProcuctDetails") as Max_Price; Output : Example-2 :Finding the maximum product price for a given condition where the product id is 103. Select DMax("Product_Price", "ProcuctDetails","Product_Id = 103") as Max_Price; Output : DBMS-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": "\n15 Sep, 2020" }, { "code": null, "e": 25533, "s": 25513, "text": "1.DMin() Function :" }, { "code": null, "e": 26104, "s": 25533, "text": "DMin() Function in MS Access is used to determine the minimum values in a specified set of records (a domain). The DMin functions return the minimum values that satisfy the criteria. If expression identifies numeric data, the DMin functions return numeric values. If expression identifies string data, they return the string that is first alphabetically. The difference between DMin and Min is that in DMin function, values are evaluated before the data is grouped and in the case of Min function, the data is grouped before values in the field expression are evaluated." }, { "code": null, "e": 26146, "s": 26104, "text": "Syntax : DMin ( expr , domain , criteria)" }, { "code": null, "e": 26160, "s": 26146, "text": "Parameters : " }, { "code": null, "e": 26237, "s": 26160, "text": "This method accepts three-parameter as mentioned above and described below :" }, { "code": null, "e": 26462, "s": 26237, "text": "expr – It identifies the field for which we want to find the minimum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field." }, { "code": null, "e": 26619, "s": 26462, "text": "domain – It identifies the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter." }, { "code": null, "e": 26804, "s": 26619, "text": "criteria – It identifies a string expression used to restrict the range of data on which the DMin function is performed. It is optional. It is the WHERE clause to apply to the domain." }, { "code": null, "e": 26815, "s": 26804, "text": "Returns : " }, { "code": null, "e": 26872, "s": 26815, "text": "It returns minimum values in a specified set of records." }, { "code": null, "e": 26895, "s": 26872, "text": "Table -ProcuctDetails." }, { "code": null, "e": 26940, "s": 26895, "text": "Example-1 :Finding the minimum product price" }, { "code": null, "e": 27002, "s": 26940, "text": "Select DMin(\"Product_Price\", \"ProcuctDetails\") as Min_Price;\n" }, { "code": null, "e": 27011, "s": 27002, "text": "Output :" }, { "code": null, "e": 27107, "s": 27011, "text": "Example-2 :Finding the minimum product price for a given condition where the product id is 104." }, { "code": null, "e": 27189, "s": 27107, "text": "Select DMin(\"Product_Price\", \"ProcuctDetails\",\"Product_Id = 104\") as Min_Price;\n" }, { "code": null, "e": 27198, "s": 27189, "text": "Output :" }, { "code": null, "e": 27218, "s": 27198, "text": "2.DMax() Function –" }, { "code": null, "e": 27776, "s": 27218, "text": "DMax() Function in MS Access is used to determine the maximum values in a specified set of records (a domain). The DMax functions return the maximum values that satisfy the criteria. If expr identifies numeric data, the DMax functions return numeric values. If expr identifies string data, they return the string that is last alphabetically. The difference between DMax and Max is that in DMax function, values are evaluated before the data is grouped and in the case of Max function, the data is grouped before values in the field expression are evaluated." }, { "code": null, "e": 27785, "s": 27776, "text": "Syntax –" }, { "code": null, "e": 27817, "s": 27785, "text": "DMax( expr , domain , criteria)" }, { "code": null, "e": 27831, "s": 27817, "text": "Parameters : " }, { "code": null, "e": 27908, "s": 27831, "text": "This method accepts three-parameter as mentioned above and described below :" }, { "code": null, "e": 28134, "s": 27908, "text": "expr – It identifies the field for which we want to find the maximum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field." }, { "code": null, "e": 28291, "s": 28134, "text": "domain – It identifies the set of records that constitutes the domain. It can be a table name or a query name for a query that does not require a parameter." }, { "code": null, "e": 28476, "s": 28291, "text": "criteria – It identifies a string expression used to restrict the range of data on which the DMax function is performed. It is optional. It is the WHERE clause to apply to the domain." }, { "code": null, "e": 28486, "s": 28476, "text": "Returns :" }, { "code": null, "e": 28543, "s": 28486, "text": "It returns maximum values in a specified set of records." }, { "code": null, "e": 28566, "s": 28543, "text": "Table -ProcuctDetails." }, { "code": null, "e": 28612, "s": 28566, "text": "Example-1 :Finding the maximum product price." }, { "code": null, "e": 28674, "s": 28612, "text": "Select DMax(\"Product_Price\", \"ProcuctDetails\") as Max_Price;\n" }, { "code": null, "e": 28683, "s": 28674, "text": "Output :" }, { "code": null, "e": 28779, "s": 28683, "text": "Example-2 :Finding the maximum product price for a given condition where the product id is 103." }, { "code": null, "e": 28861, "s": 28779, "text": "Select DMax(\"Product_Price\", \"ProcuctDetails\",\"Product_Id = 103\") as Max_Price;\n" }, { "code": null, "e": 28870, "s": 28861, "text": "Output :" }, { "code": null, "e": 28879, "s": 28870, "text": "DBMS-SQL" }, { "code": null, "e": 28883, "s": 28879, "text": "SQL" }, { "code": null, "e": 28887, "s": 28883, "text": "SQL" }, { "code": null, "e": 28985, "s": 28887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29051, "s": 28985, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 29066, "s": 29051, "text": "SQL | Subquery" }, { "code": null, "e": 29123, "s": 29066, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29155, "s": 29123, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29233, "s": 29155, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 29269, "s": 29233, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 29286, "s": 29269, "text": "SQL using Python" }, { "code": null, "e": 29352, "s": 29286, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 29414, "s": 29352, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
sciPy stats.cumfreq() function | Python - GeeksforGeeks
15 Jan, 2022 scipy.stats.cumfreq(a, numbins, defaultreallimits, weights) works using the histogram function and calculates the cumulative frequency histogram. It includes cumulative frequency binned values, width of each bin, lower real limit, extra points. Parameters : arr : [array_like] input array. numbins : [int] number of bins to use for the histogram. [Default = 10] defaultlimits : (lower, upper) range of the histogram. weights : [array_like] weights for each array element. Results : – cumulative frequency binned values – width of each bin – lower real limit – extra points. Code #1: Python3 # cumulative frequencyfrom scipy import statsimport numpy as np arr1 = [1, 3, 27, 2, 5, 13] print ("Array element : ", arr1, "\n") a, b, c, d = stats.cumfreq(arr1, numbins = 4) print ("cumulative frequency : ", a)print ("Lower Limit : ", b)print ("bin size : ", c)print ("extra-points : ", d) Array element : [1, 3, 27, 2, 5, 13] cumulative frequency : [ 4. 5. 5. 6.] Lower Limit : -3.33333333333 bin size : 8.66666666667 extra-points : 0 Code #2: Python3 # cumulative frequencyfrom scipy import statsimport numpy as np arr1 = [1, 3, 27, 2, 5, 13] print ("Array element : ", arr1, "\n") a, b, c, d = stats.cumfreq(arr1, numbins = 4, weights = [.1, .2, .1, .3, 1, 6]) print ("cumfreqs : ", a)print ("lowlim : ", b)print ("binsize : ", c)print ("extrapoints : ", d) Array element : [1, 3, 27, 2, 5, 13] cumfreqs : [ 1.6 7.6 7.6 7.7] lowlim : -3.33333333333 binsize : 8.66666666667 extrapoints : 0 surindertarika1234 ruhelaa48 Python scipy-stats-functions Python-scipy 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 Jan, 2022" }, { "code": null, "e": 25783, "s": 25537, "text": "scipy.stats.cumfreq(a, numbins, defaultreallimits, weights) works using the histogram function and calculates the cumulative frequency histogram. It includes cumulative frequency binned values, width of each bin, lower real limit, extra points. " }, { "code": null, "e": 26113, "s": 25783, "text": "Parameters : arr : [array_like] input array. numbins : [int] number of bins to use for the histogram. [Default = 10] defaultlimits : (lower, upper) range of the histogram. weights : [array_like] weights for each array element. Results : – cumulative frequency binned values – width of each bin – lower real limit – extra points. " }, { "code": null, "e": 26123, "s": 26113, "text": "Code #1: " }, { "code": null, "e": 26131, "s": 26123, "text": "Python3" }, { "code": "# cumulative frequencyfrom scipy import statsimport numpy as np arr1 = [1, 3, 27, 2, 5, 13] print (\"Array element : \", arr1, \"\\n\") a, b, c, d = stats.cumfreq(arr1, numbins = 4) print (\"cumulative frequency : \", a)print (\"Lower Limit : \", b)print (\"bin size : \", c)print (\"extra-points : \", d)", "e": 26431, "s": 26131, "text": null }, { "code": null, "e": 26587, "s": 26431, "text": "Array element : [1, 3, 27, 2, 5, 13] \n\ncumulative frequency : [ 4. 5. 5. 6.]\nLower Limit : -3.33333333333\nbin size : 8.66666666667\nextra-points : 0" }, { "code": null, "e": 26599, "s": 26589, "text": "Code #2: " }, { "code": null, "e": 26607, "s": 26599, "text": "Python3" }, { "code": "# cumulative frequencyfrom scipy import statsimport numpy as np arr1 = [1, 3, 27, 2, 5, 13] print (\"Array element : \", arr1, \"\\n\") a, b, c, d = stats.cumfreq(arr1, numbins = 4, weights = [.1, .2, .1, .3, 1, 6]) print (\"cumfreqs : \", a)print (\"lowlim : \", b)print (\"binsize : \", c)print (\"extrapoints : \", d)", "e": 26935, "s": 26607, "text": null }, { "code": null, "e": 27076, "s": 26935, "text": "Array element : [1, 3, 27, 2, 5, 13] \n\ncumfreqs : [ 1.6 7.6 7.6 7.7]\nlowlim : -3.33333333333\nbinsize : 8.66666666667\nextrapoints : 0" }, { "code": null, "e": 27097, "s": 27078, "text": "surindertarika1234" }, { "code": null, "e": 27107, "s": 27097, "text": "ruhelaa48" }, { "code": null, "e": 27136, "s": 27107, "text": "Python scipy-stats-functions" }, { "code": null, "e": 27149, "s": 27136, "text": "Python-scipy" }, { "code": null, "e": 27156, "s": 27149, "text": "Python" }, { "code": null, "e": 27254, "s": 27156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27286, "s": 27254, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27328, "s": 27286, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27370, "s": 27328, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27397, "s": 27370, "text": "Python Classes and Objects" }, { "code": null, "e": 27453, "s": 27397, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27492, "s": 27453, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27514, "s": 27492, "text": "Defaultdict in Python" }, { "code": null, "e": 27545, "s": 27514, "text": "Python | os.path.join() method" }, { "code": null, "e": 27574, "s": 27545, "text": "Create a directory in Python" } ]
Seaborn | Style And Color - GeeksforGeeks
29 Jan, 2021 Seaborn is a statistical plotting library in python. It has beautiful default styles. This article deals with the ways of styling the different kinds of plots in seaborn. This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. The ways of styling themes are as follows: white dark whitegrid darkgrid ticks Set the background to be white: Given style with the help of countplot and the dataset is present in seaborn by default. load_dataset() function is used to load the dataset. set_style() function is used for plot styling. Python3 import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('white') # make a countplotsns.countplot(x ='sex', data = tips) Output: Set the background to ticks: Ticks appear on the sides of the plot on setting it as set_style(‘ticks’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_style('ticks')sns.countplot(x ='sex', data = tips, palette = 'deep') Output: Set the background to be darkgrid: Darkgrid appear on the sides of the plot on setting it as set_style(‘darkgrid’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data. Python3 import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('darkgrid') # make a countplotsns.countplot(x ='sex', data = tips) Output: Set the background to be Whitegrid: Whitegrid appears on the sides of the plot on setting it as set_style(‘whitegrid’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data. Python3 import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('whitegrid') # make a countplotsns.countplot(x ='sex', data = tips) Output: The despine() is a function that removes the spines from the right and upper portion of the plot by default. sns.despine(left = True) helps remove the spine from the left. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.countplot(x ='sex', data = tips)sns.despine() Output Non grid plot: The figure() is a matplotlib function used to plot the figures. The figsize is used to set the size of the figure. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')plt.figure(figsize =(12, 3))sns.countplot(x ='sex', data = tips) Output: Grid type plot: This example shows a regression plot of tips vs the total_bill from the dataset. lmplot stands for linear model plot and is used to create a regression plot. x =’total_bill’ sets the x axis to total_bill. y=’tip’ sets the y axis to tips. size=2 is used to the size(the height)of the plot. aspect is used to set the width keeping the width constant. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.lmplot(x ='total_bill', y ='tip', size = 2, aspect = 4, data = tips) Output: The set_context() allows us to override default parameters. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The context are: poster paper notebook talk Example 1: using poster. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('poster', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm') Output: Example 2: Using paper. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('paper', font_scale = 2)sns.countplot(x ='sex', data = tips, palette = 'coolwarm') Output: Example 3: Using notebook. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('notebook', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm') Output: Example 4: Using talk. Python3 import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('talk', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm') Output: kumar_satyam Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Naive Bayes Classifiers Linear Regression (Python Implementation) ML | Linear Regression Reinforcement learning Removing stop words with NLTK in Python 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": 27981, "s": 27953, "text": "\n29 Jan, 2021" }, { "code": null, "e": 28153, "s": 27981, "text": "Seaborn is a statistical plotting library in python. It has beautiful default styles. This article deals with the ways of styling the different kinds of plots in seaborn. " }, { "code": null, "e": 28269, "s": 28153, "text": "This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements." }, { "code": null, "e": 28312, "s": 28269, "text": "The ways of styling themes are as follows:" }, { "code": null, "e": 28318, "s": 28312, "text": "white" }, { "code": null, "e": 28323, "s": 28318, "text": "dark" }, { "code": null, "e": 28333, "s": 28323, "text": "whitegrid" }, { "code": null, "e": 28342, "s": 28333, "text": "darkgrid" }, { "code": null, "e": 28348, "s": 28342, "text": "ticks" }, { "code": null, "e": 28380, "s": 28348, "text": "Set the background to be white:" }, { "code": null, "e": 28569, "s": 28380, "text": "Given style with the help of countplot and the dataset is present in seaborn by default. load_dataset() function is used to load the dataset. set_style() function is used for plot styling." }, { "code": null, "e": 28577, "s": 28569, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('white') # make a countplotsns.countplot(x ='sex', data = tips)", "e": 28792, "s": 28577, "text": null }, { "code": null, "e": 28802, "s": 28792, "text": "Output: " }, { "code": null, "e": 28833, "s": 28804, "text": "Set the background to ticks:" }, { "code": null, "e": 29012, "s": 28833, "text": "Ticks appear on the sides of the plot on setting it as set_style(‘ticks’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data." }, { "code": null, "e": 29020, "s": 29012, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_style('ticks')sns.countplot(x ='sex', data = tips, palette = 'deep')", "e": 29182, "s": 29020, "text": null }, { "code": null, "e": 29190, "s": 29182, "text": "Output:" }, { "code": null, "e": 29225, "s": 29190, "text": "Set the background to be darkgrid:" }, { "code": null, "e": 29410, "s": 29225, "text": "Darkgrid appear on the sides of the plot on setting it as set_style(‘darkgrid’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data." }, { "code": null, "e": 29418, "s": 29410, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('darkgrid') # make a countplotsns.countplot(x ='sex', data = tips)", "e": 29636, "s": 29418, "text": null }, { "code": null, "e": 29644, "s": 29636, "text": "Output:" }, { "code": null, "e": 29680, "s": 29644, "text": "Set the background to be Whitegrid:" }, { "code": null, "e": 29868, "s": 29680, "text": "Whitegrid appears on the sides of the plot on setting it as set_style(‘whitegrid’). palette attribute is used to set the color of the bars. It helps to distinguish between chunks of data." }, { "code": null, "e": 29876, "s": 29868, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt # load the tips dataset present by default in seaborntips = sns.load_dataset('tips')sns.set_style('whitegrid') # make a countplotsns.countplot(x ='sex', data = tips)", "e": 30095, "s": 29876, "text": null }, { "code": null, "e": 30103, "s": 30095, "text": "Output:" }, { "code": null, "e": 30276, "s": 30103, "text": "The despine() is a function that removes the spines from the right and upper portion of the plot by default. sns.despine(left = True) helps remove the spine from the left. " }, { "code": null, "e": 30284, "s": 30276, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.countplot(x ='sex', data = tips)sns.despine()", "e": 30418, "s": 30284, "text": null }, { "code": null, "e": 30427, "s": 30418, "text": "Output " }, { "code": null, "e": 30559, "s": 30427, "text": "Non grid plot: The figure() is a matplotlib function used to plot the figures. The figsize is used to set the size of the figure. " }, { "code": null, "e": 30567, "s": 30559, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')plt.figure(figsize =(12, 3))sns.countplot(x ='sex', data = tips)", "e": 30716, "s": 30567, "text": null }, { "code": null, "e": 30726, "s": 30716, "text": "Output: " }, { "code": null, "e": 31092, "s": 30726, "text": "Grid type plot: This example shows a regression plot of tips vs the total_bill from the dataset. lmplot stands for linear model plot and is used to create a regression plot. x =’total_bill’ sets the x axis to total_bill. y=’tip’ sets the y axis to tips. size=2 is used to the size(the height)of the plot. aspect is used to set the width keeping the width constant. " }, { "code": null, "e": 31100, "s": 31092, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.lmplot(x ='total_bill', y ='tip', size = 2, aspect = 4, data = tips)", "e": 31257, "s": 31100, "text": null }, { "code": null, "e": 31267, "s": 31257, "text": "Output: " }, { "code": null, "e": 31443, "s": 31267, "text": "The set_context() allows us to override default parameters. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. " }, { "code": null, "e": 31460, "s": 31443, "text": "The context are:" }, { "code": null, "e": 31467, "s": 31460, "text": "poster" }, { "code": null, "e": 31473, "s": 31467, "text": "paper" }, { "code": null, "e": 31482, "s": 31473, "text": "notebook" }, { "code": null, "e": 31487, "s": 31482, "text": "talk" }, { "code": null, "e": 31512, "s": 31487, "text": "Example 1: using poster." }, { "code": null, "e": 31520, "s": 31512, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('poster', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm')", "e": 31703, "s": 31520, "text": null }, { "code": null, "e": 31712, "s": 31703, "text": "Output: " }, { "code": null, "e": 31736, "s": 31712, "text": "Example 2: Using paper." }, { "code": null, "e": 31744, "s": 31736, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('paper', font_scale = 2)sns.countplot(x ='sex', data = tips, palette = 'coolwarm')", "e": 31927, "s": 31744, "text": null }, { "code": null, "e": 31935, "s": 31927, "text": "Output:" }, { "code": null, "e": 31962, "s": 31935, "text": "Example 3: Using notebook." }, { "code": null, "e": 31970, "s": 31962, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('notebook', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm')", "e": 32155, "s": 31970, "text": null }, { "code": null, "e": 32163, "s": 32155, "text": "Output:" }, { "code": null, "e": 32186, "s": 32163, "text": "Example 4: Using talk." }, { "code": null, "e": 32194, "s": 32186, "text": "Python3" }, { "code": "import seaborn as snsimport matplotlib.pyplot as plt tips = sns.load_dataset('tips')sns.set_context('talk', font_scale = 2)sns.countplot(x ='sex', data = tips, palette ='coolwarm')", "e": 32375, "s": 32194, "text": null }, { "code": null, "e": 32383, "s": 32375, "text": "Output:" }, { "code": null, "e": 32398, "s": 32385, "text": "kumar_satyam" }, { "code": null, "e": 32415, "s": 32398, "text": "Machine Learning" }, { "code": null, "e": 32422, "s": 32415, "text": "Python" }, { "code": null, "e": 32439, "s": 32422, "text": "Machine Learning" }, { "code": null, "e": 32537, "s": 32439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32561, "s": 32537, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 32603, "s": 32561, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 32626, "s": 32603, "text": "ML | Linear Regression" }, { "code": null, "e": 32649, "s": 32626, "text": "Reinforcement learning" }, { "code": null, "e": 32689, "s": 32649, "text": "Removing stop words with NLTK in Python" }, { "code": null, "e": 32717, "s": 32689, "text": "Read JSON file using Python" }, { "code": null, "e": 32767, "s": 32717, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 32789, "s": 32767, "text": "Python map() function" } ]
Pointer Arithmetics in C with Examples - GeeksforGeeks
27 Jul, 2021 Pointers variables are also known as address data types because they are used to store the address of another variable. The address is the memory location that is assigned to the variable. It doesn’t store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The operations are slightly different from the ones that we generally use for mathematical calculations. The operations are: Increment/Decrement of a PointerAddition of integer to a pointerSubtraction of integer to a pointerSubtracting two pointers of the same type Increment/Decrement of a Pointer Addition of integer to a pointer Subtraction of integer to a pointer Subtracting two pointers of the same type Increment/Decrement of a Pointer Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004.Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an int) and the new address it will points to 998. While if a float type pointer is decremented then it will decrement by 4(size of a float) and the new address will be 996. Below is the program to illustrate pointer increment/decrement: C // C program to illustrate// pointer increment/decrement #include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores // the address of N ptr1 = &N; ptr2 = &N; printf("Pointer ptr1 " "before Increment: "); printf("%p \n", ptr1); // Incrementing pointer ptr1; ptr1++; printf("Pointer ptr1 after" " Increment: "); printf("%p \n\n", ptr1); printf("Pointer ptr1 before" " Decrement: "); printf("%p \n", ptr1); // Decrementing pointer ptr1; ptr1--; printf("Pointer ptr1 after" " Decrement: "); printf("%p \n\n", ptr1); return 0;} Pointer ptr1 before Increment: 0x7ffcb19385e4 Pointer ptr1 after Increment: 0x7ffcb19385e8 Pointer ptr1 before Decrement: 0x7ffcb19385e8 Pointer ptr1 after Decrement: 0x7ffcb19385e4 Addition When a pointer is added with a value, the value is first multiplied by the size of data type and then added to the pointer. C // C program to illustrate pointer Addition#include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; printf("Pointer ptr2 before Addition: "); printf("%p \n", ptr2); // Addition of 3 to ptr2 ptr2 = ptr2 + 3; printf("Pointer ptr2 after Addition: "); printf("%p \n", ptr2); return 0;} Pointer ptr2 before Addition: 0x7fffffdcd984 Pointer ptr2 after Addition: 0x7fffffdcd990 Subtraction When a pointer is subtracted with a value, the value is first multiplied by the size of the data type and then subtracted from the pointer. Below is the program to illustrate pointer Subtraction: C // C program to illustrate pointer Subtraction#include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; printf("Pointer ptr2 before Subtraction: "); printf("%p \n", ptr2); // Subtraction of 3 to ptr2 ptr2 = ptr2 - 3; printf("Pointer ptr2 after Subtraction: "); printf("%p \n", ptr2); return 0;} Pointer ptr2 before Subtraction: 0x7ffcf1221b24 Pointer ptr2 after Subtraction: 0x7ffcf1221b18 Subtraction of Two Pointers The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference between address is 16 bytes. Since the size of int is 2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8. Below is the implementation to illustrate the Subtraction of Two Pointers: C // C program to illustrate Subtraction// of two pointers#include <stdio.h> // Driver Codeint main(){ int x; // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; // Incrementing ptr2 by 3 ptr2 = ptr2 + 3; // Subtraction of ptr2 and ptr1 x = ptr2 - ptr1; // Print x to get the Increment // between ptr1 and ptr2 printf("Subtraction of ptr1 " "& ptr2 is %d\n", x); return 0;} Subtraction of ptr1 & ptr2 is 3 Pointer Arithmetic on Arrays: Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For Example: if an array named arr then arr and &arr[0] can be used to reference array as a pointer. Below is the program to illustrate the Pointer Arithmetic on arrays: Program 1: C // C program to illustrate the array// traversal using pointers#include <stdio.h> // Driver Codeint main(){ int N = 5; // An array int arr[] = { 1, 2, 3, 4, 5 }; // Declare pointer variable int* ptr; // Point the pointer to first // element in array arr[] ptr = arr; // Traverse array using ptr for (int i = 0; i < N; i++) { // Print element at which // ptr points printf("%d ", ptr[0]); ptr++; }} 1 2 3 4 5 Program 2: C // C program to illustrate the array// traversal using pointers in 2D array#include <stdio.h> // Function to traverse 2D array// using pointersvoid traverseArr(int* arr, int N, int M){ int i, j; // Traverse rows of 2D matrix for (i = 0; i < N; i++) { // Traverse columns of 2D matrix for (j = 0; j < M; j++) { // Print the element printf("%d ", *((arr + i * M) + j)); } printf("\n"); }} // Driver Codeint main(){ int N = 3, M = 2; // A 2D array int arr[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // Function Call traverseArr((int*)arr, N, M); return 0;} 1 2 3 4 5 6 surinderdawra388 simmytarika5 C-Advanced Pointer C-Pointer Basics C-Pointers Pointers C Language C Programs Pointers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25671, "s": 25643, "text": "\n27 Jul, 2021" }, { "code": null, "e": 25889, "s": 25671, "text": "Pointers variables are also known as address data types because they are used to store the address of another variable. The address is the memory location that is assigned to the variable. It doesn’t store any value. " }, { "code": null, "e": 26109, "s": 25889, "text": "Hence, there are only a few operations that are allowed to perform on Pointers in C language. The operations are slightly different from the ones that we generally use for mathematical calculations. The operations are: " }, { "code": null, "e": 26250, "s": 26109, "text": "Increment/Decrement of a PointerAddition of integer to a pointerSubtraction of integer to a pointerSubtracting two pointers of the same type" }, { "code": null, "e": 26283, "s": 26250, "text": "Increment/Decrement of a Pointer" }, { "code": null, "e": 26316, "s": 26283, "text": "Addition of integer to a pointer" }, { "code": null, "e": 26352, "s": 26316, "text": "Subtraction of integer to a pointer" }, { "code": null, "e": 26394, "s": 26352, "text": "Subtracting two pointers of the same type" }, { "code": null, "e": 26427, "s": 26394, "text": "Increment/Decrement of a Pointer" }, { "code": null, "e": 26619, "s": 26427, "text": "Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. " }, { "code": null, "e": 27101, "s": 26619, "text": "For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004.Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. " }, { "code": null, "e": 27387, "s": 27101, "text": "For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an int) and the new address it will points to 998. While if a float type pointer is decremented then it will decrement by 4(size of a float) and the new address will be 996." }, { "code": null, "e": 27452, "s": 27387, "text": "Below is the program to illustrate pointer increment/decrement: " }, { "code": null, "e": 27454, "s": 27452, "text": "C" }, { "code": "// C program to illustrate// pointer increment/decrement #include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores // the address of N ptr1 = &N; ptr2 = &N; printf(\"Pointer ptr1 \" \"before Increment: \"); printf(\"%p \\n\", ptr1); // Incrementing pointer ptr1; ptr1++; printf(\"Pointer ptr1 after\" \" Increment: \"); printf(\"%p \\n\\n\", ptr1); printf(\"Pointer ptr1 before\" \" Decrement: \"); printf(\"%p \\n\", ptr1); // Decrementing pointer ptr1; ptr1--; printf(\"Pointer ptr1 after\" \" Decrement: \"); printf(\"%p \\n\\n\", ptr1); return 0;}", "e": 28167, "s": 27454, "text": null }, { "code": null, "e": 28353, "s": 28167, "text": "Pointer ptr1 before Increment: 0x7ffcb19385e4 \nPointer ptr1 after Increment: 0x7ffcb19385e8 \n\nPointer ptr1 before Decrement: 0x7ffcb19385e8 \nPointer ptr1 after Decrement: 0x7ffcb19385e4" }, { "code": null, "e": 28364, "s": 28355, "text": "Addition" }, { "code": null, "e": 28488, "s": 28364, "text": "When a pointer is added with a value, the value is first multiplied by the size of data type and then added to the pointer." }, { "code": null, "e": 28490, "s": 28488, "text": "C" }, { "code": "// C program to illustrate pointer Addition#include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; printf(\"Pointer ptr2 before Addition: \"); printf(\"%p \\n\", ptr2); // Addition of 3 to ptr2 ptr2 = ptr2 + 3; printf(\"Pointer ptr2 after Addition: \"); printf(\"%p \\n\", ptr2); return 0;}", "e": 28938, "s": 28490, "text": null }, { "code": null, "e": 29028, "s": 28938, "text": "Pointer ptr2 before Addition: 0x7fffffdcd984 \nPointer ptr2 after Addition: 0x7fffffdcd990" }, { "code": null, "e": 29042, "s": 29030, "text": "Subtraction" }, { "code": null, "e": 29182, "s": 29042, "text": "When a pointer is subtracted with a value, the value is first multiplied by the size of the data type and then subtracted from the pointer." }, { "code": null, "e": 29238, "s": 29182, "text": "Below is the program to illustrate pointer Subtraction:" }, { "code": null, "e": 29240, "s": 29238, "text": "C" }, { "code": "// C program to illustrate pointer Subtraction#include <stdio.h> // Driver Codeint main(){ // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; printf(\"Pointer ptr2 before Subtraction: \"); printf(\"%p \\n\", ptr2); // Subtraction of 3 to ptr2 ptr2 = ptr2 - 3; printf(\"Pointer ptr2 after Subtraction: \"); printf(\"%p \\n\", ptr2); return 0;}", "e": 29700, "s": 29240, "text": null }, { "code": null, "e": 29796, "s": 29700, "text": "Pointer ptr2 before Subtraction: 0x7ffcf1221b24 \nPointer ptr2 after Subtraction: 0x7ffcf1221b18" }, { "code": null, "e": 29826, "s": 29798, "text": "Subtraction of Two Pointers" }, { "code": null, "e": 30166, "s": 29826, "text": "The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. " }, { "code": null, "e": 30410, "s": 30166, "text": "For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference between address is 16 bytes. Since the size of int is 2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8." }, { "code": null, "e": 30485, "s": 30410, "text": "Below is the implementation to illustrate the Subtraction of Two Pointers:" }, { "code": null, "e": 30487, "s": 30485, "text": "C" }, { "code": "// C program to illustrate Subtraction// of two pointers#include <stdio.h> // Driver Codeint main(){ int x; // Integer variable int N = 4; // Pointer to an integer int *ptr1, *ptr2; // Pointer stores the address of N ptr1 = &N; ptr2 = &N; // Incrementing ptr2 by 3 ptr2 = ptr2 + 3; // Subtraction of ptr2 and ptr1 x = ptr2 - ptr1; // Print x to get the Increment // between ptr1 and ptr2 printf(\"Subtraction of ptr1 \" \"& ptr2 is %d\\n\", x); return 0;}", "e": 31013, "s": 30487, "text": null }, { "code": null, "e": 31045, "s": 31013, "text": "Subtraction of ptr1 & ptr2 is 3" }, { "code": null, "e": 31488, "s": 31047, "text": "Pointer Arithmetic on Arrays: Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For Example: if an array named arr then arr and &arr[0] can be used to reference array as a pointer." }, { "code": null, "e": 31557, "s": 31488, "text": "Below is the program to illustrate the Pointer Arithmetic on arrays:" }, { "code": null, "e": 31569, "s": 31557, "text": "Program 1: " }, { "code": null, "e": 31571, "s": 31569, "text": "C" }, { "code": "// C program to illustrate the array// traversal using pointers#include <stdio.h> // Driver Codeint main(){ int N = 5; // An array int arr[] = { 1, 2, 3, 4, 5 }; // Declare pointer variable int* ptr; // Point the pointer to first // element in array arr[] ptr = arr; // Traverse array using ptr for (int i = 0; i < N; i++) { // Print element at which // ptr points printf(\"%d \", ptr[0]); ptr++; }}", "e": 32036, "s": 31571, "text": null }, { "code": null, "e": 32046, "s": 32036, "text": "1 2 3 4 5" }, { "code": null, "e": 32060, "s": 32048, "text": "Program 2: " }, { "code": null, "e": 32062, "s": 32060, "text": "C" }, { "code": "// C program to illustrate the array// traversal using pointers in 2D array#include <stdio.h> // Function to traverse 2D array// using pointersvoid traverseArr(int* arr, int N, int M){ int i, j; // Traverse rows of 2D matrix for (i = 0; i < N; i++) { // Traverse columns of 2D matrix for (j = 0; j < M; j++) { // Print the element printf(\"%d \", *((arr + i * M) + j)); } printf(\"\\n\"); }} // Driver Codeint main(){ int N = 3, M = 2; // A 2D array int arr[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // Function Call traverseArr((int*)arr, N, M); return 0;}", "e": 32757, "s": 32062, "text": null }, { "code": null, "e": 32771, "s": 32757, "text": "1 2 \n3 4 \n5 6" }, { "code": null, "e": 32790, "s": 32773, "text": "surinderdawra388" }, { "code": null, "e": 32803, "s": 32790, "text": "simmytarika5" }, { "code": null, "e": 32822, "s": 32803, "text": "C-Advanced Pointer" }, { "code": null, "e": 32839, "s": 32822, "text": "C-Pointer Basics" }, { "code": null, "e": 32850, "s": 32839, "text": "C-Pointers" }, { "code": null, "e": 32859, "s": 32850, "text": "Pointers" }, { "code": null, "e": 32870, "s": 32859, "text": "C Language" }, { "code": null, "e": 32881, "s": 32870, "text": "C Programs" }, { "code": null, "e": 32890, "s": 32881, "text": "Pointers" }, { "code": null, "e": 32988, "s": 32890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33023, "s": 32988, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 33069, "s": 33023, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33086, "s": 33069, "text": "Substring in C++" }, { "code": null, "e": 33126, "s": 33086, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 33154, "s": 33126, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 33167, "s": 33154, "text": "Strings in C" }, { "code": null, "e": 33208, "s": 33167, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33249, "s": 33208, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 33284, "s": 33249, "text": "Header files in C/C++ and its uses" } ]
Computing the Mean and Std of a Dataset in Pytorch - GeeksforGeeks
04 Jul, 2021 PyTorch provides various inbuilt mathematical utilities to monitor the descriptive statistics of a dataset at hand one of them being mean and standard deviation. Mean, denoted by, is one of the Measures of central tendencies which is calculated by finding the average of the given dataset. Standard Deviation, denoted by σ, is one of the measures of dispersion that signifies by how much are the values close to the mean. The formula for mean and standard deviation are as follows:- Installing PyTorch is the same as that of any other library in python. pip install torch Or if you want to install it in a conda environment you can use the following command:- conda install pytorch cudatoolkit=10.2 -c pytorch Before understanding how to find mean and standard deviation let’s ready our dataset by generating a random array. import torch data = torch.rand(10) Now that we have the data we can find the mean and standard deviation by calling mean() and std() methods. mean_tensor = data.mean() std_tensor = data.std() The above method works perfectly, but the values are returned as tensors, if you want to extract values inside that tensor you can either access it via index or you can call item() method. mean = data.mean().item() std = data.std().item() Example: Python3 import torch # Generate a tensor of 10 numbersdata = torch.rand(10) mean_tensor = data.mean()std_tensor = data.std() print(mean_tensor)print(std_tensor) mean = data.mean().item()std = data.std().item() print(mean)print(std) Output: tensor(0.3901) tensor(0.2846) 0.39005300402641296 0.2846093773841858 In 2-D Tensors mean is the same as that of the 1-D tensor except here we can pass an axis parameter to find the mean and std of the rows and columns. Let’s start by getting our data. import torch data = torch.rand(5,3) The mean() and std() methods when called as is will return the total standard deviation of the whole dataset, but if we pass an axis parameter we can find the mean and std of rows and columns. For axis = 0, we get a tensor having values of mean or std of each column. For axis = 1, we get a tensor having values of mean or std of each row. total_mean = data.mean() total_std = data.std() # Mean and STD of columns mean_col_wise = data.mean(axis = 0) std_col_wise = data.std(axis = 0) # Mean and STD of rows mean_row_wise = data.mean(axis = 1) std_row_wise = data.std(axis = 1) Example: Python3 import torch # Generate a tensor of shape (5,3)data = torch.rand(5,3) total_mean = data.mean()total_std = data.std() print(total_mean)print(total_std) # Mean and STD of columnsmean_col_wise = data.mean(axis = 0)std_col_wise = data.std(axis = 0) print(mean_col_wise)print(std_col_wise) # Mean and STD of rowsmean_row_wise = data.mean(axis = 1)std_row_wise = data.std(axis = 1) print(mean_row_wise)print(std_row_wise) Output: tensor(0.6483) tensor(0.2797) tensor([0.6783, 0.5986, 0.6679]) tensor([0.2548, 0.2711, 0.3614]) tensor([0.5315, 0.7770, 0.7785, 0.3403, 0.8142]) tensor([0.3749, 0.2340, 0.1397, 0.2432, 0.1386]) Picked Python-PyTorch 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n04 Jul, 2021" }, { "code": null, "e": 26020, "s": 25537, "text": "PyTorch provides various inbuilt mathematical utilities to monitor the descriptive statistics of a dataset at hand one of them being mean and standard deviation. Mean, denoted by, is one of the Measures of central tendencies which is calculated by finding the average of the given dataset. Standard Deviation, denoted by σ, is one of the measures of dispersion that signifies by how much are the values close to the mean. The formula for mean and standard deviation are as follows:-" }, { "code": null, "e": 26091, "s": 26020, "text": "Installing PyTorch is the same as that of any other library in python." }, { "code": null, "e": 26109, "s": 26091, "text": "pip install torch" }, { "code": null, "e": 26197, "s": 26109, "text": "Or if you want to install it in a conda environment you can use the following command:-" }, { "code": null, "e": 26247, "s": 26197, "text": "conda install pytorch cudatoolkit=10.2 -c pytorch" }, { "code": null, "e": 26362, "s": 26247, "text": "Before understanding how to find mean and standard deviation let’s ready our dataset by generating a random array." }, { "code": null, "e": 26397, "s": 26362, "text": "import torch\ndata = torch.rand(10)" }, { "code": null, "e": 26504, "s": 26397, "text": "Now that we have the data we can find the mean and standard deviation by calling mean() and std() methods." }, { "code": null, "e": 26554, "s": 26504, "text": "mean_tensor = data.mean()\nstd_tensor = data.std()" }, { "code": null, "e": 26743, "s": 26554, "text": "The above method works perfectly, but the values are returned as tensors, if you want to extract values inside that tensor you can either access it via index or you can call item() method." }, { "code": null, "e": 26793, "s": 26743, "text": "mean = data.mean().item()\nstd = data.std().item()" }, { "code": null, "e": 26802, "s": 26793, "text": "Example:" }, { "code": null, "e": 26810, "s": 26802, "text": "Python3" }, { "code": "import torch # Generate a tensor of 10 numbersdata = torch.rand(10) mean_tensor = data.mean()std_tensor = data.std() print(mean_tensor)print(std_tensor) mean = data.mean().item()std = data.std().item() print(mean)print(std)", "e": 27044, "s": 26810, "text": null }, { "code": null, "e": 27052, "s": 27044, "text": "Output:" }, { "code": null, "e": 27121, "s": 27052, "text": "tensor(0.3901)\ntensor(0.2846)\n0.39005300402641296\n0.2846093773841858" }, { "code": null, "e": 27304, "s": 27121, "text": "In 2-D Tensors mean is the same as that of the 1-D tensor except here we can pass an axis parameter to find the mean and std of the rows and columns. Let’s start by getting our data." }, { "code": null, "e": 27340, "s": 27304, "text": "import torch\ndata = torch.rand(5,3)" }, { "code": null, "e": 27680, "s": 27340, "text": "The mean() and std() methods when called as is will return the total standard deviation of the whole dataset, but if we pass an axis parameter we can find the mean and std of rows and columns. For axis = 0, we get a tensor having values of mean or std of each column. For axis = 1, we get a tensor having values of mean or std of each row." }, { "code": null, "e": 27919, "s": 27680, "text": "total_mean = data.mean()\ntotal_std = data.std()\n\n# Mean and STD of columns\nmean_col_wise = data.mean(axis = 0)\nstd_col_wise = data.std(axis = 0)\n\n# Mean and STD of rows\nmean_row_wise = data.mean(axis = 1)\nstd_row_wise = data.std(axis = 1)" }, { "code": null, "e": 27928, "s": 27919, "text": "Example:" }, { "code": null, "e": 27936, "s": 27928, "text": "Python3" }, { "code": "import torch # Generate a tensor of shape (5,3)data = torch.rand(5,3) total_mean = data.mean()total_std = data.std() print(total_mean)print(total_std) # Mean and STD of columnsmean_col_wise = data.mean(axis = 0)std_col_wise = data.std(axis = 0) print(mean_col_wise)print(std_col_wise) # Mean and STD of rowsmean_row_wise = data.mean(axis = 1)std_row_wise = data.std(axis = 1) print(mean_row_wise)print(std_row_wise)", "e": 28365, "s": 27936, "text": null }, { "code": null, "e": 28373, "s": 28365, "text": "Output:" }, { "code": null, "e": 28567, "s": 28373, "text": "tensor(0.6483)\ntensor(0.2797)\ntensor([0.6783, 0.5986, 0.6679])\ntensor([0.2548, 0.2711, 0.3614])\ntensor([0.5315, 0.7770, 0.7785, 0.3403, 0.8142])\ntensor([0.3749, 0.2340, 0.1397, 0.2432, 0.1386])" }, { "code": null, "e": 28574, "s": 28567, "text": "Picked" }, { "code": null, "e": 28589, "s": 28574, "text": "Python-PyTorch" }, { "code": null, "e": 28596, "s": 28589, "text": "Python" }, { "code": null, "e": 28694, "s": 28596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28726, "s": 28694, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28768, "s": 28726, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28810, "s": 28768, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28837, "s": 28810, "text": "Python Classes and Objects" }, { "code": null, "e": 28893, "s": 28837, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28932, "s": 28893, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28954, "s": 28932, "text": "Defaultdict in Python" }, { "code": null, "e": 28985, "s": 28954, "text": "Python | os.path.join() method" }, { "code": null, "e": 29014, "s": 28985, "text": "Create a directory in Python" } ]
Nested Loops in C++ with Examples - GeeksforGeeks
03 Dec, 2019 Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“. Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop } Syntax for Nested While loop: while(condition) { while(condition) { // statement of inside loop } // statement of outer loop } Syntax for Nested Do-While loop: do{ do{ // statement of inside loop }while(condition); // statement of outer loop }while(condition); Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level. Syntax: do{ while(condition) { for ( initialization; condition; increment ) { // statement of inside for loop } // statement of inside while loop } // statement of outer do-while loop }while(condition); Below are some examples to demonstrate the use of Nested Loops: Example 1: Below program uses a nested for loop to print a 2D matrix of 3×3. // C++ program that uses nested for loop// to print a 2D matrix #include <bits/stdc++.h>using namespace std; #define ROW 3#define COL 3 // Driver programint main(){ int i, j; // Declare the matrix int matrix[ROW][COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; cout << "Given matrix is \n"; // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) cout << matrix[i][j]; cout << "\n"; } return 0;} Given matrix is 123 456 789 Example 2: Below program uses a nested for loop to print all prime factors of a number. // C++ Program to print all prime factors// of a number using nested loop #include <bits/stdc++.h>using namespace std; // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2; n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i; n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) cout << n;} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;} 3357 Loops & Control Structure C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n03 Dec, 2019" }, { "code": null, "e": 25497, "s": 25367, "text": "Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“." }, { "code": null, "e": 25525, "s": 25497, "text": "Syntax for Nested For loop:" }, { "code": null, "e": 25703, "s": 25525, "text": "for ( initialization; condition; increment ) {\n\n for ( initialization; condition; increment ) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}\n" }, { "code": null, "e": 25733, "s": 25703, "text": "Syntax for Nested While loop:" }, { "code": null, "e": 25855, "s": 25733, "text": "while(condition) {\n\n while(condition) {\n \n // statement of inside loop\n }\n\n // statement of outer loop\n}\n" }, { "code": null, "e": 25888, "s": 25855, "text": "Syntax for Nested Do-While loop:" }, { "code": null, "e": 26014, "s": 25888, "text": "do{\n\n do{\n \n // statement of inside loop\n }while(condition);\n\n // statement of outer loop\n}while(condition);\n" }, { "code": null, "e": 26165, "s": 26014, "text": "Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level." }, { "code": null, "e": 26173, "s": 26165, "text": "Syntax:" }, { "code": null, "e": 26422, "s": 26173, "text": "do{\n\n while(condition) {\n \n for ( initialization; condition; increment ) {\n \n // statement of inside for loop\n }\n\n // statement of inside while loop\n }\n\n // statement of outer do-while loop\n}while(condition);\n" }, { "code": null, "e": 26486, "s": 26422, "text": "Below are some examples to demonstrate the use of Nested Loops:" }, { "code": null, "e": 26563, "s": 26486, "text": "Example 1: Below program uses a nested for loop to print a 2D matrix of 3×3." }, { "code": "// C++ program that uses nested for loop// to print a 2D matrix #include <bits/stdc++.h>using namespace std; #define ROW 3#define COL 3 // Driver programint main(){ int i, j; // Declare the matrix int matrix[ROW][COL] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; cout << \"Given matrix is \\n\"; // Print the matrix using nested loops for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) cout << matrix[i][j]; cout << \"\\n\"; } return 0;}", "e": 27118, "s": 26563, "text": null }, { "code": null, "e": 27148, "s": 27118, "text": "Given matrix is \n123\n456\n789\n" }, { "code": null, "e": 27236, "s": 27148, "text": "Example 2: Below program uses a nested for loop to print all prime factors of a number." }, { "code": "// C++ Program to print all prime factors// of a number using nested loop #include <bits/stdc++.h>using namespace std; // A function to print all prime factors of a given number nvoid primeFactors(int n){ // Print the number of 2s that divide n while (n % 2 == 0) { cout << 2; n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { cout << i; n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) cout << n;} /* Driver program to test above function */int main(){ int n = 315; primeFactors(n); return 0;}", "e": 28049, "s": 27236, "text": null }, { "code": null, "e": 28055, "s": 28049, "text": "3357\n" }, { "code": null, "e": 28081, "s": 28055, "text": "Loops & Control Structure" }, { "code": null, "e": 28085, "s": 28081, "text": "C++" }, { "code": null, "e": 28089, "s": 28085, "text": "CPP" }, { "code": null, "e": 28187, "s": 28089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28215, "s": 28187, "text": "Operator Overloading in C++" }, { "code": null, "e": 28235, "s": 28215, "text": "Polymorphism in C++" }, { "code": null, "e": 28259, "s": 28235, "text": "Sorting a vector in C++" }, { "code": null, "e": 28292, "s": 28259, "text": "Friend class and function in C++" }, { "code": null, "e": 28317, "s": 28292, "text": "std::string class in C++" }, { "code": null, "e": 28361, "s": 28317, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28406, "s": 28361, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 28430, "s": 28406, "text": "Inline Functions in C++" }, { "code": null, "e": 28483, "s": 28430, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Print Kth character in sorted concatenated substrings of a string - GeeksforGeeks
29 Dec, 2021 Given a string of lower alphabetic characters, find K-th character in a string formed by substrings (of given string) when concatenated in sorted form. Examples: Input : str = “banana” K = 10 Output : n All substring in sorted form are, "a", "an", "ana", "anan", "anana", "b", "ba", "ban", "bana", "banan", "banana", "n", "na", "nan", "nana" Concatenated string = “aananaanana nanabbabanbanabananbananannanannana” We can see a 10th character in the above concatenated string is ‘n’ which is our final answer. A simple solution is to generate all substrings of a given string and store them in an array. Once substrings are generated, sort them and concatenate after sorting. Finally print K-th character in the concatenated string. An efficient solution is based om counting distinct substring of a string using suffix array. Same method is used in solving this problem also. After getting suffix array and lcp array, we loop over all lcp values and for each such value, we calculate characters to skip. We keep subtracting these many characters from our K, when character to skip becomes more than K, we stop and loop over substrings corresponding to current lcp[i], in which we loop from lcp[i] till the maximum length of string and then print the Kth character. C++ Python3 // C++ program to print Kth character// in sorted concatenated substrings#include <bits/stdc++.h>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next // rank pair}; // A comparison function used by sort() to compare// two suffixes. Compares two pairs, returns 1 if// first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string// 'txt' of size n as an argument, builds and return// the suffix array for the given stringvector<int> buildSuffixArray(string txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr;} /* To construct and return LCP */vector<int> kasai(string txt, vector<int> suffixArr){ int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp;} // Utility method to get sum of first N numbersint sumOfFirstN(int N){ return (N * (N + 1)) / 2;} // Returns Kth character in sorted concatenated// substrings of strchar printKthCharInConcatSubstring(string str, int K){ int n = str.length(); // calculating suffix array and lcp array vector<int> suffixArr = buildSuffixArray(str, n); vector<int> lcp = kasai(str, suffixArr); for (int i = 0; i < lcp.size(); i++) { // skipping characters common to substring // (n - suffixArr[i]) is length of current // maximum substring lcp[i] will length of // common substring int charToSkip = sumOfFirstN(n - suffixArr[i]) - sumOfFirstN(lcp[i]); /* if characters are more than K, that means Kth character belongs to substring corresponding to current lcp[i]*/ if (K <= charToSkip) { // loop from current lcp value to current // string length for (int j = lcp[i] + 1; j <= (n-suffixArr[i]); j++) { int curSubstringLen = j; /* Again reduce K by current substring's length one by one and when it becomes less, print Kth character of current substring */ if (K <= curSubstringLen) return str[(suffixArr[i] + K - 1)]; else K -= curSubstringLen; } break; } else K -= charToSkip; }} // Driver code to test above methodsint main(){ string str = "banana"; int K = 10; cout << printKthCharInConcatSubstring(str, K); return 0;} # Python3 program to print Kth character# in sorted concatenated substrings # Structure to store information of a suffixclass suffix: def __init__(self): self.index = 0 # To store original index self.rank = [0] * 2 # To store ranks and next # rank pair # This is the main function that takes a string# 'txt' of size n as an argument, builds and return# the suffix array for the given stringdef buildSuffixArray(txt: str, n: int) -> list: # A structure to store suffixes # and their indexes suffixes = [0] * n for i in range(n): suffixes[i] = suffix() # Store suffixes and their indexes in an array # of structures. The structure is needed to sort # the suffixes alphabetically and maintain their # old indexes while sorting for i in range(n): suffixes[i].index = i suffixes[i].rank[0] = ord(txt[i]) - ord('a') suffixes[i].rank[1] = (ord(txt[i + 1]) - ord('a')) if ((i + 1) < n) else -1 # Sort the suffixes using the comparison function # defined above. suffixes.sort(key = lambda a: a.rank) # At his point, all suffixes are sorted according # to first 2 characters. Let us sort suffixes # according to first 4 characters, then first # 8 and so on ind = [0] * n # This array is needed to get the # index in suffixes[] from original # index. This mapping is needed to get # next suffix. k = 4 while k < 2 * n: k *= 2 # for k in range(4, 2 * n, k * 2): # Assigning rank and index values # to first suffix rank = 0 prev_rank = suffixes[0].rank[0] suffixes[0].rank[0] = rank ind[suffixes[0].index] = 0 # Assigning rank to suffixes for i in range(1, n): # If first rank and next ranks are same as # that of previous suffix in array, assign # the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank and suffixes[i].rank[1] == suffixes[i - 1].rank[1]): prev_rank = suffixes[i].rank[0] suffixes[i].rank[0] = rank # Otherwise increment rank and assign else: prev_rank = suffixes[i].rank[0] rank += 1 suffixes[i].rank[0] = rank ind[suffixes[i].index] = i # Assign next rank to every suffix for i in range(n): nextindex = suffixes[i].index + k // 2 suffixes[i].rank[1] = suffixes[ind[nextindex]].rank[0] if ( nextindex < n) else -1 # Sort the suffixes according to first k characters suffixes.sort(key = lambda a : a.rank) # Store indexes of all sorted suffixes # in the suffix array suffixArr = [] for i in range(n): suffixArr.append(suffixes[i].index) # Return the suffix array return suffixArr # To construct and return LCP */def kasai(txt: str, suffixArr: list) -> list: n = len(suffixArr) # To store LCP array lcp = [0] * n # An auxiliary array to store inverse of # suffix array elements. For example if # suffixArr[0] is 5, the invSuff[5] would # store 0. This is used to get next # suffix string from suffix array. invSuff = [0] * n # Fill values in invSuff[] for i in range(n): invSuff[suffixArr[i]] = i # Initialize length of previous LCP k = 0 # Process all suffixes one by one # starting from first suffix in txt[] for i in range(n): # If the current suffix is at n-1, then # we don’t have next substring to # consider. So lcp is not defined for # this substring, we put zero. if (invSuff[i] == n - 1): k = 0 continue # j contains index of the next substring to # be considered to compare with the present # substring, i.e., next string in suffix array j = suffixArr[invSuff[i] + 1] # Directly start matching from k'th index as # at-least k-1 characters will match while (i + k < n and j + k < n and txt[i + k] == txt[j + k]): k += 1 lcp[invSuff[i]] = k # lcp for the present suffix. # Deleting the starting character # from the string. if (k > 0): k -= 1 # Return the constructed lcp array return lcp # Utility method to get sum of first N numbersdef sumOfFirstN(N: int) -> int: return (N * (N + 1)) // 2 # Returns Kth character in sorted concatenated# substrings of strdef printKthCharInConcatSubstring(string: str, K: int) -> str: n = len(string) # Calculating suffix array and lcp array suffixArr = buildSuffixArray(string, n) lcp = kasai(string, suffixArr) for i in range(len(lcp)): # Skipping characters common to substring # (n - suffixArr[i]) is length of current # maximum substring lcp[i] will length of # common substring charToSkip = (sumOfFirstN(n - suffixArr[i]) - sumOfFirstN(lcp[i])) # If characters are more than K, that means # Kth character belongs to substring # corresponding to current lcp[i] if (K <= charToSkip): # Loop from current lcp value to current # string length for j in range(lcp[i] + 1, (n - suffixArr[i]) + 1): curSubstringLen = j # Again reduce K by current substring's # length one by one and when it becomes less, # print Kth character of current substring if (K <= curSubstringLen): return string[(suffixArr[i] + K - 1)] else: K -= curSubstringLen break else: K -= charToSkip # Driver codeif __name__ == "__main__": string = "banana" K = 10 print(printKthCharInConcatSubstring(string, K)) # This code is contributed by sanjeev2552 Output: n This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 varshagumber28 surindertarika1234 Suffix-Array Advanced Data Structure Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26715, "s": 26687, "text": "\n29 Dec, 2021" }, { "code": null, "e": 26868, "s": 26715, "text": "Given a string of lower alphabetic characters, find K-th character in a string formed by substrings (of given string) when concatenated in sorted form. " }, { "code": null, "e": 26880, "s": 26868, "text": "Examples: " }, { "code": null, "e": 27241, "s": 26880, "text": "Input : str = “banana”\n K = 10\nOutput : n\nAll substring in sorted form are,\n\"a\", \"an\", \"ana\", \"anan\", \"anana\", \n\"b\", \"ba\", \"ban\", \"bana\", \"banan\", \n\"banana\", \"n\", \"na\", \"nan\", \"nana\"\nConcatenated string = “aananaanana\nnanabbabanbanabananbananannanannana”\nWe can see a 10th character in the \nabove concatenated string is ‘n’ \nwhich is our final answer." }, { "code": null, "e": 27464, "s": 27241, "text": "A simple solution is to generate all substrings of a given string and store them in an array. Once substrings are generated, sort them and concatenate after sorting. Finally print K-th character in the concatenated string." }, { "code": null, "e": 27998, "s": 27464, "text": "An efficient solution is based om counting distinct substring of a string using suffix array. Same method is used in solving this problem also. After getting suffix array and lcp array, we loop over all lcp values and for each such value, we calculate characters to skip. We keep subtracting these many characters from our K, when character to skip becomes more than K, we stop and loop over substrings corresponding to current lcp[i], in which we loop from lcp[i] till the maximum length of string and then print the Kth character. " }, { "code": null, "e": 28002, "s": 27998, "text": "C++" }, { "code": null, "e": 28010, "s": 28002, "text": "Python3" }, { "code": "// C++ program to print Kth character// in sorted concatenated substrings#include <bits/stdc++.h>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next // rank pair}; // A comparison function used by sort() to compare// two suffixes. Compares two pairs, returns 1 if// first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string// 'txt' of size n as an argument, builds and return// the suffix array for the given stringvector<int> buildSuffixArray(string txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr;} /* To construct and return LCP */vector<int> kasai(string txt, vector<int> suffixArr){ int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp;} // Utility method to get sum of first N numbersint sumOfFirstN(int N){ return (N * (N + 1)) / 2;} // Returns Kth character in sorted concatenated// substrings of strchar printKthCharInConcatSubstring(string str, int K){ int n = str.length(); // calculating suffix array and lcp array vector<int> suffixArr = buildSuffixArray(str, n); vector<int> lcp = kasai(str, suffixArr); for (int i = 0; i < lcp.size(); i++) { // skipping characters common to substring // (n - suffixArr[i]) is length of current // maximum substring lcp[i] will length of // common substring int charToSkip = sumOfFirstN(n - suffixArr[i]) - sumOfFirstN(lcp[i]); /* if characters are more than K, that means Kth character belongs to substring corresponding to current lcp[i]*/ if (K <= charToSkip) { // loop from current lcp value to current // string length for (int j = lcp[i] + 1; j <= (n-suffixArr[i]); j++) { int curSubstringLen = j; /* Again reduce K by current substring's length one by one and when it becomes less, print Kth character of current substring */ if (K <= curSubstringLen) return str[(suffixArr[i] + K - 1)]; else K -= curSubstringLen; } break; } else K -= charToSkip; }} // Driver code to test above methodsint main(){ string str = \"banana\"; int K = 10; cout << printKthCharInConcatSubstring(str, K); return 0;}", "e": 34461, "s": 28010, "text": null }, { "code": "# Python3 program to print Kth character# in sorted concatenated substrings # Structure to store information of a suffixclass suffix: def __init__(self): self.index = 0 # To store original index self.rank = [0] * 2 # To store ranks and next # rank pair # This is the main function that takes a string# 'txt' of size n as an argument, builds and return# the suffix array for the given stringdef buildSuffixArray(txt: str, n: int) -> list: # A structure to store suffixes # and their indexes suffixes = [0] * n for i in range(n): suffixes[i] = suffix() # Store suffixes and their indexes in an array # of structures. The structure is needed to sort # the suffixes alphabetically and maintain their # old indexes while sorting for i in range(n): suffixes[i].index = i suffixes[i].rank[0] = ord(txt[i]) - ord('a') suffixes[i].rank[1] = (ord(txt[i + 1]) - ord('a')) if ((i + 1) < n) else -1 # Sort the suffixes using the comparison function # defined above. suffixes.sort(key = lambda a: a.rank) # At his point, all suffixes are sorted according # to first 2 characters. Let us sort suffixes # according to first 4 characters, then first # 8 and so on ind = [0] * n # This array is needed to get the # index in suffixes[] from original # index. This mapping is needed to get # next suffix. k = 4 while k < 2 * n: k *= 2 # for k in range(4, 2 * n, k * 2): # Assigning rank and index values # to first suffix rank = 0 prev_rank = suffixes[0].rank[0] suffixes[0].rank[0] = rank ind[suffixes[0].index] = 0 # Assigning rank to suffixes for i in range(1, n): # If first rank and next ranks are same as # that of previous suffix in array, assign # the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank and suffixes[i].rank[1] == suffixes[i - 1].rank[1]): prev_rank = suffixes[i].rank[0] suffixes[i].rank[0] = rank # Otherwise increment rank and assign else: prev_rank = suffixes[i].rank[0] rank += 1 suffixes[i].rank[0] = rank ind[suffixes[i].index] = i # Assign next rank to every suffix for i in range(n): nextindex = suffixes[i].index + k // 2 suffixes[i].rank[1] = suffixes[ind[nextindex]].rank[0] if ( nextindex < n) else -1 # Sort the suffixes according to first k characters suffixes.sort(key = lambda a : a.rank) # Store indexes of all sorted suffixes # in the suffix array suffixArr = [] for i in range(n): suffixArr.append(suffixes[i].index) # Return the suffix array return suffixArr # To construct and return LCP */def kasai(txt: str, suffixArr: list) -> list: n = len(suffixArr) # To store LCP array lcp = [0] * n # An auxiliary array to store inverse of # suffix array elements. For example if # suffixArr[0] is 5, the invSuff[5] would # store 0. This is used to get next # suffix string from suffix array. invSuff = [0] * n # Fill values in invSuff[] for i in range(n): invSuff[suffixArr[i]] = i # Initialize length of previous LCP k = 0 # Process all suffixes one by one # starting from first suffix in txt[] for i in range(n): # If the current suffix is at n-1, then # we don’t have next substring to # consider. So lcp is not defined for # this substring, we put zero. if (invSuff[i] == n - 1): k = 0 continue # j contains index of the next substring to # be considered to compare with the present # substring, i.e., next string in suffix array j = suffixArr[invSuff[i] + 1] # Directly start matching from k'th index as # at-least k-1 characters will match while (i + k < n and j + k < n and txt[i + k] == txt[j + k]): k += 1 lcp[invSuff[i]] = k # lcp for the present suffix. # Deleting the starting character # from the string. if (k > 0): k -= 1 # Return the constructed lcp array return lcp # Utility method to get sum of first N numbersdef sumOfFirstN(N: int) -> int: return (N * (N + 1)) // 2 # Returns Kth character in sorted concatenated# substrings of strdef printKthCharInConcatSubstring(string: str, K: int) -> str: n = len(string) # Calculating suffix array and lcp array suffixArr = buildSuffixArray(string, n) lcp = kasai(string, suffixArr) for i in range(len(lcp)): # Skipping characters common to substring # (n - suffixArr[i]) is length of current # maximum substring lcp[i] will length of # common substring charToSkip = (sumOfFirstN(n - suffixArr[i]) - sumOfFirstN(lcp[i])) # If characters are more than K, that means # Kth character belongs to substring # corresponding to current lcp[i] if (K <= charToSkip): # Loop from current lcp value to current # string length for j in range(lcp[i] + 1, (n - suffixArr[i]) + 1): curSubstringLen = j # Again reduce K by current substring's # length one by one and when it becomes less, # print Kth character of current substring if (K <= curSubstringLen): return string[(suffixArr[i] + K - 1)] else: K -= curSubstringLen break else: K -= charToSkip # Driver codeif __name__ == \"__main__\": string = \"banana\" K = 10 print(printKthCharInConcatSubstring(string, K)) # This code is contributed by sanjeev2552", "e": 40550, "s": 34461, "text": null }, { "code": null, "e": 40559, "s": 40550, "text": "Output: " }, { "code": null, "e": 40561, "s": 40559, "text": "n" }, { "code": null, "e": 40985, "s": 40561, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40997, "s": 40985, "text": "sanjeev2552" }, { "code": null, "e": 41012, "s": 40997, "text": "varshagumber28" }, { "code": null, "e": 41031, "s": 41012, "text": "surindertarika1234" }, { "code": null, "e": 41044, "s": 41031, "text": "Suffix-Array" }, { "code": null, "e": 41068, "s": 41044, "text": "Advanced Data Structure" }, { "code": null, "e": 41076, "s": 41068, "text": "Strings" }, { "code": null, "e": 41084, "s": 41076, "text": "Strings" }, { "code": null, "e": 41182, "s": 41084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41216, "s": 41182, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 41256, "s": 41216, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 41298, "s": 41256, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 41326, "s": 41298, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 41355, "s": 41326, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 41401, "s": 41355, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 41426, "s": 41401, "text": "Reverse a string in Java" }, { "code": null, "e": 41486, "s": 41426, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 41501, "s": 41486, "text": "C++ Data Types" } ]
Python MariaDB - Update Query using PyMySQL - GeeksforGeeks
14 Oct, 2020 MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql. The update is used to change the existing values in a database. By using the update statement a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate. Syntax : UPDATE tablename SET column_nmae = "new value" WHERE conditions; The following programs will help you understand this better. Example 1 : Python3 import pymysql # Create a connection object# IP address of the MySQL database serverHost = "localhost" # User name of the database serverUser = "user" # Password for the database userPassword = "" database = "GFG" conn = pymysql.connect(host=Host, user=User, password=Password, database) # Create a cursor objectcur = conn.cursor() query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'" cur.execute(query) #To commit the changesconn.commit() conn.close() Output : Before:After In the above program, We update Broad Band price from 1200 to 1400. Example 2 : Python3 import pymysql # Create a connection objectconn = pymysql.connect('localhost', 'user', 'password', 'database') # Create a cursor objectcur = conn.cursor() query = f"update PRODUCT set PRODUCT_ID = 'A123' WHERE \price = 14782 AND PRODUCT_TYPE = 'Voice'" cur.execute(query) # To commit the changesconn.commit() conn.close() Output : BeforeAfter In the above program, We update PRODUCT_ID to A123 WHERE price = 14782 AND PRODUCT_TYPE = ‘Voice’. Python-MariaDB 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": 25537, "s": 25509, "text": "\n14 Oct, 2020" }, { "code": null, "e": 25715, "s": 25537, "text": "MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python." }, { "code": null, "e": 26114, "s": 25715, "text": "In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql. The update is used to change the existing values in a database. By using the update statement a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate." }, { "code": null, "e": 26123, "s": 26114, "text": "Syntax :" }, { "code": null, "e": 26189, "s": 26123, "text": "UPDATE tablename\nSET column_nmae = \"new value\"\nWHERE conditions;\n" }, { "code": null, "e": 26250, "s": 26189, "text": "The following programs will help you understand this better." }, { "code": null, "e": 26263, "s": 26250, "text": "Example 1 : " }, { "code": null, "e": 26271, "s": 26263, "text": "Python3" }, { "code": "import pymysql # Create a connection object# IP address of the MySQL database serverHost = \"localhost\" # User name of the database serverUser = \"user\" # Password for the database userPassword = \"\" database = \"GFG\" conn = pymysql.connect(host=Host, user=User, password=Password, database) # Create a cursor objectcur = conn.cursor() query = f\"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'\" cur.execute(query) #To commit the changesconn.commit() conn.close()", "e": 26780, "s": 26271, "text": null }, { "code": null, "e": 26789, "s": 26780, "text": "Output :" }, { "code": null, "e": 26802, "s": 26789, "text": "Before:After" }, { "code": null, "e": 26871, "s": 26802, "text": "In the above program, We update Broad Band price from 1200 to 1400." }, { "code": null, "e": 26883, "s": 26871, "text": "Example 2 :" }, { "code": null, "e": 26891, "s": 26883, "text": "Python3" }, { "code": "import pymysql # Create a connection objectconn = pymysql.connect('localhost', 'user', 'password', 'database') # Create a cursor objectcur = conn.cursor() query = f\"update PRODUCT set PRODUCT_ID = 'A123' WHERE \\price = 14782 AND PRODUCT_TYPE = 'Voice'\" cur.execute(query) # To commit the changesconn.commit() conn.close()", "e": 27251, "s": 26891, "text": null }, { "code": null, "e": 27260, "s": 27251, "text": "Output :" }, { "code": null, "e": 27272, "s": 27260, "text": "BeforeAfter" }, { "code": null, "e": 27373, "s": 27272, "text": "In the above program, We update PRODUCT_ID to A123 WHERE price = 14782 AND PRODUCT_TYPE = ‘Voice’." }, { "code": null, "e": 27388, "s": 27373, "text": "Python-MariaDB" }, { "code": null, "e": 27395, "s": 27388, "text": "Python" }, { "code": null, "e": 27493, "s": 27395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27525, "s": 27493, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27567, "s": 27525, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27609, "s": 27567, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27665, "s": 27609, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27692, "s": 27665, "text": "Python Classes and Objects" }, { "code": null, "e": 27723, "s": 27692, "text": "Python | os.path.join() method" }, { "code": null, "e": 27762, "s": 27723, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27791, "s": 27762, "text": "Create a directory in Python" }, { "code": null, "e": 27813, "s": 27791, "text": "Defaultdict in Python" } ]
How to Calculate Percentiles For Monitoring Data-Intensive Systems? - GeeksforGeeks
08 Dec, 2021 Monitoring often involves the use of percentiles. Unlike average values, which are heavily influenced by outliers, percentiles help understand how the system works most of the time. If 9 out of 10 requests are executed in 1 second and the last one takes 10 seconds, the average will be 1.9 seconds while the 50th percentile will be 1 second. This is but one example of how the average value is not appropriate for monitoring. Thus, the need to count percentiles arises, and for this very reason, we added a summary collector to our tarantool/metrics. Summary collectors calculate quantiles for the monitored data. Let me tell you about the algorithm we used to compute quantiles and how we implemented it for tarantool/metrics. Algorithm A -quantile is a value that a random variable does not exceed with a probability of . For example, in HTTP request monitoring, a 0.5-quantile (basically the 50th percentile) that equals 1-second means that 50% of requests were processed in less than a second. To calculate a for a sorted array of size n, you need to find the element with the index of . This approach requires storing all the monitored data, and there can be a lot of data in metrics. If there are one billion requests to be processed, they would require a billion array elements, which would make up about 1 GB of data. This problem can be solved by a number of algorithms that calculate approximate quantile values for data streams. We took the algorithm used in Prometheus. It compresses the original data, representing them as a set of segments. Each segment is described by a structure of three numbers: is the distance from the beginning of the previous segment to the beginning of the current segment; is the length of the current segment; is the approximate quantile of the segment. The graph above shows the original array elements in green and the compressed array elements in red. To find the quantile for the compressed data, we need to iterate over the segments, adding up their distances until the sum is close enough to , and identify the corresponding segment. For example, the 0.5-quantile will be located in the middle of the green array on the graph, and the approximated value will belong to the corresponding red segment. The whole compression process is described extensively in the original article. We followed the example of the Go implementation of this algorithm. Let’s create two arrays. One will serve as a buffer for the monitored values, and the other will be used as an observation array to store segment structures: Go typedef struct {int Delta, Width; double Value; } sample; This algorithm operates only on sorted values. Let’s limit the buffer size to 500 values and define the size of the observation array as 2 × 500 + 2. As compression reduces the array size by approximately half, we’ll need on average 500 elements of the uncompressed array from the previous step + 500 elements added to the array in the current step + elements like to simplify searching in the array. We worked on our implementation iteratively: created a version, checked its performance with a profiler, compared it with the Go version, then looked for ways to improve it. We assessed our results using a simple benchmark: 108 samples, which takes about 8 seconds for the Go version. Now let’s dive into details about each iteration. 1. The pure-Lua version was quite bad, as the insertion took an average of about 100 seconds. The profiler data reads as follows: The code underperforms on inserting observations into the corresponding array (`table.insert` call) and on buffer sorting (`table.sort`). That’s where ffi (foreign function interface) comes to the rescue. Ffi allows accessing functions from the C standard library and working with them in Lua as if they were routine Lua objects (well, almost; for example, while table indexing in Lua starts with 1, arrays created with C would still start with 0). 2. The Lua + ffi version involved building an array of double values instead of creating a buffer: Go local ffi = require('ffi')...array = ffi.new('double[?]', max_samples)for i = 0, max_samples - 1 do array[i] = math.hugeend We will sort this array using the C standard library: Go ffi.cdef[[ Go void qsort(void *base, size_t nitems, size_t size, int (*compare)(const void *, const void*));int cmpfunc (const void * a, const void * b); Let’s write a comparator function for `double` values in C and include it as a dynamic library. Here is the comparator function: Go int cmpfunc (const void * a, const void * b) { if (*(double*)a > *(double*)b) return 1; else if (*(double*)a < *(double*)b) return -1; else return 0;} Now let’s build it: Go gcc -c -o metrics/quantile.o metrics/quantile.cgcc -shared -o metrics/libquantile.so metrics/quantile.o Then we’ll include the library in our Lua code: Go local dlib_path = package.search('libquantile', package.cpath)local dlib = ffi.load(dlib_path) Now we can populate the `double` array and invoke its sorting: Go local DOUBLE_SIZE = ffi.sizeof('double')ffi.C.qsort(array, len, DOUBLE_SIZE, dlib.cmpfunc) Tests showed a 3x increase in performance, with insertion time averaging up to 30 seconds. This time, the code underperformed because Lua tables do not have a fixed size, and element types are not predefined, either. Although this allows for more flexibility in table processing, it notably reduces performance. With ffi, you can switch from Lua tables to fixed-size C arrays, so that inserting and calculating array size costs O(1) instead of O(log n). Sorting is also much faster due to the fixed types and, therefore, fixed element sizes. But this solution introduces a GCC dependency that complicates application delivery. So we had to get rid of the C code. 3. Lua + ffi + homebrew sorting. The simplest quicksort in Lua turned out to run only a couple of seconds longer than our previous version involving a C library. This result was good enough for us, especially since it didn’t depend on GCC, so we decided to stop here. The last step was to add quantile rotation using the sliding window algorithm. We create a ring queue consisting of several collectors (5, for example) and make one of them the leading one (head). Monitored values are written to each of these collectors. After the specified time has expired (60 seconds, for instance), the head collector is reset and the next one in the queue becomes the new head. The quantile value is fetched from the current head only. This approach ensures that the data are kept up-to-date because, without a sliding window, the values would be calculated over the entire period. `metrics.quantile` uses two arrays: A buffer of `max_samples * sizeof(double)` = 500 × 8 bytes. An observation array of `(2 * max_samples + 2) * sizeof(struct sample)` = 1002 × 16 bytes. The size of the observation array can increase when the observed values vary by several orders of magnitude. There are `age_buckets_count` collectors created in `metrics.summary`, so the total size is: `age_buckets_count * (max_samples * sizeof(double) + (2 * max_samples + 2) * sizeof(struct sample))` = 5 × (500 × 8 + 1002 × 16) bytes, or about 100 KB. We performed load testing with Yandex.Tank. With all application metrics turned off, the results read as follows: With our summary collector: Performance dropped by ~10%, which is a cost you have to pay for using metrics. If you want to avoid significant drawdown, you might want to use the collector carefully, for instance, measure only a portion of requests. Go tarantoolctl rocks install metrics 0.10.0 Go local metrics = require('metrics') -- attaching metrics -- Creating a summary collectorlocal http_requests_latency = metrics.summary( 'http_requests_latency', 'HTTP requests latency', {[0.5]=0.01, [0.9]=0.01, [0.99]=0.01}, {max_age_time = 60, age_buckets_count = 5}) -- Monitoring a valuelocal latency = math.random(1, 10)http_requests_latency:observe(latency) Export to JSON, Prometheus, and Graphite is supported. Here is what the collected results might look like in Grafana: We wrote a summary collector for tarantool/metrics. During development, we encountered a performance challenge, which we solved using ffi. You can use the new collector to monitor values that may benefit from keeping track of quantiles, such as HTTP request latency. The summary collector can be applied in any Tarantool-based product where service response time is critical, like data-intensive applications where large amounts of data are accessed via HTTP requests. Monitoring this metric will help you understand what requests are straining your system. This article is contributed by Igor Zolotarev. kapoorsagar226 Go Language Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Time Durations in Golang Strings in Golang Structures in Golang Naive Bayes Classifiers Linear Regression (Python Implementation) ML | Linear Regression Reinforcement learning Removing stop words with NLTK in Python
[ { "code": null, "e": 25729, "s": 25701, "text": "\n08 Dec, 2021" }, { "code": null, "e": 26457, "s": 25729, "text": "Monitoring often involves the use of percentiles. Unlike average values, which are heavily influenced by outliers, percentiles help understand how the system works most of the time. If 9 out of 10 requests are executed in 1 second and the last one takes 10 seconds, the average will be 1.9 seconds while the 50th percentile will be 1 second. This is but one example of how the average value is not appropriate for monitoring. Thus, the need to count percentiles arises, and for this very reason, we added a summary collector to our tarantool/metrics. Summary collectors calculate quantiles for the monitored data. Let me tell you about the algorithm we used to compute quantiles and how we implemented it for tarantool/metrics." }, { "code": null, "e": 26467, "s": 26457, "text": "Algorithm" }, { "code": null, "e": 27056, "s": 26467, "text": "A -quantile is a value that a random variable does not exceed with a probability of . For example, in HTTP request monitoring, a 0.5-quantile (basically the 50th percentile) that equals 1-second means that 50% of requests were processed in less than a second. To calculate a for a sorted array of size n, you need to find the element with the index of . This approach requires storing all the monitored data, and there can be a lot of data in metrics. If there are one billion requests to be processed, they would require a billion array elements, which would make up about 1 GB of data." }, { "code": null, "e": 27528, "s": 27056, "text": "This problem can be solved by a number of algorithms that calculate approximate quantile values for data streams. We took the algorithm used in Prometheus. It compresses the original data, representing them as a set of segments. Each segment is described by a structure of three numbers: is the distance from the beginning of the previous segment to the beginning of the current segment; is the length of the current segment; is the approximate quantile of the segment." }, { "code": null, "e": 28060, "s": 27528, "text": "The graph above shows the original array elements in green and the compressed array elements in red. To find the quantile for the compressed data, we need to iterate over the segments, adding up their distances until the sum is close enough to , and identify the corresponding segment. For example, the 0.5-quantile will be located in the middle of the green array on the graph, and the approximated value will belong to the corresponding red segment. The whole compression process is described extensively in the original article." }, { "code": null, "e": 28286, "s": 28060, "text": "We followed the example of the Go implementation of this algorithm. Let’s create two arrays. One will serve as a buffer for the monitored values, and the other will be used as an observation array to store segment structures:" }, { "code": null, "e": 28289, "s": 28286, "text": "Go" }, { "code": "typedef struct {int Delta, Width; double Value; } sample;", "e": 28347, "s": 28289, "text": null }, { "code": null, "e": 28751, "s": 28347, "text": " This algorithm operates only on sorted values. Let’s limit the buffer size to 500 values and define the size of the observation array as 2 × 500 + 2. As compression reduces the array size by approximately half, we’ll need on average 500 elements of the uncompressed array from the previous step + 500 elements added to the array in the current step + elements like to simplify searching in the array. " }, { "code": null, "e": 29086, "s": 28751, "text": "We worked on our implementation iteratively: created a version, checked its performance with a profiler, compared it with the Go version, then looked for ways to improve it. We assessed our results using a simple benchmark: 108 samples, which takes about 8 seconds for the Go version. Now let’s dive into details about each iteration." }, { "code": null, "e": 29216, "s": 29086, "text": "1. The pure-Lua version was quite bad, as the insertion took an average of about 100 seconds. The profiler data reads as follows:" }, { "code": null, "e": 29665, "s": 29216, "text": "The code underperforms on inserting observations into the corresponding array (`table.insert` call) and on buffer sorting (`table.sort`). That’s where ffi (foreign function interface) comes to the rescue. Ffi allows accessing functions from the C standard library and working with them in Lua as if they were routine Lua objects (well, almost; for example, while table indexing in Lua starts with 1, arrays created with C would still start with 0)." }, { "code": null, "e": 29764, "s": 29665, "text": "2. The Lua + ffi version involved building an array of double values instead of creating a buffer:" }, { "code": null, "e": 29767, "s": 29764, "text": "Go" }, { "code": "local ffi = require('ffi')...array = ffi.new('double[?]', max_samples)for i = 0, max_samples - 1 do array[i] = math.hugeend", "e": 29894, "s": 29767, "text": null }, { "code": null, "e": 29948, "s": 29894, "text": "We will sort this array using the C standard library:" }, { "code": null, "e": 29951, "s": 29948, "text": "Go" }, { "code": "ffi.cdef[[", "e": 29962, "s": 29951, "text": null }, { "code": null, "e": 29968, "s": 29965, "text": "Go" }, { "code": "void qsort(void *base, size_t nitems, size_t size, int (*compare)(const void *, const void*));int cmpfunc (const void * a, const void * b);", "e": 30108, "s": 29968, "text": null }, { "code": null, "e": 30237, "s": 30108, "text": "Let’s write a comparator function for `double` values in C and include it as a dynamic library. Here is the comparator function:" }, { "code": null, "e": 30240, "s": 30237, "text": "Go" }, { "code": "int cmpfunc (const void * a, const void * b) { if (*(double*)a > *(double*)b) return 1; else if (*(double*)a < *(double*)b) return -1; else return 0;}", "e": 30421, "s": 30240, "text": null }, { "code": null, "e": 30441, "s": 30421, "text": "Now let’s build it:" }, { "code": null, "e": 30444, "s": 30441, "text": "Go" }, { "code": "gcc -c -o metrics/quantile.o metrics/quantile.cgcc -shared -o metrics/libquantile.so metrics/quantile.o", "e": 30548, "s": 30444, "text": null }, { "code": null, "e": 30596, "s": 30548, "text": "Then we’ll include the library in our Lua code:" }, { "code": null, "e": 30599, "s": 30596, "text": "Go" }, { "code": "local dlib_path = package.search('libquantile', package.cpath)local dlib = ffi.load(dlib_path)", "e": 30694, "s": 30599, "text": null }, { "code": null, "e": 30757, "s": 30694, "text": "Now we can populate the `double` array and invoke its sorting:" }, { "code": null, "e": 30760, "s": 30757, "text": "Go" }, { "code": "local DOUBLE_SIZE = ffi.sizeof('double')ffi.C.qsort(array, len, DOUBLE_SIZE, dlib.cmpfunc)", "e": 30851, "s": 30760, "text": null }, { "code": null, "e": 31516, "s": 30851, "text": " Tests showed a 3x increase in performance, with insertion time averaging up to 30 seconds. This time, the code underperformed because Lua tables do not have a fixed size, and element types are not predefined, either. Although this allows for more flexibility in table processing, it notably reduces performance. With ffi, you can switch from Lua tables to fixed-size C arrays, so that inserting and calculating array size costs O(1) instead of O(log n). Sorting is also much faster due to the fixed types and, therefore, fixed element sizes. But this solution introduces a GCC dependency that complicates application delivery. So we had to get rid of the C code. " }, { "code": null, "e": 31785, "s": 31516, "text": "3. Lua + ffi + homebrew sorting. The simplest quicksort in Lua turned out to run only a couple of seconds longer than our previous version involving a C library. This result was good enough for us, especially since it didn’t depend on GCC, so we decided to stop here. " }, { "code": null, "e": 32389, "s": 31785, "text": "The last step was to add quantile rotation using the sliding window algorithm. We create a ring queue consisting of several collectors (5, for example) and make one of them the leading one (head). Monitored values are written to each of these collectors. After the specified time has expired (60 seconds, for instance), the head collector is reset and the next one in the queue becomes the new head. The quantile value is fetched from the current head only. This approach ensures that the data are kept up-to-date because, without a sliding window, the values would be calculated over the entire period." }, { "code": null, "e": 32425, "s": 32389, "text": "`metrics.quantile` uses two arrays:" }, { "code": null, "e": 32485, "s": 32425, "text": "A buffer of `max_samples * sizeof(double)` = 500 × 8 bytes." }, { "code": null, "e": 32685, "s": 32485, "text": "An observation array of `(2 * max_samples + 2) * sizeof(struct sample)` = 1002 × 16 bytes. The size of the observation array can increase when the observed values vary by several orders of magnitude." }, { "code": null, "e": 32778, "s": 32685, "text": "There are `age_buckets_count` collectors created in `metrics.summary`, so the total size is:" }, { "code": null, "e": 32931, "s": 32778, "text": "`age_buckets_count * (max_samples * sizeof(double) + (2 * max_samples + 2) * sizeof(struct sample))` = 5 × (500 × 8 + 1002 × 16) bytes, or about 100 KB." }, { "code": null, "e": 33045, "s": 32931, "text": "We performed load testing with Yandex.Tank. With all application metrics turned off, the results read as follows:" }, { "code": null, "e": 33073, "s": 33045, "text": "With our summary collector:" }, { "code": null, "e": 33293, "s": 33073, "text": "Performance dropped by ~10%, which is a cost you have to pay for using metrics. If you want to avoid significant drawdown, you might want to use the collector carefully, for instance, measure only a portion of requests." }, { "code": null, "e": 33296, "s": 33293, "text": "Go" }, { "code": "tarantoolctl rocks install metrics 0.10.0", "e": 33338, "s": 33296, "text": null }, { "code": null, "e": 33341, "s": 33338, "text": "Go" }, { "code": "local metrics = require('metrics') -- attaching metrics -- Creating a summary collectorlocal http_requests_latency = metrics.summary( 'http_requests_latency', 'HTTP requests latency', {[0.5]=0.01, [0.9]=0.01, [0.99]=0.01}, {max_age_time = 60, age_buckets_count = 5}) -- Monitoring a valuelocal latency = math.random(1, 10)http_requests_latency:observe(latency)", "e": 33711, "s": 33341, "text": null }, { "code": null, "e": 33830, "s": 33711, "text": "Export to JSON, Prometheus, and Graphite is supported. Here is what the collected results might look like in Grafana: " }, { "code": null, "e": 34388, "s": 33830, "text": "We wrote a summary collector for tarantool/metrics. During development, we encountered a performance challenge, which we solved using ffi. You can use the new collector to monitor values that may benefit from keeping track of quantiles, such as HTTP request latency. The summary collector can be applied in any Tarantool-based product where service response time is critical, like data-intensive applications where large amounts of data are accessed via HTTP requests. Monitoring this metric will help you understand what requests are straining your system." }, { "code": null, "e": 34435, "s": 34388, "text": "This article is contributed by Igor Zolotarev." }, { "code": null, "e": 34450, "s": 34435, "text": "kapoorsagar226" }, { "code": null, "e": 34462, "s": 34450, "text": "Go Language" }, { "code": null, "e": 34479, "s": 34462, "text": "Machine Learning" }, { "code": null, "e": 34496, "s": 34479, "text": "Machine Learning" }, { "code": null, "e": 34594, "s": 34496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34640, "s": 34594, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 34669, "s": 34640, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 34694, "s": 34669, "text": "Time Durations in Golang" }, { "code": null, "e": 34712, "s": 34694, "text": "Strings in Golang" }, { "code": null, "e": 34733, "s": 34712, "text": "Structures in Golang" }, { "code": null, "e": 34757, "s": 34733, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 34799, "s": 34757, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 34822, "s": 34799, "text": "ML | Linear Regression" }, { "code": null, "e": 34845, "s": 34822, "text": "Reinforcement learning" } ]
HashSet In Scala - GeeksforGeeks
04 Jul, 2019 HashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantics is known HashSet.Syntax: var HashsetName = HashSet(element1, element2, element3, ....) Initialize a HashSet : Below is the example to create or initialize HashSet.Example :// Scala program of Initializing HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hashSet: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hashSet") }} Output:Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) // Scala program of Initializing HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hashSet: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hashSet") }} Output: Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Check specific elements in HashSet :Example :// Scala program of Check specific elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hashSet: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hashSet") // Checking println(s"Element Geeks = ${hashSet("Geeks")}") println(s"Element Student = ${hashSet("Student")}") }} Output:Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Element Geeks = true Element Student = false // Scala program of Check specific elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hashSet: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hashSet") // Checking println(s"Element Geeks = ${hashSet("Geeks")}") println(s"Element Student = ${hashSet("Student")}") }} Output: Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Element Geeks = true Element Student = false Adding an elements in HashSet : We can add an element in HashSet by using + sign. below is the example of adding an element in HashSet.Example :// Scala program of adding an element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // Adding an element in HashSet val hs1: HashSet[String] = hs + "GeeksClasses" println(s"Adding elements to HashSet = $hs1") }}Output:Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Adding elements to HashSet = Set(GeeksClasses, Geeks, Author, GeeksForGeeks) // Scala program of adding an element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // Adding an element in HashSet val hs1: HashSet[String] = hs + "GeeksClasses" println(s"Adding elements to HashSet = $hs1") }} Output: Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Adding elements to HashSet = Set(GeeksClasses, Geeks, Author, GeeksForGeeks) Adding more than one element in HashSet : We can add more than one element in HashSet by using ++ sign. below is the example of adding more than one elements in HashSet.Example :// Scala program of adding more elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // Adding elements in HashSet val hs1: HashSet[String] = hs ++ HashSet[String]("Java", "Scala") println(s"Add more than one HashSets = $hs1") }}Output:Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Add more than one HashSets = Set(Scala, Geeks, Author, Java, GeeksForGeeks) // Scala program of adding more elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // Adding elements in HashSet val hs1: HashSet[String] = hs ++ HashSet[String]("Java", "Scala") println(s"Add more than one HashSets = $hs1") }} Output: Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) Add more than one HashSets = Set(Scala, Geeks, Author, Java, GeeksForGeeks) Remove element in HashSet : We can remove an element in HashSet by using – sign. below is the example of removing an element in HashSet.Example :// Scala program of removing element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // removing elements in HashSet val hs1: HashSet[String] = hs - "Geeks" println(s"remove element from hashset = $hs1") }}Output:Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) remove element from hashset = Set(Author, GeeksForGeeks) // Scala program of removing element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize a HashSet") // Creating HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements are = $hs") // removing elements in HashSet val hs1: HashSet[String] = hs - "Geeks" println(s"remove element from hashset = $hs1") }} Output: Initialize a HashSet Elements are = Set(Geeks, Author, GeeksForGeeks) remove element from hashset = Set(Author, GeeksForGeeks) Find the intersection between two HashSets : We can find intersection between two HashSets by using & sign. below is the example of finding intersection between two HashSets.Example :// Scala program of finding the intersection between two HashSetsimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize two HashSets") // Creating two HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements of hashset1 are = $hs") val hs1: HashSet[String] = HashSet("Java", "Geeks", "Scala") println(s"Elements of hashset2 are = $hs1") // finding the intersection between two HashSets println(s"Intersection of hashSet1 and hashSet2 = ${hs & hs1}") }}Output:Initialize two HashSets Elements of hashset1 are = Set(Geeks, Author, GeeksForGeeks) Elements of hashset2 are = Set(Scala, Geeks, Java) Intersection of hashSet1 and hashSet2 = Set(Geeks) // Scala program of finding the intersection between two HashSetsimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println("Initialize two HashSets") // Creating two HashSet val hs: HashSet[String] = HashSet("Geeks", "GeeksForGeeks", "Author") println(s"Elements of hashset1 are = $hs") val hs1: HashSet[String] = HashSet("Java", "Geeks", "Scala") println(s"Elements of hashset2 are = $hs1") // finding the intersection between two HashSets println(s"Intersection of hashSet1 and hashSet2 = ${hs & hs1}") }} Output: Initialize two HashSets Elements of hashset1 are = Set(Geeks, Author, GeeksForGeeks) Elements of hashset2 are = Set(Scala, Geeks, Java) Intersection of hashSet1 and hashSet2 = Set(Geeks) Initializing an empty HashSet :Example :// Scala program of Initializing an empty HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Initializing an empty HashSet val emptyHashSet: HashSet[String] = HashSet.empty[String] println(s"Empty HashSet = $emptyHashSet") }}Output:Empty HashSet = Set() // Scala program of Initializing an empty HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Initializing an empty HashSet val emptyHashSet: HashSet[String] = HashSet.empty[String] println(s"Empty HashSet = $emptyHashSet") }} Output: Empty HashSet = Set() Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | flatMap Method Scala | map() method Scala List filter() method with example Scala | reduce() Function String concatenation in Scala Type Casting in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala List contains() method with example Scala String substring() method with example
[ { "code": null, "e": 26063, "s": 26035, "text": "\n04 Jul, 2019" }, { "code": null, "e": 26390, "s": 26063, "text": "HashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantics is known HashSet.Syntax:" }, { "code": null, "e": 26454, "s": 26390, "text": "var HashsetName = HashSet(element1, element2, element3, ....) " }, { "code": null, "e": 27028, "s": 26454, "text": "Initialize a HashSet : Below is the example to create or initialize HashSet.Example :// Scala program of Initializing HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hashSet: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hashSet\") }} Output:Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)" }, { "code": "// Scala program of Initializing HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hashSet: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hashSet\") }} ", "e": 27441, "s": 27028, "text": null }, { "code": null, "e": 27449, "s": 27441, "text": "Output:" }, { "code": null, "e": 27519, "s": 27449, "text": "Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)" }, { "code": null, "e": 28252, "s": 27519, "text": "Check specific elements in HashSet :Example :// Scala program of Check specific elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hashSet: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hashSet\") // Checking println(s\"Element Geeks = ${hashSet(\"Geeks\")}\") println(s\"Element Student = ${hashSet(\"Student\")}\") }} Output:Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nElement Geeks = true\nElement Student = false\n" }, { "code": "// Scala program of Check specific elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hashSet: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hashSet\") // Checking println(s\"Element Geeks = ${hashSet(\"Geeks\")}\") println(s\"Element Student = ${hashSet(\"Student\")}\") }} ", "e": 28818, "s": 28252, "text": null }, { "code": null, "e": 28826, "s": 28818, "text": "Output:" }, { "code": null, "e": 28942, "s": 28826, "text": "Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nElement Geeks = true\nElement Student = false\n" }, { "code": null, "e": 29798, "s": 28942, "text": "Adding an elements in HashSet : We can add an element in HashSet by using + sign. below is the example of adding an element in HashSet.Example :// Scala program of adding an element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // Adding an element in HashSet val hs1: HashSet[String] = hs + \"GeeksClasses\" println(s\"Adding elements to HashSet = $hs1\") }}Output:Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nAdding elements to HashSet = Set(GeeksClasses, Geeks, Author, GeeksForGeeks)\n" }, { "code": "// Scala program of adding an element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // Adding an element in HashSet val hs1: HashSet[String] = hs + \"GeeksClasses\" println(s\"Adding elements to HashSet = $hs1\") }}", "e": 30356, "s": 29798, "text": null }, { "code": null, "e": 30364, "s": 30356, "text": "Output:" }, { "code": null, "e": 30512, "s": 30364, "text": "Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nAdding elements to HashSet = Set(GeeksClasses, Geeks, Author, GeeksForGeeks)\n" }, { "code": null, "e": 31425, "s": 30512, "text": "Adding more than one element in HashSet : We can add more than one element in HashSet by using ++ sign. below is the example of adding more than one elements in HashSet.Example :// Scala program of adding more elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // Adding elements in HashSet val hs1: HashSet[String] = hs ++ HashSet[String](\"Java\", \"Scala\") println(s\"Add more than one HashSets = $hs1\") }}Output:Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nAdd more than one HashSets = Set(Scala, Geeks, Author, Java, GeeksForGeeks)\n" }, { "code": "// Scala program of adding more elements in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // Adding elements in HashSet val hs1: HashSet[String] = hs ++ HashSet[String](\"Java\", \"Scala\") println(s\"Add more than one HashSets = $hs1\") }}", "e": 32007, "s": 31425, "text": null }, { "code": null, "e": 32015, "s": 32007, "text": "Output:" }, { "code": null, "e": 32162, "s": 32015, "text": "Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nAdd more than one HashSets = Set(Scala, Geeks, Author, Java, GeeksForGeeks)\n" }, { "code": null, "e": 32995, "s": 32162, "text": "Remove element in HashSet : We can remove an element in HashSet by using – sign. below is the example of removing an element in HashSet.Example :// Scala program of removing element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // removing elements in HashSet val hs1: HashSet[String] = hs - \"Geeks\" println(s\"remove element from hashset = $hs1\") }}Output:Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nremove element from hashset = Set(Author, GeeksForGeeks)" }, { "code": "// Scala program of removing element in HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize a HashSet\") // Creating HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements are = $hs\") // removing elements in HashSet val hs1: HashSet[String] = hs - \"Geeks\" println(s\"remove element from hashset = $hs1\") }}", "e": 33550, "s": 32995, "text": null }, { "code": null, "e": 33558, "s": 33550, "text": "Output:" }, { "code": null, "e": 33685, "s": 33558, "text": "Initialize a HashSet\nElements are = Set(Geeks, Author, GeeksForGeeks)\nremove element from hashset = Set(Author, GeeksForGeeks)" }, { "code": null, "e": 34803, "s": 33685, "text": "Find the intersection between two HashSets : We can find intersection between two HashSets by using & sign. below is the example of finding intersection between two HashSets.Example :// Scala program of finding the intersection between two HashSetsimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize two HashSets\") // Creating two HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements of hashset1 are = $hs\") val hs1: HashSet[String] = HashSet(\"Java\", \"Geeks\", \"Scala\") println(s\"Elements of hashset2 are = $hs1\") // finding the intersection between two HashSets println(s\"Intersection of hashSet1 and hashSet2 = ${hs & hs1}\") }}Output:Initialize two HashSets\nElements of hashset1 are = Set(Geeks, Author, GeeksForGeeks)\nElements of hashset2 are = Set(Scala, Geeks, Java)\nIntersection of hashSet1 and hashSet2 = Set(Geeks)\n" }, { "code": "// Scala program of finding the intersection between two HashSetsimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { println(\"Initialize two HashSets\") // Creating two HashSet val hs: HashSet[String] = HashSet(\"Geeks\", \"GeeksForGeeks\", \"Author\") println(s\"Elements of hashset1 are = $hs\") val hs1: HashSet[String] = HashSet(\"Java\", \"Geeks\", \"Scala\") println(s\"Elements of hashset2 are = $hs1\") // finding the intersection between two HashSets println(s\"Intersection of hashSet1 and hashSet2 = ${hs & hs1}\") }}", "e": 35543, "s": 34803, "text": null }, { "code": null, "e": 35551, "s": 35543, "text": "Output:" }, { "code": null, "e": 35740, "s": 35551, "text": "Initialize two HashSets\nElements of hashset1 are = Set(Geeks, Author, GeeksForGeeks)\nElements of hashset2 are = Set(Scala, Geeks, Java)\nIntersection of hashSet1 and hashSet2 = Set(Geeks)\n" }, { "code": null, "e": 36148, "s": 35740, "text": "Initializing an empty HashSet :Example :// Scala program of Initializing an empty HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Initializing an empty HashSet val emptyHashSet: HashSet[String] = HashSet.empty[String] println(s\"Empty HashSet = $emptyHashSet\") }}Output:Empty HashSet = Set()" }, { "code": "// Scala program of Initializing an empty HashSetimport scala.collection.immutable.HashSet // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Initializing an empty HashSet val emptyHashSet: HashSet[String] = HashSet.empty[String] println(s\"Empty HashSet = $emptyHashSet\") }}", "e": 36488, "s": 36148, "text": null }, { "code": null, "e": 36496, "s": 36488, "text": "Output:" }, { "code": null, "e": 36518, "s": 36496, "text": "Empty HashSet = Set()" }, { "code": null, "e": 36524, "s": 36518, "text": "Scala" }, { "code": null, "e": 36622, "s": 36524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36640, "s": 36622, "text": "For Loop in Scala" }, { "code": null, "e": 36663, "s": 36640, "text": "Scala | flatMap Method" }, { "code": null, "e": 36684, "s": 36663, "text": "Scala | map() method" }, { "code": null, "e": 36724, "s": 36684, "text": "Scala List filter() method with example" }, { "code": null, "e": 36750, "s": 36724, "text": "Scala | reduce() Function" }, { "code": null, "e": 36780, "s": 36750, "text": "String concatenation in Scala" }, { "code": null, "e": 36802, "s": 36780, "text": "Type Casting in Scala" }, { "code": null, "e": 36855, "s": 36802, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 36897, "s": 36855, "text": "Scala List contains() method with example" } ]
Golang | Checking the byte of slice for specified regular expression - GeeksforGeeks
05 Sep, 2019 A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.In Go regexp, you are allowed to check whether the given slice byte contains any match of the specified regular expression pattern with the help of Match() function. This function is defined under the regexp package, so for accessing this method you need to import the regexp package in your program. Syntax: func Match(p string, s []byte) (result bool, err error) Here, p represents the pattern and s represents a slice of bytes. This function returns true if the pattern matched or return false if the pattern does not match. And also return an error if found. Example 1: // Go program to illustrate how to check// the given regexp present in the given slicepackage main import ( "fmt" "regexp") // Main functionfunc main() { // Creating and initializing // slice of bytes // Using shorthand declaration s1 := []byte{'G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'} s2 := []byte{'g', 'f', 'g'} // Pattern p1 := "G" p2 := "g" p3 := "^^" p4 := "@" // Matching pattern // Using Match() function res1, e := regexp.Match(p1, s1) fmt.Println("Result and Error is:", res1, e) res2, e := regexp.Match(p2, s1) fmt.Println("Result and Error is:", res2, e) res3, e := regexp.Match(p3, s1) fmt.Println("Result and Error is:", res3, e) res4, e := regexp.Match(p4, s1) fmt.Println("Result and Error is:", res4, e) res5, e := regexp.Match(p1, s2) fmt.Println("Result and Error is:", res5, e) res6, e := regexp.Match(p2, s2) fmt.Println("Result and Error is:", res6, e) res7, e := regexp.Match(p3, s2) fmt.Println("Result and Error is:", res7, e) res8, e := regexp.Match(p4, s2) fmt.Println("Result and Error is:", res8, e) } Output: Result and Error is: true <nil> Result and Error is: false <nil> Result and Error is: true <nil> Result and Error is: false <nil> Result and Error is: false <nil> Result and Error is: true <nil> Result and Error is: true <nil> Result and Error is: false <nil> Example 2: // Go program to illustrate how to check// the given regexp present in the given slicepackage main import ( "fmt" "regexp") // Main functionfunc main() { // Matching pattern in the // given slice of bytes // Using Match() function res1, e := regexp.Match(`eks`, []byte(`GeeksforGeeks`)) fmt.Println(res1, e) res2, e := regexp.Match(`BAN`, []byte(`Banana`)) fmt.Println(res2, e) res3, e := regexp.Match(`123`, []byte(`GeeksforGeeks`)) fmt.Println(res3, e) res4, e := regexp.Match(`e(ks`, []byte(`GeeksforGeeks`)) fmt.Println(res4, e) } Output: true <nil> false <nil> false <nil> false error parsing regexp: missing closing ): `e(ks` Golang Golang-Slices Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Golang Maps Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang How to Trim a String in Golang? How to compare times in Golang?
[ { "code": null, "e": 25659, "s": 25631, "text": "\n05 Sep, 2019" }, { "code": null, "e": 26258, "s": 25659, "text": "A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.In Go regexp, you are allowed to check whether the given slice byte contains any match of the specified regular expression pattern with the help of Match() function. This function is defined under the regexp package, so for accessing this method you need to import the regexp package in your program." }, { "code": null, "e": 26266, "s": 26258, "text": "Syntax:" }, { "code": null, "e": 26322, "s": 26266, "text": "func Match(p string, s []byte) (result bool, err error)" }, { "code": null, "e": 26520, "s": 26322, "text": "Here, p represents the pattern and s represents a slice of bytes. This function returns true if the pattern matched or return false if the pattern does not match. And also return an error if found." }, { "code": null, "e": 26531, "s": 26520, "text": "Example 1:" }, { "code": "// Go program to illustrate how to check// the given regexp present in the given slicepackage main import ( \"fmt\" \"regexp\") // Main functionfunc main() { // Creating and initializing // slice of bytes // Using shorthand declaration s1 := []byte{'G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S'} s2 := []byte{'g', 'f', 'g'} // Pattern p1 := \"G\" p2 := \"g\" p3 := \"^^\" p4 := \"@\" // Matching pattern // Using Match() function res1, e := regexp.Match(p1, s1) fmt.Println(\"Result and Error is:\", res1, e) res2, e := regexp.Match(p2, s1) fmt.Println(\"Result and Error is:\", res2, e) res3, e := regexp.Match(p3, s1) fmt.Println(\"Result and Error is:\", res3, e) res4, e := regexp.Match(p4, s1) fmt.Println(\"Result and Error is:\", res4, e) res5, e := regexp.Match(p1, s2) fmt.Println(\"Result and Error is:\", res5, e) res6, e := regexp.Match(p2, s2) fmt.Println(\"Result and Error is:\", res6, e) res7, e := regexp.Match(p3, s2) fmt.Println(\"Result and Error is:\", res7, e) res8, e := regexp.Match(p4, s2) fmt.Println(\"Result and Error is:\", res8, e) }", "e": 27725, "s": 26531, "text": null }, { "code": null, "e": 27733, "s": 27725, "text": "Output:" }, { "code": null, "e": 27994, "s": 27733, "text": "Result and Error is: true <nil>\nResult and Error is: false <nil>\nResult and Error is: true <nil>\nResult and Error is: false <nil>\nResult and Error is: false <nil>\nResult and Error is: true <nil>\nResult and Error is: true <nil>\nResult and Error is: false <nil>\n" }, { "code": null, "e": 28005, "s": 27994, "text": "Example 2:" }, { "code": "// Go program to illustrate how to check// the given regexp present in the given slicepackage main import ( \"fmt\" \"regexp\") // Main functionfunc main() { // Matching pattern in the // given slice of bytes // Using Match() function res1, e := regexp.Match(`eks`, []byte(`GeeksforGeeks`)) fmt.Println(res1, e) res2, e := regexp.Match(`BAN`, []byte(`Banana`)) fmt.Println(res2, e) res3, e := regexp.Match(`123`, []byte(`GeeksforGeeks`)) fmt.Println(res3, e) res4, e := regexp.Match(`e(ks`, []byte(`GeeksforGeeks`)) fmt.Println(res4, e) }", "e": 28590, "s": 28005, "text": null }, { "code": null, "e": 28598, "s": 28590, "text": "Output:" }, { "code": null, "e": 28688, "s": 28598, "text": "true <nil>\nfalse <nil>\nfalse <nil>\nfalse error parsing regexp: missing closing ): `e(ks`\n" }, { "code": null, "e": 28695, "s": 28688, "text": "Golang" }, { "code": null, "e": 28709, "s": 28695, "text": "Golang-Slices" }, { "code": null, "e": 28721, "s": 28709, "text": "Go Language" }, { "code": null, "e": 28819, "s": 28721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28865, "s": 28819, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28916, "s": 28865, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28963, "s": 28916, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28996, "s": 28963, "text": "How to Split a String in Golang?" }, { "code": null, "e": 29008, "s": 28996, "text": "Golang Maps" }, { "code": null, "e": 29030, "s": 29008, "text": "Inheritance in GoLang" }, { "code": null, "e": 29084, "s": 29030, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 29105, "s": 29084, "text": "Interfaces in Golang" }, { "code": null, "e": 29137, "s": 29105, "text": "How to Trim a String in Golang?" } ]
Find all palindromic sub-strings of a given string | Set 2 - GeeksforGeeks
04 Aug, 2021 Given a string, the task is to find all the palindromic sub-strings from the given string.In Set – 1, another approach has been already discussed and that consider only distinct sub-strings but in this equal sub-strings i.e. ll and ll are considered as two sub-strings, not one. Examples: Input : hellolle Output : 13 [h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e] Explanation: 1) ellolle 2) ll, ll – Note that these are two distinct sub-strings that only happen to be equal 3) lol and lloll 4) And, of course, each letter can be considered a palindrome – all 8 of them. Input : geeksforgeeks Output : 15 [g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s] Approach: 1- We can have two types of palindrome strings that we need to handle -Even Length -Odd Length 2- The idea is to consider a mid point and keep checking for the palindrome string by comparing the elements on the left and the elements on the right by increasing the distance or palindromeRadius by one at a time until there is a mismatch. 3- The algorithm handles the even and odd length palindrome scenarios in a single pass. 4- The pivot starts from 0 and moves till the end with a step size of 0.5. .......a) when the pivot is a non-fractional value, then the palindromeRadius values are integral starting from 0. .......b) when the pivot is a fractional value, then the palindromeRadius values are like 0.5, 1.5, 2.5, 3.5 .. 5- So, each time we get a palindrome match, we put it in a list (so that the duplicate values are preserved because each duplicate sub-string is obtained by a different combination of alphabet positions) C++ Java Python3 C# Javascript // c++ program to Count number of ways we// can get palindrome string from a given// string#include<bits/stdc++.h>using namespace std; // function to find the substring of the// stringstring substring(string s,int a,int b){ string s1=""; // extract the specified position of // the string for(int i = a; i < b; i++) s1 = s1 + s[i]; return s1;} // can get palindrome string from a// given stringvector<string> allPalindromeSubstring(string s){ vector<string> v ; // moving the pivot from starting till // end of the string for (float pivot = 0; pivot < s.length(); pivot += .5) { // set radius to the first nearest // element on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be // compared has an element and the // characters at left and right // matches while ((pivot + palindromeRadius) < s.length() && (pivot - palindromeRadius) >= 0 && s[((int)(pivot - palindromeRadius))] == s[((int)(pivot + palindromeRadius))]) { v.push_back(substring(s,(int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point // to the next elements in left and right palindromeRadius++; } } return v;} // Driver codeint main(){ vector <string> v = allPalindromeSubstring("hellolle"); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << ","; cout << endl; v = allPalindromeSubstring("geeksforgeeks"); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << ",";} // This code is contributed by Arnab Kundu. // Java program to Count number of ways we// can get palindrome string from a given stringimport java.util.ArrayList;import java.util.List; public class AllPalindromeSubstringsPossible { public static List<String> allPalindromeSubstring(String s) { List<String> list = new ArrayList<String>(); // moving the pivot from starting till end of the string for (float pivot = 0; pivot < s.length(); pivot += .5) { // set radius to the first nearest element // on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.length() && (pivot - palindromeRadius) >= 0 && s.charAt((int)(pivot - palindromeRadius)) == s.charAt((int)(pivot + palindromeRadius))) { list.add(s.substring((int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list; } // Drivers code public static void main(String[] args) { List<String> list = allPalindromeSubstring("hellolle"); System.out.println(list.size()); System.out.println(list); list = allPalindromeSubstring("geeksforgeeks"); System.out.println(list.size()); System.out.println(list); }} # Python3 program to Count number of ways we# can get palindrome string from a given# string # function to find the substring of the# stringdef substring(s, a, b): s1 = "" # extract the specified position of # the string for i in range(a, b, 1): s1 += s[i] return s1 # can get palindrome string from a# given stringdef allPalindromeSubstring(s): v = [] # moving the pivot from starting till # end of the string pivot = 0.0 while pivot < len(s): # set radius to the first nearest # element on left and right palindromeRadius = pivot - int(pivot) # if the position needs to be # compared has an element and the # characters at left and right # matches while ((pivot + palindromeRadius) < len(s) and (pivot - palindromeRadius) >= 0 and (s[int(pivot - palindromeRadius)] == s[int(pivot + palindromeRadius)])): v.append(s[int(pivot - palindromeRadius): int(pivot + palindromeRadius + 1)]) # increasing the radius by 1 to point # to the next elements in left and right palindromeRadius += 1 pivot += 0.5 return v # Driver Codeif __name__ == "__main__": v = allPalindromeSubstring("hellolle") print(len(v)) print(v) v = allPalindromeSubstring("geeksforgeeks") print(len(v)) print(v) # This code is contributed by# sanjeev2552 // C# program to Count number of ways we// can get palindrome string from a given stringusing System;using System.Collections.Generic; public class AllPalindromeSubstringsPossible{ public static List<String> allPalindromeSubstring(String s) { List<String> list = new List<String>(); // moving the pivot from starting till end of the string for (float pivot = 0; pivot < s.Length; pivot+= (float).5) { // set radius to the first nearest element // on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.Length && (pivot - palindromeRadius) >= 0 && s[(int)(pivot - palindromeRadius)] == s[(int)(pivot + palindromeRadius)]) { list.Add(s.Substring((int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1)- (int)(pivot - palindromeRadius))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list; } // Drivers code public static void Main(String[] args) { List<String> list = allPalindromeSubstring("hellolle"); Console.WriteLine(list.Count); for(int i = 0; i < list.Count; i++) Console.Write(list[i]+","); list = allPalindromeSubstring("geeksforgeeks"); Console.WriteLine("\n"+list.Count); for(int i = 0; i < list.Count; i++) Console.Write(list[i]+","); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to Count number of ways we// can get palindrome string from a given string function allPalindromeSubstring(s){ let list = []; // moving the pivot from starting till end of the string for (let pivot = 0; pivot < s.length; pivot += .5) { // set radius to the first nearest element // on left and right let palindromeRadius = pivot - Math.floor(pivot); // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.length && (pivot - palindromeRadius) >= 0 && s[(Math.floor(pivot - palindromeRadius))] == s[Math.floor(pivot + palindromeRadius)]) { list.push(s.substring(Math.floor(pivot - palindromeRadius), Math.floor(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list;} // Drivers codelet list = allPalindromeSubstring("hellolle");document.write(list.length+"<br>");document.write("["+list.join(", ")+"]<br>");list = allPalindromeSubstring("geeksforgeeks");document.write(list.length+"<br>");document.write("["+list.join(", ")+"]<br>"); // This code is contributed by avanitrachhadiya2155 </script> 13 [h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e] 15 [g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s] Note: To print distinct substrings, use Set as it only takes distinct elements. andrew1234 princiraj1992 sanjeev2552 avanitrachhadiya2155 surindertarika1234 Java-String-Programs palindrome Java Java Programs Strings Strings Java palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Queue Interface In Java LinkedList in Java HashMap in Java with Examples ArrayList in Java Convert a String to Character Array in Java Initializing a List in Java How to Iterate HashMap in Java? Convert Double to Integer in Java Iterate Over the Characters of a String in Java
[ { "code": null, "e": 26015, "s": 25987, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26294, "s": 26015, "text": "Given a string, the task is to find all the palindromic sub-strings from the given string.In Set – 1, another approach has been already discussed and that consider only distinct sub-strings but in this equal sub-strings i.e. ll and ll are considered as two sub-strings, not one." }, { "code": null, "e": 26305, "s": 26294, "text": "Examples: " }, { "code": null, "e": 26678, "s": 26305, "text": "Input : hellolle Output : 13 [h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e] Explanation: 1) ellolle 2) ll, ll – Note that these are two distinct sub-strings that only happen to be equal 3) lol and lloll 4) And, of course, each letter can be considered a palindrome – all 8 of them. Input : geeksforgeeks Output : 15 [g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s]" }, { "code": null, "e": 27619, "s": 26678, "text": "Approach: 1- We can have two types of palindrome strings that we need to handle -Even Length -Odd Length 2- The idea is to consider a mid point and keep checking for the palindrome string by comparing the elements on the left and the elements on the right by increasing the distance or palindromeRadius by one at a time until there is a mismatch. 3- The algorithm handles the even and odd length palindrome scenarios in a single pass. 4- The pivot starts from 0 and moves till the end with a step size of 0.5. .......a) when the pivot is a non-fractional value, then the palindromeRadius values are integral starting from 0. .......b) when the pivot is a fractional value, then the palindromeRadius values are like 0.5, 1.5, 2.5, 3.5 .. 5- So, each time we get a palindrome match, we put it in a list (so that the duplicate values are preserved because each duplicate sub-string is obtained by a different combination of alphabet positions)" }, { "code": null, "e": 27623, "s": 27619, "text": "C++" }, { "code": null, "e": 27628, "s": 27623, "text": "Java" }, { "code": null, "e": 27636, "s": 27628, "text": "Python3" }, { "code": null, "e": 27639, "s": 27636, "text": "C#" }, { "code": null, "e": 27650, "s": 27639, "text": "Javascript" }, { "code": "// c++ program to Count number of ways we// can get palindrome string from a given// string#include<bits/stdc++.h>using namespace std; // function to find the substring of the// stringstring substring(string s,int a,int b){ string s1=\"\"; // extract the specified position of // the string for(int i = a; i < b; i++) s1 = s1 + s[i]; return s1;} // can get palindrome string from a// given stringvector<string> allPalindromeSubstring(string s){ vector<string> v ; // moving the pivot from starting till // end of the string for (float pivot = 0; pivot < s.length(); pivot += .5) { // set radius to the first nearest // element on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be // compared has an element and the // characters at left and right // matches while ((pivot + palindromeRadius) < s.length() && (pivot - palindromeRadius) >= 0 && s[((int)(pivot - palindromeRadius))] == s[((int)(pivot + palindromeRadius))]) { v.push_back(substring(s,(int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point // to the next elements in left and right palindromeRadius++; } } return v;} // Driver codeint main(){ vector <string> v = allPalindromeSubstring(\"hellolle\"); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << \",\"; cout << endl; v = allPalindromeSubstring(\"geeksforgeeks\"); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << \",\";} // This code is contributed by Arnab Kundu.", "e": 29564, "s": 27650, "text": null }, { "code": "// Java program to Count number of ways we// can get palindrome string from a given stringimport java.util.ArrayList;import java.util.List; public class AllPalindromeSubstringsPossible { public static List<String> allPalindromeSubstring(String s) { List<String> list = new ArrayList<String>(); // moving the pivot from starting till end of the string for (float pivot = 0; pivot < s.length(); pivot += .5) { // set radius to the first nearest element // on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.length() && (pivot - palindromeRadius) >= 0 && s.charAt((int)(pivot - palindromeRadius)) == s.charAt((int)(pivot + palindromeRadius))) { list.add(s.substring((int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list; } // Drivers code public static void main(String[] args) { List<String> list = allPalindromeSubstring(\"hellolle\"); System.out.println(list.size()); System.out.println(list); list = allPalindromeSubstring(\"geeksforgeeks\"); System.out.println(list.size()); System.out.println(list); }}", "e": 31193, "s": 29564, "text": null }, { "code": "# Python3 program to Count number of ways we# can get palindrome string from a given# string # function to find the substring of the# stringdef substring(s, a, b): s1 = \"\" # extract the specified position of # the string for i in range(a, b, 1): s1 += s[i] return s1 # can get palindrome string from a# given stringdef allPalindromeSubstring(s): v = [] # moving the pivot from starting till # end of the string pivot = 0.0 while pivot < len(s): # set radius to the first nearest # element on left and right palindromeRadius = pivot - int(pivot) # if the position needs to be # compared has an element and the # characters at left and right # matches while ((pivot + palindromeRadius) < len(s) and (pivot - palindromeRadius) >= 0 and (s[int(pivot - palindromeRadius)] == s[int(pivot + palindromeRadius)])): v.append(s[int(pivot - palindromeRadius): int(pivot + palindromeRadius + 1)]) # increasing the radius by 1 to point # to the next elements in left and right palindromeRadius += 1 pivot += 0.5 return v # Driver Codeif __name__ == \"__main__\": v = allPalindromeSubstring(\"hellolle\") print(len(v)) print(v) v = allPalindromeSubstring(\"geeksforgeeks\") print(len(v)) print(v) # This code is contributed by# sanjeev2552", "e": 32665, "s": 31193, "text": null }, { "code": "// C# program to Count number of ways we// can get palindrome string from a given stringusing System;using System.Collections.Generic; public class AllPalindromeSubstringsPossible{ public static List<String> allPalindromeSubstring(String s) { List<String> list = new List<String>(); // moving the pivot from starting till end of the string for (float pivot = 0; pivot < s.Length; pivot+= (float).5) { // set radius to the first nearest element // on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.Length && (pivot - palindromeRadius) >= 0 && s[(int)(pivot - palindromeRadius)] == s[(int)(pivot + palindromeRadius)]) { list.Add(s.Substring((int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1)- (int)(pivot - palindromeRadius))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list; } // Drivers code public static void Main(String[] args) { List<String> list = allPalindromeSubstring(\"hellolle\"); Console.WriteLine(list.Count); for(int i = 0; i < list.Count; i++) Console.Write(list[i]+\",\"); list = allPalindromeSubstring(\"geeksforgeeks\"); Console.WriteLine(\"\\n\"+list.Count); for(int i = 0; i < list.Count; i++) Console.Write(list[i]+\",\"); }} /* This code contributed by PrinciRaj1992 */", "e": 34476, "s": 32665, "text": null }, { "code": "<script> // JavaScript program to Count number of ways we// can get palindrome string from a given string function allPalindromeSubstring(s){ let list = []; // moving the pivot from starting till end of the string for (let pivot = 0; pivot < s.length; pivot += .5) { // set radius to the first nearest element // on left and right let palindromeRadius = pivot - Math.floor(pivot); // if the position needs to be compared has an element // and the characters at left and right matches while ((pivot + palindromeRadius) < s.length && (pivot - palindromeRadius) >= 0 && s[(Math.floor(pivot - palindromeRadius))] == s[Math.floor(pivot + palindromeRadius)]) { list.push(s.substring(Math.floor(pivot - palindromeRadius), Math.floor(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point to the // next elements in left and right palindromeRadius++; } } return list;} // Drivers codelet list = allPalindromeSubstring(\"hellolle\");document.write(list.length+\"<br>\");document.write(\"[\"+list.join(\", \")+\"]<br>\");list = allPalindromeSubstring(\"geeksforgeeks\");document.write(list.length+\"<br>\");document.write(\"[\"+list.join(\", \")+\"]<br>\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 35985, "s": 34476, "text": null }, { "code": null, "e": 36093, "s": 35985, "text": "13\n[h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e]\n15\n[g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s]" }, { "code": null, "e": 36176, "s": 36095, "text": "Note: To print distinct substrings, use Set as it only takes distinct elements. " }, { "code": null, "e": 36187, "s": 36176, "text": "andrew1234" }, { "code": null, "e": 36201, "s": 36187, "text": "princiraj1992" }, { "code": null, "e": 36213, "s": 36201, "text": "sanjeev2552" }, { "code": null, "e": 36234, "s": 36213, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36253, "s": 36234, "text": "surindertarika1234" }, { "code": null, "e": 36274, "s": 36253, "text": "Java-String-Programs" }, { "code": null, "e": 36285, "s": 36274, "text": "palindrome" }, { "code": null, "e": 36290, "s": 36285, "text": "Java" }, { "code": null, "e": 36304, "s": 36290, "text": "Java Programs" }, { "code": null, "e": 36312, "s": 36304, "text": "Strings" }, { "code": null, "e": 36320, "s": 36312, "text": "Strings" }, { "code": null, "e": 36325, "s": 36320, "text": "Java" }, { "code": null, "e": 36336, "s": 36325, "text": "palindrome" }, { "code": null, "e": 36434, "s": 36336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36466, "s": 36434, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36490, "s": 36466, "text": "Queue Interface In Java" }, { "code": null, "e": 36509, "s": 36490, "text": "LinkedList in Java" }, { "code": null, "e": 36539, "s": 36509, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36557, "s": 36539, "text": "ArrayList in Java" }, { "code": null, "e": 36601, "s": 36557, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 36629, "s": 36601, "text": "Initializing a List in Java" }, { "code": null, "e": 36661, "s": 36629, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 36695, "s": 36661, "text": "Convert Double to Integer in Java" } ]
Custom Legends with Matplotlib - GeeksforGeeks
28 Nov, 2021 In this article, you learn to customize the legend in matplotlib. matplotlib is a popular data visualization library. It is a plotting library in python and has its numerical extension NumPy. Legend is an area of the graph describing each part of the graph. A graph can be simple as it is. But adding the title, X label, Y label and legend will be more clear. By seeing the names we can easily guess what the graph is representing and what type of data it is representing. Let us first see how to create a legend in matplotlib. syntax: legend(*args, **kwargs) This can be called as follows, legend() -> automatically detects which element to show. It does this by displaying all plots that have been labeled with the label keyword argument. legend(labels) -> Name of X and name of Y that is displayed on the legend legend(handles, labels) -> A list of lines that should be added to the legend. Using handles and labels together can give full control of what should be displayed in the legend. The length of the legend and handles should be the same. Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="A")plt.plot(b, label="B") # Creating legendplt.legend() Output: legend Legend adds meaning to the graph plots. Adding the font, location, and many more, make the legend more legible and easily recognizable. Now, let’s see some sample programs to customize the legends of the plots. Sometimes the legend may or may not be in the appropriate place. In matplotlib, we can also add the location where we want to place it. With this flexibility, we can place the legend somewhere where it does not overlay the plots, and hence the plots will look much cleaner and tidier. Syntax: legend(loc=”) It can be passed as follows, ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ -> It is placed on the corresponding corner of the plot. ‘upper center’, ‘lower center’, ‘center left’, ‘center right’ -> It is placed on the center of corresponding edge. ‘center’ -> It is placed exact center of the plot. ‘best’ -> It is placed without the overlapping of the artists For example, Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="A")plt.plot(b, label="B") # Creating legend# Adding the locationplt.legend(loc='center left') Output: center left To make the legend more appealing we can also change the font size of the legend, by passing the parameter font size to the function we can change the fontsize inside the legend box just like the plot titles. Syntax: legend(fontsize=”) It can be passed as, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ Example: Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") # Creating legendplt.legend(fontsize='xx-large') Output: Changing font size Sometimes we can feel that it would be great if the legend box was filled with some color to make it more attractive and makes the legends stand out from the plots. Matplotlib also covers this by letting us change the theme of the legend by changing the background, text, and even the edge color of the legend.-+ Syntax: legend(labelcolor=”) labelcolor is used to change the color of the text. legend(facecolor=”) facecolor is used to change background color of the legend. legend(edgecolor=”) edgecolor is used to change the edge color of the legend Example: Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") # Creating legend# Adding color to the legendplt.legend(labelcolor='white', facecolor='black', edgecolor='red', fontsize='xx-large') Output: changing color of the legend. In the above example, you can clearly see which keyword arguments give color to the legend. If you see the legend box, Syntax: legend(markerfirst = bool, default: True) By default, the marker is placed first and the label is placed second. marker first parameter is used to change the position of the marker. By making it False, the marker and labels places will be swapped. Example: Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") # Creating legendplt.legend(markerfirst=False) Output: markerfirst = False We can make the legend have some of the basic CSS properties like adding a shadow, adding a frame and making the corners round, and also let us add transparency to the legend box if you don’t want to cover those small details in the plot by a frame. shadow -> This argument gives shadow behind the legend. frameon -> Gives the frame to legend. fancybox -> Gives round edges to the legend. framealpha -> Gives transparency to legend background. Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") # Creating legend# Adding shadow and fancybox to the legendplt.legend(shadow=True, fancybox=True) Output: Shadow and fancybox Python3 #importing libraryimport matplotlib.pyplot as plt #plotting valuesa = [1,2,3,4]b = [1,4,9,16] #PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") #Creating legend#removing frameplt.legend(frameon = False) Output: Removes the frame Adding a title to the legend will be an important aspect to add to the legend box. The title parameter will let us give a title for the legend and the title_size let us assign a specific fontsize for the title. Syntax: legend(title=”” , title_fontsize=”) title gives title to the legend title_fontize gives size to the title. It can be, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ Example: Python3 # importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label="label1")plt.plot(b, label="label2") # Creating legend# giving title and fontsizeplt.legend(title="Legend", title_fontsize='xx-large') output: Title to the legend Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25729, "s": 25537, "text": "In this article, you learn to customize the legend in matplotlib. matplotlib is a popular data visualization library. It is a plotting library in python and has its numerical extension NumPy." }, { "code": null, "e": 26012, "s": 25729, "text": "Legend is an area of the graph describing each part of the graph. A graph can be simple as it is. But adding the title, X label, Y label and legend will be more clear. By seeing the names we can easily guess what the graph is representing and what type of data it is representing. " }, { "code": null, "e": 26069, "s": 26012, "text": "Let us first see how to create a legend in matplotlib. " }, { "code": null, "e": 26101, "s": 26069, "text": "syntax: legend(*args, **kwargs)" }, { "code": null, "e": 26132, "s": 26101, "text": "This can be called as follows," }, { "code": null, "e": 26284, "s": 26132, "text": "legend() -> automatically detects which element to show. It does this by displaying all plots that have been labeled with the label keyword argument. " }, { "code": null, "e": 26359, "s": 26284, "text": "legend(labels) -> Name of X and name of Y that is displayed on the legend " }, { "code": null, "e": 26594, "s": 26359, "text": "legend(handles, labels) -> A list of lines that should be added to the legend. Using handles and labels together can give full control of what should be displayed in the legend. The length of the legend and handles should be the same." }, { "code": null, "e": 26602, "s": 26594, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"A\")plt.plot(b, label=\"B\") # Creating legendplt.legend()", "e": 26809, "s": 26602, "text": null }, { "code": null, "e": 26817, "s": 26809, "text": "Output:" }, { "code": null, "e": 26824, "s": 26817, "text": "legend" }, { "code": null, "e": 27035, "s": 26824, "text": "Legend adds meaning to the graph plots. Adding the font, location, and many more, make the legend more legible and easily recognizable. Now, let’s see some sample programs to customize the legends of the plots." }, { "code": null, "e": 27321, "s": 27035, "text": "Sometimes the legend may or may not be in the appropriate place. In matplotlib, we can also add the location where we want to place it. With this flexibility, we can place the legend somewhere where it does not overlay the plots, and hence the plots will look much cleaner and tidier. " }, { "code": null, "e": 27343, "s": 27321, "text": "Syntax: legend(loc=”)" }, { "code": null, "e": 27373, "s": 27343, "text": "It can be passed as follows, " }, { "code": null, "e": 27487, "s": 27373, "text": "‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ -> It is placed on the corresponding corner of the plot." }, { "code": null, "e": 27604, "s": 27487, "text": "‘upper center’, ‘lower center’, ‘center left’, ‘center right’ -> It is placed on the center of corresponding edge. " }, { "code": null, "e": 27655, "s": 27604, "text": "‘center’ -> It is placed exact center of the plot." }, { "code": null, "e": 27718, "s": 27655, "text": "‘best’ -> It is placed without the overlapping of the artists" }, { "code": null, "e": 27732, "s": 27718, "text": "For example, " }, { "code": null, "e": 27740, "s": 27732, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"A\")plt.plot(b, label=\"B\") # Creating legend# Adding the locationplt.legend(loc='center left')", "e": 27985, "s": 27740, "text": null }, { "code": null, "e": 27993, "s": 27985, "text": "Output:" }, { "code": null, "e": 28005, "s": 27993, "text": "center left" }, { "code": null, "e": 28215, "s": 28005, "text": "To make the legend more appealing we can also change the font size of the legend, by passing the parameter font size to the function we can change the fontsize inside the legend box just like the plot titles. " }, { "code": null, "e": 28242, "s": 28215, "text": "Syntax: legend(fontsize=”)" }, { "code": null, "e": 28336, "s": 28242, "text": "It can be passed as, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’" }, { "code": null, "e": 28345, "s": 28336, "text": "Example:" }, { "code": null, "e": 28353, "s": 28345, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") # Creating legendplt.legend(fontsize='xx-large')", "e": 28589, "s": 28353, "text": null }, { "code": null, "e": 28597, "s": 28589, "text": "Output:" }, { "code": null, "e": 28616, "s": 28597, "text": "Changing font size" }, { "code": null, "e": 28929, "s": 28616, "text": "Sometimes we can feel that it would be great if the legend box was filled with some color to make it more attractive and makes the legends stand out from the plots. Matplotlib also covers this by letting us change the theme of the legend by changing the background, text, and even the edge color of the legend.-+" }, { "code": null, "e": 28938, "s": 28929, "text": "Syntax: " }, { "code": null, "e": 28959, "s": 28938, "text": "legend(labelcolor=”)" }, { "code": null, "e": 29012, "s": 28959, "text": "labelcolor is used to change the color of the text." }, { "code": null, "e": 29032, "s": 29012, "text": "legend(facecolor=”)" }, { "code": null, "e": 29092, "s": 29032, "text": "facecolor is used to change background color of the legend." }, { "code": null, "e": 29112, "s": 29092, "text": "legend(edgecolor=”)" }, { "code": null, "e": 29169, "s": 29112, "text": "edgecolor is used to change the edge color of the legend" }, { "code": null, "e": 29178, "s": 29169, "text": "Example:" }, { "code": null, "e": 29186, "s": 29178, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") # Creating legend# Adding color to the legendplt.legend(labelcolor='white', facecolor='black', edgecolor='red', fontsize='xx-large')", "e": 29516, "s": 29186, "text": null }, { "code": null, "e": 29524, "s": 29516, "text": "Output:" }, { "code": null, "e": 29554, "s": 29524, "text": "changing color of the legend." }, { "code": null, "e": 29646, "s": 29554, "text": "In the above example, you can clearly see which keyword arguments give color to the legend." }, { "code": null, "e": 29673, "s": 29646, "text": "If you see the legend box," }, { "code": null, "e": 29682, "s": 29673, "text": "Syntax: " }, { "code": null, "e": 29724, "s": 29682, "text": "legend(markerfirst = bool, default: True)" }, { "code": null, "e": 29930, "s": 29724, "text": "By default, the marker is placed first and the label is placed second. marker first parameter is used to change the position of the marker. By making it False, the marker and labels places will be swapped." }, { "code": null, "e": 29939, "s": 29930, "text": "Example:" }, { "code": null, "e": 29947, "s": 29939, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") # Creating legendplt.legend(markerfirst=False)", "e": 30181, "s": 29947, "text": null }, { "code": null, "e": 30190, "s": 30181, "text": " Output:" }, { "code": null, "e": 30210, "s": 30190, "text": "markerfirst = False" }, { "code": null, "e": 30460, "s": 30210, "text": "We can make the legend have some of the basic CSS properties like adding a shadow, adding a frame and making the corners round, and also let us add transparency to the legend box if you don’t want to cover those small details in the plot by a frame." }, { "code": null, "e": 30517, "s": 30460, "text": "shadow -> This argument gives shadow behind the legend. " }, { "code": null, "e": 30556, "s": 30517, "text": "frameon -> Gives the frame to legend." }, { "code": null, "e": 30602, "s": 30556, "text": "fancybox -> Gives round edges to the legend. " }, { "code": null, "e": 30657, "s": 30602, "text": "framealpha -> Gives transparency to legend background." }, { "code": null, "e": 30665, "s": 30657, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") # Creating legend# Adding shadow and fancybox to the legendplt.legend(shadow=True, fancybox=True)", "e": 30950, "s": 30665, "text": null }, { "code": null, "e": 30958, "s": 30950, "text": "Output:" }, { "code": null, "e": 30978, "s": 30958, "text": "Shadow and fancybox" }, { "code": null, "e": 30986, "s": 30978, "text": "Python3" }, { "code": "#importing libraryimport matplotlib.pyplot as plt #plotting valuesa = [1,2,3,4]b = [1,4,9,16] #PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") #Creating legend#removing frameplt.legend(frameon = False)", "e": 31223, "s": 30986, "text": null }, { "code": null, "e": 31231, "s": 31223, "text": "Output:" }, { "code": null, "e": 31249, "s": 31231, "text": "Removes the frame" }, { "code": null, "e": 31460, "s": 31249, "text": "Adding a title to the legend will be an important aspect to add to the legend box. The title parameter will let us give a title for the legend and the title_size let us assign a specific fontsize for the title." }, { "code": null, "e": 31468, "s": 31460, "text": "Syntax:" }, { "code": null, "e": 31504, "s": 31468, "text": "legend(title=”” , title_fontsize=”)" }, { "code": null, "e": 31536, "s": 31504, "text": "title gives title to the legend" }, { "code": null, "e": 31575, "s": 31536, "text": "title_fontize gives size to the title." }, { "code": null, "e": 31659, "s": 31575, "text": "It can be, ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’" }, { "code": null, "e": 31669, "s": 31659, "text": "Example: " }, { "code": null, "e": 31677, "s": 31669, "text": "Python3" }, { "code": "# importing libraryimport matplotlib.pyplot as plt # plotting valuesa = [1, 2, 3, 4]b = [1, 4, 9, 16] # PLotting using matplotlibplt.plot(a, label=\"label1\")plt.plot(b, label=\"label2\") # Creating legend# giving title and fontsizeplt.legend(title=\"Legend\", title_fontsize='xx-large')", "e": 31962, "s": 31677, "text": null }, { "code": null, "e": 31970, "s": 31962, "text": "output:" }, { "code": null, "e": 31990, "s": 31970, "text": "Title to the legend" }, { "code": null, "e": 31997, "s": 31990, "text": "Picked" }, { "code": null, "e": 32015, "s": 31997, "text": "Python-matplotlib" }, { "code": null, "e": 32022, "s": 32015, "text": "Python" }, { "code": null, "e": 32120, "s": 32022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32152, "s": 32120, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32194, "s": 32152, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32236, "s": 32194, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32263, "s": 32236, "text": "Python Classes and Objects" }, { "code": null, "e": 32319, "s": 32263, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32341, "s": 32319, "text": "Defaultdict in Python" }, { "code": null, "e": 32380, "s": 32341, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32411, "s": 32380, "text": "Python | os.path.join() method" }, { "code": null, "e": 32440, "s": 32411, "text": "Create a directory in Python" } ]
PHP | JsonSerializable jsonSerialize() Function - GeeksforGeeks
27 Sep, 2019 The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function. Syntax: mixed JsonSerializable::jsonSerialize( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the data which is serialized by json_encode() function. Below programs illustrate the JsonSerializable::jsonSerialize() function in PHP: Program 1: <?php class vector implements JsonSerializable { public function __construct(array $arr) { $this->array = $arr; } public function jsonSerialize() { return $this->array; } } // Declare an array $arr = [1, 2, 3, 4, 5]; echo("JSON elements:\n"); // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT); ?> JSON elements: [ 1, 2, 3, 4, 5 ] Program 2: <?php class vector implements JsonSerializable { public function __construct(array $arr) { $this->array = $arr; } public function jsonSerialize() { return $this->array; } } // Declare an array $arr = [ "x" => "geeks", "y" => "for", "z" => "geeks"]; echo("Convert the array element into JSON:\n"); // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT); ?> Convert the array element into JSON: { "x": "geeks", "y": "for", "z": "geeks" } Reference: https://www.php.net/manual/en/jsonserializable.jsonserialize.php JSON PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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": 25925, "s": 25897, "text": "\n27 Sep, 2019" }, { "code": null, "e": 26121, "s": 25925, "text": "The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function." }, { "code": null, "e": 26129, "s": 26121, "text": "Syntax:" }, { "code": null, "e": 26175, "s": 26129, "text": "mixed JsonSerializable::jsonSerialize( void )" }, { "code": null, "e": 26233, "s": 26175, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 26325, "s": 26233, "text": "Return Value: This function returns the data which is serialized by json_encode() function." }, { "code": null, "e": 26406, "s": 26325, "text": "Below programs illustrate the JsonSerializable::jsonSerialize() function in PHP:" }, { "code": null, "e": 26417, "s": 26406, "text": "Program 1:" }, { "code": "<?php class vector implements JsonSerializable { public function __construct(array $arr) { $this->array = $arr; } public function jsonSerialize() { return $this->array; } } // Declare an array $arr = [1, 2, 3, 4, 5]; echo(\"JSON elements:\\n\"); // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT); ?> ", "e": 26799, "s": 26417, "text": null }, { "code": null, "e": 26853, "s": 26799, "text": "JSON elements:\n[\n 1,\n 2,\n 3,\n 4,\n 5\n]\n" }, { "code": null, "e": 26864, "s": 26853, "text": "Program 2:" }, { "code": "<?php class vector implements JsonSerializable { public function __construct(array $arr) { $this->array = $arr; } public function jsonSerialize() { return $this->array; } } // Declare an array $arr = [ \"x\" => \"geeks\", \"y\" => \"for\", \"z\" => \"geeks\"]; echo(\"Convert the array element into JSON:\\n\"); // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT); ?> ", "e": 27310, "s": 26864, "text": null }, { "code": null, "e": 27403, "s": 27310, "text": "Convert the array element into JSON:\n{\n \"x\": \"geeks\",\n \"y\": \"for\",\n \"z\": \"geeks\"\n}\n" }, { "code": null, "e": 27479, "s": 27403, "text": "Reference: https://www.php.net/manual/en/jsonserializable.jsonserialize.php" }, { "code": null, "e": 27484, "s": 27479, "text": "JSON" }, { "code": null, "e": 27497, "s": 27484, "text": "PHP-function" }, { "code": null, "e": 27501, "s": 27497, "text": "PHP" }, { "code": null, "e": 27518, "s": 27501, "text": "Web Technologies" }, { "code": null, "e": 27522, "s": 27518, "text": "PHP" }, { "code": null, "e": 27620, "s": 27522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27670, "s": 27620, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27710, "s": 27670, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27771, "s": 27710, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27821, "s": 27771, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27866, "s": 27821, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27906, "s": 27866, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27939, "s": 27906, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27984, "s": 27939, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28027, "s": 27984, "text": "How to fetch data from an API in ReactJS ?" } ]
Generate boolean (yes/no) questions from any content using T5 text-to-text transformer model | by Ramsri Goutham | Towards Data Science
The input to our program will be any general content/paragraph - Months earlier, Coca-Cola had begun “Project Kansas.” It sounds like a nuclear experiment but it was just a testing project for the new flavor. In individual surveys, they’d found that more than 75% of respondents loved the taste, 15% were indifferent, and 10% had a strong aversion to the taste to the point that they were angry. The output will be boolean (yes/no) questions generated from the above input. Boolean (yes/no) questions generated from the T5 Model : 1: Does coca cola have a kansas flavor?2: Is project kansas a new coca cola flavor?3: Is project kansas the same as coca cola? Today we will see how we can train a T5 model from Huggingface’s transformers library to generate these boolean questions. We will also see how we can use the pre-trained model provided to generate these boolean (yes/no) questions. Imagine a scenario where, as a student, you interact with a chatbot to learn a concept interactively. The chatbot presents you with relevant byte-sized snippets of content from a textbook chapter based on your responses. It also wants to assess in real-time whether you have understood the topic presented. It is impractical to manually pre-generate assessments for each snippet of the textbook chapter. The chatbot can make use of this algorithm to generate boolean(yes/no) questions in real-time and evaluate your understanding of the topic. Let’s get started — I used the BoolQ dataset to collect the passage, question and answer triplets, and prepared training and validation sets. The boolQ dataset has the following format - { "question": "is france the same timezone as the uk", "passage": "At the Liberation of France in the summer of 1944, Metropolitan France kept GMT+2 as it was the time then used by the Allies (British Double Summer Time). In the winter of 1944--1945, Metropolitan France switched to GMT+1, same as in the United Kingdom, and switched again to GMT+2 in April 1945 like its British ally. In September 1945, Metropolitan France returned to GMT+1 (pre-war summer time), which the British had already done in July 1945. Metropolitan France was officially scheduled to return to GMT+0 on November 18, 1945 (the British returned to GMT+0 in on October 7, 1945), but the French government canceled the decision on November 5, 1945, and GMT+1 has since then remained the official time of Metropolitan France." "answer": false, "title": "Time in France",} There is a “passage” which has a corresponding “question” and the correct boolean “answer” — true or false. We will discuss in detail how you can - Use my pre-trained model to generate boolean questions for any given content.Use my training code and dataset to replicate the results on your own GPU machine. Use my pre-trained model to generate boolean questions for any given content. Use my training code and dataset to replicate the results on your own GPU machine. T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here. It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation, etc using a text-to-text transformer trained on a large text corpus. I gave the “passage” and “answer” as input to my T5 transformer model and trained it to generate the “question” as output. All the code for using pre-trained model and training the model with given data is available at - github.com The Python file t5_inference.py contains all the code presented below. First, install the necessary libraries - !pip install torch==1.4.0!pip install transformers==2.9.0!pip install pytorch_lightning==0.7.5 Run inference with any text/paragraph as input and see the boolean questions generated - The output from the above code is - Context: Months earlier, Coca-Cola had begun “Project Kansas.” It sounds like a nuclear experiment but it was just a testing project for the new flavor. In individual surveys, they’d found that more than 75% of respondents loved the taste, 15% were indifferent, and 10% had a strong aversion to the taste to the point that they were angry.Beam decoding [Most accurate questions] ::Does coca cola have a kansas flavor?Is project kansas the same as coca cola?Is project kansas a new coca cola flavor?TopKP decoding [Not very accurate but more variety in questions] ::Does coca cola have a koala flavor?Is kakao the same as project kansas?Was project ksoda a real thing?Time elapsed 1.2351574897766113 All the training code and dataset used for training are available in the Github repo mentioned. We will go through the steps that I used to train the model. The file boolQ_prepare_train_validation_dataset.ipynb contains all the code to prepare the train and validation datasets. I took the boolQ dataset which is available as a JSON file and converted it into a csv file. Thanks to Suraj Patil for the amazing Colab notebook on training T5 for any text-to-text task. I borrowed most of the training code from the Colab notebook, changing only the dataset class and training parameters. I adapted the dataset class to our boolQ dataset. The training code is available as train.py in the Github Repo. All you need to do is clone the repo on any GPU machine, install requirements.txt, and run train.py to train the T5 model. Training this model for 4 epochs (default) took about 5–6 hrs on p2.xlarge (AWS ec2). The dataset class looks like below — The key is how we give our input and output to the T5 model trainer. I gave the “passage” and “answer” as input to my T5 transformer model and trained it to generate the “question” as output as shown below - Input format to T5 for training truefalse: yes passage: At the Liberation of France in the summer of 1944, Metropolitan France kept GMT+2 as it was the time then used by the Allies (British Double Summer Time). In the winter of 1944--1945, Metropolitan France switched to GMT+1, same as in the United Kingdom, and switched again to GMT+2 in April 1945 like its British ally. In September 1945, Metropolitan France returned to GMT+1 (pre-war summer time), which the British had already done in July 1945. Metropolitan France was officially scheduled to return to GMT+0 on November 18, 1945 (the British returned to GMT+0 in on October 7, 1945), but the French government canceled the decision on November 5, 1945, and GMT+1 has since then remained the official time of Metropolitan France. </s> Output format to T5 for training Is france the same timezone as the uk? </s> Note: The text “truefalse: yes” or “truefalse: no” is supposed to generate an appropriate boolean question to which the answer is “yes” or “no” as given in the text. But with my trails to train T5, it hasn’t been effective. So make sure that you don’t rely on the initial token “yes” or “no” given as an answer to the boolean question generated. The total dataset is only about ~10k samples hence the quality of questions generated is sometimes not very great. Please note that. Happy coding! I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now! I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link. Feel free to connect on Linkedin if you have any questions or you just wanted to say hi!
[ { "code": null, "e": 237, "s": 172, "text": "The input to our program will be any general content/paragraph -" }, { "code": null, "e": 568, "s": 237, "text": "Months earlier, Coca-Cola had begun “Project Kansas.” It sounds like a nuclear experiment but it was just a testing project for the new flavor. In individual surveys, they’d found that more than 75% of respondents loved the taste, 15% were indifferent, and 10% had a strong aversion to the taste to the point that they were angry." }, { "code": null, "e": 646, "s": 568, "text": "The output will be boolean (yes/no) questions generated from the above input." }, { "code": null, "e": 703, "s": 646, "text": "Boolean (yes/no) questions generated from the T5 Model :" }, { "code": null, "e": 830, "s": 703, "text": "1: Does coca cola have a kansas flavor?2: Is project kansas a new coca cola flavor?3: Is project kansas the same as coca cola?" }, { "code": null, "e": 1062, "s": 830, "text": "Today we will see how we can train a T5 model from Huggingface’s transformers library to generate these boolean questions. We will also see how we can use the pre-trained model provided to generate these boolean (yes/no) questions." }, { "code": null, "e": 1606, "s": 1062, "text": "Imagine a scenario where, as a student, you interact with a chatbot to learn a concept interactively. The chatbot presents you with relevant byte-sized snippets of content from a textbook chapter based on your responses. It also wants to assess in real-time whether you have understood the topic presented. It is impractical to manually pre-generate assessments for each snippet of the textbook chapter. The chatbot can make use of this algorithm to generate boolean(yes/no) questions in real-time and evaluate your understanding of the topic." }, { "code": null, "e": 1626, "s": 1606, "text": "Let’s get started —" }, { "code": null, "e": 1748, "s": 1626, "text": "I used the BoolQ dataset to collect the passage, question and answer triplets, and prepared training and validation sets." }, { "code": null, "e": 1793, "s": 1748, "text": "The boolQ dataset has the following format -" }, { "code": null, "e": 2643, "s": 1793, "text": "{ \"question\": \"is france the same timezone as the uk\", \"passage\": \"At the Liberation of France in the summer of 1944, Metropolitan France kept GMT+2 as it was the time then used by the Allies (British Double Summer Time). In the winter of 1944--1945, Metropolitan France switched to GMT+1, same as in the United Kingdom, and switched again to GMT+2 in April 1945 like its British ally. In September 1945, Metropolitan France returned to GMT+1 (pre-war summer time), which the British had already done in July 1945. Metropolitan France was officially scheduled to return to GMT+0 on November 18, 1945 (the British returned to GMT+0 in on October 7, 1945), but the French government canceled the decision on November 5, 1945, and GMT+1 has since then remained the official time of Metropolitan France.\" \"answer\": false, \"title\": \"Time in France\",}" }, { "code": null, "e": 2751, "s": 2643, "text": "There is a “passage” which has a corresponding “question” and the correct boolean “answer” — true or false." }, { "code": null, "e": 2791, "s": 2751, "text": "We will discuss in detail how you can -" }, { "code": null, "e": 2951, "s": 2791, "text": "Use my pre-trained model to generate boolean questions for any given content.Use my training code and dataset to replicate the results on your own GPU machine." }, { "code": null, "e": 3029, "s": 2951, "text": "Use my pre-trained model to generate boolean questions for any given content." }, { "code": null, "e": 3112, "s": 3029, "text": "Use my training code and dataset to replicate the results on your own GPU machine." }, { "code": null, "e": 3275, "s": 3112, "text": "T5 is a new transformer model from Google that is trained in an end-to-end manner with text as input and modified text as output. You can read more about it here." }, { "code": null, "e": 3464, "s": 3275, "text": "It achieves state-of-the-art results on multiple NLP tasks like summarization, question answering, machine translation, etc using a text-to-text transformer trained on a large text corpus." }, { "code": null, "e": 3587, "s": 3464, "text": "I gave the “passage” and “answer” as input to my T5 transformer model and trained it to generate the “question” as output." }, { "code": null, "e": 3685, "s": 3587, "text": "All the code for using pre-trained model and training the model with given data is available at -" }, { "code": null, "e": 3696, "s": 3685, "text": "github.com" }, { "code": null, "e": 3767, "s": 3696, "text": "The Python file t5_inference.py contains all the code presented below." }, { "code": null, "e": 3808, "s": 3767, "text": "First, install the necessary libraries -" }, { "code": null, "e": 3903, "s": 3808, "text": "!pip install torch==1.4.0!pip install transformers==2.9.0!pip install pytorch_lightning==0.7.5" }, { "code": null, "e": 3992, "s": 3903, "text": "Run inference with any text/paragraph as input and see the boolean questions generated -" }, { "code": null, "e": 4028, "s": 3992, "text": "The output from the above code is -" }, { "code": null, "e": 4729, "s": 4028, "text": "Context: Months earlier, Coca-Cola had begun “Project Kansas.” It sounds like a nuclear experiment but it was just a testing project for the new flavor. In individual surveys, they’d found that more than 75% of respondents loved the taste, 15% were indifferent, and 10% had a strong aversion to the taste to the point that they were angry.Beam decoding [Most accurate questions] ::Does coca cola have a kansas flavor?Is project kansas the same as coca cola?Is project kansas a new coca cola flavor?TopKP decoding [Not very accurate but more variety in questions] ::Does coca cola have a koala flavor?Is kakao the same as project kansas?Was project ksoda a real thing?Time elapsed 1.2351574897766113" }, { "code": null, "e": 4886, "s": 4729, "text": "All the training code and dataset used for training are available in the Github repo mentioned. We will go through the steps that I used to train the model." }, { "code": null, "e": 5101, "s": 4886, "text": "The file boolQ_prepare_train_validation_dataset.ipynb contains all the code to prepare the train and validation datasets. I took the boolQ dataset which is available as a JSON file and converted it into a csv file." }, { "code": null, "e": 5365, "s": 5101, "text": "Thanks to Suraj Patil for the amazing Colab notebook on training T5 for any text-to-text task. I borrowed most of the training code from the Colab notebook, changing only the dataset class and training parameters. I adapted the dataset class to our boolQ dataset." }, { "code": null, "e": 5428, "s": 5365, "text": "The training code is available as train.py in the Github Repo." }, { "code": null, "e": 5551, "s": 5428, "text": "All you need to do is clone the repo on any GPU machine, install requirements.txt, and run train.py to train the T5 model." }, { "code": null, "e": 5637, "s": 5551, "text": "Training this model for 4 epochs (default) took about 5–6 hrs on p2.xlarge (AWS ec2)." }, { "code": null, "e": 5674, "s": 5637, "text": "The dataset class looks like below —" }, { "code": null, "e": 5882, "s": 5674, "text": "The key is how we give our input and output to the T5 model trainer. I gave the “passage” and “answer” as input to my T5 transformer model and trained it to generate the “question” as output as shown below -" }, { "code": null, "e": 5914, "s": 5882, "text": "Input format to T5 for training" }, { "code": null, "e": 6676, "s": 5914, "text": "truefalse: yes passage: At the Liberation of France in the summer of 1944, Metropolitan France kept GMT+2 as it was the time then used by the Allies (British Double Summer Time). In the winter of 1944--1945, Metropolitan France switched to GMT+1, same as in the United Kingdom, and switched again to GMT+2 in April 1945 like its British ally. In September 1945, Metropolitan France returned to GMT+1 (pre-war summer time), which the British had already done in July 1945. Metropolitan France was officially scheduled to return to GMT+0 on November 18, 1945 (the British returned to GMT+0 in on October 7, 1945), but the French government canceled the decision on November 5, 1945, and GMT+1 has since then remained the official time of Metropolitan France. </s>" }, { "code": null, "e": 6709, "s": 6676, "text": "Output format to T5 for training" }, { "code": null, "e": 6753, "s": 6709, "text": "Is france the same timezone as the uk? </s>" }, { "code": null, "e": 7099, "s": 6753, "text": "Note: The text “truefalse: yes” or “truefalse: no” is supposed to generate an appropriate boolean question to which the answer is “yes” or “no” as given in the text. But with my trails to train T5, it hasn’t been effective. So make sure that you don’t rely on the initial token “yes” or “no” given as an answer to the boolean question generated." }, { "code": null, "e": 7232, "s": 7099, "text": "The total dataset is only about ~10k samples hence the quality of questions generated is sometimes not very great. Please note that." }, { "code": null, "e": 7246, "s": 7232, "text": "Happy coding!" }, { "code": null, "e": 7538, "s": 7246, "text": "I am running a 4-week cohort-based course on “Practical Introduction to NLP” with Maven, the world’s best platform for cohort-based learning. If you wish to transform yourself from a Python developer to a junior NLP developer with practical project experience in 4 weeks, grab your spot now!" }, { "code": null, "e": 7743, "s": 7538, "text": "I launched a very interesting Udemy course titled “Question generation using NLP” expanding on some of the techniques discussed in this blog post. If you would like to take a look at it, here is the link." } ]
Multi-Label Classification using BERT, RoBERTa, XLNet, XLM, and DistilBERT with Simple Transformers | by Thilina Rajapakse | Towards Data Science
The Simple Transformers library is built on top of the excellent Transformers library by Hugging Face. You guys are incredible! Simple Transformers now supports: Binary Classification Multiclass Classification Named Entity Recognition (and similar token level tasks) Multilabel Classification There’s plenty more in the pipeline. Transformer models and Transfer Learning methods continue to propel the field of Natural Language Processing forward at a tremendous pace. However, state-of-the-art performance too often comes at the price of tons of (complex) code. Simple Transformers avoids all the complexity and lets you get down to what matters, training and using Transformer models. Bypass all the complicated setups, boilerplates, and other general unpleasantness to initialize a model in one line, train in the next, and evaluate with the third. This guide shows how you can use Simple Transformers to perform Multilabel Classification. In Multilabel Classification, each sample can have any combination (none, one, some, or all) of labels from a given set of labels. All source code is available on the Github Repo. If you have any issues or questions, that’s the place to resolve them. Please do check it out! Install Anaconda or Miniconda Package Manager from here.Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install seqevalpip install tensorboardxInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers Install Anaconda or Miniconda Package Manager from here. Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install seqevalpip install tensorboardx Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.) Install simpletransformers.pip install simpletransformers To demonstrate Multilabel Classification we will use the Toxic Comments dataset from Kaggle. Download the dataset from the link above and place the csv files in the data/ directory. The comments in the dataset have been labelled according to the criteria below. toxic severe_toxic obscene threat insult identity_hate The dataset contains a column for each criterion with a Boolean 1 or 0 indicating whether or not the comment contains the corresponding toxicity. import pandas as pd train_df = pd.read_csv('data/train.csv') train_df.head() However, Simple Transformers requires a column labels which contains multi-hot encoded lists of labels as well as a column text which contains all the text (duh!). import pandas as pd df = pd.read_csv('data/train.csv') df.head() df['labels'] = list(zip(df.toxic.tolist(), df.severe_toxic.tolist(), df.obscene.tolist(), df.threat.tolist(), df.insult.tolist(), df.identity_hate.tolist())) df['text'] = df['comment_text'].apply(lambda x: x.replace('\n', ' ')) df.head() Let’s split the dfinto train and eval datasets so we can validate the model easily. Now the dataset is ready for use! This creates a MultiLabelClassificationModel that can be used for training, evaluating, and predicting on multilabel classification tasks. The first parameter is the model_type, the second is the model_name, and the third is the number of labels in the data. model_type may be one of ['bert', 'xlnet', 'xlm', 'roberta', 'distilbert']. For a full list of pretrained models that can be used for model_name, please refer to Current Pretrained Models. The args parameter takes in an optional Python dictionary of hyper-parameter values and configuration options. I highly recommend checking out all the options here. The default values are shown below. To load a model a previously saved model instead of a default model, you can change the model_name to the path to a directory which contains a saved model. model = MultiLabelClassificationModel('xlnet', 'path_to_model/', num_labels=6) This will train the model on the training data. You can also change the hyperparameters by passing in a dict containing the relevant attributes to the train_model method. Note that, these modifications will persist even after training is completed. The train_model method will create a checkpoint (save) of the model at every nth step where n is self.args['save_steps']. Upon completion of training, the final model will be saved to self.args['output_dir']. The eval_model method is used to perform evaluation on an evaluation dataset. This method has three return values. result: The evaluation result in the form of a dict. By default, only the Label ranking average precision (LRAP) is reported for multilabel classification. model_outputs: A list of model outputs for each item in the evaluation dataset. This is useful if you need probabilities for each class rather than a single prediction. Note that a sigmoid function has been applied to each output to squash the values between 0 and . wrong_predictions: A list of InputFeature of each incorrect prediction. The text may be obtained from the InputFeature.text_a attribute. (The InputFeature class can be found in the utils.py file in the repo) You can also include additional metrics to be used in the evaluation. Simply pass in the metrics functions as keyword arguments to the eval_model method. The metrics functions should take in two parameters, the first one being the true labels, and the second being the predictions. This follows the sklearn standard. Make sure that the metric functions are compatible with multilabel classification. While eval_model is useful when we know the correct labels and merely need to asses the performance of a model, we rarely know the true labels in real-world tasks (I’m sure there’s some profound philosophy there). In such cases, the predict method comes in handy. It is similar to the eval_model method except that it doesn’t require the true labels and returns the predictions and the model outputs. We can try it out on the test data provided in the Toxic Comments dataset. Submitting this to Kaggle nets me a score of 0.98468, once again demonstrating how far NLP has progressed since the advent of Transformers and Transfer Learning. Keep in mind that I haven’t done much hyper-parameter tuning here! BERT and its derivatives are awesome! I hope Simple Transformers helps smooth out a few bumps on the road to using them.
[ { "code": null, "e": 299, "s": 171, "text": "The Simple Transformers library is built on top of the excellent Transformers library by Hugging Face. You guys are incredible!" }, { "code": null, "e": 333, "s": 299, "text": "Simple Transformers now supports:" }, { "code": null, "e": 355, "s": 333, "text": "Binary Classification" }, { "code": null, "e": 381, "s": 355, "text": "Multiclass Classification" }, { "code": null, "e": 438, "s": 381, "text": "Named Entity Recognition (and similar token level tasks)" }, { "code": null, "e": 464, "s": 438, "text": "Multilabel Classification" }, { "code": null, "e": 501, "s": 464, "text": "There’s plenty more in the pipeline." }, { "code": null, "e": 734, "s": 501, "text": "Transformer models and Transfer Learning methods continue to propel the field of Natural Language Processing forward at a tremendous pace. However, state-of-the-art performance too often comes at the price of tons of (complex) code." }, { "code": null, "e": 1023, "s": 734, "text": "Simple Transformers avoids all the complexity and lets you get down to what matters, training and using Transformer models. Bypass all the complicated setups, boilerplates, and other general unpleasantness to initialize a model in one line, train in the next, and evaluate with the third." }, { "code": null, "e": 1245, "s": 1023, "text": "This guide shows how you can use Simple Transformers to perform Multilabel Classification. In Multilabel Classification, each sample can have any combination (none, one, some, or all) of labels from a given set of labels." }, { "code": null, "e": 1389, "s": 1245, "text": "All source code is available on the Github Repo. If you have any issues or questions, that’s the place to resolve them. Please do check it out!" }, { "code": null, "e": 2035, "s": 1389, "text": "Install Anaconda or Miniconda Package Manager from here.Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install seqevalpip install tensorboardxInstall Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)Install simpletransformers.pip install simpletransformers" }, { "code": null, "e": 2092, "s": 2035, "text": "Install Anaconda or Miniconda Package Manager from here." }, { "code": null, "e": 2479, "s": 2092, "text": "Create a new virtual environment and install packages.conda create -n simpletransformers python pandas tqdmconda activate simpletransformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install seqevalpip install tensorboardx" }, { "code": null, "e": 2626, "s": 2479, "text": "Install Apex if you are using fp16 training. Please follow the instructions here. (Installing Apex from pip has caused issues for several people.)" }, { "code": null, "e": 2684, "s": 2626, "text": "Install simpletransformers.pip install simpletransformers" }, { "code": null, "e": 2866, "s": 2684, "text": "To demonstrate Multilabel Classification we will use the Toxic Comments dataset from Kaggle. Download the dataset from the link above and place the csv files in the data/ directory." }, { "code": null, "e": 2946, "s": 2866, "text": "The comments in the dataset have been labelled according to the criteria below." }, { "code": null, "e": 2952, "s": 2946, "text": "toxic" }, { "code": null, "e": 2965, "s": 2952, "text": "severe_toxic" }, { "code": null, "e": 2973, "s": 2965, "text": "obscene" }, { "code": null, "e": 2980, "s": 2973, "text": "threat" }, { "code": null, "e": 2987, "s": 2980, "text": "insult" }, { "code": null, "e": 3001, "s": 2987, "text": "identity_hate" }, { "code": null, "e": 3147, "s": 3001, "text": "The dataset contains a column for each criterion with a Boolean 1 or 0 indicating whether or not the comment contains the corresponding toxicity." }, { "code": null, "e": 3168, "s": 3147, "text": "import pandas as pd\n" }, { "code": null, "e": 3226, "s": 3168, "text": "train_df = pd.read_csv('data/train.csv')\ntrain_df.head()\n" }, { "code": null, "e": 3393, "s": 3229, "text": "However, Simple Transformers requires a column labels which contains multi-hot encoded lists of labels as well as a column text which contains all the text (duh!)." }, { "code": null, "e": 3414, "s": 3393, "text": "import pandas as pd\n" }, { "code": null, "e": 3460, "s": 3414, "text": "df = pd.read_csv('data/train.csv')\ndf.head()\n" }, { "code": null, "e": 3701, "s": 3460, "text": "df['labels'] = list(zip(df.toxic.tolist(), df.severe_toxic.tolist(), df.obscene.tolist(), df.threat.tolist(), df.insult.tolist(), df.identity_hate.tolist()))\ndf['text'] = df['comment_text'].apply(lambda x: x.replace('\\n', ' '))\n\ndf.head()\n" }, { "code": null, "e": 3785, "s": 3701, "text": "Let’s split the dfinto train and eval datasets so we can validate the model easily." }, { "code": null, "e": 3819, "s": 3785, "text": "Now the dataset is ready for use!" }, { "code": null, "e": 4078, "s": 3819, "text": "This creates a MultiLabelClassificationModel that can be used for training, evaluating, and predicting on multilabel classification tasks. The first parameter is the model_type, the second is the model_name, and the third is the number of labels in the data." }, { "code": null, "e": 4154, "s": 4078, "text": "model_type may be one of ['bert', 'xlnet', 'xlm', 'roberta', 'distilbert']." }, { "code": null, "e": 4267, "s": 4154, "text": "For a full list of pretrained models that can be used for model_name, please refer to Current Pretrained Models." }, { "code": null, "e": 4432, "s": 4267, "text": "The args parameter takes in an optional Python dictionary of hyper-parameter values and configuration options. I highly recommend checking out all the options here." }, { "code": null, "e": 4468, "s": 4432, "text": "The default values are shown below." }, { "code": null, "e": 4624, "s": 4468, "text": "To load a model a previously saved model instead of a default model, you can change the model_name to the path to a directory which contains a saved model." }, { "code": null, "e": 4703, "s": 4624, "text": "model = MultiLabelClassificationModel('xlnet', 'path_to_model/', num_labels=6)" }, { "code": null, "e": 4952, "s": 4703, "text": "This will train the model on the training data. You can also change the hyperparameters by passing in a dict containing the relevant attributes to the train_model method. Note that, these modifications will persist even after training is completed." }, { "code": null, "e": 5161, "s": 4952, "text": "The train_model method will create a checkpoint (save) of the model at every nth step where n is self.args['save_steps']. Upon completion of training, the final model will be saved to self.args['output_dir']." }, { "code": null, "e": 5276, "s": 5161, "text": "The eval_model method is used to perform evaluation on an evaluation dataset. This method has three return values." }, { "code": null, "e": 5432, "s": 5276, "text": "result: The evaluation result in the form of a dict. By default, only the Label ranking average precision (LRAP) is reported for multilabel classification." }, { "code": null, "e": 5699, "s": 5432, "text": "model_outputs: A list of model outputs for each item in the evaluation dataset. This is useful if you need probabilities for each class rather than a single prediction. Note that a sigmoid function has been applied to each output to squash the values between 0 and ." }, { "code": null, "e": 5907, "s": 5699, "text": "wrong_predictions: A list of InputFeature of each incorrect prediction. The text may be obtained from the InputFeature.text_a attribute. (The InputFeature class can be found in the utils.py file in the repo)" }, { "code": null, "e": 6224, "s": 5907, "text": "You can also include additional metrics to be used in the evaluation. Simply pass in the metrics functions as keyword arguments to the eval_model method. The metrics functions should take in two parameters, the first one being the true labels, and the second being the predictions. This follows the sklearn standard." }, { "code": null, "e": 6307, "s": 6224, "text": "Make sure that the metric functions are compatible with multilabel classification." }, { "code": null, "e": 6708, "s": 6307, "text": "While eval_model is useful when we know the correct labels and merely need to asses the performance of a model, we rarely know the true labels in real-world tasks (I’m sure there’s some profound philosophy there). In such cases, the predict method comes in handy. It is similar to the eval_model method except that it doesn’t require the true labels and returns the predictions and the model outputs." }, { "code": null, "e": 6783, "s": 6708, "text": "We can try it out on the test data provided in the Toxic Comments dataset." }, { "code": null, "e": 7012, "s": 6783, "text": "Submitting this to Kaggle nets me a score of 0.98468, once again demonstrating how far NLP has progressed since the advent of Transformers and Transfer Learning. Keep in mind that I haven’t done much hyper-parameter tuning here!" } ]
Queue peek() method in Java - GeeksforGeeks
26 Sep, 2018 The peek() method of Queue Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the queue. The method does not throws an exception when the Queue is empty, it returns null instead. Syntax: E peek() Returns: This method returns the head of the Queue, it returns false when the Queue is empty Below programs illustrate peek() method of Queue: Program 1: With the help of LinkedList. // Java Program Demonstrate peek()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.peek()); // print queue System.out.println("Queue: " + Q); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Queue: [7855642, 35658786, 5278367, 74381793] Program 2: To demonstrate peek() method of Queue when Queue is empty // Java Program Demonstrate peek()// method of Queue when Queue is empty import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.peek()); }} Queue: [] Queue's head: null Program 3: With the help of ArrayDeque. // Java Program Demonstrate peek()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.peek()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Program 4: With the help of LinkedBlockingDeque. // Java Program Demonstrate peek()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.peek()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Program 5: With the help of ConcurrentLinkedDeque. // Java Program Demonstrate peek()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head System.out.println("Queue's head: " + Q.peek()); }} Queue: [7855642, 35658786, 5278367, 74381793] Queue's head: 7855642 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#peek– Java - util package java-basics Java-Collections Java-Functions java-queue Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n26 Sep, 2018" }, { "code": null, "e": 23825, "s": 23557, "text": "The peek() method of Queue Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the queue. The method does not throws an exception when the Queue is empty, it returns null instead." }, { "code": null, "e": 23833, "s": 23825, "text": "Syntax:" }, { "code": null, "e": 23842, "s": 23833, "text": "E peek()" }, { "code": null, "e": 23935, "s": 23842, "text": "Returns: This method returns the head of the Queue, it returns false when the Queue is empty" }, { "code": null, "e": 23985, "s": 23935, "text": "Below programs illustrate peek() method of Queue:" }, { "code": null, "e": 24025, "s": 23985, "text": "Program 1: With the help of LinkedList." }, { "code": "// Java Program Demonstrate peek()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.peek()); // print queue System.out.println(\"Queue: \" + Q); }}", "e": 24652, "s": 24025, "text": null }, { "code": null, "e": 24767, "s": 24652, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue: [7855642, 35658786, 5278367, 74381793]\n" }, { "code": null, "e": 24836, "s": 24767, "text": "Program 2: To demonstrate peek() method of Queue when Queue is empty" }, { "code": "// Java Program Demonstrate peek()// method of Queue when Queue is empty import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.peek()); }}", "e": 25283, "s": 24836, "text": null }, { "code": null, "e": 25313, "s": 25283, "text": "Queue: []\nQueue's head: null\n" }, { "code": null, "e": 25353, "s": 25313, "text": "Program 3: With the help of ArrayDeque." }, { "code": "// Java Program Demonstrate peek()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.peek()); }}", "e": 25914, "s": 25353, "text": null }, { "code": null, "e": 25983, "s": 25914, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 26032, "s": 25983, "text": "Program 4: With the help of LinkedBlockingDeque." }, { "code": "// Java Program Demonstrate peek()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.peek()); }}", "e": 26650, "s": 26032, "text": null }, { "code": null, "e": 26719, "s": 26650, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 26770, "s": 26719, "text": "Program 5: With the help of ConcurrentLinkedDeque." }, { "code": "// Java Program Demonstrate peek()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head System.out.println(\"Queue's head: \" + Q.peek()); }}", "e": 27392, "s": 26770, "text": null }, { "code": null, "e": 27461, "s": 27392, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\n" }, { "code": null, "e": 27541, "s": 27461, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#peek–" }, { "code": null, "e": 27561, "s": 27541, "text": "Java - util package" }, { "code": null, "e": 27573, "s": 27561, "text": "java-basics" }, { "code": null, "e": 27590, "s": 27573, "text": "Java-Collections" }, { "code": null, "e": 27605, "s": 27590, "text": "Java-Functions" }, { "code": null, "e": 27616, "s": 27605, "text": "java-queue" }, { "code": null, "e": 27621, "s": 27616, "text": "Java" }, { "code": null, "e": 27626, "s": 27621, "text": "Java" }, { "code": null, "e": 27643, "s": 27626, "text": "Java-Collections" }, { "code": null, "e": 27741, "s": 27643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27750, "s": 27741, "text": "Comments" }, { "code": null, "e": 27763, "s": 27750, "text": "Old Comments" }, { "code": null, "e": 27793, "s": 27763, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27808, "s": 27793, "text": "Stream In Java" }, { "code": null, "e": 27829, "s": 27808, "text": "Constructors in Java" }, { "code": null, "e": 27875, "s": 27829, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27894, "s": 27875, "text": "Exceptions in Java" }, { "code": null, "e": 27911, "s": 27894, "text": "Generics in Java" }, { "code": null, "e": 27954, "s": 27911, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27970, "s": 27954, "text": "Strings in Java" }, { "code": null, "e": 28026, "s": 27970, "text": "Difference between Abstract Class and Interface in Java" } ]